From e636103bd1ab7413ba842e3024f57bb49ca110cf Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky Date: Sun, 6 Dec 2026 00:47:18 +0100 Subject: [PATCH 01/65] =?UTF-8?q?test(ctx=5Fcheckpoint):=20S1=20contract?= =?UTF-8?q?=20for=20access-group=20bindings=20=E2=80=94=20inert=20stubs,?= =?UTF-8?q?=20fakes=20of=20ctx=20and=20the=20Hermes=20host,=20and=20the=20?= =?UTF-8?q?red=20tests=20of=20P-A=20to=20P-G=20behind=20a=20per-cluster=20?= =?UTF-8?q?shield?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plugin side of per-group ctx bindings is split into clusters P-A to P-G that are built in parallel; this commit fixes what they build against. New modules hold the final data forms and inert stubs: memory/access.py (field schema, detection, decision table, markers), memory/narrowing.py (client narrowing, whoami proof), memory/base_blocks.py (the access_group_fields hook), memory/access_cli.py (operator tools); CtxClient takes a narrowing and gains get_blocks, status.py gains record_access/read_access, checkpoint.py gains window_writes. Nothing calls them yet, so the plugin behaves as before (both suites unchanged: 763 passed + 2 skipped, 655 passed). tests/fakes holds a ctx server with the target narrowing semantics and the Hermes surface of the access-group core change (aligned to its code, not to the draft). Each cluster's red tests carry a marker; while the cluster is listed in tests/fakes/s1_pending.py they are strict xfails that only an assertion about the missing behaviour satisfies. Co-Authored-By: Claude Opus 5.5 --- .../plugin/ctx_checkpoint/memory/access.py | 299 +++++++++++ .../ctx_checkpoint/memory/access_cli.py | 51 ++ .../ctx_checkpoint/memory/base_blocks.py | 82 +++ .../ctx_checkpoint/memory/checkpoint.py | 14 + .../plugin/ctx_checkpoint/memory/client.py | 14 + .../plugin/ctx_checkpoint/memory/narrowing.py | 130 +++++ .../plugin/ctx_checkpoint/memory/status.py | 21 +- .../plugin/ctx_checkpoint/tests/conftest.py | 47 ++ .../ctx_checkpoint/tests/fakes/__init__.py | 3 + .../ctx_checkpoint/tests/fakes/access_host.py | 363 ++++++++++++++ .../ctx_checkpoint/tests/fakes/ctx_server.py | 474 ++++++++++++++++++ .../ctx_checkpoint/tests/fakes/s1_pending.py | 15 + .../tests/test_access_pa_client.py | 256 ++++++++++ .../tests/test_access_pb_decide.py | 291 +++++++++++ .../tests/test_access_pc_binding.py | 176 +++++++ .../tests/test_access_pd_base_blocks.py | 235 +++++++++ .../tests/test_access_pe_tools.py | 111 ++++ .../tests/test_access_pf_docs.py | 30 ++ .../tests/test_access_pg_window.py | 29 ++ 19 files changed, 2640 insertions(+), 1 deletion(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/access.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py new file mode 100644 index 000000000..11654f786 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -0,0 +1,299 @@ +"""Access groups: the fields ctx_checkpoint adds to them and the binding decision (contract, S1). + +Hermes' access groups (``gateway.access_groups``) run each sender of a governed server in the +profile of the first group that matches. A plugin adds fields to those groups +(``PluginContext.register_access_fields``) and is told, per agent build, which group the turn serves +(``initialize(scope_id=, access_group=, access_group_restricted=, access_fields=, +restricted_profile=)``) and, inside a turn, through ``gateway.access_groups.current_access()``. + +This module holds the schema of ctx_checkpoint's twelve fields, the detection of that host surface +and the pure decision which connection a session gets (``off``, the profile's own, or a group +binding). S1 state: the data forms are final, the functions are inert stubs; nothing in the plugin +calls them yet, so the plugin behaves as 0.19.1. The decision cluster (P-B) fills them in. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +from types import MappingProxyType +from typing import Any, Literal + +# The namespace is the plugin id ``memory.provider`` selects the provider by. +NAMESPACE = "ctx_checkpoint" +# The hook the core fires before a governed server's turn (gateway/access_prompt.py). +HOOK_NAME = "access_group_fields" + +# Platforms of a local, interactive session (``ungoverned: local`` admits them; forks only when +# their parent session was local). +# The profile's markers (``read_markers``, ``raise_markers``, ``reset_markers``), under the home. +MARKERS_FILE = "ctx_state/access-mode.json" + +LOCAL_PLATFORMS = frozenset({"cli", "tui", "desktop", "local", "codex", "acp", "gui"}) + +# ``memory.ctx_checkpoint.*`` keys of config.yaml this axis reads (never from ctx.json), with defaults. +SETTINGS_DEFAULTS: Mapping[str, Any] = MappingProxyType( + { + "ungoverned": "auto", # auto | profile | local | off + "governed_unbound": "off", # profile | off + "restricted_allow": (), # subset of ("recall", "capture") + "base_cache_s": 900, # 60 .. 86400 + "base_cache_entries": 2048, # 64 .. 65536 + "base_timeout_s": 4, # 1 .. 10 + "base_workers": 4, # 1 .. 32 + "verify_timeout_s": 3, # 1 .. 10 + } +) + + +def _spec(kind: str, description: str) -> Mapping[str, str]: + return MappingProxyType({"type": kind, "description": description}) + + +# The twelve fields (registered without ``default``: the values that apply when a field is not set +# depend on whether the group is restricted, and the core's profile check must judge set values). +# The list only grows: no field changes its type or meaning, none is renamed (the core's registry is +# process-wide, profiles may carry different plugin versions). +SCHEMA: Mapping[str, Mapping[str, str]] = MappingProxyType( + { + "key": _spec( + "env_name", + "Variable in the serving profile's .env holding the ctx key: CTX_KEY, CTX_API_KEY or CTX_KEY_<...>;" + " restricted groups only CTX_KEY__<...>. Not set: restricted groups get no ctx," + " others follow memory.ctx_checkpoint.governed_unbound.", + ), + "base_url": _spec( + "env_name", + "Variable holding the https URL of this group's ctx server: CTX_BASE_URL or CTX_BASE_URL_<...>." + " Not set: the profile's ctx URL.", + ), + "tenant": _spec( + "str", + "Expected tenant slug of the key; the group binds only when the key belongs to it." + " Not set: not checked (restricted groups need it).", + ), + "read": _spec( + "list", + "ctx scopes (:, 1 to 8) recall, read tools and base blocks read." + " Not set: the key's read set without 'write' (restricted groups need it).", + ), + "write": _spec( + "str", + "ctx scope the chain, facts, digests and mirror write to; must be the key's home scope." + " Not set: the key's home scope (restricted groups need it).", + ), + "store": _spec( + "str", + "ctx scope the ctx_store tool writes to; unrestricted groups only, within the key's write set." + " Not set: 'write'.", + ), + "recall": _spec( + "bool", + "Recall before each turn. Not set: on for unrestricted groups, off for restricted ones;" + " restricted groups need memory.ctx_checkpoint.restricted_allow to list recall.", + ), + "capture": _spec( + "bool", + "Chain, facts, digests and mirror are written. Not set: on for unrestricted groups, off for" + " restricted ones; restricted groups need memory.ctx_checkpoint.restricted_allow to list capture.", + ), + "base_blocks": _spec( + "list", + "ctx block ids (up to 16) whose content joins the group's prompt. Not set: no base blocks.", + ), + "base_max_chars": _spec( + "int", + "Most characters the base blocks add to the group's prompt (256 to 8000). Not set: 4000.", + ), + "base_rev": _spec( + "int", + "Raise it to reload the base blocks in every session of the group. Not set: 0.", + ), + "enabled": _spec( + "bool", + "false: this group gets no ctx (counts as set for the core's profile check). Not set: true.", + ), + } +) + + +@dataclass(frozen=True) +class AccessContext: + """The access group a session serves, in ctx_checkpoint's terms: from ``initialize``'s access + kwargs or from ``gateway.access_groups.current_access()``. ``restricted``: the group's (``None`` + = unknown, which counts as restricted). ``fields``: this plugin's namespace only.""" + + platform: str + scope_id: str + group: str + profile: str | None + restricted: bool | None + admin: bool = False + fields: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}), compare=False) + + +@dataclass(frozen=True) +class GroupFields: + """The group's fields, parsed and with their forms checked (``parse_fields``); defaults applied + for the group's strictness.""" + + key: str + base_url: str + tenant: str + read: tuple[str, ...] + write: str + store: str + recall: bool | None + capture: bool | None + base_blocks: tuple[str, ...] + base_max_chars: int + base_rev: int + enabled: bool + + +@dataclass(frozen=True) +class FieldError: + """Why the fields do not bind: the field and the rule it breaks, never its value.""" + + field: str + reason: str + + +@dataclass(frozen=True) +class Markers: + """The profile's monotone markers (``/ctx_state/access-mode.json``).""" + + restricted_seen: bool = False + governed_seen: bool = False + + +@dataclass(frozen=True) +class Decision: + """What ``initialize`` binds: ``off`` (no ctx at all), ``profile`` (the profile's own connection, + as 0.19.1) or ``group`` (a group binding from ``fields``). ``reason`` names the row of the + decision table and the cause; ``strict``: the group counts as restricted.""" + + kind: Literal["off", "profile", "group"] + reason: str + context: AccessContext | None = None + fields: GroupFields | None = None + strict: bool = False + + +def access_supported() -> bool: + """V8b: the host has the core's access-group fields and hook, read on the public class + ``hermes_cli.plugins.PluginContext`` (a memory provider's ``ctx`` answers every ``register_*``). + S1 stub: ``False``.""" + return False + + +def current_access() -> AccessContext | None: + """V8a/V6a: the access group serving the current turn, through the published + ``gateway.access_groups.current_access`` (imported at call time; ``None`` when the host lacks it, + outside a turn, or for a server that is not governed), with this plugin's namespace only. + S1 stub: ``None``.""" + return None + + +def session_parent_platform() -> str | None: + """The platform of the session a fork was built in: ``HERMES_SESSION_PLATFORM`` through the + published ``gateway.session_context.get_session_env``, and only when the name is not in + ``os.environ`` (else ``get_session_env`` answers with the process value, which says nothing about + the session); ``None`` when unknown. The ``parent_platform`` of ``decide``. S1 stub: ``None``.""" + return None + + +def context_from_init(init_kwargs: Mapping[str, Any]) -> AccessContext | None: + """The access group ``initialize`` was told about (``platform``, ``scope_id``, ``access_group``, + ``access_group_restricted``, ``access_fields``, ``agent_identity``); ``None`` without + ``access_group``. S1 stub: ``None``.""" + return None + + +def is_strict(context: AccessContext | None, *, restricted_profile: bool | None, markers: Markers) -> bool: + """The one definition of "restricted" (design 02 §3.3): the group's ``restricted``; unknown counts + as restricted when the profile is restricted or the marker ``restricted_seen`` is set; in the hook + (no profile knowledge) unknown counts as restricted. S1 stub: ``True``.""" + return True + + +def parse_fields(raw: Mapping[str, Any], *, scope_id: str, strict: bool) -> GroupFields | FieldError: + """The group's fields with their forms checked before any secret is read or request sent: ``key`` + and ``base_url`` name ctx variables (restricted: ``CTX_KEY__...``), scopes match the ctx + scope pattern, bounds hold; with ``strict`` the rules of E1. S1 stub: a ``FieldError``.""" + return FieldError(field="*", reason="access groups are not available") + + +def load_settings(hermes_home: str) -> Mapping[str, Any]: + """``memory.ctx_checkpoint.*`` of this axis from the home's config.yaml only (``ctx.json`` never + sets them), bounded, unknown values replaced by the defaults. S1 stub: the defaults.""" + return SETTINGS_DEFAULTS + + +def read_markers(hermes_home: str) -> Markers: + """The markers of ``/ctx_state/access-mode.json``; a missing file is no marker, an + unreadable one counts as both set. S1 stub: no marker.""" + return Markers() + + +def raise_markers(hermes_home: str, **flags: bool) -> None: + """Set the named markers (``restricted_seen=True``, ``governed_seen=True``), only from false to + true, atomically; ``False`` never lowers one (only ``access reset-marker`` does). S1 stub: no-op.""" + return None + + +def reset_markers(hermes_home: str, *, restricted: bool = False, governed: bool = False) -> None: + """Lower the named markers (``access reset-marker``, the only way down), atomically; the other + marker stays. File: ``MARKERS_FILE`` under the home, JSON ``{"restricted_seen": bool, + "governed_seen": bool, "since": ""}``. S1 stub: no-op.""" + return None + + +def e7_inputs(hermes_home: str, platform: str) -> tuple[tuple[str, ...], tuple[str, ...]] | None: + """What rule E7 judges, read without network from the profile at *hermes_home*: the variable + NAMES in its ``.env`` (never a value) and the toolset list ``platform_toolsets.`` of its + config.yaml, exactly as configured. ``None`` when either cannot be read, which fails E7 (the one + reader P-C, P-D and P-E share). S1 stub: ``None``.""" + return None + + +def decide( + init_kwargs: Mapping[str, Any], + current: AccessContext | None, + parent_platform: str | None, + settings: Mapping[str, Any], + markers: Markers, + v8: bool, +) -> Decision: + """The decision table of design 02 §4.2 (first matching row): pure, no network, no files. + ``current``: ``current_access()`` at the build; ``parent_platform``: the copied session variable + ``HERMES_SESSION_PLATFORM`` of a fork (only when it is not in ``os.environ``). S1 stub: the + profile's own connection, as 0.19.1.""" + return Decision(kind="profile", reason="access groups are not available") + + +__all__ = [ + "HOOK_NAME", + "LOCAL_PLATFORMS", + "MARKERS_FILE", + "NAMESPACE", + "SCHEMA", + "SETTINGS_DEFAULTS", + "AccessContext", + "Decision", + "FieldError", + "GroupFields", + "Markers", + "access_supported", + "context_from_init", + "current_access", + "decide", + "e7_inputs", + "is_strict", + "load_settings", + "parse_fields", + "raise_markers", + "read_markers", + "reset_markers", + "session_parent_platform", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py new file mode 100644 index 000000000..9455de6aa --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -0,0 +1,51 @@ +"""``hermes ctx_checkpoint access `` (contract, S1). + +Operator tools for access-group bindings (design 02 §4.7): ``status`` reads the per-binding status +files without network; ``check`` proves a group's fields (E1 to E7) and names every broken rule with +the expected value; ``provision`` computes scope names and the label, calls ctx's +``keyset-provision`` with ``replace_label`` and a tenant-admin key read from a named variable (never +stored), adds the new key to the target profile's ``.env`` and prints the ``/policy field`` lines +(``--emit-yaml``: the whole group entry); ``reset-marker`` lowers the profile's markers. + +Naming (design 02 §3.4): a ctx scope name is 1 to 24 characters of lowercase letters, digits and +inner hyphens (ctx ``scopeNamePattern``). Group names may hold ``_`` and 32 characters: ``_`` becomes +``-``, the edges are cleaned, the text is cut; when the name was changed or cut, its last four +characters are a hash of the original. Collisions are refused. One tenant per operator: +``d-k`` and ``d-``; one tenant +per community: ``k`` and ````. The key variable is ``CTX_KEY__`` (profile +upper-cased, ``-`` as ``_``), at most 64 characters (a hash suffix replaces the rest). + +S1 state: the forms are final, the functions are inert stubs, and ``memory/cli.py`` does not offer +``access`` yet. The tools cluster (P-E) fills them in and wires the subcommand. +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping, Sequence + +# ctx: go/internal/handler/tenant_manage.go scopeNamePattern (name part of :). +SCOPE_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,22}[a-z0-9])?$") +# Hermes: hermes_cli/access_fields.py ENV_NAME. +ENV_NAME = re.compile(r"^[A-Z][A-Z0-9_]{0,63}$") +KNOWLEDGE = "k" + + +def scope_layout(scope_id: str, groups: Sequence[str], *, per_community: bool = False) -> Mapping[str, str]: + """The ctx scope name (name part, no slug) for the server's knowledge scope (key ``"k"``) and for + each group in *groups*; ``ValueError`` when two map to the same name. S1 stub: ``{}``.""" + return {} + + +def key_env_name(scope_id: str, profile: str) -> str: + """The ``.env`` variable holding a restricted group's key on server *scope_id* served by + *profile*. S1 stub: ``""``.""" + return "" + + +def run_access(argv: Sequence[str], *, hermes_home: str) -> int: + """Run ``access `` for the home; the exit code. S1 stub: 2 (not available).""" + return 2 + + +__all__ = ["ENV_NAME", "KNOWLEDGE", "SCOPE_NAME", "key_env_name", "run_access", "scope_layout"] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py new file mode 100644 index 000000000..865d80d08 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -0,0 +1,82 @@ +"""Base blocks: ctx blocks whose content joins an access group's prompt (contract, S1). + +The core fires the hook ``access_group_fields`` before a governed server's turn, in the serving +profile (its secrets are readable), once per session, group and digest of the group's fields and +prompt; it keeps answers (``None`` too) and asks again after a callback that raised or timed out. +The callback is an ``async def`` (the core awaits it on the gateway loop under +``plugins.hook_callback_timeout``); the blocking work runs on this module's own thread pool, so a +slow ctx server holds neither the loop nor its default executor. Only whole answers: a transient +failure or the end of ``base_timeout_s`` raises ``BaseBlocksUnavailable``, never a partial text. +The callback takes every value from its arguments or ``current_access()``, never from a provider +instance (the active provider's hooks hang on an instance that is never initialized). + +S1 state: the forms are final, the functions are inert stubs, and nothing registers the hook yet. +The base-block cluster (P-D) fills them in. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +# The heading the rendered text starts with (part of the deterministic form). +HEADING = "## Knowledge for this conversation (ctx)" +TRUNCATED_MARK = "…[truncated]" + + +class BaseBlocksUnavailable(Exception): + """A base block could not be fetched now (network, time, 429) or the budget ran out: the hook + gives no partial text, the core keeps the group's prompt and asks again on a later turn.""" + + +@dataclass(frozen=True) +class BaseBlock: + """One fetched base block: its id, title, content and the ctx scope it lives in.""" + + id: str + title: str + content: str + scope: str + + +async def on_access_group_fields( + *, + platform: str, + scope_id: str, + group: str, + restricted: bool | None = None, + profile: str, + fields: Mapping[str, Mapping[str, Any]], + session_key: str, + user_id: str, + **kwargs: Any, +) -> dict | None: + """The hook callback: ``{"prompt": text}`` from the group's base blocks, or ``None``. + ``restricted``: the group's (``None`` = unknown = restricted); ``fields``: every valid namespace + of the group (this plugin reads ``fields["ctx_checkpoint"]``). S1 stub: ``None``.""" + return None + + +def render(blocks: Sequence[BaseBlock], max_chars: int, *, redact: Sequence[str] = ()) -> str: + """The deterministic text of *blocks* (heading, then ``### `` and content per block, in + list order), every value of *redact* removed, filled up to *max_chars*: the block that overflows + is cut with ``…[truncated]``, the rest dropped. S1 stub: ``""``.""" + return "" + + +def reset_state() -> None: + """Drop the render cache, the joined in-flight fetches and the thread pool (tests). S1 stub: + no-op.""" + return None + + +__all__ = [ + "HEADING", + "TRUNCATED_MARK", + "BaseBlock", + "BaseBlocksUnavailable", + "on_access_group_fields", + "render", + "reset_state", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py index 07c38b0fb..578378cdb 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py @@ -102,6 +102,17 @@ # would cut recall, the agent's ctx tools and other sessions' checkpoints of the profile off for a # minute. MAX_RATE_REFUSALS = 2 + + +def window_writes(max_parts: int, rate_limit_write: int | None = None) -> int: + """Writes one chain plans inside one rate window: ``max_parts`` parts (at most + ``MAX_PARTS_CEILING``) plus manifest and head. ``rate_limit_write``: the write limit per 60 s the + server reports for the key (``whoami``; ctx with per-request narrowing), which the chain is to + follow (contract, S1: the chain cluster P-G makes it count and wires ``ChainWriter`` to it; + until then the reported limit is ignored).""" + return max(1, min(int(max_parts), MAX_PARTS_CEILING)) + 2 + + # How long (real seconds) a call waits for the answer of another call of the same entry before it # looks at its deadline again (EntryState.admit: the answer in flight decides whether it may go). ENTRY_WAIT_POLL_S = 0.05 @@ -1619,6 +1630,9 @@ class ChainWriter: # The process-wide state of the server entry the client writes to (entry_state; the provider # binds it before each checkpoint). None: every chain keeps a state of its own (before 0.17.0). entry: EntryState | None = field(default=None, repr=False) + # The write limit per 60 s the server reports for the bound key (``whoami.rate_limit_write``; + # the binding sets it, ``window_writes`` follows it). S1 contract: kept, not yet read. + rate_limit_write: int | None = None _tool_evidence_warned: bool = field(default=False, init=False) def _notify(self, message: str) -> None: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py index 450ef0cdd..d1c08651d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py @@ -33,8 +33,11 @@ import urllib.error import urllib.parse import urllib.request +from collections.abc import Mapping, Sequence from typing import Any +from .narrowing import Narrowing + logger = logging.getLogger(__name__) @@ -378,6 +381,7 @@ def __init__( api_key: str, timeout: float = 10.0, synthesis_timeout: float = 90.0, + narrowing: Narrowing | None = None, ): parsed = urllib.parse.urlsplit(str(base_url or "").strip()) if parsed.scheme not in ("http", "https") or not parsed.netloc: @@ -393,6 +397,9 @@ def __init__( self._key = api_key self._timeout = timeout self._synthesis_timeout = synthesis_timeout + # Per-request scope narrowing (access groups): sent with every call and checked against the + # server's echo on every answer (CtxApiError code "narrowing_lost"). S1: kept, not yet sent. + self._narrowing = narrowing # The server registry's type names (``query_types``), read once per client. self._type_names: frozenset[str] | None = None @@ -632,3 +639,10 @@ def get_block(self, block_id: str, timeout: float | None = None) -> dict[str, An if left <= 0: raise CtxApiError("connection error: timed out") # what the bound ends a call with return self._request("POST", "/api/manage", {"action": "get", "data": {"id": block_id}}, timeout=left) + + def get_blocks(self, ids: Sequence[str], timeout: float | None = None) -> list[Mapping[str, Any]]: + """The blocks *ids* (1 to 16), in order, with one ``get`` carrying ``ids`` (ctx with the + multi-id get); against a server that answers that with 400, one ``get`` per id within the + same bound. A block that cannot be had is an entry with ``error`` (and ``code``), never an + exception for the whole call; a transient failure raises. S1 stub: no blocks.""" + return [] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py new file mode 100644 index 000000000..cb727351b --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py @@ -0,0 +1,130 @@ +"""Per-request scope narrowing on the client side and the proof of a group binding (contract, S1). + +A narrowed client sends ``X-Context-Read-Scopes`` (and ``X-Context-Write-Scope``) on every call and +expects the server's echo ``X-Context-Narrowed: <read,...>;<write>`` on every answer. A binding is +proven by ``whoami`` answers: one narrowed, and for restricted groups one unnarrowed of the same key. +Only the raw answers are remembered (per base URL, key digest and header set: 60 s after success, +15 s after failure); every binding evaluates the rules E2 to E5 and E7 itself, so a proof for one +group never satisfies another's stricter expectation. + +S1 state: the data forms are final, the functions are inert stubs (nothing calls them yet). The +client cluster (P-A) fills them in. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: # pragma: no cover - typing only + from .client import CtxClient + +HEADER_READ_SCOPES = "X-Context-Read-Scopes" +HEADER_WRITE_SCOPE = "X-Context-Write-Scope" +HEADER_NARROWED = "X-Context-Narrowed" + +# Raw whoami answers are kept this long (seconds) after a success and after a failure. +PROOF_TTL_OK_S = 60.0 +PROOF_TTL_FAILED_S = 15.0 +# The ctx label column is VARCHAR(100); a longer label hashes the profile part. +LABEL_MAX = 100 + + +@dataclass(frozen=True) +class Narrowing: + """The narrowing a client sends: ``read`` = the request's read set, in order (1 to 8 scopes); + ``write`` = its write scope (``None``: the client writes nothing).""" + + read: tuple[str, ...] + write: str | None = None + + def headers(self) -> dict[str, str]: + """The request headers of this narrowing.""" + out = {HEADER_READ_SCOPES: ",".join(self.read)} + if self.write: + out[HEADER_WRITE_SCOPE] = self.write + return out + + def echo(self) -> str: + """The ``X-Context-Narrowed`` value a server answers this narrowing with.""" + return f"{','.join(self.read)};{self.write or ''}" + + +@dataclass(frozen=True) +class Expect: + """What a binding expects of the key (design 02 §3.3). ``strict``: the group is restricted (E2 + to E4 apply in full); ``tenant``/``label``: expected values or ``None``; ``env_names``: the + variable names in the profile's ``.env`` and ``platform_toolsets``: the toolset list of the + platform in the profile (both for E7); ``scope_id``: the server the binding is for; ``write``: + the group's write scope (E3: the key's home scope, its write set exactly ``{write}``, its + unnarrowed read set exactly ``read ∪ {write}``) — the narrowing of a read client carries no write + scope, so it is named here (``None``: the key's home scope, unrestricted groups only).""" + + narrowing: Narrowing + strict: bool + tenant: str | None + label: str | None + env_names: tuple[str, ...] + platform_toolsets: tuple[str, ...] + scope_id: str + write: str | None = None + + +@dataclass(frozen=True) +class VerifyResult: + """The outcome of ``evaluate``: ``ok`` and, when not, the rules broken (``"E2"`` ...) with the + expected value per rule (no key value ever).""" + + ok: bool + failed: tuple[str, ...] = () + detail: Mapping[str, str] = field(default_factory=dict) + + +def key_digest(api_key: str) -> str: + """The first 16 hex characters of SHA-256 of a key: the only form of a key in caches, status + files and logs.""" + return hashlib.sha256(str(api_key or "").encode("utf-8")).hexdigest()[:16] + + +def expected_label(platform: str, scope_id: str, profile: str) -> str: + """The label a restricted group's key carries (E4): ``hermes:<platform>:<scope_id>:<profile>``; + past 100 characters ``#`` and 16 hex characters of SHA-256 of the profile name replace the + profile part. S1 stub: ``""``.""" + return "" + + +def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping[str, Any]: + """The raw ``whoami`` answer of *client* (narrowed: with its headers; else the same key without + them), from the proof store or the server within *budget_s*; a failure is remembered 15 s and + raised as ``CtxApiError``. S1 stub: an empty answer.""" + return {} + + +def evaluate(raw_narrowed: Mapping[str, Any], raw_unnarrowed: Mapping[str, Any] | None, expect: Expect) -> VerifyResult: + """E2 to E5 and E7 over raw answers, pure, without network. S1 stub: not proven.""" + return VerifyResult(ok=False, failed=("E5",), detail={"E5": "narrowing is not available"}) + + +def reset_proofs() -> None: + """Forget every remembered ``whoami`` answer (tests, ``access check``). S1 stub: no-op.""" + return None + + +__all__ = [ + "HEADER_NARROWED", + "HEADER_READ_SCOPES", + "HEADER_WRITE_SCOPE", + "LABEL_MAX", + "PROOF_TTL_FAILED_S", + "PROOF_TTL_OK_S", + "Expect", + "Narrowing", + "VerifyResult", + "evaluate", + "expected_label", + "key_digest", + "reset_proofs", + "whoami_raw", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py index 34a7dae22..72569d56b 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py @@ -17,7 +17,7 @@ import tempfile import threading import time -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator, Mapping from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timezone @@ -749,3 +749,22 @@ def mcp_report(hermes_home: str) -> dict[str, Any]: secrets=profile_ctx_keys(name), servers=servers if isinstance(servers, dict) else {}, ) + + +# -- access groups (contract, S1) --------------------------------------------------------------- +# One small file per binding under <home>/ctx_state/access/<platform>-<scope_id>-<profile>.json, +# written atomically and only when the state changes: ``bound`` or ``off: <reason>``, the rules +# checked (E1-E7), the key digest (16 hex), tenant slug, read, write, time, base blocks loaded and +# skipped with reason. Display only (``hermes memory status``, ``access status``): never read to +# bind, never a key value. The binding cluster (P-C) writes through ``record_access``; the tools +# cluster (P-E) owns the rest. + + +def record_access(hermes_home: str, platform: str, scope_id: str, profile: str, result: Mapping[str, Any]) -> None: + """Record the state of one binding (see above). S1 stub: no-op.""" + return None + + +def read_access(hermes_home: str) -> list[Mapping[str, Any]]: + """Every recorded binding of the home, sorted by platform, server and profile. S1 stub: none.""" + return [] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py b/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py index b1728fcd1..9c12acdec 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py @@ -7,9 +7,11 @@ from __future__ import annotations +import os import sys import pytest +from fakes.s1_pending import S1_PENDING @pytest.fixture(autouse=True) @@ -35,3 +37,48 @@ def reset() -> None: reset() yield reset() + + +# -- access groups (S1): cluster shield and shared fakes ----------------------------------------- +# Red S1 tests carry ``pytestmark = pytest.mark.access_cluster("<P-x>")``. While their cluster is +# listed in ``fakes/s1_pending.py`` each test gets a strict xfail that only an assertion about the +# missing behaviour satisfies (a TypeError or an import error stays an error); ``s1_green`` marks a +# guard that already holds on the stubs. ``CTX_S1_UNSHIELD=1`` lifts the shield (the red proof). + + +def pytest_configure(config): + config.addinivalue_line("markers", "access_cluster(name): red S1 test of an access-group plugin cluster") + config.addinivalue_line("markers", "s1_green: S1 guard that already holds on the stubs") + + +def pytest_collection_modifyitems(config, items): + if os.environ.get("CTX_S1_UNSHIELD") == "1": + return + for item in items: + marker = item.get_closest_marker("access_cluster") + if marker is None or item.get_closest_marker("s1_green") is not None: + continue + cluster = marker.args[0] if marker.args else "" + if cluster in S1_PENDING: + item.add_marker( + pytest.mark.xfail( + strict=True, + raises=(AssertionError, pytest.fail.Exception), + reason=f"S1 red: {cluster} not built yet", + ) + ) + + +@pytest.fixture +def fake_ctx(monkeypatch): + """A running fake ctx server (``fakes/ctx_server.py``); requests to it on 127.0.0.1 never go + through a proxy of the environment.""" + from fakes.ctx_server import FakeCtx + + monkeypatch.setenv("no_proxy", "127.0.0.1,localhost") + monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost") + server = FakeCtx().start() + try: + yield server + finally: + server.stop() diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py new file mode 100644 index 000000000..441862ecb --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/__init__.py @@ -0,0 +1,3 @@ +"""Test fakes of the access-group surfaces (S1): a local ctx server with per-request narrowing +(``ctx_server``) and the Hermes surface of the access-groups core PR over the pinned Hermes +(``access_host``). They belong to no cluster; every plugin cluster tests against them.""" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py new file mode 100644 index 000000000..2c0999f32 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/access_host.py @@ -0,0 +1,363 @@ +"""The Hermes surface of the access-groups core PR (NousResearch/hermes-agent#164604, head +``0b613f2fdf``) over the pinned Hermes the CI runs (``26cd2e6d83``, without the PR), through +``monkeypatch`` only. Forms as the PR's code has them: + +- V8b: ``register_access_fields`` on the class ``hermes_cli.plugins.PluginContext`` + (``hermes_cli/plugins_context.py:825``); a memory provider's ``ctx`` is the collector, which + answers ``register_access_fields`` itself (``plugins/memory/__init__.py:562-564``) and every other + ``register_*`` through ``__getattr__`` (``FakeCollector``). +- V8a/V6a: a module ``gateway.access_groups`` with ``AccessContext(platform, scope_id, group, + profile, restricted: bool, admin=False, fields)`` and ``fields_for`` (``gateway/access_groups.py:131-148``) + and ``current_access()`` read from a ContextVar, so copied contexts (threads, ``/background``) + see it and a cron run sees ``None`` (``:949-980``). +- V4: ``ainvoke_hook_callback`` (``hermes_cli/plugins_dispatch.py:684-729``): an ``async def`` + callback is awaited on the loop under ``asyncio.wait_for(timeout)`` and cancelled when it passes; + any other runs on a daemon thread of its own; a raise or a timeout is ``(False, None)``. The + kwargs of ``gateway/access_prompt.py:46-60`` (``hook_kwargs``), ``fields`` deep-copied per call. +- Secrets: ``agent.secret_scope.get_secret`` reads a ContextVar mapping and counts reads. +- V5: ``initialize`` always gets ``scope_id``, ``access_group``, ``access_group_restricted``, + ``access_fields`` and ``restricted_profile`` (``agent/agent_init_memory_provider.py:180-201``); + ``truth_filter=True`` simulates a host that passes only true values (VB-2). +""" + +from __future__ import annotations + +import asyncio +import contextvars +import copy +import importlib +import importlib.util +import inspect +import sys +import threading +import types +from collections import Counter +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass, field +from pathlib import Path +from types import MappingProxyType +from typing import Any + +PLUGIN_DIR = Path(__file__).resolve().parents[2] +_EMPTY: Mapping[str, Any] = MappingProxyType({}) +OBSERVER_SCHEMA_VERSION = 1 + + +def load_plugin(name: str) -> types.ModuleType: + """The plugin package under a name of its own (as ``tests/test_provider_contract.py`` does).""" + if name in sys.modules: + return sys.modules[name] + spec = importlib.util.spec_from_file_location( + name, PLUGIN_DIR / "__init__.py", submodule_search_locations=[str(PLUGIN_DIR)] + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def plugin_module(package: types.ModuleType, sub: str) -> types.ModuleType: + """A submodule of a loaded plugin copy (``memory.access`` ...).""" + return importlib.import_module(f"{package.__name__}.{sub}") + + +# -- V6a --------------------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class AccessContext: + """The core's form (``gateway/access_groups.py:131-148``).""" + + platform: str + scope_id: str + group: str + profile: str | None + restricted: bool + admin: bool = False + fields: Mapping[str, Mapping[str, Any]] = field(default=_EMPTY, compare=False) + + def fields_for(self, plugin_id: str) -> Mapping[str, Any]: + return self.fields.get(plugin_id) or _EMPTY + + +_CURRENT: contextvars.ContextVar[AccessContext | None] = contextvars.ContextVar("fake_current_access", default=None) + + +def make_access( + *, + platform: str = "discord", + scope_id: str = "111", + group: str = "members", + profile: str | None = "members", + restricted: bool = True, + admin: bool = False, + fields: Mapping[str, Any] | None = None, + namespace: str = "ctx_checkpoint", +) -> AccessContext: + spaces = {namespace: MappingProxyType(copy.deepcopy(dict(fields)))} if fields else {} + return AccessContext(platform, str(scope_id), group, profile, restricted, admin, MappingProxyType(spaces)) + + +@contextmanager +def turn(access: AccessContext | None) -> Iterator[None]: + """Run the block as a gateway turn whose ``current_access()`` is *access*.""" + token = _CURRENT.set(access) + try: + yield + finally: + _CURRENT.reset(token) + + +# -- secrets ----------------------------------------------------------------------------------- + + +class SecretScope: + """``agent.secret_scope.get_secret`` over a ContextVar mapping, with a read counter.""" + + def __init__(self, base: Mapping[str, str] | None = None) -> None: + self.var: contextvars.ContextVar[Mapping[str, str]] = contextvars.ContextVar( + "fake_secret_scope", default=MappingProxyType(dict(base or {})) + ) + self.reads: Counter[str] = Counter() + self._lock = threading.Lock() + + def get_secret(self, name: str, default: str | None = None) -> str | None: + with self._lock: + self.reads[name] += 1 + return self.var.get().get(name, default) + + def set_base(self, values: Mapping[str, str]) -> None: + self.var.set(MappingProxyType(dict(values))) + + @contextmanager + def scoped(self, values: Mapping[str, str]) -> Iterator[None]: + token = self.var.set(MappingProxyType(dict(values))) + try: + yield + finally: + self.var.reset(token) + + def total_reads(self) -> int: + return sum(self.reads.values()) + + +# -- the collector a memory provider's register(ctx) gets --------------------------------------- + + +class FakeCollector: + """What ``register(ctx)`` of a memory plugin is handed: records every ``register_*`` call. + ``register_access_fields`` exists on the instance only when the host has V8 (the real collector + answers it itself, and only forwards it while the provider is active).""" + + def __init__(self, *, v8: bool, active: bool = True) -> None: + self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] + self.hooks: dict[str, list[Callable[..., Any]]] = {} + self.providers: list[Any] = [] + self.access_fields: list[Mapping[str, Any]] = [] + self._v8 = v8 + self._active = active + + def register_memory_provider(self, provider: Any) -> None: + self.calls.append(("register_memory_provider", (provider,), {})) + self.providers.append(provider) + + def register_hook(self, name: str, callback: Callable[..., Any], **kwargs: Any) -> None: + self.calls.append(("register_hook", (name, callback), kwargs)) + self.hooks.setdefault(name, []).append(callback) + + def register_access_fields(self, schema: Mapping[str, Any]) -> Any: + self.calls.append(("register_access_fields", (schema,), {})) + if not self._v8: + raise AttributeError("register_access_fields") # a pre-PR host's collector forwards nothing + if self._active: + self.access_fields.append(schema) + return None + + def __getattr__(self, name: str) -> Any: + if name.startswith("register_"): + + def record(*args: Any, **kwargs: Any) -> None: + self.calls.append((name, args, kwargs)) + + return record + raise AttributeError(name) + + def called(self, name: str) -> int: + return sum(1 for call in self.calls if call[0] == name) + + +# -- V5 ---------------------------------------------------------------------------------------- + + +def v5_kwargs( + *, + scope_id: str | None = None, + group: str | None = None, + group_restricted: bool = False, + fields: Mapping[str, Any] | None = None, + restricted_profile: bool = False, + truth_filter: bool = False, +) -> dict[str, Any]: + """The five access kwargs of every ``initialize`` (all of them; ``truth_filter``: only true ones).""" + out: dict[str, Any] = { + "scope_id": scope_id, + "access_group": group, + "access_group_restricted": bool(group_restricted) if group else False, + "access_fields": copy.deepcopy(dict(fields or {})), + "restricted_profile": bool(restricted_profile), + } + if truth_filter: + out = {k: v for k, v in out.items() if v} + return out + + +# -- V4 ---------------------------------------------------------------------------------------- + + +def hook_kwargs( + *, + platform: str = "discord", + scope_id: str = "111", + group: str = "members", + restricted: bool = True, + profile: str = "members", + fields: Mapping[str, Mapping[str, Any]] | None = None, + session_key: str = "agent:main:discord:group:111:222", + user_id: str = "333", +) -> dict[str, Any]: + """The hook's kwargs as ``gateway/access_prompt.py:_payload`` builds them.""" + return { + "platform": platform, + "scope_id": str(scope_id), + "group": group, + "restricted": bool(restricted), + "profile": profile, + "fields": copy.deepcopy(dict(fields or {})), + "session_key": session_key, + "user_id": user_id, + "telemetry_schema_version": OBSERVER_SCHEMA_VERSION, + } + + +@dataclass +class HookOutcome: + answered: bool + result: Any + error: BaseException | None = None + + +async def ainvoke_hook_callback(callback: Callable[..., Any], *, timeout: float = 30.0, **kwargs: Any) -> HookOutcome: + """One callback the way the core's dispatcher runs it (see the module text).""" + kwargs = dict(kwargs, fields=copy.deepcopy(kwargs.get("fields") or {})) + kwargs.setdefault("telemetry_schema_version", OBSERVER_SCHEMA_VERSION) + try: + if inspect.iscoroutinefunction(callback): + try: + return HookOutcome(True, await asyncio.wait_for(callback(**kwargs), timeout)) + except TimeoutError as exc: + return HookOutcome(False, None, exc) + loop = asyncio.get_running_loop() + done: asyncio.Future[Any] = loop.create_future() + ctx = contextvars.copy_context() + + def run() -> None: + try: + value = ctx.run(callback, **kwargs) + except BaseException as exc: # reported as the callback's failure + loop.call_soon_threadsafe(_settle, done, None, exc) + else: + loop.call_soon_threadsafe(_settle, done, value, None) + + threading.Thread(target=run, name="hermes-hook-access_group_fields", daemon=True).start() + return HookOutcome(True, await done) + except asyncio.CancelledError as exc: + task = asyncio.current_task() + if task is not None and task.cancelling(): + raise + return HookOutcome(False, None, exc) + except BaseException as exc: + return HookOutcome(False, None, exc) + + +def _settle(future: asyncio.Future[Any], value: Any, exc: BaseException | None) -> None: + if future.done(): + return + if exc is not None: + future.set_exception(exc) + else: + future.set_result(value) + + +# -- installation ------------------------------------------------------------------------------ + + +@dataclass +class Host: + """The installed surface; ``v8`` says whether the class carries ``register_access_fields``.""" + + v8: bool + secrets: SecretScope + module: types.ModuleType + + def collector(self, *, active: bool = True) -> FakeCollector: + return FakeCollector(v8=self.v8, active=active) + + +def install(monkeypatch: Any, *, v8: bool = True, secrets: Mapping[str, str] | None = None) -> Host: + """Patch the pinned Hermes with the PR's surface (``v8=False``: the pinned Hermes as it is, but + with the fake secret scope).""" + import agent.secret_scope as secret_scope + import hermes_cli.plugins as plugins + + scope = SecretScope(secrets) + monkeypatch.setattr(secret_scope, "get_secret", scope.get_secret) + module = types.ModuleType("gateway.access_groups") + module.AccessContext = AccessContext # type: ignore[attr-defined] + module.current_access = _CURRENT.get # type: ignore[attr-defined] + if v8: + + def register_access_fields(self: Any, schema: Mapping[str, Any]) -> None: + return None + + monkeypatch.setattr(plugins.PluginContext, "register_access_fields", register_access_fields, raising=False) + monkeypatch.setitem(sys.modules, "gateway.access_groups", module) + import gateway + + monkeypatch.setattr(gateway, "access_groups", module, raising=False) + else: + monkeypatch.delattr(plugins.PluginContext, "register_access_fields", raising=False) + monkeypatch.delitem(sys.modules, "gateway.access_groups", raising=False) + return Host(v8=v8, secrets=scope, module=module) + + +# -- the core's field schema rules (hermes_cli/access_fields.py), for schema checks -------------- + +FIELD_TYPES = frozenset({"str", "int", "float", "bool", "list", "env_name"}) +SPEC_KEYS = frozenset({"type", "description", "default"}) +MAX_FIELDS = 16 +FIELD_NAME = r"^[a-z][a-z0-9_]{0,63}$" +ENV_NAME = r"^[A-Z][A-Z0-9_]{0,63}$" + + +__all__ = [ + "ENV_NAME", + "FIELD_NAME", + "FIELD_TYPES", + "MAX_FIELDS", + "SPEC_KEYS", + "AccessContext", + "FakeCollector", + "HookOutcome", + "Host", + "SecretScope", + "ainvoke_hook_callback", + "hook_kwargs", + "install", + "load_plugin", + "make_access", + "plugin_module", + "turn", + "v5_kwargs", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py new file mode 100644 index 000000000..b702a7cce --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -0,0 +1,474 @@ +"""A local ctx server with the target semantics of per-request narrowing (design 02 §3.5 C-1 to +C-4), stdlib only: one thread, ``127.0.0.1``, port 0. + +Keys carry tenant (slug), home, ``allowed_scopes``, tenant grants, ``write_scopes``, +``scope_narrowing``, label, role, admin and ``confirm_writes``. Narrowing headers follow C-1 +(subset rule, write scope rules, closed route list, ``get``/``type-list`` only on ``/api/manage``), +C-2 (``required`` keys refuse every unnarrowed request but ``whoami``), C-3 (``keyset-provision``) +and C-4 (``get`` with ``ids``). Every request is counted per route and header set. Faults are +switches on the server object: echo missing or wrong, latency per route, 429 per route, a server +without C-1 (headers ignored, ``whoami`` without the new fields) and without C-4 (``ids`` refused). + +Answer forms follow what ``memory/client.py`` and ``memory/provider.py`` read today: +``/api/query`` ``{"success", "answer", "sources"}``, ``/api/search`` ``{"success", "results"}``, +``/api/store`` ``{"block": {...}}``, ``/api/manage`` ``get`` as ctx answers it today +(``{"action": "get", "success": true, "block": {...}}``; a miss is 200 with ``{"success": false, +"error": "Block not found"}``). The multi-id form (C-4) is the S1 contract, the same the Go test of +C-4 pins: ``{"success": true, "blocks": [block | {"id", "error", "code": "not_found"}]}``. +""" + +from __future__ import annotations + +import hashlib +import json +import threading +import time +import uuid +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any + +HEADER_READ = "X-Context-Read-Scopes" +HEADER_WRITE = "X-Context-Write-Scope" +HEADER_NARROWED = "X-Context-Narrowed" +# C-1: the closed list of routes a narrowed request may take. +NARROWED_ROUTES = frozenset( + { + ("POST", "/api/query"), + ("POST", "/api/search"), + ("POST", "/api/store"), + ("GET", "/api/whoami"), + ("POST", "/api/manage"), + } +) +NARROWED_ACTIONS = frozenset({"get", "type-list"}) +MAX_READ_SCOPES = 8 +MAX_IDS = 16 +TYPE_NAMES = ("knowledge", "checkpoint", "session-digest", "fact") + + +@dataclass +class FakeKey: + """One API key of the fake (the secret is what ``X-Context-Key`` carries).""" + + secret: str + tenant: str + home: str + allowed: tuple[str, ...] = () + grants: tuple[str, ...] = () # tenant grants: readable, never writable + write_scopes: tuple[str, ...] = () + scope_narrowing: str = "optional" + label: str = "" + role: str = "member" + admin: bool = False + confirm_writes: bool = False + active: bool = True + + @property + def read_scopes(self) -> list[str]: + out: list[str] = [] + for scope in (self.home, *self.allowed, *self.grants): + if scope not in out: + out.append(scope) + return out + + @property + def writable(self) -> list[str]: + return [self.home, *[s for s in self.write_scopes if s != self.home]] + + +@dataclass +class Seen: + """One request as the fake saw it.""" + + method: str + path: str + action: str + key_digest: str + read_header: str | None + write_header: str | None + status: int + body: Mapping[str, Any] = field(default_factory=dict) + + +def digest(secret: str) -> str: + return hashlib.sha256(secret.encode("utf-8")).hexdigest()[:16] + + +class FakeCtx: + """The fake server: keys, blocks per scope, counters and fault switches.""" + + def __init__(self) -> None: + self.keys: dict[str, FakeKey] = {} + self.blocks: dict[str, dict[str, Any]] = {} + self.scopes: set[str] = set() # scopes keyset-provision created or found (C-3) + self.seen: list[Seen] = [] + self.lock = threading.Lock() + # Fault switches. + self.echo_missing = False + self.echo_wrong = False + self.without_c1 = False + self.without_c4 = False + self.leak_on_get = False # get answers blocks outside the request's read set (E6 is the client's too) + self.latency: dict[str, float] = {} # route key ("/api/whoami", "manage:get", ...) -> seconds + self.throttle: dict[str, int] = {} # route key -> number of 429 answers still to give + self.rate_limit_write = 97 + self.max_keys = 50 + self._server: ThreadingHTTPServer | None = None + self._thread: threading.Thread | None = None + + # -- set-up ------------------------------------------------------------------------------ + + def add_key(self, **kwargs: Any) -> FakeKey: + key = FakeKey(**kwargs) + self.keys[key.secret] = key + return key + + def add_block(self, scope: str, title: str, content: str, *, block_id: str = "", **extra: Any) -> str: + block_id = block_id or str(uuid.uuid4()) + self.blocks[block_id] = { + "id": block_id, + "title": title, + "content": content, + "category": extra.pop("category", "reference"), + "type": extra.pop("type", "knowledge"), + "scope": scope, + "tags": list(extra.pop("tags", [])), + "metadata": dict(extra.pop("metadata", {})), + "archived": bool(extra.pop("archived", False)), + } + return block_id + + # -- counters ---------------------------------------------------------------------------- + + def count(self, path: str | None = None, action: str | None = None, *, narrowed: bool | None = None) -> int: + with self.lock: + rows = list(self.seen) + return sum( + 1 + for row in rows + if (path is None or row.path == path) + and (action is None or row.action == action) + and (narrowed is None or (row.read_header is not None) == narrowed) + ) + + def requests(self, path: str | None = None) -> list[Seen]: + with self.lock: + return [row for row in self.seen if path is None or row.path == path] + + def reset_counters(self) -> None: + with self.lock: + self.seen.clear() + + # -- life cycle -------------------------------------------------------------------------- + + @property + def url(self) -> str: + assert self._server is not None + return f"http://127.0.0.1:{self._server.server_port}" + + def start(self) -> FakeCtx: + fake = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args: Any) -> None: + return None + + def do_GET(self) -> None: + fake._handle(self, "GET") + + def do_POST(self) -> None: + fake._handle(self, "POST") + + self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self._server.daemon_threads = True + self._thread = threading.Thread(target=self._server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True) + self._thread.start() + return self + + def stop(self) -> None: + if self._server is not None: + self._server.shutdown() + self._server.server_close() + self._server = None + + # -- request handling -------------------------------------------------------------------- + + def _handle(self, h: BaseHTTPRequestHandler, method: str) -> None: + path = h.path.split("?", 1)[0] + length = int(h.headers.get("Content-Length") or 0) + raw = h.rfile.read(length) if length else b"" + try: + body = json.loads(raw.decode("utf-8")) if raw else {} + except ValueError: + body = {} + if not isinstance(body, dict): + body = {} + action = str(body.get("action") or "") if path == "/api/manage" else "" + secret = h.headers.get("X-Context-Key") or "" + read_values = h.headers.get_all(HEADER_READ) or [] + write_values = h.headers.get_all(HEADER_WRITE) or [] + route = f"manage:{action}" if action else path + status, payload, echo = self._answer(method, path, action, body, secret, read_values, write_values) + with self.lock: + self.seen.append( + Seen( + method=method, + path=path, + action=action, + key_digest=digest(secret), + read_header=",".join(read_values) if read_values else None, + write_header=",".join(write_values) if write_values else None, + status=status, + body=body, + ) + ) + delay = self.latency.get(route, self.latency.get(path, 0.0)) + if delay: + time.sleep(delay) + data = json.dumps(payload).encode("utf-8") + try: + h.send_response(status) + h.send_header("Content-Type", "application/json") + h.send_header("Content-Length", str(len(data))) + if echo is not None and not self.echo_missing: + h.send_header(HEADER_NARROWED, "x;y" if self.echo_wrong else echo) + h.end_headers() + h.wfile.write(data) + except OSError: + pass # the client gave up (its deadline); nothing to answer + + def _answer( + self, + method: str, + path: str, + action: str, + body: Mapping[str, Any], + secret: str, + read_values: list[str], + write_values: list[str], + ) -> tuple[int, dict[str, Any], str | None]: + key = self.keys.get(secret) + if key is None or not key.active: + return 401, {"success": False, "error": "unauthorized", "code": "unauthorized"}, None + route = f"manage:{action}" if action else path + with self.lock: + left = self.throttle.get(route, self.throttle.get(path, 0)) + if left > 0: + self.throttle[route if route in self.throttle else path] = left - 1 + return 429, {"success": False, "error": "rate limited", "code": "rate_limit"}, None + narrowed: tuple[list[str], str] | None = None + if not self.without_c1 and (read_values or write_values): + if not read_values: + return 400, _err("write scope without read scopes", "scope_narrowing_invalid"), None + if len(read_values) > 1 or len(write_values) > 1: + return 400, _err("narrowing header repeated", "scope_narrowing_invalid"), None + read = [s.strip() for s in read_values[0].split(",")] + if not read_values[0].strip() or any(not s for s in read) or len(read) != len(set(read)): + return 400, _err("empty or doubled narrowing", "scope_narrowing_invalid"), None + if len(read) > MAX_READ_SCOPES: + return 400, _err("too many read scopes", "scope_narrowing_invalid"), None + write = write_values[0].strip() if write_values else "" + if write_values and not write: + return 400, _err("empty write scope", "scope_narrowing_invalid"), None + if any(s not in key.read_scopes for s in read): + return 403, _err("scope outside the key", "scope_denied"), None + if write and (write not in key.writable or write not in read): + return 403, _err("write scope outside the key", "scope_denied"), None + if (method, path) not in NARROWED_ROUTES: + return 403, _err("route not open to narrowing", "scope_narrowing_route"), None + narrowed = (read, write) + elif not self.without_c1 and key.scope_narrowing == "required" and (method, path) != ("GET", "/api/whoami"): + return 403, _err("this key requires narrowing", "scope_narrowing_required"), None + echo = f"{','.join(narrowed[0])};{narrowed[1]}" if narrowed else None + read_set = narrowed[0] if narrowed else key.read_scopes + if (method, path) == ("GET", "/api/whoami"): + return 200, self._whoami(key, narrowed), echo + if (method, path) == ("POST", "/api/query"): + hits = self._visible(read_set, body.get("types_exclude")) + return 200, {"success": True, "answer": "", "sources": hits}, echo + if (method, path) == ("POST", "/api/search"): + hits = self._visible(read_set, body.get("types_exclude")) + return 200, {"success": True, "results": hits}, echo + if (method, path) == ("POST", "/api/store"): + if narrowed is not None: + if not narrowed[1]: + return 403, _err("no write scope on a narrowed request", "scope_denied"), echo + scope = narrowed[1] + else: + scope = key.home + block_id = self.add_block( + scope, + str(body.get("title") or ""), + str(body.get("content") or ""), + category=str(body.get("category") or "reference"), + type=str(body.get("type") or "knowledge"), + tags=list(body.get("tags") or []), + metadata=dict(body.get("metadata") or {}), + ) + now = "2026-12-06T00:00:00Z" + block = dict(self.blocks[block_id], created_at=now, updated_at=now) + return 200, {"block": block}, echo + if (method, path) == ("POST", "/api/manage"): + if narrowed is not None and (action not in NARROWED_ACTIONS or _shadowed_action(body)): + return 403, _err("action not open to narrowing", "scope_narrowing_route"), echo + return self._manage(key, action, body, read_set, echo) + if narrowed is not None: # unreachable: other routes were refused above + return 403, _err("route not open to narrowing", "scope_narrowing_route"), echo + return 200, {"success": True}, echo + + def whoami_answer(self, secret: str, read: Iterable[str] | None = None, write: str = "") -> dict[str, Any]: + """The ``whoami`` body this server gives *secret* (narrowed to *read*/*write* when given), + without a request: raw answers for the pure rule checks.""" + return self._whoami(self.keys[secret], (list(read), write) if read is not None else None) + + def _whoami(self, key: FakeKey, narrowed: tuple[list[str], str] | None) -> dict[str, Any]: + out: dict[str, Any] = { + "success": True, + "home_scope": key.home, + "read_scopes": list(key.read_scopes), + "tenant_slug": key.tenant, + "label": key.label, + "role": key.role, + "admin": key.admin, + } + if self.without_c1: + return out + out.update( + { + "write_scopes": [narrowed[1]] if narrowed and narrowed[1] else ([] if narrowed else key.writable), + "confirm_writes": key.confirm_writes, + "narrowed": {"read": list(narrowed[0]), "write": narrowed[1]} if narrowed else None, + "scope_narrowing": key.scope_narrowing, + "rate_limit_write": self.rate_limit_write, + } + ) + if narrowed: + out["read_scopes"] = list(narrowed[0]) + out["admin"] = False + out["role"] = "member" + return out + + def _visible(self, read_set: Iterable[str], types_exclude: Any) -> list[dict[str, Any]]: + excluded = {str(t) for t in types_exclude} if isinstance(types_exclude, list) else set() + scopes = set(read_set) + return [ + {k: v for k, v in block.items() if k != "archived"} + for block in self.blocks.values() + if block["scope"] in scopes and not block["archived"] and block["type"] not in excluded + ] + + def _manage( + self, key: FakeKey, action: str, body: Mapping[str, Any], read_set: list[str], echo: str | None + ) -> tuple[int, dict[str, Any], str | None]: + if action == "type-list": + return 200, {"success": True, "types": [{"name": name} for name in TYPE_NAMES]}, echo + if action == "get": + if "ids" in body: + ids = body.get("ids") + if self.without_c4: + return 400, _err("Missing required field: id", "missing_fields"), echo + if not isinstance(ids, list) or not 1 <= len(ids) <= MAX_IDS: + return 400, _err("ids: 1 to 16", "invalid_body"), echo + return 200, {"success": True, "blocks": [self._get_one(str(i), read_set) for i in ids]}, echo + block_id = str(body.get("id") or "") + if not block_id: + return 400, _err("Missing required field: id", "missing_fields"), echo + # The single get answers as ctx does today (go/internal/handler/context_manage.go handleGet): + # 200 with {"action": "get", "success": true, "block": ...}; a miss is 200 with + # {"success": false, "error": "Block not found"}. + one = self._get_one(block_id, read_set) + if "error" in one: + return 200, {"success": False, "error": "Block not found"}, echo + return 200, {"action": "get", "success": True, "block": one}, echo + if action == "keyset-provision": + return self._keyset_provision(key, body, echo) + return 200, {"success": True}, echo + + def _get_one(self, block_id: str, read_set: list[str]) -> dict[str, Any]: + block = self.blocks.get(block_id) + if block is None or block["archived"] or (block["scope"] not in read_set and not self.leak_on_get): + return {"id": block_id, "error": "block not found", "code": "not_found"} + return {k: v for k, v in block.items() if k != "archived"} + + def _keyset_provision( + self, admin: FakeKey, body: Mapping[str, Any], echo: str | None + ) -> tuple[int, dict[str, Any], str | None]: + # Wire form of the S1 contract, the same the Go test of C-3 pins + # (go/cmd/ctxd/keyset_provision_c3_integration_test.go): tenant owner or admin (or a ctx server + # admin); data.scopes = bare scope names, created when missing; the answer lists the scopes as + # {"scope", "created"} and the keys as {"id", "label", "home_scope", "allowed_scopes", + # "write_scopes", "scope_narrowing", "api_key"}, both in request order. + if admin.role not in ("owner", "admin") and not admin.admin: + return 403, _err("tenant admin required", "scope_denied"), echo + data = body.get("data") if isinstance(body.get("data"), dict) else {} + keys = data.get("keys") if isinstance(data.get("keys"), list) else [] + names = data.get("scopes") if isinstance(data.get("scopes"), list) else [] + if len(names) > 64: + return 400, _err("at most 64 scopes", "invalid_body"), echo + if len(keys) > 64: + return 400, _err("at most 64 keys", "invalid_body"), echo + active = [k for k in self.keys.values() if k.tenant == admin.tenant and k.active] + replaced = {str(spec.get("label")) for spec in keys if isinstance(spec, dict) and spec.get("replace_label")} + after = len([k for k in active if k.label not in replaced]) + len(keys) + if after > self.max_keys: + return ( + 429, + { + "success": False, + "error": "max_keys", + "code": "rate_limit", + "limit": self.max_keys, + "count": len(active), + }, + echo, + ) + scopes_out = [] + for name in names: + full = f"{admin.tenant}:{name}" + created = full not in self.scopes + self.scopes.add(full) + scopes_out.append({"scope": full, "created": created}) + out = [] + for spec in keys: + label = str(spec.get("label") or "") + if spec.get("replace_label"): + for other in active: + if other.label == label: + other.active = False + secret = "ctx_" + uuid.uuid4().hex + scope = lambda name: name if ":" in name else f"{admin.tenant}:{name}" # noqa: E731 + made = self.add_key( + secret=secret, + tenant=admin.tenant, + home=scope(str(spec.get("home_scope") or "")), + allowed=tuple(scope(str(s)) for s in spec.get("allowed_scopes") or ()), + write_scopes=tuple(scope(str(s)) for s in spec.get("write_scopes") or ()), + scope_narrowing=str(spec.get("scope_narrowing") or "optional"), + label=label, + ) + out.append( + { + "id": str(uuid.uuid4()), + "label": label, + "home_scope": made.home, + "allowed_scopes": list(made.allowed), + "write_scopes": list(made.write_scopes), + "scope_narrowing": made.scope_narrowing, + "api_key": secret, + } + ) + return 200, {"success": True, "scopes": scopes_out, "keys": out}, echo + + +def _shadowed_action(body: Mapping[str, Any]) -> bool: + """A second spelling of ``action`` (``{"action":"get","ACTION":"purge"}``) counts as another action.""" + return any(k.lower() == "action" and k != "action" for k in body) + + +def _err(text: str, code: str) -> dict[str, Any]: + return {"success": False, "error": text, "code": code} + + +__all__ = ["HEADER_NARROWED", "HEADER_READ", "HEADER_WRITE", "FakeCtx", "FakeKey", "Seen", "digest"] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py new file mode 100644 index 000000000..fc032c8d1 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -0,0 +1,15 @@ +"""Clusters whose red S1 tests are still shielded (``tests/conftest.py`` gives each test marked +``access_cluster(<c>)`` with ``c`` listed here a strict xfail). Switching a cluster on = deleting +its line. ``CTX_S1_UNSHIELD=1`` lifts the shield for every cluster (the red proof).""" + +S1_PENDING = frozenset( + { + "P-A", + "P-B", + "P-C", + "P-D", + "P-E", + "P-F", + "P-G", + } +) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py new file mode 100644 index 000000000..3f7d2a70f --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py @@ -0,0 +1,256 @@ +"""P-A (design 02 §4.5, §7.3): the client narrows every call, checks the server's echo, proves a +binding by raw ``whoami`` answers and fetches base blocks with one multi-id ``get``. Red on S1: +``CtxClient`` keeps the narrowing but sends nothing, ``whoami_raw``/``evaluate``/``get_blocks`` are +stubs. Real ``CtxClient`` against the fake ctx server (``fakes/ctx_server.py``).""" + +from __future__ import annotations + +import time + +import pytest +from fakes.access_host import load_plugin, plugin_module + +pytestmark = pytest.mark.access_cluster("P-A") + +_PKG = load_plugin("ctx_checkpoint_access_pa") +_client = plugin_module(_PKG, "memory.client") +_nar = plugin_module(_PKG, "memory.narrowing") +CtxClient, CtxApiError = _client.CtxClient, _client.CtxApiError +Narrowing, Expect = _nar.Narrowing, _nar.Expect + +K, M, B = "t:d111-k", "t:d111-members", "t:d222-k" +LABEL = "hermes:discord:111:members" +MEMBER_KEY = "ctx_member_111" +OPS_KEY = "ctx_ops" + + +@pytest.fixture(autouse=True) +def _fresh_proofs(): + _nar.reset_proofs() + yield + _nar.reset_proofs() + + +def _keys(fake, *, narrowing="optional"): + fake.add_key( + secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing=narrowing, label=LABEL, role="member" + ) + fake.add_key(secret=OPS_KEY, tenant="t", home="t:d111-ops", allowed=(K, M, B), write_scopes=(K,), role="admin") + + +def _expect(**overrides): + values = { + "narrowing": Narrowing(read=(K,)), + "strict": True, + "tenant": "t", + "label": LABEL, + "env_names": ("CTX_KEY_111_MEMBERS",), + "platform_toolsets": ("web",), + "scope_id": "111", + "write": M, + } + values.update(overrides) + return Expect(**values) + + +def _raws(fake, secret=MEMBER_KEY, read=(K,), write=""): + return fake.whoami_answer(secret, read, write), fake.whoami_answer(secret) + + +def _baseline_ok(fake): + narrowed, unnarrowed = _raws(fake) + result = _nar.evaluate(narrowed, unnarrowed, _expect()) + assert result.ok, f"a key that fits the restricted layout proves the binding: {result}" + return narrowed, unnarrowed + + +# -- headers and echo --------------------------------------------------------------------------- + + +def test_narrowed_client_sends_read_scopes_on_search_store_get_and_type_list(fake_ctx): + _keys(fake_ctx) + block = fake_ctx.add_block(K, "rules", "be kind") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K, M), write=M)) + client.search("rules") + client.store("reference", "note", "text") + client.get_block(block) + client.query_types("rules", ["knowledge"], limit=3) + seen = fake_ctx.requests() + assert {(r.path, r.action) for r in seen} >= { + ("/api/search", ""), + ("/api/store", ""), + ("/api/manage", "get"), + ("/api/manage", "type-list"), + } + assert all(r.read_header == f"{K},{M}" for r in seen), [(r.path, r.read_header) for r in seen] + assert all(r.write_header == M for r in seen), [(r.path, r.write_header) for r in seen] + + +@pytest.mark.parametrize("fault", ["echo_missing", "echo_wrong"]) +def test_answer_without_the_right_echo_is_narrowing_lost(fake_ctx, fault): + _keys(fake_ctx) + setattr(fake_ctx, fault, True) + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError) as caught: + client.search("rules") + assert caught.value.code == "narrowing_lost" + + +@pytest.mark.s1_green +def test_client_without_narrowing_sends_no_narrowing_header(fake_ctx): + """Guard: a client built without ``narrowing`` stays as 0.19.1 (no header, no echo check).""" + _keys(fake_ctx) + fake_ctx.echo_missing = True + CtxClient(fake_ctx.url, OPS_KEY, timeout=5).search("rules") + assert [r.read_header for r in fake_ctx.requests()] == [None] + + +# -- proof: raw whoami answers, rules evaluated per binding -------------------------------------- + + +def test_whoami_raw_returns_the_narrowed_and_the_unnarrowed_answer(fake_ctx): + _keys(fake_ctx, narrowing="required") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + narrowed = _nar.whoami_raw(client, narrowed=True, budget_s=3) + unnarrowed = _nar.whoami_raw(client, narrowed=False, budget_s=3) + assert narrowed.get("narrowed") == {"read": [K], "write": ""} + assert unnarrowed.get("narrowed") is None + assert unnarrowed.get("home_scope") == M + assert fake_ctx.count("/api/whoami", narrowed=True) == 1 + assert fake_ctx.count("/api/whoami", narrowed=False) == 1 + + +def test_server_without_narrowed_in_whoami_fails_e5(fake_ctx): + _keys(fake_ctx, narrowing="required") + _baseline_ok(fake_ctx) + fake_ctx.without_c1 = True + narrowed, unnarrowed = _raws(fake_ctx) + result = _nar.evaluate(narrowed, unnarrowed, _expect()) + assert not result.ok and "E5" in result.failed + + +def test_other_narrowed_list_fails_e5(fake_ctx): + _keys(fake_ctx, narrowing="required") + _baseline_ok(fake_ctx) + narrowed, unnarrowed = _raws(fake_ctx, read=(K, M)) + result = _nar.evaluate(narrowed, unnarrowed, _expect()) + assert not result.ok and "E5" in result.failed + + +@pytest.mark.parametrize( + ("change", "rule"), + [ + ("grant", "E3"), + ("write_not_home", "E3"), + ("admin", "E2"), + ("role", "E2"), + ("optional", "E2"), + ("tenant", "E2"), + ("label", "E4"), + ("toolset", "E7"), + ], +) +def test_strict_expectation_names_the_broken_rule(fake_ctx, change, rule): + _keys(fake_ctx, narrowing="required") + narrowed, unnarrowed = _baseline_ok(fake_ctx) + unnarrowed = dict(unnarrowed) + expect = _expect() + if change == "grant": + unnarrowed["read_scopes"] = [*unnarrowed["read_scopes"], "u:shared"] + elif change == "write_not_home": + expect = _expect(write="t:d111-mods") + elif change == "admin": + unnarrowed["admin"] = True + elif change == "role": + unnarrowed["role"] = "admin" + elif change == "optional": + unnarrowed["scope_narrowing"] = "optional" + elif change == "tenant": + expect = _expect(tenant="other") + elif change == "label": + expect = _expect(label="hermes:discord:111:mods") + elif change == "toolset": + expect = _expect(env_names=("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS"), platform_toolsets=("web", "file")) + result = _nar.evaluate(narrowed, unnarrowed, expect) + assert not result.ok + assert rule in result.failed, result + assert rule in result.detail and MEMBER_KEY not in str(result.detail) + + +def test_other_label_within_the_proof_ttl_is_off(fake_ctx): + """BP-21: the remembered answers are raw; a second binding with the same key and scopes but + another label is evaluated anew and fails E4.""" + _keys(fake_ctx, narrowing="required") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + first = _nar.evaluate( + _nar.whoami_raw(client, narrowed=True, budget_s=3), + _nar.whoami_raw(client, narrowed=False, budget_s=3), + _expect(), + ) + assert first.ok, first + second = _nar.evaluate( + _nar.whoami_raw(client, narrowed=True, budget_s=3), + _nar.whoami_raw(client, narrowed=False, budget_s=3), + _expect(label="hermes:discord:111:other-profile"), + ) + assert fake_ctx.count("/api/whoami") == 2, "the second binding reads the remembered answers" + assert not second.ok and "E4" in second.failed + + +def test_failed_proof_is_remembered_15_s_then_asked_again(fake_ctx, monkeypatch): + _keys(fake_ctx, narrowing="required") + fake_ctx.throttle["/api/whoami"] = 2 # the first answer and its one retry are 429 + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + clock = [time.monotonic()] + monkeypatch.setattr(time, "monotonic", lambda: clock[0]) + with pytest.raises(CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=3) + asked = fake_ctx.count("/api/whoami") + with pytest.raises(CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=3) + assert fake_ctx.count("/api/whoami") == asked, "a failure is remembered" + clock[0] += _nar.PROOF_TTL_FAILED_S + 1 + assert _nar.whoami_raw(client, narrowed=True, budget_s=3).get("narrowed") == {"read": [K], "write": ""} + assert fake_ctx.count("/api/whoami") == asked + 1 + + +def test_proof_holds_its_budget(fake_ctx): + _keys(fake_ctx, narrowing="required") + fake_ctx.latency["/api/whoami"] = 4.0 + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=10, narrowing=Narrowing(read=(K,))) + started = time.monotonic() + with pytest.raises(CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=1.0) + assert time.monotonic() - started < 2.0 + + +def test_expected_label_and_its_hash_past_100_characters(): + assert _nar.expected_label("discord", "111", "members") == LABEL + long_profile = "p" * 120 + label = _nar.expected_label("discord", "111", long_profile) + assert len(label) <= _nar.LABEL_MAX + assert label.startswith("hermes:discord:111:#") and len(label.rsplit("#", 1)[1]) == 16 + + +# -- multi-id get (C-4) and its fallback --------------------------------------------------------- + + +def test_get_blocks_is_one_request_with_ids(fake_ctx): + _keys(fake_ctx) + first = fake_ctx.add_block(K, "one", "1") + second = fake_ctx.add_block(K, "two", "2") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + blocks = client.get_blocks([second, "missing-id", first]) + assert [b.get("id") for b in blocks] == [second, "missing-id", first] + assert blocks[1].get("code") == "not_found" and "error" in blocks[1] + assert fake_ctx.count("/api/manage", "get") == 1 + + +def test_get_blocks_falls_back_to_one_get_per_id_on_400(fake_ctx): + _keys(fake_ctx) + fake_ctx.without_c4 = True + ids = [fake_ctx.add_block(K, f"b{i}", str(i)) for i in range(3)] + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + blocks = client.get_blocks(ids) + assert [b.get("title") for b in blocks] == ["b0", "b1", "b2"] + assert fake_ctx.count("/api/manage", "get") == 1 + len(ids) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py new file mode 100644 index 000000000..0336898b8 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_decide.py @@ -0,0 +1,291 @@ +"""P-B (design 02 §3.1, §3.2, §3.6, §4.1 steps 1-2, §4.2 table): detection, the field schema, the +decision table and the markers. Red on S1: ``access_supported``/``decide``/``parse_fields``/markers +are stubs and ``register`` registers no fields. Aligned to the core PR's code: ``initialize`` always +gets the five access kwargs, ``access_group_restricted`` is the group's (the draft had no +restriction in V5, VB-11).""" + +from __future__ import annotations + +import json +import logging +import re + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-B") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pb") +acc = ah.plugin_module(_PKG, "memory.access") + +K, M = "t:d111-k", "t:d111-members" +RESTRICTED_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M, "base_blocks": ["b1"]} +OPS_FIELDS = {"key": "CTX_KEY_OPS", "read": [K], "write": "t:d111-ops"} + + +def _settings(**overrides): + return {**dict(acc.SETTINGS_DEFAULTS), **overrides} + + +def _init(platform="discord", agent_context="primary", **v5): + return {"platform": platform, "agent_context": agent_context, "hermes_home": "/h/profiles/members", **v5} + + +def _decide(init, *, current=None, parent=None, markers=None, v8=True, **settings): + return acc.decide(init, current, parent, _settings(**settings), markers or acc.Markers(), v8) + + +def _group_init(fields, *, restricted=True, truth_filter=False): + return _init( + **ah.v5_kwargs( + scope_id="111", group="members", group_restricted=restricted, fields=fields, truth_filter=truth_filter + ) + ) + + +# -- register(ctx): detection (V8b), fields (V3) ------------------------------------------------- + + +def test_register_on_a_host_with_v8_registers_the_schema(monkeypatch): + host = ah.install(monkeypatch, v8=True) + collector = host.collector() + _PKG.register(collector) + assert collector.access_fields == [acc.SCHEMA] + assert collector.called("register_memory_provider") == 1 + + +@pytest.mark.s1_green +def test_register_on_a_host_without_v8_calls_nothing_new_and_warns_nothing(monkeypatch, caplog): + """Guard: the collector answers every ``register_*``; detection reads the class, so a pre-PR + host sees no call and no WARNING.""" + host = ah.install(monkeypatch, v8=False) + collector = host.collector() + with caplog.at_level(logging.WARNING): + _PKG.register(collector) + assert collector.called("register_access_fields") == 0 + assert collector.called("register_hook") == 0 + assert collector.called("register_memory_provider") == 1 + assert not [r for r in caplog.records if r.levelno >= logging.WARNING] + + +def test_access_supported_reads_the_public_class(monkeypatch): + ah.install(monkeypatch, v8=True) + assert acc.access_supported() is True + ah.install(monkeypatch, v8=False) + assert acc.access_supported() is False + + +@pytest.mark.s1_green +def test_schema_fits_the_core_rules(): + assert 0 < len(acc.SCHEMA) <= ah.MAX_FIELDS + for name, spec in acc.SCHEMA.items(): + assert re.match(ah.FIELD_NAME, name), name + assert set(spec) <= ah.SPEC_KEYS - {"default"}, (name, spec) + assert spec["type"] in ah.FIELD_TYPES, (name, spec) + assert "Not set" in spec.get("description", ""), name + + +# -- current_access (V6a) and the init kwargs (V5) ----------------------------------------------- + + +def test_current_access_gives_this_plugins_namespace(monkeypatch): + ah.install(monkeypatch, v8=True) + access = ah.make_access(fields=RESTRICTED_FIELDS) + with ah.turn(access): + got = acc.current_access() + assert got is not None + assert (got.platform, got.scope_id, got.group, got.profile, got.restricted) == ( + "discord", + "111", + "members", + "members", + True, + ) + assert dict(got.fields) == RESTRICTED_FIELDS + + +@pytest.mark.s1_green +def test_current_access_is_none_outside_a_turn_and_without_the_core(monkeypatch): + ah.install(monkeypatch, v8=True) + assert acc.current_access() is None + ah.install(monkeypatch, v8=False) + assert acc.current_access() is None + + +def test_context_from_init_takes_the_groups_restriction(): + ctx = acc.context_from_init(_group_init(RESTRICTED_FIELDS, restricted=False)) + assert ctx is not None + assert (ctx.scope_id, ctx.group, ctx.restricted) == ("111", "members", False) + assert dict(ctx.fields) == RESTRICTED_FIELDS + assert acc.context_from_init(_init(**ah.v5_kwargs())) is None + + +def test_is_strict_follows_the_group_then_profile_then_marker(): + open_group = acc.AccessContext("discord", "111", "ops", "ops", False) + unknown = acc.AccessContext("discord", "111", "ops", "ops", None) + assert acc.is_strict(open_group, restricted_profile=False, markers=acc.Markers()) is False + assert acc.is_strict(unknown, restricted_profile=True, markers=acc.Markers()) is True + assert acc.is_strict(unknown, restricted_profile=False, markers=acc.Markers(restricted_seen=True)) is True + + +# -- the decision table (§4.2), one case per row -------------------------------------------------- + + +def test_row1_v8_false_with_restricted_seen_is_off(): + decision = _decide(_init(platform="cli"), v8=False, markers=acc.Markers(restricted_seen=True)) + assert decision.kind == "off" + + +@pytest.mark.s1_green +def test_row1_v8_false_without_marker_is_the_profile_connection(): + assert _decide(_init(platform="cli"), v8=False).kind == "profile" + + +def test_row2_group_with_fields_binds_the_group(): + decision = _decide(_group_init(RESTRICTED_FIELDS)) + assert decision.kind == "group" + assert decision.strict is True + assert decision.fields is not None + assert (decision.fields.read, decision.fields.write, decision.fields.tenant) == ((K,), M, "t") + + +def test_row2_enabled_false_is_off(): + assert _decide(_group_init({**RESTRICTED_FIELDS, "enabled": False})).kind == "off" + + +def test_row2_without_key_restricted_off_unrestricted_governed_unbound(): + no_key = {k: v for k, v in OPS_FIELDS.items() if k != "key"} + restricted_no_key = {k: v for k, v in RESTRICTED_FIELDS.items() if k != "key"} + assert _decide(_group_init(restricted_no_key, restricted=True)).kind == "off" + assert _decide(_group_init(no_key, restricted=False)).kind == "off" + assert _decide(_group_init(no_key, restricted=False), governed_unbound="profile").kind == "profile" + + +def test_row3_group_without_fields_restricted_off_unrestricted_governed_unbound(): + assert _decide(_group_init({}, restricted=True)).kind == "off" + assert _decide(_group_init({}, restricted=False)).kind == "off" + assert _decide(_group_init({}, restricted=False), governed_unbound="profile").kind == "profile" + + +@pytest.mark.parametrize("profile", ["members", None]) +def test_row4_background_with_a_turn_context_binds_its_group(profile): + current = acc.AccessContext("discord", "111", "members", profile, True, fields=RESTRICTED_FIELDS) + decision = _decide(_init(platform="discord", agent_context="primary", **ah.v5_kwargs()), current=current) + assert decision.kind == "group" and decision.strict is True + + +def test_row5_restricted_profile_is_off(): + assert _decide(_init(platform="cli", **ah.v5_kwargs(restricted_profile=True))).kind == "off" + + +def test_row6_restricted_seen_is_off_even_when_the_host_drops_false_values(): + init = _init(platform="cli", **ah.v5_kwargs(restricted_profile=False, truth_filter=True)) + assert "restricted_profile" not in init + assert _decide(init, markers=acc.Markers(restricted_seen=True)).kind == "off" + + +def test_row7_messaging_session_without_context_after_governed_seen_is_off(): + init = _init(platform="discord", **ah.v5_kwargs()) + assert _decide(init, markers=acc.Markers(governed_seen=True), ungoverned="profile").kind == "off" + + +def test_parent_platform_comes_from_the_session_never_from_the_process_env(monkeypatch): + """Row 7 and ``ungoverned: local`` for forks read the copied ``HERMES_SESSION_PLATFORM`` only + through ``get_session_env`` and only while the name is not in ``os.environ`` (where + ``get_session_env`` would answer with the process value).""" + import gateway.session_context as session_context + + def session_env(name, default=""): + return "discord" if name == "HERMES_SESSION_PLATFORM" else default + + monkeypatch.setattr(session_context, "get_session_env", session_env) + monkeypatch.delenv("HERMES_SESSION_PLATFORM", raising=False) + assert acc.session_parent_platform() == "discord" + monkeypatch.setenv("HERMES_SESSION_PLATFORM", "discord") + assert acc.session_parent_platform() is None + + +def test_row8_auto_is_profile_before_and_local_after_governed_seen(): + discord = _init(platform="discord", **ah.v5_kwargs()) + cli = _init(platform="cli", **ah.v5_kwargs()) + assert _decide(discord).kind == "profile" + assert _decide(discord, markers=acc.Markers(governed_seen=True)).kind == "off" + assert _decide(cli, markers=acc.Markers(governed_seen=True)).kind == "profile" + + +@pytest.mark.parametrize( + ("platform", "agent_context", "parent", "kind"), + [ + ("cli", "primary", None, "profile"), + ("tui", "primary", None, "profile"), + ("cron", "cron", None, "off"), + ("api_server", "primary", None, "off"), + ("discord", "primary", None, "off"), + ("cli", "subagent", "cli", "profile"), + ("discord", "subagent", "discord", "off"), + ], +) +def test_ungoverned_local_admits_local_sessions_only(platform, agent_context, parent, kind): + init = _init(platform=platform, agent_context=agent_context, **ah.v5_kwargs()) + assert _decide(init, parent=parent, ungoverned="local").kind == kind + assert _decide(init, parent=parent, ungoverned="off").kind == "off" + + +# -- fields: forms before any secret -------------------------------------------------------------- + + +def test_parse_fields_accepts_the_restricted_layout(): + parsed = acc.parse_fields(RESTRICTED_FIELDS, scope_id="111", strict=True) + assert isinstance(parsed, acc.GroupFields), parsed + assert parsed.recall is None or parsed.recall is False + assert parsed.base_blocks == ("b1",) and parsed.base_max_chars == 4000 and parsed.enabled is True + + +@pytest.mark.parametrize( + ("change", "field", "strict"), + [ + ({"key": "OPENAI_API_KEY"}, "key", False), + ({"key": "CTX_KEY_222_MEMBERS"}, "key", True), + ({"base_url": "HOME_URL"}, "base_url", False), + ({"read": ["no scope"]}, "read", False), + ({"read": [f"t:s{i}" for i in range(9)]}, "read", False), + ({"write": "t:d111-k"}, "write", True), + ({"tenant": "Bad_Slug"}, "tenant", False), + ({"base_blocks": [f"b{i}" for i in range(17)]}, "base_blocks", False), + ({"base_max_chars": 100}, "base_max_chars", False), + ], +) +def test_parse_fields_names_the_broken_field(change, field, strict): + assert isinstance(acc.parse_fields(RESTRICTED_FIELDS, scope_id="111", strict=True), acc.GroupFields) + parsed = acc.parse_fields({**RESTRICTED_FIELDS, **change}, scope_id="111", strict=strict) + assert isinstance(parsed, acc.FieldError) and parsed.field == field, parsed + assert str(change[field]) not in parsed.reason + + +# -- settings and markers (§3.2, §3.6) ------------------------------------------------------------ + + +def test_settings_come_from_config_yaml_never_from_ctx_json(tmp_path): + (tmp_path / "config.yaml").write_text( + "memory:\n ctx_checkpoint:\n governed_unbound: profile\n base_timeout_s: 99\n", encoding="utf-8" + ) + (tmp_path / "ctx.json").write_text(json.dumps({"ungoverned": "off"}), encoding="utf-8") + settings = acc.load_settings(str(tmp_path)) + assert settings["governed_unbound"] == "profile" + assert settings["ungoverned"] == "auto" + assert settings["base_timeout_s"] == 10 + + +def test_markers_only_rise(tmp_path): + home = str(tmp_path) + acc.raise_markers(home, restricted_seen=True) + assert acc.read_markers(home).restricted_seen is True + acc.raise_markers(home, restricted_seen=False, governed_seen=True) + assert acc.read_markers(home) == acc.Markers(restricted_seen=True, governed_seen=True) + + +def test_unreadable_marker_file_counts_as_both_set(tmp_path): + state = tmp_path / "ctx_state" + state.mkdir() + (state / "access-mode.json").write_text("{not json", encoding="utf-8") + assert acc.read_markers(str(tmp_path)) == acc.Markers(restricted_seen=True, governed_seen=True) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py new file mode 100644 index 000000000..05fc79e9d --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py @@ -0,0 +1,176 @@ +"""P-C (design 02 §4.2 steps 0, 3-9, §4.6): the provider binds a group, or nothing, from the access +kwargs every ``initialize`` gets (V5) and drops a binding whose group changed under it (V6a). Red on +S1: the provider ignores the access kwargs and connects as 0.19.1 with the profile's key. Real +``CtxCheckpointMemoryProvider`` over REST against the fake ctx server, secrets from the fake +secret scope.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah +from fakes.ctx_server import digest + +pytestmark = pytest.mark.access_cluster("P-C") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pc") +_cfg = ah.plugin_module(_PKG, "memory.config") +Provider = _PKG.CtxCheckpointMemoryProvider + +A_K, A_OPS, B_K = "t:d111-k", "t:d111-ops", "t:d222-k" +A_MEMBERS = "t:d111-members" +PROFILE_KEY = "ctx_profile_operator" +OPS_A_KEY = "ctx_ops_a" +MEMBER_KEY = "ctx_member_111" +MEMBER_LABEL = "hermes:discord:111:members" +OPS_FIELDS = {"key": "CTX_KEY_111_OPS", "read": [A_K], "write": A_OPS} +MEMBER_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [A_K], "write": A_MEMBERS} + + +@pytest.fixture +def world(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:main", allowed=(A_K, B_K, A_OPS, A_MEMBERS)) + fake_ctx.add_key(secret=OPS_A_KEY, tenant="t", home=A_OPS, allowed=(A_K,), write_scopes=(A_K,)) + fake_ctx.add_key( + secret=MEMBER_KEY, tenant="t", home=A_MEMBERS, allowed=(A_K,), scope_narrowing="required", label=MEMBER_LABEL + ) + fake_ctx.add_block(A_K, "Server A rules", "alpha knowledge") + fake_ctx.add_block(B_K, "Server B secret plans", "bravo knowledge") + fake_ctx.add_block(A_MEMBERS, "member transcript", "what another member said") + host = ah.install( + monkeypatch, + v8=True, + secrets={ + "CTX_KEY": PROFILE_KEY, + "CTX_BASE_URL": fake_ctx.url, + "CTX_KEY_111_OPS": OPS_A_KEY, + "CTX_KEY_111_MEMBERS": MEMBER_KEY, + }, + ) + home = tmp_path / "profiles" / "members" + home.mkdir(parents=True) + return fake_ctx, host, home + + +def _write_settings(home, text): + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n" + text, encoding="utf-8") + + +def _provider(home, *, platform="discord", **v5): + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize("s-1", hermes_home=str(home), platform=platform, agent_context="primary", **v5) + return provider + + +def test_restricted_profile_group_without_fields_sends_nothing(world): + fake, _host, home = world + provider = _provider( + home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, restricted_profile=True) + ) + text = provider.prefetch("what are the plans?") + assert fake.count() == 0, [(r.path, r.action) for r in fake.requests()] + assert text == "" and provider.get_tool_schemas() == [] and provider.system_prompt_block() == "" + + +def test_session_in_server_a_never_reads_server_b(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + text = provider.prefetch("what are the plans?") + assert "bravo knowledge" not in text + assert "alpha knowledge" in text + assert all(r.read_header == A_K for r in fake.requests() if r.path != "/api/whoami") + assert {r.key_digest for r in fake.requests()} == {digest(OPS_A_KEY)} + + +def test_changed_fields_under_a_cached_agent_turn_the_binding_off(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + changed = ah.make_access(group="ops", profile="members", restricted=False, fields={**OPS_FIELDS, "read": [B_K]}) + fake.reset_counters() + with ah.turn(changed): + text = provider.prefetch("what are the plans?") + assert text == "" and fake.count() == 0 + with ah.turn(None): + assert provider.prefetch("what are the plans?") == "", "the trip wire turns the instance off for good" + + +def test_member_layout_binds_and_recall_never_reads_the_write_scope(world): + _fake, _host, home = world + _write_settings(home, " restricted_allow: [recall]\n") + fields = {**MEMBER_FIELDS, "recall": True} + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) + text = provider.prefetch("rules?") + assert "alpha knowledge" in text + assert "what another member said" not in text + names = [s.get("name") for s in provider.get_tool_schemas()] + assert "ctx_store" not in names and "ctx_query" in names + + +def test_swapped_fields_are_off_e3(world): + fake, _host, home = world + swapped = {**MEMBER_FIELDS, "read": [A_MEMBERS], "write": A_K, "recall": True} + _write_settings(home, " restricted_allow: [recall]\n") + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=swapped)) + assert fake.count("/api/whoami") >= 1, "the proof asked the server" + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_restricted_recall_without_restricted_allow_stays_off(world): + fake, _host, home = world + fields = {**MEMBER_FIELDS, "recall": True} + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) + assert fake.count("/api/whoami", narrowed=True) == 1, "the group is proven" + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_foreign_key_in_env_with_file_toolset_is_off_e7(world): + fake, _host, home = world + _write_settings(home, " restricted_allow: [recall]\n") + (home / ".env").write_text("CTX_KEY_111_MEMBERS=x\nCTX_KEY_222_MEMBERS=y\n", encoding="utf-8") + (home / "config.yaml").write_text( + "platform_toolsets:\n discord: [web, file]\nmemory:\n ctx_checkpoint:\n restricted_allow: [recall]\n", + encoding="utf-8", + ) + fields = {**MEMBER_FIELDS, "recall": True} + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) + assert fake.count("/api/whoami") >= 1, "E7 is evaluated with the proof" + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_invalid_key_name_reads_no_secret_and_sends_nothing(world): + fake, host, home = world + bad = {**OPS_FIELDS, "key": "OPENAI_API_KEY"} + host.secrets.reads.clear() + _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=bad)) + assert host.secrets.reads["OPENAI_API_KEY"] == 0 + assert fake.count() == 0 + + +def test_reinit_that_fails_validation_reads_nothing_after(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + assert "alpha knowledge" in provider.prefetch("plans?") + provider.initialize( + "s-2", + hermes_home=str(home), + platform="discord", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields={**OPS_FIELDS, "read": ["bad"]}), + ) + fake.reset_counters() + assert provider.prefetch("plans?") == "" and fake.count() == 0 + + +def test_profile_without_default_key_is_available_with_ungoverned_local(world, monkeypatch): + fake, host, home = world + host.secrets.set_base({"CTX_BASE_URL": fake.url}) + _write_settings(home, " ungoverned: local\n") + monkeypatch.setenv("HERMES_HOME", str(home)) + assert Provider(config={"transport": "rest"}).is_available() is True + + +def test_group_and_server_tags_are_reserved_for_the_plugin(): + tags = _cfg.merge_tags(["server:discord:999", "group:admins", "topic"], "members", "tool") + assert "topic" in tags + assert not [t for t in tags if t.startswith(("server:", "group:"))] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py new file mode 100644 index 000000000..6c66188bc --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py @@ -0,0 +1,235 @@ +"""P-D (design 02 §4.1 step 3, §4.4): the hook ``access_group_fields`` puts the group's base blocks +into its prompt, whole or not at all, without holding the gateway loop. Red on S1: ``register`` +registers no hook and the callback returns ``None``. Driven through the core's dispatcher form +(``fakes.access_host.ainvoke_hook_callback``) against the fake ctx server. + +Aligned to the core PR's code, not the draft: the core passes ``restricted`` (the group's) to the +hook, so "unknown" is only the absence of that kwarg (an older core); a plain callback would run on a +daemon thread of its own, not inline on the loop (the draft's reason for ``async def`` is now the +bounded ``wait_for`` and the cancellation, not a blocked loop).""" + +from __future__ import annotations + +import asyncio +import inspect +import time + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-D") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pd") +bb = ah.plugin_module(_PKG, "memory.base_blocks") +_nar = ah.plugin_module(_PKG, "memory.narrowing") + +K, M, B = "t:d111-k", "t:d111-members", "t:d222-k" +MEMBER_KEY = "ctx_member_111_secret_value" +LABEL = "hermes:discord:111:members" + + +@pytest.fixture +def world(fake_ctx, monkeypatch, _isolated_hermes_home): + bb.reset_state() + _nar.reset_proofs() + fake_ctx.add_key( + secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL, role="member" + ) + ids = { + "one": fake_ctx.add_block(K, "House rules", "Be kind to each other."), + "two": fake_ctx.add_block(K, "FAQ", "Ask in #help."), + "other_server": fake_ctx.add_block(B, "Server B notes", "bravo"), + "own_write": fake_ctx.add_block(M, "Member chatter", "said by a member"), + } + host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + yield fake_ctx, host, ids, _isolated_hermes_home + bb.reset_state() + _nar.reset_proofs() + + +def _fields(ids, *names, **extra): + own = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M} + own["base_blocks"] = [ids.get(n, n) for n in names] + own.update(extra) + return {"ctx_checkpoint": own} + + +def _call(fields, **overrides): + kwargs = ah.hook_kwargs(fields=fields, **overrides) + return asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) + + +def _prompt(outcome): + assert outcome.answered, f"the hook failed: {outcome.error!r}" + assert isinstance(outcome.result, dict) and isinstance(outcome.result.get("prompt"), str), outcome.result + return outcome.result["prompt"] + + +def test_hook_gives_the_prompt_of_two_base_blocks(world): + _fake, _host, ids, _home = world + text = _prompt(_call(_fields(ids, "one", "two"))) + assert text.startswith(bb.HEADING) + assert text.index("### House rules") < text.index("### FAQ") + assert "Be kind to each other." in text and "Ask in #help." in text + + +def test_register_on_v8_registers_the_async_hook(monkeypatch): + host = ah.install(monkeypatch, v8=True) + collector = host.collector() + _PKG.register(collector) + callbacks = collector.hooks.get("access_group_fields") or [] + assert len(callbacks) == 1 and inspect.iscoroutinefunction(callbacks[0]) + + +@pytest.mark.s1_green +def test_restricted_group_without_fields_is_none_with_no_request_and_no_secret(world): + fake, host, _ids, _home = world + host.secrets.reads.clear() + outcome = _call({}) + assert outcome.answered and outcome.result is None + assert fake.count() == 0 and host.secrets.total_reads() == 0 + + +@pytest.mark.s1_green +def test_enabled_false_is_none_with_no_request_and_no_secret(world): + fake, host, ids, _home = world + host.secrets.reads.clear() + outcome = _call(_fields(ids, "one", enabled=False)) + assert outcome.answered and outcome.result is None + assert fake.count() == 0 and host.secrets.total_reads() == 0 + + +def test_unknown_strictness_counts_as_restricted(world): + fake, _host, ids, _home = world + no_tenant = _fields(ids, "one") + del no_tenant["ctx_checkpoint"]["tenant"] + kwargs = ah.hook_kwargs(fields=no_tenant) + del kwargs["restricted"] # an older core: the group's restriction is not told + outcome = asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) + assert outcome.answered and outcome.result is None and fake.count() == 0 + assert "House rules" in _prompt(_call(no_tenant, restricted=False)) + + +def test_swapped_fields_are_none_without_get(world): + fake, _host, ids, _home = world + assert "House rules" in _prompt(_call(_fields(ids, "one"))) + bb.reset_state() + fake.reset_counters() + swapped = _fields(ids, "one", read=[M], write=K) + outcome = _call(swapped) + assert outcome.answered and outcome.result is None + assert fake.count("/api/manage", "get") == 0 + + +def test_block_outside_read_is_skipped(world): + _fake, _host, ids, _home = world + text = _prompt(_call(_fields(ids, "one", "other_server"))) + assert "House rules" in text and "bravo" not in text + + +def test_block_of_the_write_scope_is_refused_e6(world): + fake, _host, ids, _home = world + fake.leak_on_get = True # a server that answers outside the narrowing: E6 holds on the client too + text = _prompt(_call(_fields(ids, "one", "own_write"))) + assert "House rules" in text and "said by a member" not in text + + +def test_render_is_deterministic_and_cut_with_a_marker(): + blocks = [bb.BaseBlock("1", "First", "a" * 300, K), bb.BaseBlock("2", "Second", "b" * 300, K)] + once, twice = bb.render(blocks, 4000), bb.render(blocks, 4000) + assert once == twice and once.startswith(bb.HEADING) and "### First" in once and "### Second" in once + short = bb.render(blocks, 200) + assert len(short) <= 200 and short.endswith(bb.TRUNCATED_MARK) and "### Second" not in short + + +def test_key_value_in_a_block_is_redacted(world): + fake, _host, ids, _home = world + leaked = fake.add_block(K, "Leaky", f"the key is {MEMBER_KEY} here") + text = _prompt(_call(_fields(ids, leaked))) + assert "Leaky" in text and MEMBER_KEY not in text + + +def test_base_rev_changes_the_cache_key(world): + fake, _host, ids, _home = world + _prompt(_call(_fields(ids, "one"))) + _prompt(_call(_fields(ids, "one"))) + assert fake.count("/api/manage", "get") == 1, "the second call is a cache hit" + _prompt(_call(_fields(ids, "one", base_rev=1))) + assert fake.count("/api/manage", "get") == 2 + + +def test_loop_stays_free_while_a_fetch_hangs(world): + fake, _host, ids, _home = world + fake.latency["manage:get"] = 3.0 + kwargs = ah.hook_kwargs(fields=_fields(ids, "one")) + ticks = [] + + async def ticker(stop): + while not stop.is_set(): + ticks.append(time.monotonic()) + await asyncio.sleep(0.1) + + async def main(): + stop = asyncio.Event() + tick = asyncio.create_task(ticker(stop)) + outcome = await ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs) + stop.set() + await tick + return outcome + + text = _prompt(asyncio.run(main())) + assert "House rules" in text + assert len(ticks) >= 15, f"the loop ran only {len(ticks)} ticks during a 3 s fetch" + + +def test_budget_ends_in_unavailable_never_a_partial_text(world): + fake, _host, ids, home = world + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n base_timeout_s: 1\n", encoding="utf-8") + fake.latency["manage:get"] = 5.0 + started = time.monotonic() + outcome = _call(_fields(ids, "one", "two")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert time.monotonic() - started < 1.5 + + +def test_transient_failure_of_one_block_is_unavailable(world): + fake, _host, ids, _home = world + fake.without_c4 = True + fake.throttle["manage:get"] = 4 # the multi-id get is refused (400 without C-4); per-id gets meet 429s + outcome = _call(_fields(ids, "one", "two")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + + +def test_one_request_with_c4_one_per_id_without(world): + fake, _host, ids, _home = world + _prompt(_call(_fields(ids, "one", "two"))) + assert fake.count("/api/manage", "get") == 1 + bb.reset_state() + fake.reset_counters() + fake.without_c4 = True + _prompt(_call(_fields(ids, "one", "two"))) + assert fake.count("/api/manage", "get") == 3 + + +def test_concurrent_calls_with_the_same_key_fetch_once(world): + fake, _host, ids, _home = world + fake.latency["manage:get"] = 0.5 + kwargs = ah.hook_kwargs(fields=_fields(ids, "one")) + + async def main(): + return await asyncio.gather( + ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs), + ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs), + ) + + first, second = asyncio.run(main()) + assert _prompt(first) == _prompt(second) + assert fake.count("/api/manage", "get") == 1 + + +def test_secret_of_the_turn_scope_is_read_in_the_hook(world): + fake, host, ids, _home = world + host.secrets.set_base({"CTX_BASE_URL": fake.url}) + with host.secrets.scoped({"CTX_BASE_URL": fake.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}): + text = _prompt(_call(_fields(ids, "one"))) + assert "House rules" in text and host.secrets.reads["CTX_KEY_111_MEMBERS"] >= 1 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py new file mode 100644 index 000000000..f374805d6 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py @@ -0,0 +1,111 @@ +"""P-E (design 02 §3.6, §4.7): per-binding status files and ``hermes ctx_checkpoint access ...``. +Red on S1: ``record_access``/``read_access`` and ``access_cli`` are stubs. ``provision`` runs against +the fake ctx server's ``keyset-provision`` (C-3).""" + +from __future__ import annotations + +import re + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-E") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pe") +st = ah.plugin_module(_PKG, "memory.status") +cli = ah.plugin_module(_PKG, "memory.access_cli") +acc = ah.plugin_module(_PKG, "memory.access") + +ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_do_not_store" +OFF_RESULT = { + "state": "off: E4", + "rules": {"E4": "label hermes:discord:111:members"}, + "key_digest": "0123456789abcdef", + "tenant_slug": "t", + "read": ["t:d111-k"], + "write": "t:d111-members", +} + + +def _files_text(root): + return "\n".join(p.read_text(encoding="utf-8", errors="replace") for p in root.rglob("*") if p.is_file()) + + +def test_record_access_is_read_back_without_a_key_value(tmp_path): + st.record_access(str(tmp_path), "discord", "111", "members", {**OFF_RESULT, "key": "ctx_secret_value"}) + rows = st.read_access(str(tmp_path)) + assert len(rows) == 1 and rows[0].get("state") == "off: E4" + assert (tmp_path / "ctx_state" / "access" / "discord-111-members.json").is_file() + assert "ctx_secret_value" not in _files_text(tmp_path) + + +def test_access_status_names_an_off_binding(tmp_path, capsys): + st.record_access(str(tmp_path), "discord", "111", "members", OFF_RESULT) + assert cli.run_access(["status"], hermes_home=str(tmp_path)) == 0 + out = capsys.readouterr().out + assert "111" in out and "off: E4" in out and "api-key-update" in out + + +def test_reset_marker_lowers_the_markers(tmp_path): + home = str(tmp_path) + acc.raise_markers(home, restricted_seen=True, governed_seen=True) + assert acc.read_markers(home) == acc.Markers(True, True) + assert cli.run_access(["reset-marker", "--profile", "members", "--restricted"], hermes_home=home) == 0 + assert acc.read_markers(home) == acc.Markers(False, True) + + +def test_scope_names_fit_the_ctx_pattern_and_refuse_collisions(): + layout = cli.scope_layout("1234567890123456789", ["members", "Mod_Team_With_A_Long_Name"]) + assert layout.get(cli.KNOWLEDGE, "").endswith("-k") + assert set(layout) == {cli.KNOWLEDGE, "members", "Mod_Team_With_A_Long_Name"} + for name in layout.values(): + assert cli.SCOPE_NAME.match(name) and "_" not in name, name + assert layout["members"].startswith("d") and len(layout["members"]) <= 24 + with pytest.raises(ValueError): + cli.scope_layout("111", ["a_b", "a-b"]) + + +def test_key_variable_name_is_bounded(): + name = cli.key_env_name("1234567890123456789", "members-eu") + assert name == "CTX_KEY_1234567890123456789_MEMBERS_EU" + long_name = cli.key_env_name("1234567890123456789", "p" * 80) + assert ( + len(long_name) <= 64 and cli.ENV_NAME.match(long_name) and long_name.startswith("CTX_KEY_1234567890123456789_") + ) + + +def _provision_world(fake_ctx, monkeypatch, home): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) + monkeypatch.setenv("CTX_BASE_URL", fake_ctx.url) + return host + + +def _provision(home, *extra): + argv = ["provision", "--server", "discord:111", "--profile", "members", "--group", "members"] + return cli.run_access([*argv, "--admin-key-env", "CTX_ADMIN", *extra], hermes_home=str(home)) + + +def test_provision_at_the_key_limit_writes_no_env_line(fake_ctx, monkeypatch, tmp_path, caplog, capsys): + _provision_world(fake_ctx, monkeypatch, tmp_path) + fake_ctx.max_keys = 1 + assert _provision(tmp_path) != 0 + assert fake_ctx.count("/api/manage", "keyset-provision") == 1 + env = tmp_path / ".env" + assert not env.exists() or "CTX_KEY_111" not in env.read_text(encoding="utf-8") + assert ADMIN_KEY not in caplog.text + capsys.readouterr().out + _files_text(tmp_path) + + +def test_provision_twice_leaves_one_active_key_per_label(fake_ctx, monkeypatch, tmp_path, capsys): + _provision_world(fake_ctx, monkeypatch, tmp_path) + assert _provision(tmp_path, "--emit-yaml") == 0 + assert _provision(tmp_path) == 0 + calls = [r.body for r in fake_ctx.requests("/api/manage") if r.action == "keyset-provision"] + assert len(calls) == 2 and all(k.get("replace_label") for c in calls for k in c["data"]["keys"]) + labels = [k.label for k in fake_ctx.keys.values() if k.active and k.label.startswith("hermes:")] + assert labels == ["hermes:discord:111:members"] + out = capsys.readouterr().out + assert "members" in out and "ctx_checkpoint" in out + assert ADMIN_KEY not in out + _files_text(tmp_path) + assert re.search(r"^CTX_KEY_111_MEMBERS=", (tmp_path / ".env").read_text(encoding="utf-8"), re.M) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py new file mode 100644 index 000000000..efb6f86cc --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pf_docs.py @@ -0,0 +1,30 @@ +"""P-F (design 02 §7.3): the README names every access-group field and every setting of this axis. +Red on S1: the README predates both.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-F") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pf") +acc = ah.plugin_module(_PKG, "memory.access") +README = (ah.PLUGIN_DIR / "README.md").read_text(encoding="utf-8") + + +@pytest.mark.parametrize("name", sorted(acc.SCHEMA)) +def test_readme_names_every_field(name): + assert f"`{name}`" in README and "Access groups" in README + + +@pytest.mark.parametrize("name", sorted(acc.SETTINGS_DEFAULTS)) +def test_readme_names_every_setting(name): + assert f"`{name}`" in README and "Access groups" in README + + +@pytest.mark.parametrize( + "heading", ["Access groups", "Base blocks", "Recipe for restricted profiles", "What this does not promise"] +) +def test_readme_has_the_sections(heading): + assert heading in README diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py new file mode 100644 index 000000000..8e99e7c79 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py @@ -0,0 +1,29 @@ +"""P-G (design 02 §7.3, CC-7): the chain's writes per rate window follow the write limit the +server reports for the key (``whoami.rate_limit_write``). Red on S1: ``window_writes`` ignores it.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-G") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pg") +cp = ah.plugin_module(_PKG, "memory.checkpoint") + + +def test_reported_limit_bounds_the_window(): + assert cp.window_writes(cp.MAX_PARTS_CEILING, 40) <= 40 + assert cp.window_writes(10, 40) == 12 + + +@pytest.mark.s1_green +def test_server_without_the_field_keeps_todays_window(): + assert cp.window_writes(cp.MAX_PARTS_CEILING, None) == cp.MAX_PARTS_CEILING + 2 + assert cp.window_writes(10) == 12 + + +@pytest.mark.s1_green +def test_reported_limit_over_100_never_raises_the_window(): + assert cp.window_writes(500, 1000) == min(500, cp.MAX_PARTS_CEILING) + 2 + assert cp.window_writes(cp.MAX_PARTS_CEILING, 101) == cp.MAX_PARTS_CEILING + 2 From e8df54f750db42aadc538e0b51adb05f56b838fd Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 01:12:54 +0100 Subject: [PATCH 02/65] =?UTF-8?q?test(auth):=20S1=20contract=20for=20per-r?= =?UTF-8?q?equest=20scope=20narrowing=20=E2=80=94=20inert=20stubs=20and=20?= =?UTF-8?q?call=20sites,=20the=20red=20tests=20of=20C-1=20to=20C-4=20behin?= =?UTF-8?q?d=20per-cluster=20build=20tags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The contract the four server clusters of the access-group binding build against, with behaviour unchanged: auth.Narrowing and the AuthResult fields Narrowed and ScopeNarrowing, the scope_narrowing values, narrowAuth (headers ignored) in the Auth middleware between the validity check and the context value, fed only to the handlers while store.WithRequestKey keeps the unnarrowed key, the action check of a narrowed /api/manage request on the one decoded action, and insertApiKeyTx's scopeNarrowing parameter (every caller passes optional; the column is migration 198's). The red tests drive the production router and stay out of every gate behind `integration && s1red_cN`; a cluster enables its file by shortening that line to `//go:build integration`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../keyset_provision_c3_integration_test.go | 494 +++++++++++ .../manage_get_ids_c4_integration_test.go | 261 ++++++ go/cmd/ctxd/narrowing_c1_integration_test.go | 806 ++++++++++++++++++ ..._narrowing_required_c2_integration_test.go | 385 +++++++++ go/internal/auth/auth.go | 28 + go/internal/handler/manage_table.go | 9 + go/internal/handler/middleware.go | 15 +- go/internal/handler/narrowing.go | 65 ++ go/internal/store/api_keys.go | 16 +- go/internal/store/api_keys_insert_test.go | 4 +- .../store/api_keys_write_scopes_test.go | 4 +- go/internal/store/provision.go | 3 +- 12 files changed, 2081 insertions(+), 9 deletions(-) create mode 100644 go/cmd/ctxd/keyset_provision_c3_integration_test.go create mode 100644 go/cmd/ctxd/manage_get_ids_c4_integration_test.go create mode 100644 go/cmd/ctxd/narrowing_c1_integration_test.go create mode 100644 go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go create mode 100644 go/internal/handler/narrowing.go diff --git a/go/cmd/ctxd/keyset_provision_c3_integration_test.go b/go/cmd/ctxd/keyset_provision_c3_integration_test.go new file mode 100644 index 000000000..f1074158f --- /dev/null +++ b/go/cmd/ctxd/keyset_provision_c3_integration_test.go @@ -0,0 +1,494 @@ +//go:build integration && s1red_c3 + +// Achse 02, cluster C-3 (design2/02-ctx-checkpoint.md §3.5 C-3, §7.3, BP-26): +// the manage action keyset-provision creates, for a tenant-admin in its own +// tenant, the missing scopes and then the keys of one set in ONE transaction +// under the tenant row's lock, with the checks of scope-create and +// api-key-create (name rules, max_scopes, max_keys, write_scopes ⊆ +// allowed ∪ {home}), at most 64 scopes and 64 keys per call, each key its own +// principal; replace_label deactivates the active keys of the same label in +// the same transaction. Written in S1, where the action does not exist; the +// second build tag keeps the file out of every gate until C-3 lands. To +// enable, shorten the constraint line to `//go:build integration`. The +// required keys need C-2 (integration order C-1, C-2, C-4, C-3). +// +// Wire form fixed by these tests (S1 contract, design §3.5 plus the lead's +// reading where the design is silent): +// +// request: {"action":"keyset-provision","data":{"scopes":[<name>…], +// "keys":[{"label","home_scope","allowed_scopes","write_scopes", +// "scope_narrowing","replace_label"}…]}} +// names in "scopes" are bare scope names (scope-create's rule); +// a key's scopes are bare names (the tenant's "<slug>:" is put in +// front) or full scope names, which must be the tenant's own (403). +// answer: {"success":true,"scopes":[{"scope":"<slug>:<name>","created":bool}…], +// "keys":[{"id","label","home_scope","allowed_scopes","write_scopes", +// "scope_narrowing","api_key"}…]} — both in request order, the +// plaintext (api_key) only here. +// +// Every refusal test ends with a valid call of the same caller (its control): +// on a tree without the action the refusals would pass for the wrong reason +// (an unknown action is a 400 that creates nothing too). +// +// go test -tags=integration,s1red_c3 -p 1 -count=1 -run '^TestC3' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/dispatch" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +// c3AdminKey is the bootstrap server-admin key (default tenant, owner). +const c3AdminKey = "c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0" + +type c3Resp struct { + status int + body map[string]any + raw string +} + +// c3World: tenant c3t with its owner key; the server-admin key. +type c3World struct { + pool *pgxpool.Pool + router http.Handler + owner string // owner key of c3t + tenantID string // id of c3t +} + +func c3Setup(t *testing.T) *c3World { + t.Helper() + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + applyEnv(t, map[string]string{}) + cc, issues := loadFromEnv() + if config.HasErrors(issues) { + t.Fatalf("env fixture invalid: %v", issues) + } + cfgStore := config.NewStore(cc) + backendPool := backends.NewPool(pool, nil) + scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) + projectHub := events.NewProjectHub(ctx, pool, cfgStore) + d := dispatch.New(nil, dispatch.DefaultSettings()) + t.Cleanup(d.Close) + scheduler.SetDispatcher(d) + if created, _, err := store.BootstrapAdminKey(ctx, pool, c3AdminKey, "c3-admin"); err != nil || !created { + t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) + } + w := &c3World{pool: pool, router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d)} + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3t", "display_name": "C3"}}).must(t, "tenant-create") + w.owner, _ = r.body["owner_key"].(string) + tn, _ := r.body["tenant"].(map[string]any) + w.tenantID, _ = tn["id"].(string) + if w.owner == "" || w.tenantID == "" { + t.Fatalf("fixture tenant-create: %s", r.raw) + } + return w +} + +func (w *c3World) do(t *testing.T, method, path, key string, body any) c3Resp { + t.Helper() + var rd io.Reader = http.NoBody + if body != nil { + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rd = bytes.NewReader(b) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("X-Context-Key", key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + rec := httptest.NewRecorder() + w.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return c3Resp{status: rec.Code, body: out, raw: rec.Body.String()} +} + +func (w *c3World) manage(t *testing.T, key string, body map[string]any) c3Resp { + t.Helper() + return w.do(t, http.MethodPost, "/api/manage", key, body) +} + +func (r c3Resp) must(t *testing.T, what string) c3Resp { + t.Helper() + if r.status != http.StatusOK || r.body["success"] != true { + t.Fatalf("%s: HTTP %d %s", what, r.status, r.raw) + } + return r +} + +// provision posts one keyset-provision as key. +func (w *c3World) provision(t *testing.T, key string, scopes []string, keys ...map[string]any) c3Resp { + t.Helper() + if scopes == nil { + scopes = []string{} + } + return w.manage(t, key, map[string]any{"action": "keyset-provision", "data": map[string]any{"scopes": scopes, "keys": keys}}) +} + +// c3Key is one key spec. +func c3Key(label, home string, allowed, write []string, narrowing string) map[string]any { + if allowed == nil { + allowed = []string{} + } + if write == nil { + write = []string{} + } + return map[string]any{"label": label, "home_scope": home, "allowed_scopes": allowed, "write_scopes": write, "scope_narrowing": narrowing} +} + +// state is the tenant's scopes and active key labels, sorted. +func (w *c3World) state(t *testing.T) (scopes, labels []string) { + t.Helper() + ctx := context.Background() + rows, err := w.pool.Query(ctx, `SELECT scope FROM context_tenant_scopes WHERE tenant_id = $1::uuid ORDER BY scope`, w.tenantID) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var s string + if err := rows.Scan(&s); err != nil { + t.Fatal(err) + } + scopes = append(scopes, s) + } + rows.Close() + rows, err = w.pool.Query(ctx, `SELECT label FROM context_api_keys WHERE tenant_id = $1::uuid AND active ORDER BY label`, w.tenantID) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var s string + if err := rows.Scan(&s); err != nil { + t.Fatal(err) + } + labels = append(labels, s) + } + rows.Close() + return scopes, labels +} + +// wantUnchanged fails unless the tenant's scopes and active keys are exactly +// the ones before. +func (w *c3World) wantUnchanged(t *testing.T, what string, scopes, labels []string) { + t.Helper() + s, l := w.state(t) + if !slices.Equal(s, scopes) || !slices.Equal(l, labels) { + t.Errorf("%s: scopes %v keys %v, want unchanged %v %v (nothing created)", what, s, l, scopes, labels) + } +} + +// keysOf reads the answer's keys: label → (id, plaintext). +func c3KeysOf(r c3Resp) (labels []string, ids, plains map[string]string) { + ids, plains = map[string]string{}, map[string]string{} + list, _ := r.body["keys"].([]any) + for _, e := range list { + m, _ := e.(map[string]any) + l, _ := m["label"].(string) + labels = append(labels, l) + ids[l], _ = m["id"].(string) + plains[l], _ = m["api_key"].(string) + } + return labels, ids, plains +} + +func (w *c3World) whoami(t *testing.T, key string) map[string]any { + t.Helper() + r := w.do(t, http.MethodGet, "/api/whoami", key, nil) + if r.status != http.StatusOK { + t.Fatalf("whoami: HTTP %d %s", r.status, r.raw) + } + return r.body +} + +// TestC3KeysetProvisionCreatesScopesAndKeys: missing scopes are created, an +// existing own scope is reused, the keys carry label, scopes and +// scope_narrowing as asked, and their plaintexts appear in this answer only. +func TestC3KeysetProvisionCreatesScopesAndKeys(t *testing.T) { + w := c3Setup(t) + w.manage(t, w.owner, map[string]any{"action": "scope-create", "data": map[string]any{"name": "k"}}).must(t, "scope-create k") + + r := w.provision(t, w.owner, []string{"k", "members", "mods"}, + c3Key("hermes:discord:111:members", "members", []string{"k"}, nil, "required"), + c3Key("hermes:discord:111:mods", "mods", []string{"k", "members"}, nil, "required")) + r.must(t, "keyset-provision") + + sc, _ := r.body["scopes"].([]any) + var got []string + for _, e := range sc { + m, _ := e.(map[string]any) + got = append(got, fmt.Sprintf("%v=%v", m["scope"], m["created"])) + } + if want := []string{"c3t:k=false", "c3t:members=true", "c3t:mods=true"}; !slices.Equal(got, want) { + t.Errorf("answer scopes %v, want %v (in request order, k reused)", got, want) + } + scopes, _ := w.state(t) + if want := []string{"c3t:k", "c3t:main", "c3t:members", "c3t:mods"}; !slices.Equal(scopes, want) { + t.Errorf("tenant scopes %v, want %v", scopes, want) + } + + labels, ids, plains := c3KeysOf(r) + if want := []string{"hermes:discord:111:members", "hermes:discord:111:mods"}; !slices.Equal(labels, want) { + t.Fatalf("answer keys %v, want %v in request order", labels, want) + } + for l, wantHome := range map[string]string{"hermes:discord:111:members": "c3t:members", "hermes:discord:111:mods": "c3t:mods"} { + if plains[l] == "" || ids[l] == "" { + t.Errorf("%s: no id or plaintext in the answer", l) + continue + } + b := w.whoami(t, plains[l]) + if b["label"] != l || b["home_scope"] != wantHome || b["scope_narrowing"] != "required" || b["role"] != "member" || b["admin"] != false || b["api_key_id"] != ids[l] { + t.Errorf("%s: whoami label %v home %v scope_narrowing %v role %v admin %v id %v, want %s %s required member false %s", + l, b["label"], b["home_scope"], b["scope_narrowing"], b["role"], b["admin"], b["api_key_id"], l, wantHome, ids[l]) + } + } + b := w.whoami(t, plains["hermes:discord:111:mods"]) + rs, _ := b["read_scopes"].([]any) + if fmt.Sprint(rs) != "[c3t:mods c3t:k c3t:members]" { + t.Errorf("mods key reads %v, want [c3t:mods c3t:k c3t:members]", rs) + } + + // The plaintexts are in no later answer. + list := w.manage(t, w.owner, map[string]any{"action": "api-key-list"}).must(t, "api-key-list") + for l, p := range plains { + if strings.Contains(list.raw, p) { + t.Errorf("api-key-list carries the plaintext of %s", l) + } + } +} + +// TestC3QuotaRefusesTheWholeSet: a set that would pass max_scopes after its +// second new scope, or max_keys, is a 429 and creates nothing — not the +// scopes before the limit, not a key. +func TestC3QuotaRefusesTheWholeSet(t *testing.T) { + w := c3Setup(t) + w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 3, "max_keys": 3}}).must(t, "tenant-limit-set") + scopes, labels := w.state(t) + + r := w.provision(t, w.owner, []string{"a", "b", "c"}, c3Key("c3-q", "a", nil, nil, "required")) + if r.status != http.StatusTooManyRequests { + t.Errorf("third new scope over max_scopes 3 (main counts): HTTP %d %s, want 429", r.status, r.raw) + } + if r.body["limit"] != float64(3) || r.body["count"] == nil { + t.Errorf("the 429 names limit %v and count %v, want the limit 3 and the tenant's count", r.body["limit"], r.body["count"]) + } + w.wantUnchanged(t, "after the scope refusal", scopes, labels) + + r = w.provision(t, w.owner, []string{"a"}, c3Key("c3-q1", "a", nil, nil, "required"), c3Key("c3-q2", "a", nil, nil, "required"), c3Key("c3-q3", "a", nil, nil, "required")) + if r.status != http.StatusTooManyRequests { + t.Errorf("three keys over max_keys 3 (the owner key counts): HTTP %d %s, want 429", r.status, r.raw) + } + w.wantUnchanged(t, "after the key refusal", scopes, labels) + + w.provision(t, w.owner, []string{"a", "b"}, c3Key("c3-q1", "a", nil, nil, "required"), c3Key("c3-q2", "b", nil, nil, "required")).must(t, "control: within both limits") +} + +// TestC3MemberIsRefused: keyset-provision is a tenant-admin action. +func TestC3MemberIsRefused(t *testing.T) { + w := c3Setup(t) + r := w.manage(t, w.owner, map[string]any{"action": "api-key-create", "data": map[string]any{"label": "c3-member", "home_scope": "c3t:main"}}).must(t, "member key") + member, _ := r.body["api_key"].(string) + scopes, labels := w.state(t) + if r := w.provision(t, member, []string{"members"}, c3Key("c3-by-member", "members", nil, nil, "required")); r.status != http.StatusForbidden { + t.Errorf("member: HTTP %d %s, want 403", r.status, r.raw) + } + w.wantUnchanged(t, "after the member's call", scopes, labels) + w.provision(t, w.owner, []string{"members"}, c3Key("c3-by-owner", "members", nil, nil, "required")).must(t, "control: the owner") +} + +// TestC3ForeignScopeIsRefused: a key that names another tenant's scope is a +// 403, and nothing of the set is created. +func TestC3ForeignScopeIsRefused(t *testing.T) { + w := c3Setup(t) + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3u", "display_name": "C3 other"}}).must(t, "second tenant") + foreign, _ := r.body["scope"].(string) + scopes, labels := w.state(t) + for _, k := range []map[string]any{ + c3Key("c3-foreign-read", "members", []string{foreign}, nil, "required"), + c3Key("c3-foreign-home", foreign, nil, nil, "required"), + } { + if r := w.provision(t, w.owner, []string{"members"}, k); r.status != http.StatusForbidden { + t.Errorf("%s: HTTP %d %s, want 403", k["label"], r.status, r.raw) + } + w.wantUnchanged(t, fmt.Sprint(k["label"]), scopes, labels) + } + w.provision(t, w.owner, []string{"members"}, c3Key("c3-own", "members", []string{"c3t:main"}, nil, "required")).must(t, "control: own scopes, bare and full") +} + +// TestC3WriteScopesOutsideTheReadSetAreRefused: write_scopes ⊄ allowed ∪ +// {home} is a 400, and nothing is created. +func TestC3WriteScopesOutsideTheReadSetAreRefused(t *testing.T) { + w := c3Setup(t) + scopes, labels := w.state(t) + r := w.provision(t, w.owner, []string{"k", "members", "mods"}, + c3Key("c3-ok", "members", []string{"k"}, nil, "required"), + c3Key("c3-blind", "members", []string{"k"}, []string{"mods"}, "required")) + if e, _ := r.body["error"].(string); r.status != http.StatusBadRequest || !strings.Contains(e, "write_scope") { + t.Errorf("write scope outside the read set: HTTP %d %s, want 400 naming the write_scope", r.status, r.raw) + } + w.wantUnchanged(t, "after the refusal", scopes, labels) + w.provision(t, w.owner, []string{"k", "members"}, c3Key("c3-ok", "members", []string{"k"}, []string{"k"}, "required")).must(t, "control: write scope inside the read set") +} + +// TestC3SizeOfASetIsCapped: 65 keys or 65 scopes in one call are a 400 before +// anything is created, also when the tenant's limits would allow them; 64 +// keys pass. +func TestC3SizeOfASetIsCapped(t *testing.T) { + w := c3Setup(t) + w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 1000, "max_keys": 1000}}).must(t, "tenant-limit-set") + scopes, labels := w.state(t) + keys := func(n int) []map[string]any { + out := make([]map[string]any, n) + for i := range out { + out[i] = c3Key(fmt.Sprintf("c3-many-%02d", i), "many", nil, nil, "required") + } + return out + } + if r := w.provision(t, w.owner, []string{"many"}, keys(65)...); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "64") { + t.Errorf("65 keys: HTTP %d %s, want 400 naming the cap 64", r.status, r.raw) + } + w.wantUnchanged(t, "after 65 keys", scopes, labels) + names := make([]string, 65) + for i := range names { + names[i] = fmt.Sprintf("s%02d", i) + } + if r := w.provision(t, w.owner, names, c3Key("c3-many-scopes", "s00", nil, nil, "required")); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "64") { + t.Errorf("65 scopes: HTTP %d %s, want 400 naming the cap 64", r.status, r.raw) + } + w.wantUnchanged(t, "after 65 scopes", scopes, labels) + r := w.provision(t, w.owner, []string{"many"}, keys(64)...).must(t, "control: 64 keys") + if l, _, _ := c3KeysOf(r); len(l) != 64 { + t.Errorf("64 keys asked, %d answered", len(l)) + } +} + +// TestC3ReplaceLabelDeactivatesThePreviousKey: replace_label deactivates the +// active keys of the tenant with the same label, in the same call, so a +// repeated provision leaves one active key per label. +func TestC3ReplaceLabelDeactivatesThePreviousKey(t *testing.T) { + w := c3Setup(t) + const label = "hermes:discord:222:members" + + // The same label in another tenant: labels are predictable, so the + // replacement must stay inside the caller's tenant. + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3v", "display_name": "C3 same label"}}).must(t, "second tenant") + otherOwner, _ := r.body["owner_key"].(string) + r = w.provision(t, otherOwner, []string{"members"}, c3Key(label, "members", nil, nil, "required")).must(t, "the other tenant's key") + _, _, other := c3KeysOf(r) + + r = w.provision(t, w.owner, []string{"members"}, c3Key(label, "members", nil, nil, "required")).must(t, "first provision") + _, _, first := c3KeysOf(r) + // At the key limit (owner key and the first key): the replacement does not + // count the key it deactivates. + w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 25, "max_keys": 2}}).must(t, "tenant-limit-set") + k := c3Key(label, "members", nil, nil, "required") + k["replace_label"] = true + r = w.provision(t, w.owner, []string{"members"}, k).must(t, "second provision with replace_label, at max_keys") + _, _, second := c3KeysOf(r) + if s := w.do(t, http.MethodGet, "/api/whoami", first[label], nil); s.status != http.StatusUnauthorized { + t.Errorf("the replaced key still authenticates: HTTP %d", s.status) + } + if s := w.do(t, http.MethodGet, "/api/whoami", second[label], nil); s.status != http.StatusOK { + t.Errorf("the new key does not authenticate: HTTP %d %s", s.status, s.raw) + } + if s := w.do(t, http.MethodGet, "/api/whoami", other[label], nil); s.status != http.StatusOK { + t.Errorf("the other tenant's key with the same label was deactivated: HTTP %d %s", s.status, s.raw) + } + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_api_keys WHERE label = $1 AND active AND tenant_id = $2::uuid`, label, w.tenantID).Scan(&n); err != nil || n != 1 { + t.Errorf("%d active key(s) with the label in the tenant (err %v), want 1", n, err) + } +} + +// TestC3TenantIDIsServerAdminOnly: like api-key-create, only a server-admin +// may name tenant_id; a tenant-admin naming another tenant is a 403 and +// nothing is created in either tenant. +func TestC3TenantIDIsServerAdminOnly(t *testing.T) { + w := c3Setup(t) + r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3w", "display_name": "C3 target"}}).must(t, "target tenant") + tn, _ := r.body["tenant"].(map[string]any) + target, _ := tn["id"].(string) + scopes, labels := w.state(t) + data := map[string]any{"tenant_id": target, "scopes": []string{"members"}, "keys": []map[string]any{c3Key("c3-cross", "members", nil, nil, "required")}} + + r = w.manage(t, w.owner, map[string]any{"action": "keyset-provision", "data": data}) + if r.status != http.StatusForbidden { + t.Errorf("tenant-admin naming another tenant: HTTP %d %s, want 403", r.status, r.raw) + } + w.wantUnchanged(t, "the caller's tenant", scopes, labels) + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT (SELECT count(*) FROM context_api_keys WHERE label = 'c3-cross') + (SELECT count(*) FROM context_tenant_scopes WHERE scope = 'c3w:members')`).Scan(&n); err != nil || n != 0 { + t.Errorf("the refused call created %d key(s) or scope(s) (err %v)", n, err) + } + + r = w.manage(t, c3AdminKey, map[string]any{"action": "keyset-provision", "data": data}).must(t, "server-admin naming the tenant") + _, _, plains := c3KeysOf(r) + if b := w.whoami(t, plains["c3-cross"]); b["tenant_slug"] != "c3w" || b["home_scope"] != "c3w:members" { + t.Errorf("server-admin provision: key in tenant %v home %v, want c3w c3w:members", b["tenant_slug"], b["home_scope"]) + } + w.wantUnchanged(t, "the caller's tenant after the server-admin call", scopes, labels) +} + +// TestC3EveryKeyIsItsOwnPrincipal (BP-26): the keys of one set never share a +// principal — signed in with one of them, /api/session/keys lists that one +// key and no other, so a leaked key cannot select its way to the others. +func TestC3EveryKeyIsItsOwnPrincipal(t *testing.T) { + w := c3Setup(t) + r := w.provision(t, w.owner, []string{"a", "b"}, + c3Key("c3-p-a", "a", nil, nil, "optional"), + c3Key("c3-p-b", "b", nil, nil, "optional"), + c3Key("c3-p-c", "b", []string{"a"}, nil, "required")).must(t, "keyset-provision") + _, ids, plains := c3KeysOf(r) + principals := map[string]string{} + for l, p := range plains { + b := w.whoami(t, p) + pid, _ := b["principal_id"].(string) + if pid == "" { + t.Errorf("%s: no principal_id", l) + } + if other, dup := principals[pid]; dup { + t.Errorf("%s and %s share the principal %s", l, other, pid) + } + principals[pid] = l + } + if ob := w.whoami(t, w.owner); principals[fmt.Sprint(ob["principal_id"])] != "" { + t.Errorf("a provisioned key shares the owner's principal") + } + for _, l := range []string{"c3-p-a", "c3-p-b"} { + s := w.do(t, http.MethodGet, "/api/session/keys", plains[l], nil) + if s.status != http.StatusOK { + t.Errorf("%s: session keys: HTTP %d %s", l, s.status, s.raw) + continue + } + list, _ := s.body["keys"].([]any) + if len(list) != 1 { + t.Errorf("%s: /api/session/keys lists %d key(s), want exactly its own (%s)", l, len(list), s.raw) + continue + } + if m, _ := list[0].(map[string]any); m["api_key_id"] != ids[l] { + t.Errorf("%s: /api/session/keys lists %v, want %s", l, m["api_key_id"], ids[l]) + } + } +} diff --git a/go/cmd/ctxd/manage_get_ids_c4_integration_test.go b/go/cmd/ctxd/manage_get_ids_c4_integration_test.go new file mode 100644 index 000000000..22384951f --- /dev/null +++ b/go/cmd/ctxd/manage_get_ids_c4_integration_test.go @@ -0,0 +1,261 @@ +//go:build integration && s1red_c4 + +// Achse 02, cluster C-4 (design2/02-ctx-checkpoint.md §3.5 C-4, §7.3): +// POST /api/manage {"action":"get","ids":[…]} with 1 to 16 ids answers the +// blocks in request order, each id through the resolution of today's get +// (store.ResolveBlockID over the read scopes and the block grants); an id +// that resolves to no visible block is an entry with a code, never a failure +// of the whole request. "id" alone stays as it is. Written in S1, where "ids" +// is ignored; the second build tag keeps the file out of every gate until C-4 +// lands. To enable, shorten the constraint line to `//go:build integration`. +// The narrowed cases need C-1 as well (integration order C-1, C-2, C-4). +// +// Wire form fixed by these tests (S1 contract; the reading of the plugin fake +// tests/fakes/ctx_server.py where the design is silent): +// +// {"success":true,"blocks":[ +// {…the block a single get answers under "block"…}, +// {"id":"<as asked>","code":"not_found","error":"…"}, …]} +// +// one entry per asked id, in request order; an entry with "code" is a miss. +// An id the caller may not see answers exactly like an id that does not exist +// (no existence oracle). +// +// go test -tags=integration,s1red_c4 -p 1 -count=1 -run '^TestC4' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/dispatch" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/handler" + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +// c4AdminKey is the bootstrap server-admin key (default tenant, owner). +const c4AdminKey = "c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0" + +// c4Missing is a well-formed id no block has. +const c4Missing = "00000000-0000-7000-8000-00000000c4c4" + +type c4Resp struct { + status int + body map[string]any + header http.Header + raw string +} + +// c4World: default tenant with scope default:k; key w (home work, allowed +// shared and default:k); blocks in private (granted to the default tenant as +// a single block), private (not granted), shared, work (two), default:k. +type c4World struct { + router http.Handler + w string + blocks map[string]string +} + +func (c *c4World) do(t *testing.T, key string, extra http.Header, body any) c4Resp { + t.Helper() + return c.req(t, http.MethodPost, "/api/manage", key, extra, body) +} + +func (c *c4World) req(t *testing.T, method, path, key string, extra http.Header, body any) c4Resp { + t.Helper() + var rd io.Reader = http.NoBody + if body != nil { + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rd = bytes.NewReader(b) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("X-Context-Key", key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + for k, vs := range extra { + for _, v := range vs { + req.Header.Add(k, v) + } + } + rec := httptest.NewRecorder() + c.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return c4Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} +} + +func (r c4Resp) must(t *testing.T, what string) c4Resp { + t.Helper() + if r.status != http.StatusOK || r.body["success"] != true { + t.Fatalf("%s: HTTP %d %s", what, r.status, r.raw) + } + return r +} + +func c4Setup(t *testing.T) *c4World { + t.Helper() + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + applyEnv(t, map[string]string{}) + cc, issues := loadFromEnv() + if config.HasErrors(issues) { + t.Fatalf("env fixture invalid: %v", issues) + } + cfgStore := config.NewStore(cc) + backendPool := backends.NewPool(pool, nil) + scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) + projectHub := events.NewProjectHub(ctx, pool, cfgStore) + d := dispatch.New(nil, dispatch.DefaultSettings()) + t.Cleanup(d.Close) + scheduler.SetDispatcher(d) + if created, _, err := store.BootstrapAdminKey(ctx, pool, c4AdminKey, "c4-admin"); err != nil || !created { + t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) + } + c := &c4World{router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d), blocks: map[string]string{}} + + c.do(t, c4AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": "k"}}).must(t, "scope-create k") + mint := func(data map[string]any) string { + r := c.do(t, c4AdminKey, nil, map[string]any{"action": "api-key-create", "data": data}).must(t, "api-key-create") + k, _ := r.body["api_key"].(string) + return k + } + c.w = mint(map[string]any{"label": "c4-w", "home_scope": "work", "allowed_scopes": []string{"shared", "default:k"}}) + kw := mint(map[string]any{"label": "c4-kw", "home_scope": "default:k"}) + put := func(name, key, scope string) { + body := map[string]any{"category": "learnings", "title": "c4 " + name, "content": "c4 " + name + " content"} + if scope != "" { + body["scope"] = scope + } + r := c.req(t, http.MethodPost, "/api/store", key, nil, body).must(t, "store "+name) + blk, _ := r.body["block"].(map[string]any) + c.blocks[name], _ = blk["id"].(string) + } + put("granted", c4AdminKey, "") + put("private", c4AdminKey, "") + put("shared", c4AdminKey, "shared") + put("work1", c.w, "") + put("work2", c.w, "") + put("k", kw, "") + c.do(t, c4AdminKey, nil, map[string]any{"action": "block-grant-create", + "data": map[string]any{"block_id": c.blocks["granted"], "grantee_tenant": store.DefaultTenantID}}).must(t, "block-grant-create") + return c +} + +// c4Entry is one entry of a multi-get answer: its "id" (the block's id when +// found, the asked id when missed) and its code ("" when found). +type c4Entry struct{ id, code, err string } + +func c4Entries(t *testing.T, r c4Resp) []c4Entry { + t.Helper() + list, ok := r.body["blocks"].([]any) + if !ok { + t.Errorf("answer has no blocks list: HTTP %d %s", r.status, r.raw) + return nil + } + out := make([]c4Entry, 0, len(list)) + for _, e := range list { + m, _ := e.(map[string]any) + var en c4Entry + en.id, _ = m["id"].(string) + en.code, _ = m["code"].(string) + en.err, _ = m["error"].(string) + out = append(out, en) + } + return out +} + +// wantEntries checks the answer entry by entry: name "" means "not found". +func (c *c4World) wantEntries(t *testing.T, what string, r c4Resp, asked []string, found []string) { + t.Helper() + if r.status != http.StatusOK || r.body["success"] != true { + t.Errorf("%s: HTTP %d %s, want 200 success", what, r.status, r.raw) + return + } + got := c4Entries(t, r) + if len(got) != len(asked) { + t.Errorf("%s: %d entries, want %d (one per id, in order)", what, len(got), len(asked)) + return + } + for i, e := range got { + switch want := found[i]; { + case want == "" && (e.id != asked[i] || e.code != "not_found"): + t.Errorf("%s: entry %d (%s): id %q code %q, want a not_found entry for the asked id", what, i, asked[i], e.id, e.code) + case want != "" && (e.id != c.blocks[want] || e.code != ""): + t.Errorf("%s: entry %d: id %q code %q, want block %s (%s), request order", what, i, e.id, e.code, want, c.blocks[want]) + } + } +} + +// TestC4GetIdsAnswersInOrder: found blocks and misses in the order asked; an +// id the key may not read answers like one that does not exist; a block read +// through a block grant is found unnarrowed. +func TestC4GetIdsAnswersInOrder(t *testing.T) { + c := c4Setup(t) + asked := []string{c.blocks["work2"], c.blocks["shared"], c4Missing, c.blocks["work1"], c.blocks["private"], c.blocks["k"], c.blocks["granted"]} + r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": asked}) + c.wantEntries(t, "seven ids", r, asked, []string{"work2", "shared", "", "work1", "", "k", "granted"}) + // No existence oracle: the miss of a block the key may not read and the + // miss of an id no block has differ in nothing but the id. + if e := c4Entries(t, r); len(e) == len(asked) && (e[2].code != e[4].code || e[2].err != e[4].err || e[2].err == "") { + t.Errorf("the invisible block's entry %+v differs from the missing id's %+v", e[4], e[2]) + } + // "id" alone is unchanged: one block under "block". + one := c.do(t, c.w, nil, map[string]any{"action": "get", "id": c.blocks["work1"]}).must(t, "single get") + if b, _ := one.body["block"].(map[string]any); b["id"] != c.blocks["work1"] { + t.Errorf("single get answers %v", one.raw) + } +} + +// TestC4GetIdsCountIsCapped: 17 ids are a 400; 16 are answered (control). +func TestC4GetIdsCountIsCapped(t *testing.T) { + c := c4Setup(t) + ids := func(n int) []string { + out := make([]string, n) + for i := range out { + out[i] = fmt.Sprintf("00000000-0000-7000-8000-%012d", i) + } + out[0] = c.blocks["work1"] + return out + } + if r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": ids(17)}); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "16") { + t.Errorf("17 ids: HTTP %d %s, want 400 naming the cap 16", r.status, r.raw) + } + r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": ids(16)}) + want := make([]string, 16) + want[0] = "work1" + c.wantEntries(t, "16 ids", r, ids(16), want) +} + +// TestC4NarrowedGetIdsReadsOnlyTheNamedScopes: under a narrowing the multi-get +// finds blocks of the named scopes only; a block-grant block is not found. +func TestC4NarrowedGetIdsReadsOnlyTheNamedScopes(t *testing.T) { + c := c4Setup(t) + h := http.Header{} + h.Set(handler.HeaderReadScopes, "work") + asked := []string{c.blocks["work1"], c.blocks["shared"], c.blocks["k"], c.blocks["granted"]} + r := c.do(t, c.w, h, map[string]any{"action": "get", "ids": asked}) + c.wantEntries(t, "narrowed to work", r, asked, []string{"work1", "", "", ""}) + if got := r.header.Get(handler.HeaderNarrowed); got != "work;" { + t.Errorf("narrowed multi-get: echo %q, want \"work;\"", got) + } + + h.Set(handler.HeaderReadScopes, "work,shared,default:k") + r = c.do(t, c.w, h, map[string]any{"action": "get", "ids": asked}) + c.wantEntries(t, "narrowed to all own scopes", r, asked, []string{"work1", "shared", "k", ""}) +} diff --git a/go/cmd/ctxd/narrowing_c1_integration_test.go b/go/cmd/ctxd/narrowing_c1_integration_test.go new file mode 100644 index 000000000..2066593d8 --- /dev/null +++ b/go/cmd/ctxd/narrowing_c1_integration_test.go @@ -0,0 +1,806 @@ +//go:build integration && s1red_c1 + +// Achse 02, cluster C-1 (design2/02-ctx-checkpoint.md §3.5 C-1, §7.3): a +// request narrows its key's rights to the scopes it names — X-Context-Read- +// Scopes (1 to 8, in order) and X-Context-Write-Scope (one, inside the read +// set, writable for the key) — on a closed list of routes and /api/manage +// actions, echoed in X-Context-Narrowed. Written in S1 against the inert stubs +// of internal/handler/narrowing.go; the second build tag keeps the file out of +// every gate until C-1 lands. To enable, shorten the constraint line to +// `//go:build integration`. +// +// The tests drive the PRODUCTION router (NewRouter): the route rule sits in the +// Auth middleware and means something only against the mounts production +// serves. Every fixture goes through a write path — tenant-create, +// scope-create, api-key-create, /api/store, delete, tenant-grant-create, +// block-grant-create, PUT /api/settings — except confirm_writes, which has none +// and is set in SQL. TestC1Pin* are green on the stubs on purpose: they pin +// what a narrowing must leave alone (the mutant "HomeScope rewritten") and +// carry no red reason of their own. +// +// go test -tags=integration,s1red_c1 -p 1 -count=1 -run '^TestC1' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/dispatch" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/handler" + "github.com/GottZ/ctx/internal/settings" + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" +) + +// c1AdminKey is the bootstrap server-admin key (default tenant, owner). +const c1AdminKey = "c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0" + +// c1Probe is the word every fixture block carries, so one search finds them all. +const c1Probe = "narrowprobe" + +// c1Resp is one answer of the router. +type c1Resp struct { + status int + body map[string]any + header http.Header + raw string +} + +// c1World is the fixture: the router, the keys and the blocks. +// +// Default tenant: scopes private, work, shared (baseline) plus default:k and +// default:m. Key w: home work, allowed shared and default:k (writable: work, +// shared; default:k read-only). Key x: home default:m, allowed and write +// default:k. Key kw: home default:k. Tenant c1two: owner key, home c1two:main, +// granted to the default tenant (a grant scope in every default key's read +// set). Block "private" is granted to the default tenant as a single block. +type c1World struct { + pool *pgxpool.Pool + router http.Handler + keys map[string]string + blocks map[string]string + two string // c1two:main, the grant scope +} + +// c1EmbedHost serves the embed and translate halves of an Ollama backend: one +// fixed vector per input. +func c1EmbedHost(t *testing.T) string { + t.Helper() + vec := make([]float64, 1024) + for i := range vec { + vec[i] = float64((i % 2) * 2) + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api/embed": + var req struct { + Input any `json:"input"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + n := 1 + if in, ok := req.Input.([]any); ok { + n = len(in) + } + out := make([][]float64, n) + for i := range out { + out[i] = vec + } + _ = json.NewEncoder(w).Encode(map[string]any{"embeddings": out}) + case "/api/chat": + _, _ = io.Copy(io.Discard, r.Body) + _ = json.NewEncoder(w).Encode(map[string]any{ + "message": map[string]any{"role": "assistant", "content": c1Probe}, + "eval_count": 1, "prompt_eval_count": 1, + }) + default: + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv.URL +} + +// c1Router builds the production router on a fresh database, with an embed +// backend, and the bootstrap admin key. +func c1Router(t *testing.T) (*pgxpool.Pool, http.Handler) { + t.Helper() + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + applyEnv(t, map[string]string{}) + cc, issues := loadFromEnv() + if config.HasErrors(issues) { + t.Fatalf("env fixture invalid: %v", issues) + } + cfgStore := config.NewStore(cc) + // The tenant overlay, as the boot wires it (main.go): the settings a + // tenant-admin writes reach that tenant's requests. + cfgStore.SetOverlay(settings.TenantOverlay(pool)) + backendPool := backends.NewPool(pool, nil) + host := c1EmbedHost(t) + backendPool.SeedSnapshotForTest([]backends.Backend{ + {ID: "c1-embed", Name: "c1-embed", Scope: "_global", Host: host, Protocol: backends.ProtocolOllama, + Model: "test-embed", Trust: backends.TrustFull, Enabled: true, Priority: 1, Roles: []string{backends.RoleEmbed}}, + {ID: "c1-chat", Name: "c1-chat", Scope: "_global", Host: host, Protocol: backends.ProtocolOllama, + Model: "test-chat", Trust: backends.TrustFull, Enabled: true, Priority: 1, Roles: []string{backends.RoleTranslate}}, + }) + scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) + projectHub := events.NewProjectHub(ctx, pool, cfgStore) + d := dispatch.New(nil, dispatch.DefaultSettings()) + t.Cleanup(d.Close) + scheduler.SetDispatcher(d) + if created, _, err := store.BootstrapAdminKey(ctx, pool, c1AdminKey, "c1-admin"); err != nil || !created { + t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) + } + return pool, NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d) +} + +// c1Narrow is the header set of a narrowing: read scopes, optionally the +// write scope. +func c1Narrow(read string, write ...string) http.Header { + h := http.Header{} + h.Set(handler.HeaderReadScopes, read) + if len(write) > 0 { + h.Set(handler.HeaderWriteScope, write[0]) + } + return h +} + +// do sends one request with the raw key and the extra headers. +func (w *c1World) do(t *testing.T, method, path, key string, extra http.Header, body any) c1Resp { + t.Helper() + var rd io.Reader = http.NoBody + if body != nil { + b, ok := body.([]byte) + if !ok { + var err error + if b, err = json.Marshal(body); err != nil { + t.Fatal(err) + } + } + rd = bytes.NewReader(b) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("X-Context-Key", key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + for k, vs := range extra { + for _, v := range vs { + req.Header.Add(k, v) + } + } + rec := httptest.NewRecorder() + w.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return c1Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} +} + +// manage posts one /api/manage body. +func (w *c1World) manage(t *testing.T, key string, extra http.Header, body map[string]any) c1Resp { + t.Helper() + return w.do(t, http.MethodPost, "/api/manage", key, extra, body) +} + +// must fails the test unless the answer is a 200. +func (r c1Resp) must(t *testing.T, what string) c1Resp { + t.Helper() + if r.status != http.StatusOK { + t.Fatalf("fixture %s: HTTP %d %s", what, r.status, r.raw) + } + return r +} + +// storeBlock writes one block through /api/store and returns its id. +func (w *c1World) storeBlock(t *testing.T, key, scope, title string) string { + t.Helper() + body := map[string]any{"category": "learnings", "title": title, "content": title + " " + c1Probe + " content"} + if scope != "" { + body["scope"] = scope + } + r := w.do(t, http.MethodPost, "/api/store", key, nil, body).must(t, "store "+title) + blk, _ := r.body["block"].(map[string]any) + id, _ := blk["id"].(string) + if id == "" { + t.Fatalf("fixture store %s: no block id in %s", title, r.raw) + } + return id +} + +// mintKey creates one key through api-key-create as the admin. +func (w *c1World) mintKey(t *testing.T, data map[string]any) string { + t.Helper() + r := w.manage(t, c1AdminKey, nil, map[string]any{"action": "api-key-create", "data": data}).must(t, "api-key-create") + k, _ := r.body["api_key"].(string) + if k == "" { + t.Fatalf("fixture api-key-create: no key in %s", r.raw) + } + return k +} + +func c1Setup(t *testing.T) *c1World { + t.Helper() + pool, router := c1Router(t) + w := &c1World{pool: pool, router: router, keys: map[string]string{}, blocks: map[string]string{}} + for _, n := range []string{"k", "m"} { + w.manage(t, c1AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": n}}).must(t, "scope-create "+n) + } + w.keys["w"] = w.mintKey(t, map[string]any{"label": "c1-w", "home_scope": "work", "allowed_scopes": []string{"shared", "default:k"}}) + w.keys["x"] = w.mintKey(t, map[string]any{"label": "c1-x", "home_scope": "default:m", + "allowed_scopes": []string{"default:k"}, "write_scopes": []string{"default:k"}}) + w.keys["kw"] = w.mintKey(t, map[string]any{"label": "c1-kw", "home_scope": "default:k"}) + + w.blocks["private"] = w.storeBlock(t, c1AdminKey, "", "c1 private alpha") + w.blocks["shared"] = w.storeBlock(t, c1AdminKey, "shared", "c1 shared foxtrot") + w.blocks["work"] = w.storeBlock(t, w.keys["w"], "", "c1 work bravo") + w.blocks["k"] = w.storeBlock(t, w.keys["kw"], "", "c1 k charlie") + w.blocks["m"] = w.storeBlock(t, w.keys["x"], "", "c1 m golf") + + r := w.manage(t, c1AdminKey, nil, map[string]any{"action": "tenant-create", + "data": map[string]any{"slug": "c1two", "display_name": "C1 two"}}).must(t, "tenant-create") + w.keys["two"], _ = r.body["owner_key"].(string) + w.two, _ = r.body["scope"].(string) + if w.keys["two"] == "" || w.two == "" { + t.Fatalf("fixture tenant-create: %s", r.raw) + } + w.blocks["two"] = w.storeBlock(t, w.keys["two"], "", "c1 two delta") + w.blocks["twoArchived"] = w.storeBlock(t, w.keys["two"], "", "c1 two archived echo") + w.manage(t, w.keys["two"], nil, map[string]any{"action": "delete", "id": w.blocks["twoArchived"]}).must(t, "delete") + w.manage(t, c1AdminKey, nil, map[string]any{"action": "tenant-grant-create", + "data": map[string]any{"grantee_tenant": store.DefaultTenantID, "granted_scope": w.two}}).must(t, "tenant-grant-create") + w.manage(t, c1AdminKey, nil, map[string]any{"action": "block-grant-create", + "data": map[string]any{"block_id": w.blocks["private"], "grantee_tenant": store.DefaultTenantID}}).must(t, "block-grant-create") + return w +} + +// c1IDs reads the "id" of every element of the list under key. +func c1IDs(body map[string]any, key string) []string { + list, _ := body[key].([]any) + var ids []string + for _, e := range list { + m, _ := e.(map[string]any) + if id, _ := m["id"].(string); id != "" { + ids = append(ids, id) + } + } + return ids +} + +// names maps block ids back to their fixture names, for readable failures. +func (w *c1World) names(ids []string) []string { + out := make([]string, 0, len(ids)) + for _, id := range ids { + name := id + for n, b := range w.blocks { + if b == id { + name = n + } + } + out = append(out, name) + } + slices.Sort(out) + return out +} + +// code is the machine code of an answer. +func (r c1Resp) code() string { + c, _ := r.body["code"].(string) + return c +} + +// wantRefused fails unless the answer is status with code. +func c1WantRefused(t *testing.T, what string, r c1Resp, status int, code string) { + t.Helper() + if r.status != status || r.code() != code { + t.Errorf("%s: HTTP %d code %q, want %d %q (%s)", what, r.status, r.code(), status, code, strings.TrimSpace(r.raw)) + } +} + +// wantEcho fails unless the answer carries the narrowing echo want. +func c1WantEcho(t *testing.T, what string, r c1Resp, want string) { + t.Helper() + if got := r.header.Get(handler.HeaderNarrowed); got != want || len(r.header.Values(handler.HeaderNarrowed)) != 1 { + t.Errorf("%s: %s = %q (%d value(s)), want exactly %q", what, handler.HeaderNarrowed, got, len(r.header.Values(handler.HeaderNarrowed)), want) + } +} + +// TestC1NarrowedSearchReadsOnlyTheNamedScopes: a narrowed /api/search finds +// blocks of the named scopes and nothing else; the unnarrowed request of the +// same key finds the rest (fixture control). +func TestC1NarrowedSearchReadsOnlyTheNamedScopes(t *testing.T) { + w := c1Setup(t) + body := map[string]any{"query": c1Probe, "limit": 50} + all := w.do(t, http.MethodPost, "/api/search", w.keys["w"], nil, body).must(t, "unnarrowed search") + // private: through the block grant; two: through the tenant grant. + if got := w.names(c1IDs(all.body, "results")); !slices.Equal(got, []string{"k", "private", "shared", "two", "work"}) { + t.Fatalf("fixture: the unnarrowed search of key w finds %v, want [k private shared two work] (%s)", got, all.raw) + } + for _, c := range []struct { + read string + want []string + }{ + {"work", []string{"work"}}, + {"default:k", []string{"k"}}, + {w.two, []string{"two"}}, + {"shared,work", []string{"shared", "work"}}, + } { + r := w.do(t, http.MethodPost, "/api/search", w.keys["w"], c1Narrow(c.read), body) + if r.status != http.StatusOK { + t.Errorf("search narrowed to %s: HTTP %d %s", c.read, r.status, r.raw) + continue + } + if got := w.names(c1IDs(r.body, "results")); !slices.Equal(got, c.want) { + t.Errorf("search narrowed to %s finds %v, want %v", c.read, got, c.want) + } + c1WantEcho(t, "search narrowed to "+c.read, r, c.read+";") + } +} + +// TestC1NarrowedQueryReadsOnlyTheNamedScopes: the same for /api/query +// (synthesize off) — the red test the design names first. +func TestC1NarrowedQueryReadsOnlyTheNamedScopes(t *testing.T) { + w := c1Setup(t) + body := map[string]any{"query": c1Probe, "synthesize": false, "limit": 20} + all := w.do(t, http.MethodPost, "/api/query", w.keys["w"], nil, body).must(t, "unnarrowed query") + if got := w.names(c1IDs(all.body, "sources")); len(got) < 2 || !slices.Contains(got, "work") { + t.Fatalf("fixture: the unnarrowed query of key w finds %v, want work and at least one other scope's block (%s)", got, all.raw) + } + for _, c := range []struct { + read string + want []string + }{ + {"work", []string{"work"}}, + {"default:k", []string{"k"}}, + } { + r := w.do(t, http.MethodPost, "/api/query", w.keys["w"], c1Narrow(c.read), body) + if r.status != http.StatusOK { + t.Errorf("query narrowed to %s: HTTP %d %s", c.read, r.status, r.raw) + continue + } + if got := w.names(c1IDs(r.body, "sources")); !slices.Equal(got, c.want) { + t.Errorf("query narrowed to %s finds %v, want %v", c.read, got, c.want) + } + c1WantEcho(t, "query narrowed to "+c.read, r, c.read+";") + } +} + +// TestC1ScopeOutsideTheKeyIsDenied: a read scope the key cannot read is a +// 403 scope_denied, on every route — never a silently smaller read set. +func TestC1ScopeOutsideTheKeyIsDenied(t *testing.T) { + w := c1Setup(t) + h := c1Narrow("work,private") + c1WantRefused(t, "search", w.do(t, http.MethodPost, "/api/search", w.keys["w"], h, map[string]any{"query": c1Probe}), http.StatusForbidden, "scope_denied") + c1WantRefused(t, "query", w.do(t, http.MethodPost, "/api/query", w.keys["w"], h, map[string]any{"query": c1Probe, "synthesize": false}), http.StatusForbidden, "scope_denied") + c1WantRefused(t, "whoami", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], h, nil), http.StatusForbidden, "scope_denied") +} + +// c1Count counts the blocks with this title, archived included. +func (w *c1World) c1Count(t *testing.T, title string) int { + t.Helper() + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_blocks WHERE title = $1`, title).Scan(&n); err != nil { + t.Fatal(err) + } + return n +} + +// TestC1NarrowedWriteNeedsItsWriteScope: a narrowed write without +// X-Context-Write-Scope writes nothing (403 scope_denied, the answer still +// carries the echo — the narrowing itself was valid). A write scope the key +// can only read, or one outside the read set, makes the narrowing itself +// invalid: 403 scope_denied on every route, whoami included. Nothing lands in +// any scope. +func TestC1NarrowedWriteNeedsItsWriteScope(t *testing.T) { + w := c1Setup(t) + for _, c := range []struct { + name string + h http.Header + scope string + badWrite bool // the write scope itself is refused (in the Auth middleware) + }{ + {"read header only", c1Narrow("work"), "", false}, + {"read header only, scope named in the body", c1Narrow("work"), "work", false}, + {"read-only scope as write scope", c1Narrow("work,default:k", "default:k"), "", true}, + {"write scope outside the read set", c1Narrow("work", "shared"), "", true}, + } { + title := "c1 refused write " + c.name + body := map[string]any{"category": "learnings", "title": title, "content": "x " + c1Probe} + if c.scope != "" { + body["scope"] = c.scope + } + r := w.do(t, http.MethodPost, "/api/store", w.keys["w"], c.h, body) + c1WantRefused(t, c.name, r, http.StatusForbidden, "scope_denied") + if n := w.c1Count(t, title); n != 0 { + t.Errorf("%s: %d block(s) written, want none", c.name, n) + } + if c.badWrite { + c1WantRefused(t, c.name+" (whoami)", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c.h, nil), http.StatusForbidden, "scope_denied") + } else { + c1WantEcho(t, c.name, r, "work;") + } + } +} + +// TestC1NarrowingHeaderFormIsChecked: X-Context-Write-Scope alone, an empty +// header, a header that occurs twice, an empty list element and more than +// eight read scopes are 400 scope_narrowing_invalid — before any handler runs. +func TestC1NarrowingHeaderFormIsChecked(t *testing.T) { + w := c1Setup(t) + writeOnly := http.Header{} + writeOnly.Set(handler.HeaderWriteScope, "work") + empty := http.Header{} + empty.Set(handler.HeaderReadScopes, "") + twiceRead := http.Header{} + twiceRead.Add(handler.HeaderReadScopes, "work") + twiceRead.Add(handler.HeaderReadScopes, "shared") + twiceWrite := c1Narrow("work") + twiceWrite.Add(handler.HeaderWriteScope, "work") + twiceWrite.Add(handler.HeaderWriteScope, "work") + emptyElement := c1Narrow("work,,shared") + for _, c := range []struct { + name string + h http.Header + }{ + {"write scope alone", writeOnly}, + {"empty read header", empty}, + {"read header twice", twiceRead}, + {"write header twice", twiceWrite}, + {"empty list element", emptyElement}, + } { + c1WantRefused(t, c.name+" (whoami)", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c.h, nil), http.StatusBadRequest, "scope_narrowing_invalid") + title := "c1 invalid header " + c.name + c1WantRefused(t, c.name+" (store)", w.do(t, http.MethodPost, "/api/store", w.keys["w"], c.h, + map[string]any{"category": "learnings", "title": title, "content": "x"}), http.StatusBadRequest, "scope_narrowing_invalid") + if n := w.c1Count(t, title); n != 0 { + t.Errorf("%s: %d block(s) written, want none", c.name, n) + } + } +} + +// TestC1ReadScopesAreCappedAtEight: eight distinct readable scopes narrow a +// request; a ninth is 400 scope_narrowing_invalid, also when the key reads all +// nine. +func TestC1ReadScopesAreCappedAtEight(t *testing.T) { + w := c1Setup(t) + for _, n := range []string{"n1", "n2", "n3"} { + w.manage(t, c1AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": n}}).must(t, "scope-create "+n) + } + key := w.mintKey(t, map[string]any{"label": "c1-nine", "home_scope": "work", + "allowed_scopes": []string{"private", "shared", "default:k", "default:m", "default:n1", "default:n2", "default:n3"}}) + eight := "work,private,shared,default:k,default:m,default:n1,default:n2,default:n3" + r := w.do(t, http.MethodGet, "/api/whoami", key, nil, nil).must(t, "whoami of the nine-scope key") + if rs := c1Strings(r.body["read_scopes"]); len(rs) != 9 || !slices.Contains(rs, w.two) { + t.Fatalf("fixture: the key reads %v, want nine scopes with the grant scope %s", rs, w.two) + } + r = w.do(t, http.MethodGet, "/api/whoami", key, c1Narrow(eight), nil) + if r.status != http.StatusOK { + t.Errorf("eight read scopes: HTTP %d %s, want 200", r.status, r.raw) + } + c1WantEcho(t, "eight read scopes", r, eight+";") + c1WantRefused(t, "nine read scopes", w.do(t, http.MethodGet, "/api/whoami", key, c1Narrow(eight+","+w.two), nil), http.StatusBadRequest, "scope_narrowing_invalid") +} + +// TestC1NarrowedWriteLandsInItsWriteScope: a narrowed write without a scope in +// the body lands in X-Context-Write-Scope — here a write_scope of the key, +// not its home — and passes the write recheck of issue #555 +// (store.WithRequestKey carries the key's own scopes, and default:k is one of +// its write_scopes). The answer carries the echo. +func TestC1NarrowedWriteLandsInItsWriteScope(t *testing.T) { + w := c1Setup(t) + r := w.do(t, http.MethodPost, "/api/store", w.keys["x"], c1Narrow("default:k", "default:k"), + map[string]any{"category": "learnings", "title": "c1 narrowed write hotel", "content": "x " + c1Probe}) + if r.status != http.StatusOK { + t.Fatalf("narrowed write: HTTP %d %s", r.status, r.raw) + } + blk, _ := r.body["block"].(map[string]any) + if got, _ := blk["scope"].(string); got != "default:k" { + t.Errorf("narrowed write answered scope %q, want default:k (the write scope, not the home default:m)", got) + } + var scope string + if err := w.pool.QueryRow(context.Background(), `SELECT scope FROM context_blocks WHERE title = 'c1 narrowed write hotel' AND NOT is_archived`).Scan(&scope); err != nil { + t.Fatalf("narrowed write: row: %v", err) + } + if scope != "default:k" { + t.Errorf("narrowed write stored in %q, want default:k", scope) + } + c1WantEcho(t, "narrowed write", r, "default:k;default:k") + + // The home scope narrowed explicitly, named in the body as well. + r = w.do(t, http.MethodPost, "/api/store", w.keys["x"], c1Narrow("default:m", "default:m"), + map[string]any{"category": "learnings", "title": "c1 narrowed home write india", "content": "x", "scope": "default:m"}) + if r.status != http.StatusOK { + t.Fatalf("narrowed home write: HTTP %d %s", r.status, r.raw) + } + c1WantEcho(t, "narrowed home write", r, "default:m;default:m") +} + +// TestC1BlockGrantIsInvisibleWhenNarrowed: a block the key reads only through +// a block grant is found unnarrowed (fixture control) and not found under any +// narrowing — a narrowed request reads its named scopes and nothing else. +func TestC1BlockGrantIsInvisibleWhenNarrowed(t *testing.T) { + w := c1Setup(t) + get := map[string]any{"action": "get", "id": w.blocks["private"]} + if r := w.manage(t, w.keys["w"], nil, get).must(t, "unnarrowed get of the granted block"); r.body["success"] != true { + t.Fatalf("fixture: key w does not read the granted block unnarrowed: %s", r.raw) + } + r := w.manage(t, w.keys["w"], c1Narrow("work,shared,default:k"), get) + if r.status != http.StatusOK || r.body["success"] != false { + t.Errorf("narrowed get of the granted block: HTTP %d %s, want 200 with success false (not found)", r.status, r.raw) + } + c1WantEcho(t, "narrowed get of the granted block", r, "work,shared,default:k;") + s := w.do(t, http.MethodPost, "/api/search", w.keys["w"], c1Narrow("work,shared,default:k"), map[string]any{"query": "alpha"}) + if slices.Contains(c1IDs(s.body, "results"), w.blocks["private"]) || s.status != http.StatusOK { + t.Errorf("narrowed search: HTTP %d, finds the granted block: %s", s.status, s.raw) + } +} + +// TestC1RoutesOutsideTheListAreRefused: a narrowed request on any route but +// the five of the list is 403 scope_narrowing_route — decided in the Auth +// middleware, by method and path, before the route's handler runs. +func TestC1RoutesOutsideTheListAreRefused(t *testing.T) { + w := c1Setup(t) + h := c1Narrow("work") + mcp := c1Narrow("work") + mcp.Set("Accept", "application/json, text/event-stream") + for _, c := range []struct { + method, path string + body any + }{ + {http.MethodPost, "/mcp", map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}}, + {http.MethodPost, "/api/store/batch", map[string]any{"items": []any{map[string]any{"category": "learnings", "title": "c1 batch kilo", "content": "x"}}}}, + {http.MethodPost, "/api/blob/store", map[string]any{"file": "aGk=", "filename": "f.txt", "category": "files", "title": "c1 blob lima", "mime_type": "text/plain"}}, + {http.MethodPost, "/api/recent", map[string]any{}}, + {http.MethodGet, "/api/session/keys", nil}, + } { + hc := h + if c.path == "/mcp" { + hc = mcp + } + c1WantRefused(t, c.method+" "+c.path, w.do(t, c.method, c.path, w.keys["w"], hc, c.body), http.StatusForbidden, "scope_narrowing_route") + } + if n := w.c1Count(t, "c1 batch kilo"); n != 0 { + t.Errorf("narrowed batch wrote %d block(s)", n) + } +} + +// TestC1ManageActionsOutsideTheListAreRefused: on /api/manage a narrowed +// request runs get and type-list only; update and purge are 403 +// scope_narrowing_route and change nothing. BP-25: Go's decoder matches JSON +// keys case-insensitively and the LAST one wins, so {"action":"get", +// "ACTION":"purge"} decodes to purge — the check must judge that one decoded +// action (a check reading the lowercase key would see get). The other key +// order is left open: refusing it as well is safe. +func TestC1ManageActionsOutsideTheListAreRefused(t *testing.T) { + w := c1Setup(t) + + // The premise, on the decoder the dispatcher uses. + var probe struct { + Action string `json:"action"` + } + if err := json.NewDecoder(strings.NewReader(`{"action":"get","ACTION":"purge"}`)).Decode(&probe); err != nil || probe.Action != "purge" { + t.Fatalf("premise: the decoder reads %q (err %v), want purge — rewrite the BP-25 cases", probe.Action, err) + } + + hw := c1Narrow("work") + r := w.manage(t, w.keys["w"], hw, map[string]any{"action": "update", "id": w.blocks["work"], "data": map[string]any{"content": "c1 overwritten"}}) + c1WantRefused(t, "narrowed update", r, http.StatusForbidden, "scope_narrowing_route") + c1WantEcho(t, "narrowed update", r, "work;") + var content string + if err := w.pool.QueryRow(context.Background(), `SELECT content FROM context_blocks WHERE id = $1`, w.blocks["work"]).Scan(&content); err != nil || content == "c1 overwritten" { + t.Errorf("narrowed update changed the block: %q (err %v)", content, err) + } + + ha := c1Narrow("private") + r = w.manage(t, c1AdminKey, ha, map[string]any{"action": "purge"}) + c1WantRefused(t, "narrowed purge (owner key)", r, http.StatusForbidden, "scope_narrowing_route") + c1WantEcho(t, "narrowed purge", r, "private;") + c1WantRefused(t, "narrowed delete", w.manage(t, w.keys["w"], hw, map[string]any{"action": "delete", "id": w.blocks["work"]}), http.StatusForbidden, "scope_narrowing_route") + + raw := []byte(`{"action":"get","id":"` + w.blocks["private"] + `","ACTION":"purge"}`) + c1WantRefused(t, "BP-25 get then ACTION purge", w.do(t, http.MethodPost, "/api/manage", c1AdminKey, ha, raw), http.StatusForbidden, "scope_narrowing_route") + r = w.manage(t, w.keys["w"], hw, map[string]any{"action": "type-list"}) + if r.status != http.StatusOK { + t.Errorf("narrowed type-list: HTTP %d %s", r.status, r.raw) + } + c1WantEcho(t, "narrowed type-list", r, "work;") +} + +// TestC1EchoOnEveryNarrowedAnswer: every answer to a narrowed request carries +// X-Context-Narrowed: <read scopes as sent>;<write scope> — the client's proof +// that no proxy dropped the narrowing (E5 of the plugin). +func TestC1EchoOnEveryNarrowedAnswer(t *testing.T) { + w := c1Setup(t) + h := c1Narrow("work,shared") + for _, c := range []struct { + method, path string + body any + }{ + {http.MethodGet, "/api/whoami", nil}, + {http.MethodPost, "/api/search", map[string]any{"query": c1Probe}}, + {http.MethodPost, "/api/query", map[string]any{"query": c1Probe, "synthesize": false}}, + {http.MethodPost, "/api/manage", map[string]any{"action": "get", "id": w.blocks["work"]}}, + {http.MethodPost, "/api/manage", map[string]any{"action": "type-list"}}, + } { + r := w.do(t, c.method, c.path, w.keys["w"], h, c.body) + if r.status != http.StatusOK { + t.Errorf("%s %s narrowed: HTTP %d %s", c.method, c.path, r.status, r.raw) + } + c1WantEcho(t, c.method+" "+c.path, r, "work,shared;") + } + r := w.do(t, http.MethodPost, "/api/store", w.keys["w"], c1Narrow("work,shared", "work"), + map[string]any{"category": "learnings", "title": "c1 echo write juliet", "content": "x"}) + if r.status != http.StatusOK { + t.Errorf("narrowed store: HTTP %d %s", r.status, r.raw) + } + c1WantEcho(t, "POST /api/store", r, "work,shared;work") + if r := w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], nil, nil); len(r.header.Values(handler.HeaderNarrowed)) != 0 { + t.Errorf("an unnarrowed answer carries %s: %v", handler.HeaderNarrowed, r.header.Values(handler.HeaderNarrowed)) + } +} + +// c1Strings reads a JSON string list. +func c1Strings(v any) []string { + list, _ := v.([]any) + out := make([]string, 0, len(list)) + for _, e := range list { + s, _ := e.(string) + out = append(out, s) + } + return out +} + +// TestC1WhoamiReportsTheWriteSideAndTheNarrowing: whoami grows write_scopes +// (the effective write set), confirm_writes, narrowed ({read, write} or +// null) and rate_limit_write (the write limit per 60 s that applies to the +// key: query.rate_limit_write after the tenant overlay). +func TestC1WhoamiReportsTheWriteSideAndTheNarrowing(t *testing.T) { + w := c1Setup(t) + whoami := func(key string, h http.Header) map[string]any { + t.Helper() + r := w.do(t, http.MethodGet, "/api/whoami", key, h, nil) + if r.status != http.StatusOK { + t.Fatalf("whoami: HTTP %d %s", r.status, r.raw) + } + return r.body + } + has := func(what string, body map[string]any, field string) bool { + t.Helper() + if _, ok := body[field]; !ok { + t.Errorf("%s: whoami has no %q", what, field) + return false + } + return true + } + + // Unnarrowed: the key's effective write set, home first. + b := whoami(w.keys["x"], nil) + if has("x unnarrowed", b, "write_scopes") && !slices.Equal(c1Strings(b["write_scopes"]), []string{"default:m", "default:k"}) { + t.Errorf("x unnarrowed: write_scopes %v, want [default:m default:k]", b["write_scopes"]) + } + if has("x unnarrowed", b, "confirm_writes") && b["confirm_writes"] != false { + t.Errorf("x unnarrowed: confirm_writes %v, want false", b["confirm_writes"]) + } + if has("x unnarrowed", b, "narrowed") && b["narrowed"] != nil { + t.Errorf("x unnarrowed: narrowed %v, want null", b["narrowed"]) + } + if has("x unnarrowed", b, "rate_limit_write") && b["rate_limit_write"] != float64(100) { + t.Errorf("x unnarrowed: rate_limit_write %v, want 100 (the default of query.rate_limit_write)", b["rate_limit_write"]) + } + + // Narrowed with a write scope: the write set is that scope alone. + b = whoami(w.keys["x"], c1Narrow("default:k", "default:k")) + if has("x narrowed", b, "write_scopes") && !slices.Equal(c1Strings(b["write_scopes"]), []string{"default:k"}) { + t.Errorf("x narrowed: write_scopes %v, want [default:k]", b["write_scopes"]) + } + if n, _ := b["narrowed"].(map[string]any); n == nil || !slices.Equal(c1Strings(n["read"]), []string{"default:k"}) || n["write"] != "default:k" { + t.Errorf("x narrowed: narrowed %v, want {read:[default:k], write:default:k}", b["narrowed"]) + } + + // Narrowed without a write scope: nothing writable, read in header order. + b = whoami(w.keys["w"], c1Narrow("shared,work")) + if has("w narrowed", b, "write_scopes") && len(c1Strings(b["write_scopes"])) != 0 { + t.Errorf("w narrowed read-only: write_scopes %v, want []", b["write_scopes"]) + } + if n, _ := b["narrowed"].(map[string]any); n == nil || !slices.Equal(c1Strings(n["read"]), []string{"shared", "work"}) || n["write"] != "" { + t.Errorf("w narrowed read-only: narrowed %v, want {read:[shared work], write:\"\"}", b["narrowed"]) + } + + // confirm_writes has no write path (it is set out of band). + if _, err := w.pool.Exec(context.Background(), `UPDATE context_api_keys SET confirm_writes = true WHERE label = 'c1-kw'`); err != nil { + t.Fatal(err) + } + if b = whoami(w.keys["kw"], nil); b["confirm_writes"] != true { + t.Errorf("kw with confirm_writes: confirm_writes %v, want true", b["confirm_writes"]) + } + + // The tenant overlay of query.rate_limit_write. + w.do(t, http.MethodPut, "/api/settings/query.rate_limit_write", w.keys["two"], nil, map[string]any{"value": 40}).must(t, "tenant overlay of query.rate_limit_write") + if r := w.do(t, http.MethodGet, "/api/settings/query.rate_limit_write", w.keys["two"], nil, nil).must(t, "read back the overlay"); !strings.Contains(r.raw, `"value":40`) { + t.Fatalf("fixture: tenant c1two reads back %s, want the overlay 40", r.raw) + } + if b = whoami(w.keys["two"], nil); b["rate_limit_write"] != float64(40) { + t.Errorf("tenant c1two with the overlay 40: rate_limit_write %v, want 40", b["rate_limit_write"]) + } + if b = whoami(w.keys["w"], nil); b["rate_limit_write"] != float64(100) { + t.Errorf("default tenant beside c1two's overlay: rate_limit_write %v, want 100", b["rate_limit_write"]) + } +} + +// TestC1NarrowedRequestIsNeverAnAdmin: under a narrowing the request is a +// member without the server-admin tier, whatever the key is — a narrowed +// request is never an administration request. +func TestC1NarrowedRequestIsNeverAnAdmin(t *testing.T) { + w := c1Setup(t) + r := w.do(t, http.MethodGet, "/api/whoami", c1AdminKey, nil, nil).must(t, "unnarrowed admin whoami") + if r.body["admin"] != true || r.body["role"] != "owner" { + t.Fatalf("fixture: the admin key reads admin %v role %v, want true owner", r.body["admin"], r.body["role"]) + } + r = w.do(t, http.MethodGet, "/api/whoami", c1AdminKey, c1Narrow("private"), nil) + if r.status != http.StatusOK || r.body["admin"] != false || r.body["role"] != "member" { + t.Errorf("narrowed admin whoami: HTTP %d admin %v role %v, want 200 false member", r.status, r.body["admin"], r.body["role"]) + } +} + +// TestC1ArchivedBlockOutsideTheNarrowingStaysHidden: the archive read of a +// narrowed request covers the named scopes that are the key's own, not every +// own scope — an archived block of an own scope the request does not name is +// not found. +func TestC1ArchivedBlockOutsideTheNarrowingStaysHidden(t *testing.T) { + w := c1Setup(t) + id := w.storeBlock(t, w.keys["w"], "shared", "c1 shared archived mike") + w.manage(t, w.keys["w"], nil, map[string]any{"action": "delete", "id": id}).must(t, "delete") + get := map[string]any{"action": "get", "id": id, "include_archived": true} + if r := w.manage(t, w.keys["w"], nil, get).must(t, "unnarrowed archive read"); r.body["success"] != true { + t.Fatalf("fixture: key w does not read its own archived block unnarrowed: %s", r.raw) + } + r := w.manage(t, w.keys["w"], c1Narrow("work"), get) + if r.status != http.StatusOK || r.body["success"] != false { + t.Errorf("archive read narrowed to work of a block in shared: HTTP %d %s, want not found", r.status, r.raw) + } + c1WantEcho(t, "narrowed archive read", r, "work;") +} + +// TestC1PinHomeScopeStaysTheKeys (green on the stubs): a narrowing with a +// grant scope first leaves the home scope the key's own — backend chain, +// quota, the archive read and the settings overlay hang on it. +func TestC1PinHomeScopeStaysTheKeys(t *testing.T) { + w := c1Setup(t) + r := w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c1Narrow(w.two+",work"), nil).must(t, "narrowed whoami") + if r.body["home_scope"] != "work" { + t.Errorf("narrowed whoami with the grant scope first: home_scope %v, want work", r.body["home_scope"]) + } +} + +// TestC1PinArchivedBlockOfAGrantScopeStaysHidden (green on the stubs): the +// archive read is limited to the key's own scopes; a narrowing that names a +// grant scope, first, does not make that scope the key's own. +func TestC1PinArchivedBlockOfAGrantScopeStaysHidden(t *testing.T) { + w := c1Setup(t) + get := map[string]any{"action": "get", "id": w.blocks["twoArchived"], "include_archived": true} + for _, h := range []http.Header{nil, c1Narrow(w.two), c1Narrow(w.two + ",work")} { + r := w.manage(t, w.keys["w"], h, get) + if r.status != http.StatusOK || r.body["success"] != false { + t.Errorf("get of an archived block of the grant scope (narrowing %v): HTTP %d %s, want not found", h, r.status, r.raw) + } + } + if r := w.manage(t, w.keys["two"], nil, get).must(t, "owner get"); r.body["success"] != true { + t.Fatalf("fixture: the owner does not read its own archived block: %s", r.raw) + } +} diff --git a/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go b/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go new file mode 100644 index 000000000..d1e4e1a4a --- /dev/null +++ b/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go @@ -0,0 +1,385 @@ +//go:build integration && s1red_c2 + +// Achse 02, cluster C-2 (design2/02-ctx-checkpoint.md §3.5 C-2, §7.3): a key +// can require narrowing (context_api_keys.scope_narrowing, migration 198). A +// required key answers every unnarrowed request with 403 +// scope_narrowing_required — reads, writes, /api/session/*, /mcp — except +// GET /api/whoami, which reports the column. Set through api-key-create and +// api-key-update (tenant-admin, like write_scopes); every existing key stays +// optional. Written in S1 before the column exists; the second build tag keeps +// the file out of every gate until C-2 lands. To enable, shorten the +// constraint line to `//go:build integration`. The narrowed positive case +// needs C-1 as well (integration order C-1, C-2). +// +// The HTTP tests drive the PRODUCTION router; the migration test follows the +// migration tests of internal/store (chain up to 197, seed, 198, assert). Its +// seed is plain SQL in the 197 shape: after C-2 the production key insert +// names the new column and cannot write a 197 database. +// +// go test -tags=integration,s1red_c2 -p 1 -count=1 -run '^TestC2' ./cmd/ctxd/ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/GottZ/ctx/internal/backends" + "github.com/GottZ/ctx/internal/blocktype" + "github.com/GottZ/ctx/internal/config" + "github.com/GottZ/ctx/internal/dispatch" + "github.com/GottZ/ctx/internal/events" + "github.com/GottZ/ctx/internal/handler" + "github.com/GottZ/ctx/internal/store" + "github.com/GottZ/ctx/internal/testdb" + "github.com/GottZ/ctx/migrations" +) + +// c2AdminKey is the bootstrap server-admin key (default tenant, owner). +const c2AdminKey = "c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0" + +type c2Resp struct { + status int + body map[string]any + header http.Header + raw string +} + +type c2World struct { + pool *pgxpool.Pool + router http.Handler +} + +func c2Setup(t *testing.T) *c2World { + t.Helper() + pool := testdb.SetupTestDB(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + applyEnv(t, map[string]string{}) + cc, issues := loadFromEnv() + if config.HasErrors(issues) { + t.Fatalf("env fixture invalid: %v", issues) + } + cfgStore := config.NewStore(cc) + backendPool := backends.NewPool(pool, nil) + scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) + projectHub := events.NewProjectHub(ctx, pool, cfgStore) + d := dispatch.New(nil, dispatch.DefaultSettings()) + t.Cleanup(d.Close) + scheduler.SetDispatcher(d) + if created, _, err := store.BootstrapAdminKey(ctx, pool, c2AdminKey, "c2-admin"); err != nil || !created { + t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) + } + return &c2World{pool: pool, router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d)} +} + +func (w *c2World) do(t *testing.T, method, path, key string, extra http.Header, body any) c2Resp { + t.Helper() + var rd io.Reader = http.NoBody + if body != nil { + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + rd = bytes.NewReader(b) + } + req := httptest.NewRequest(method, path, rd) + req.Header.Set("X-Context-Key", key) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + for k, vs := range extra { + for _, v := range vs { + req.Header.Add(k, v) + } + } + rec := httptest.NewRecorder() + w.router.ServeHTTP(rec, req) + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + return c2Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} +} + +func (w *c2World) manage(t *testing.T, key string, body map[string]any) c2Resp { + t.Helper() + return w.do(t, http.MethodPost, "/api/manage", key, nil, body) +} + +func (r c2Resp) must(t *testing.T, what string) c2Resp { + t.Helper() + if r.status != http.StatusOK || r.body["success"] == false { + t.Fatalf("fixture %s: HTTP %d %s", what, r.status, r.raw) + } + return r +} + +func (r c2Resp) code() string { + c, _ := r.body["code"].(string) + return c +} + +// mint creates a key through api-key-create as the admin and returns its +// plaintext and id; the answer's status is the caller's to judge. +func (w *c2World) mint(t *testing.T, data map[string]any) (c2Resp, string, string) { + t.Helper() + r := w.manage(t, c2AdminKey, map[string]any{"action": "api-key-create", "data": data}) + k, _ := r.body["api_key"].(string) + id, _ := r.body["id"].(string) + return r, k, id +} + +// scopeNarrowing is the scope_narrowing whoami reports for key ("" when the +// field is missing). +func (w *c2World) scopeNarrowing(t *testing.T, key string) string { + t.Helper() + r := w.do(t, http.MethodGet, "/api/whoami", key, nil, nil) + if r.status != http.StatusOK { + t.Errorf("whoami: HTTP %d %s, want 200 (whoami stays open to a required key)", r.status, r.raw) + return "" + } + v, _ := r.body["scope_narrowing"].(string) + return v +} + +// c2Unnarrowed are the unnarrowed requests a required key is refused: reads, +// a write, a manage read, the session surface and /mcp. +func c2Unnarrowed(blockID string) []struct { + method, path string + body any + write string +} { + return []struct { + method, path string + body any + write string + }{ + {http.MethodPost, "/api/query", map[string]any{"query": "c2probe", "synthesize": false}, ""}, + {http.MethodPost, "/api/search", map[string]any{"query": "c2probe"}, ""}, + {http.MethodPost, "/api/store", map[string]any{"category": "learnings", "title": "c2 refused write", "content": "x"}, "c2 refused write"}, + {http.MethodPost, "/api/manage", map[string]any{"action": "get", "id": blockID}, ""}, + {http.MethodPost, "/api/recent", map[string]any{}, ""}, + {http.MethodGet, "/api/session/keys", nil, ""}, + {http.MethodPost, "/api/session/select-key", map[string]any{"api_key_id": "00000000-0000-0000-0000-000000000000"}, ""}, + {http.MethodPost, "/mcp", map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, ""}, + } +} + +// wantRequired checks every unnarrowed request of key is refused with +// scope_narrowing_required, and that the refused write wrote nothing (the +// mutant "required on reads only"). +func (w *c2World) wantRequired(t *testing.T, who, key, blockID string) { + t.Helper() + mcp := http.Header{} + mcp.Set("Accept", "application/json, text/event-stream") + for _, c := range c2Unnarrowed(blockID) { + var h http.Header + if c.path == "/mcp" { + h = mcp + } + r := w.do(t, c.method, c.path, key, h, c.body) + if r.status != http.StatusForbidden || r.code() != "scope_narrowing_required" { + t.Errorf("%s: unnarrowed %s %s: HTTP %d code %q, want 403 scope_narrowing_required (%s)", who, c.method, c.path, r.status, r.code(), strings.TrimSpace(r.raw)) + } + if c.write != "" { + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_blocks WHERE title = $1`, c.write).Scan(&n); err != nil || n != 0 { + t.Errorf("%s: the refused unnarrowed write wrote %d block(s) (err %v)", who, n, err) + } + } + } +} + +// TestC2RequiredKeyRefusesEveryUnnarrowedRequest: a key minted with +// scope_narrowing "required" is refused every unnarrowed request but whoami, +// which reports "required"; narrowed, it reads (C-1 echo). +func TestC2RequiredKeyRefusesEveryUnnarrowedRequest(t *testing.T) { + w := c2Setup(t) + r := w.do(t, http.MethodPost, "/api/store", c2AdminKey, nil, map[string]any{"category": "learnings", "title": "c2 shared block", "content": "c2probe", "scope": "shared"}).must(t, "store") + blk, _ := r.body["block"].(map[string]any) + blockID, _ := blk["id"].(string) + + r, key, _ := w.mint(t, map[string]any{"label": "c2-required", "home_scope": "work", "allowed_scopes": []string{"shared"}, "scope_narrowing": "required"}) + r.must(t, "api-key-create with scope_narrowing required") + if got, _ := r.body["scope_narrowing"].(string); got != "required" { + t.Errorf("api-key-create echoes scope_narrowing %q, want required", got) + } + if got := w.scopeNarrowing(t, key); got != "required" { + t.Errorf("whoami of the required key: scope_narrowing %q, want required", got) + } + w.wantRequired(t, "required key", key, blockID) + + h := http.Header{} + h.Set(handler.HeaderReadScopes, "shared") + n := w.do(t, http.MethodPost, "/api/search", key, h, map[string]any{"query": "c2probe"}) + if n.status != http.StatusOK || n.header.Get(handler.HeaderNarrowed) != "shared;" { + t.Errorf("narrowed search of the required key: HTTP %d echo %q, want 200 with echo \"shared;\" (%s)", n.status, n.header.Get(handler.HeaderNarrowed), n.raw) + } +} + +// TestC2KeyUpdateSwitchesTheRequirement: api-key-update turns the requirement +// on and off for an existing key. +func TestC2KeyUpdateSwitchesTheRequirement(t *testing.T) { + w := c2Setup(t) + _, key, id := w.mint(t, map[string]any{"label": "c2-switch", "home_scope": "work"}) + if key == "" || id == "" { + t.Fatal("fixture: api-key-create returned no key") + } + w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}).must(t, "optional key searches unnarrowed") + + r := w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "required"}}) + if r.status != http.StatusOK || r.body["success"] != true { + t.Fatalf("api-key-update scope_narrowing required: HTTP %d %s", r.status, r.raw) + } + if k, _ := r.body["key"].(map[string]any); k["scope_narrowing"] != "required" { + t.Errorf("api-key-update answers key %v, want scope_narrowing required", r.body["key"]) + } + if got := w.scopeNarrowing(t, key); got != "required" { + t.Errorf("whoami after the switch: scope_narrowing %q, want required", got) + } + s := w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}) + if s.status != http.StatusForbidden || s.code() != "scope_narrowing_required" { + t.Errorf("unnarrowed search after the switch: HTTP %d code %q, want 403 scope_narrowing_required", s.status, s.code()) + } + + w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "optional"}}).must(t, "switch back") + w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}).must(t, "optional again") +} + +// TestC2ScopeNarrowingValueIsChecked: a value other than optional and required +// is a 400 on create and update, and nothing is created or changed. +func TestC2ScopeNarrowingValueIsChecked(t *testing.T) { + w := c2Setup(t) + r, _, _ := w.mint(t, map[string]any{"label": "c2-bogus", "home_scope": "work", "scope_narrowing": "sometimes"}) + if r.status != http.StatusBadRequest { + t.Errorf("api-key-create scope_narrowing sometimes: HTTP %d %s, want 400", r.status, r.raw) + } + var n int + if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_api_keys WHERE label = 'c2-bogus'`).Scan(&n); err != nil || n != 0 { + t.Errorf("api-key-create with a bad value created %d key(s) (err %v)", n, err) + } + + _, key, id := w.mint(t, map[string]any{"label": "c2-keep", "home_scope": "work"}) + r = w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "sometimes"}}) + if r.status != http.StatusBadRequest { + t.Errorf("api-key-update scope_narrowing sometimes: HTTP %d %s, want 400", r.status, r.raw) + } + if got := w.scopeNarrowing(t, key); got != "optional" { + t.Errorf("whoami after the refused update: scope_narrowing %q, want optional", got) + } +} + +// TestC2KeysWithoutTheFieldStayOptional: a key minted without the field, and +// the bootstrap key, are optional and keep working unnarrowed. +func TestC2KeysWithoutTheFieldStayOptional(t *testing.T) { + w := c2Setup(t) + _, key, _ := w.mint(t, map[string]any{"label": "c2-plain", "home_scope": "work"}) + for who, k := range map[string]string{"plain key": key, "bootstrap admin": c2AdminKey} { + if got := w.scopeNarrowing(t, k); got != "optional" { + t.Errorf("%s: whoami scope_narrowing %q, want optional", who, got) + } + w.do(t, http.MethodPost, "/api/search", k, nil, map[string]any{"query": "c2probe"}).must(t, who+" searches unnarrowed") + } +} + +// c2Migration198 is the file name of migration 198, whatever C-2 calls it. +func c2Migration198(t *testing.T) string { + t.Helper() + files, err := fs.Glob(migrations.FS, "198_*.sql") + if err != nil { + t.Fatal(err) + } + if len(files) != 1 { + t.Fatalf("migration 198: %d file(s) %v in go/migrations, want exactly one", len(files), files) + } + return files[0] +} + +// c2Column describes context_api_keys.scope_narrowing: type, nullability and +// default ("" when the column does not exist). +func c2Column(t *testing.T, pool *pgxpool.Pool) string { + t.Helper() + var typ, nullable, def string + err := pool.QueryRow(context.Background(), `SELECT data_type, is_nullable, coalesce(column_default, '') + FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = 'context_api_keys' AND column_name = 'scope_narrowing'`).Scan(&typ, &nullable, &def) + if err != nil { + return "" + } + return typ + " nullable=" + nullable + " default=" + def +} + +// c2WantCheck pins the CHECK: a value outside the two is refused (23514). +func c2WantCheck(t *testing.T, pool *pgxpool.Pool, label string) { + t.Helper() + _, err := pool.Exec(context.Background(), `UPDATE context_api_keys SET scope_narrowing = 'sometimes' WHERE label = $1`, label) + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || pgErr.Code != "23514" { + t.Errorf("scope_narrowing = 'sometimes' on %s: err %v, want a CHECK violation (23514)", label, err) + } +} + +// TestC2Migration198 (design2/02 §3.5 C-2): context_api_keys.scope_narrowing +// TEXT NOT NULL DEFAULT 'optional' CHECK (optional|required), forward on a +// fresh and on a populated database; existing keys read optional, also +// through ctx_auth and ctx_auth_by_id, whose last column it is. +func TestC2Migration198(t *testing.T) { + ctx := context.Background() + const want = "text nullable=NO default='optional'::text" + file := c2Migration198(t) + + t.Run("fresh", func(t *testing.T) { + pool := testdb.SetupTestDB(t) + if got := c2Column(t, pool); got != want { + t.Fatalf("%s on a fresh database: column %q, want %q", file, got, want) + } + if _, _, err := store.CreateApiKey(ctx, pool, "c2-fresh", "work", nil, store.DefaultTenantID); err != nil { + t.Fatal(err) + } + c2WantCheck(t, pool, "c2-fresh") + }) + + t.Run("populated", func(t *testing.T) { + pool := testdb.SetupTestDBUpTo(t, 197) + const plain = "c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0" + sum := sha256.Sum256([]byte(plain)) + var keyID string + if err := pool.QueryRow(ctx, `WITH p AS (INSERT INTO context_principals (display_name) VALUES ('c2-old') RETURNING id) + INSERT INTO context_api_keys (label, key_hash, home_scope, allowed_scopes, active, tenant_id, tenant_role, principal_id) + SELECT 'c2-old', $1, 'private', '{shared}', true, $2::uuid, 'member', p.id FROM p + RETURNING id::text`, hex.EncodeToString(sum[:]), store.DefaultTenantID).Scan(&keyID); err != nil { + t.Fatalf("seed a 197 key: %v", err) + } + if err := store.RunMigrationsUpTo(ctx, pool, 198); err != nil { + t.Fatalf("run migrations up to 198: %v", err) + } + if got := c2Column(t, pool); got != want { + t.Fatalf("%s on a populated database: column %q, want %q", file, got, want) + } + var v string + if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM context_api_keys WHERE id = $1::uuid`, keyID).Scan(&v); err != nil || v != "optional" { + t.Errorf("the existing key reads %q (err %v), want optional", v, err) + } + if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM ctx_auth($1)`, plain).Scan(&v); err != nil || v != "optional" { + t.Errorf("ctx_auth: scope_narrowing %q (err %v), want optional", v, err) + } + if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM ctx_auth_by_id($1::uuid)`, keyID).Scan(&v); err != nil || v != "optional" { + t.Errorf("ctx_auth_by_id: scope_narrowing %q (err %v), want optional", v, err) + } + c2WantCheck(t, pool, "c2-old") + if err := store.RunMigrations(ctx, pool); err != nil { + t.Fatalf("run migrations again: %v", err) + } + }) +} diff --git a/go/internal/auth/auth.go b/go/internal/auth/auth.go index 64a5973d7..8e153ae90 100644 --- a/go/internal/auth/auth.go +++ b/go/internal/auth/auth.go @@ -47,8 +47,36 @@ type AuthResult struct { // sole authorisation decision. Achse 03 (token) and 05 (session) resolve // their AuthResult through the SAME ctx_auth_by_id(uuid) SQL sibling. PrincipalID string + // Narrowed is the request's per-request narrowing (Achse 02 C-1): nil for an + // unnarrowed request. Only the Auth middleware sets it, and only on the + // AuthResult it hands to the handlers; the request key that store writes + // recheck (store.WithRequestKey) stays the unnarrowed key's. + Narrowed *Narrowing + // ScopeNarrowing is the key's scope_narrowing column (Achse 02 C-2): + // ScopeNarrowingOptional or ScopeNarrowingRequired. "" reads as optional. + ScopeNarrowing string } +// Narrowing is a request's narrowing (Achse 02 C-1). Read is the read set of +// this request, in header order; Write is its write scope ("" = the request +// writes nothing); Writable is the write set handed to the block write gate +// ([Write] when the request has a write scope, else empty). A write scope the +// UNNARROWED key cannot write, or one outside Read, never gets here: the +// narrowing is refused (403 scope_denied) before an AuthResult carries it. +type Narrowing struct { + Read []string + Write string + Writable []string +} + +// The values of a key's scope_narrowing (Achse 02 C-2): an optional key may +// narrow a request, a required key answers nothing but GET /api/whoami +// without a narrowing. +const ( + ScopeNarrowingOptional = "optional" + ScopeNarrowingRequired = "required" +) + // SanitizeKey strips all non-hex characters from an API key. func SanitizeKey(raw string) string { return hexOnly.ReplaceAllString(raw, "") diff --git a/go/internal/handler/manage_table.go b/go/internal/handler/manage_table.go index 781aa8982..ea73930ab 100644 --- a/go/internal/handler/manage_table.go +++ b/go/internal/handler/manage_table.go @@ -437,6 +437,15 @@ func (h *ManageHandler) handleManage(w http.ResponseWriter, r *http.Request, act return } + // Per-request narrowing (Achse 02 C-1, BP-25): the route rule lives in the + // Auth middleware, which must not read the body; the action rule is + // checked here, on the ONE decoded req.Action the dispatch below uses — + // never on a second reading of the body. + if authResult.Narrowed != nil && !manageActionAllowedNarrowed(req.Action) { + writeNarrowingRouteRefused(w) + return + } + action, known := actions[req.Action] if !known { writeJSON(w, http.StatusBadRequest, map[string]any{ diff --git a/go/internal/handler/middleware.go b/go/internal/handler/middleware.go index 8705eb3d9..8137c8467 100644 --- a/go/internal/handler/middleware.go +++ b/go/internal/handler/middleware.go @@ -696,11 +696,22 @@ func Auth(pool *pgxpool.Pool) func(http.Handler) http.Handler { return } - ctx := context.WithValue(r.Context(), authResultKey, result) + // Per-request narrowing (Achse 02 C-1, narrowing.go): the handlers + // see the narrowed AuthResult; the request key below stays the + // key's own. + narrowed, rej := narrowAuth(r, result) + if rej != nil { + writeJSONReject(w, rej) + return + } + + ctx := context.WithValue(r.Context(), authResultKey, narrowed) // The request's key and the scopes it granted travel to every // write the request makes (issue #555, store.WithRequestKey): a // write whose key a tenant-delete removed, or took a scope from, - // while the request ran writes nothing. + // while the request ran writes nothing. Fed from the UNNARROWED + // result: a narrowing shrinks what the request may do, never what + // the recheck holds the key to. ctx = store.WithRequestKey(ctx, store.RequestKey{ ID: result.ApiKeyID, HomeScope: result.HomeScope, diff --git a/go/internal/handler/narrowing.go b/go/internal/handler/narrowing.go new file mode 100644 index 000000000..5a7736bbe --- /dev/null +++ b/go/internal/handler/narrowing.go @@ -0,0 +1,65 @@ +// Per-request scope narrowing (Achse 02, cluster C-1; design2/02 §3.5): a +// request names the scopes it reads (X-Context-Read-Scopes) and, optionally, +// the one scope it writes (X-Context-Write-Scope), and for that request the +// key's rights shrink to exactly these. The key's own scopes stay what the +// write recheck of issue #555 (store.WithRequestKey) checks against. +// +// S1 contract: the signatures below are fixed, the bodies are inert — the +// headers are ignored and every request runs unnarrowed, byte-identical to the +// tree before this file. C-1 fills them in; C-2 adds the required-narrowing +// check to narrowAuth. +package handler + +import ( + "net/http" + + "github.com/GottZ/ctx/internal/auth" +) + +// The narrowing headers. HeaderReadScopes carries 1 to 8 scopes, +// comma-separated, in the order the request reads them; HeaderWriteScope the +// one scope the request writes. HeaderNarrowed is the echo on the answer to a +// narrowed request: "<read scopes, comma-separated>;<write scope>". +const ( + HeaderReadScopes = "X-Context-Read-Scopes" + HeaderWriteScope = "X-Context-Write-Scope" + HeaderNarrowed = "X-Context-Narrowed" +) + +// codeScopeNarrowingRoute is the code of the refusal of a narrowed request on +// a route or /api/manage action outside the narrowing's closed list. It is not +// a rejectClass of errcode.go yet: a class there is closed vocabulary that +// docs/api.md and docs/mcp.md list (TestRejectClassesAreDocumented), and the +// documentation is C-1's. C-1 moves it into errcode.go next to its +// documentation. +const codeScopeNarrowingRoute = "scope_narrowing_route" + +// narrowAuth derives the AuthResult a request runs with from the key's +// AuthResult ar and the narrowing headers of r. It returns the AuthResult to +// hand to the handlers (ar itself when the request carries no narrowing) or a +// refusal the Auth middleware answers with. It never modifies ar. +// +// S1 stub: the headers are ignored, every request is unnarrowed. +func narrowAuth(r *http.Request, ar *auth.AuthResult) (*auth.AuthResult, *writeReject) { + return ar, nil +} + +// manageActionAllowedNarrowed reports whether a narrowed /api/manage request +// may run action — the one action the dispatcher decoded (BP-25). C-1: only +// "get" and "type-list". +// +// S1 stub: no request is narrowed yet, so the dispatcher never asks; every +// action is allowed. +func manageActionAllowedNarrowed(action string) bool { + return true +} + +// writeNarrowingRouteRefused answers a narrowed request whose route or manage +// action lies outside the narrowing's closed list: 403 with the house +// {"success":false,"error":…} envelope and the code scope_narrowing_route. +func writeNarrowingRouteRefused(w http.ResponseWriter) { + writeJSONCode(w, http.StatusForbidden, codeScopeNarrowingRoute, map[string]any{ + "success": false, + "error": "this route is not available to a narrowed request", + }) +} diff --git a/go/internal/store/api_keys.go b/go/internal/store/api_keys.go index b2da1d95f..7b50f770c 100644 --- a/go/internal/store/api_keys.go +++ b/go/internal/store/api_keys.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/pgxdb" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" @@ -91,7 +92,14 @@ func validateWriteScopes(homeScope string, allowedScopes, writeScopes []string) // RETURNING now carry tenant_role — additive vs v4.0.1 (whose create path // omitted the column and returned TenantRole==""); the column has existed since // 059, so this is SQL-only, NO migration. -func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role string) (ApiKey, string, error) { +// +// scopeNarrowing is the key's scope_narrowing (auth.ScopeNarrowingOptional or +// auth.ScopeNarrowingRequired, Achse 02). The S1 contract fixes the parameter +// so the keyset mint (C-3) can be built against it; the column arrives with +// migration 198 (C-2), and until then the value is not stored — every caller +// passes auth.ScopeNarrowingOptional, which is what the column's default will +// be. +func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role, scopeNarrowing string) (ApiKey, string, error) { if label == "" { return ApiKey{}, "", fmt.Errorf("api_keys: label is required") } @@ -190,7 +198,7 @@ func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, // it mints are exactly as before. Owner / quota-gated mints are separate paths // that pass their own role through the shared primitive. func CreateApiKey(ctx context.Context, pool *pgxpool.Pool, label, homeScope string, allowedScopes []string, tenantID string) (*ApiKey, string, error) { - key, plaintext, err := insertApiKeyTx(ctx, pool, label, homeScope, allowedScopes, nil, tenantID, "member") + key, plaintext, err := insertApiKeyTx(ctx, pool, label, homeScope, allowedScopes, nil, tenantID, "member", auth.ScopeNarrowingOptional) if err != nil { return nil, "", err } @@ -267,7 +275,7 @@ func MintKeyWithQuota(ctx context.Context, pool *pgxpool.Pool, label, homeScope } var err error - key, plaintext, err = insertApiKeyTx(ctx, tx, label, homeScope, allowedScopes, writeScopes, tenantID, role) + key, plaintext, err = insertApiKeyTx(ctx, tx, label, homeScope, allowedScopes, writeScopes, tenantID, role, auth.ScopeNarrowingOptional) return err }); err != nil { return ApiKey{}, "", err @@ -301,7 +309,7 @@ func MintOwnerKey(ctx context.Context, q pgxdb.Rower, label, homeScope string, a // Owner keys mint with empty write_scopes (nil): an owner's home_scope IS the // tenant's first scope and covers the bootstrap corpus; explicit write_scopes // are a later, per-key concern via api-key-update. - return insertApiKeyTx(ctx, q, label, homeScope, allowedScopes, nil, tenantID, "owner") + return insertApiKeyTx(ctx, q, label, homeScope, allowedScopes, nil, tenantID, "owner", auth.ScopeNarrowingOptional) } // ListApiKeys returns API key rows ordered by created_at desc, scoped to one diff --git a/go/internal/store/api_keys_insert_test.go b/go/internal/store/api_keys_insert_test.go index 0d8ebd20a..dfcaeb8dd 100644 --- a/go/internal/store/api_keys_insert_test.go +++ b/go/internal/store/api_keys_insert_test.go @@ -4,6 +4,8 @@ import ( "context" "strings" "testing" + + "github.com/GottZ/ctx/internal/auth" ) // insertApiKeyTx is the shared INSERT primitive behind CreateApiKey (and the @@ -36,7 +38,7 @@ func TestInsertApiKeyTx_ValidationOwnedByPrimitive(t *testing.T) { {"reserved allowed_scope", "lbl", "tenant-a", []string{"shared", "_x"}, "reserved"}, } for _, c := range cases { - _, _, err := insertApiKeyTx(ctx, nil, c.label, c.homeScope, c.allowed, nil, "", role) + _, _, err := insertApiKeyTx(ctx, nil, c.label, c.homeScope, c.allowed, nil, "", role, auth.ScopeNarrowingOptional) if err == nil { t.Errorf("role=%s %s: expected error, got nil", role, c.name) continue diff --git a/go/internal/store/api_keys_write_scopes_test.go b/go/internal/store/api_keys_write_scopes_test.go index 8b20387b1..7eac6e831 100644 --- a/go/internal/store/api_keys_write_scopes_test.go +++ b/go/internal/store/api_keys_write_scopes_test.go @@ -5,6 +5,8 @@ import ( "errors" "strings" "testing" + + "github.com/GottZ/ctx/internal/auth" ) // validateWriteScopes is the mint/update-time half of the 078 write_scopes invariant @@ -56,7 +58,7 @@ func TestValidateWriteScopes(t *testing.T) { // would fall through to q.QueryRow(nil) and panic. func TestInsertApiKeyTx_RejectsBlindWriterBeforeDB(t *testing.T) { ctx := context.Background() - _, _, err := insertApiKeyTx(ctx, nil, "lbl", "private", []string{"shared"}, []string{"work"}, "", "member") + _, _, err := insertApiKeyTx(ctx, nil, "lbl", "private", []string{"shared"}, []string{"work"}, "", "member", auth.ScopeNarrowingOptional) if !errors.Is(err, ErrWriteScopeNotAllowed) { t.Fatalf("insertApiKeyTx blind-writer err = %v, want ErrWriteScopeNotAllowed", err) } diff --git a/go/internal/store/provision.go b/go/internal/store/provision.go index 2dac1ac3a..e3373854c 100644 --- a/go/internal/store/provision.go +++ b/go/internal/store/provision.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" + "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/backends" "github.com/GottZ/ctx/internal/pgxdb" "github.com/jackc/pgx/v5" @@ -184,7 +185,7 @@ func ProvisionProject(ctx context.Context, pool *pgxpool.Pool, p ProvisionParams // (NON-NIL empty: no '{shared}' inheritance), write = [] (NON-NIL empty). The // role is 'member' (agents never own). This is the verbindlicher Vertrag §5.5. agentKey, agentPlain, err := insertApiKeyTx(ctx, tx, - p.Slug+agentKeyLabelSuffix, p.Scope, []string{}, []string{}, tn.ID, "member") + p.Slug+agentKeyLabelSuffix, p.Scope, []string{}, []string{}, tn.ID, "member", auth.ScopeNarrowingOptional) if err != nil { return err } From 4ee3407ea3f97946f50933cba6a66ad623d2f2c1 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 01:33:42 +0100 Subject: [PATCH 03/65] =?UTF-8?q?chore(ctx=5Fcheckpoint):=20S2=20P-A=20?= =?UTF-8?q?=E2=80=94=20a=20narrowed=20ctx=20client=20sends=20its=20scopes?= =?UTF-8?q?=20on=20every=20call,=20takes=20an=20answer=20only=20with=20the?= =?UTF-8?q?=20server's=20echo,=20and=20a=20binding=20is=20proven=20by=20ra?= =?UTF-8?q?w=20whoami=20answers=20each=20binding=20judges=20itself?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Design 02 §4.5 and §7.3 row P-A, built against the S1 contract and fakes. CtxClient(narrowing=...) sends X-Context-Read-Scopes and X-Context-Write-Scope on every call, takes a 2xx answer only with the matching X-Context-Narrowed echo and is off for good after one without (code narrowing_lost); answers outside 2xx keep their own code. narrowing.whoami_raw keeps raw whoami answers per (base URL, key digest, header set), 60 s after a success and 15 s after a failure, within the caller's budget; callers that miss it together ask once, and only answers of the server are remembered. evaluate judges E2 to E5 and E7 per binding, so a proof never carries one group's verdict to another (BP-21); a restricted group is proven through its read narrowing. get_blocks reads up to 16 blocks with one multi-id get and falls back to one get per id on a server without it, in the order asked or not at all, with the key redacted from the entries of blocks it cannot have. Without a narrowing the client sends and reads what 0.19.1 did. The cluster's red S1 tests are switched on; 49 tests added for the probes S1 did not state and for the findings of a fresh review. Typed chore, not feat: the user-facing docs come with P-F; the integrator's squash carries the type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/client.py | 161 ++++++- .../plugin/ctx_checkpoint/memory/narrowing.py | 279 +++++++++++- .../ctx_checkpoint/tests/fakes/s1_pending.py | 1 - .../tests/test_access_pa_client.py | 429 ++++++++++++++++++ 4 files changed, 843 insertions(+), 27 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py index d1c08651d..ec552e16e 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py @@ -15,9 +15,15 @@ - Write rejections carry a machine-readable ``"code"`` next to ``"error"`` (``handler/errcode.go``, Gap-C6-c) → ``CtxApiError.code`` - ``GET /api/whoami`` — key/scope validation -- ``POST /api/manage`` body: ``{"action": "get", "data": {"id": ...}}`` — full block +- ``POST /api/manage`` body: ``{"action": "get", "data": {"id": ...}}`` — full block; with the multi-id + get (ctx C-4) ``{"action": "get", "ids": [...]}`` → ``{"success", "blocks": [block | {"id", "code", + "error"}]}`` in the order asked Auth: ``X-Context-Key: <key>`` (alternative ``Authorization: Bearer``). + +Narrowing (access groups, design 02 §3.5 C-1): a narrowed client sends ``X-Context-Read-Scopes`` +(and ``X-Context-Write-Scope``) on every call and takes a successful answer only with the echo +``X-Context-Narrowed: <read,...>;<write>``; a client without a narrowing sends neither. """ from __future__ import annotations @@ -36,13 +42,14 @@ from collections.abc import Mapping, Sequence from typing import Any -from .narrowing import Narrowing +from .narrowing import HEADER_NARROWED, Narrowing, key_digest logger = logging.getLogger(__name__) # Closed rejection vocabulary of the CTX write surfaces (GottZ/ctx -# go/internal/handler/errcode.go, rejectClass table; docs/api.md "/api/blob/*"). +# go/internal/handler/errcode.go, rejectClass table; docs/api.md "/api/blob/*") and of per-request +# scope narrowing (design 02 §3.5 C-1, C-2). REJECT_CODES = ( "unauthorized", "invalid_body", @@ -50,6 +57,9 @@ "invalid_sensitivity", "invalid_encoding", "scope_denied", + "scope_narrowing_invalid", + "scope_narrowing_route", + "scope_narrowing_required", "size_cap", "unknown_type", "reserved_type", @@ -80,6 +90,20 @@ "CTX base URL refused before any connection: it carries user info, a query or a fragment, which the " "ctx API does not take; set it to the server address alone (https://host[:port]) and the key in CTX_KEY" ) +# The code of a narrowed client's error once an answer came without the right X-Context-Narrowed echo +# (a proxy dropped the narrowing headers, or ctx does not narrow). The client is off from then on. +NARROWING_LOST = "narrowing_lost" +NARROWING_LOST_TEXT = ( + "ctx narrowing lost: a successful answer did not carry the X-Context-Narrowed echo of the narrowing " + "this client sends; the client sends nothing more" +) +# The most ids one multi-id get carries (ctx C-4; base blocks are at most 16, design 02 §3.1). +MAX_GET_IDS = 16 +# Refusals of a request's narrowing itself (design 02 §3.5 C-1, C-2): they hold for every id of a +# ``get_blocks`` call alike, so the call raises them instead of listing them per id. +NARROWING_REFUSALS = frozenset( + {"scope_denied", "scope_narrowing_invalid", "scope_narrowing_route", "scope_narrowing_required"} +) class _RefuseRedirect(urllib.request.HTTPRedirectHandler): @@ -264,6 +288,13 @@ def _urlopen(req: urllib.request.Request, *, timeout: float) -> Any: return _OPENER.open(req, timeout=timeout) +def _echo_matches(resp: Any, narrowing: Narrowing) -> bool: + """Does an answer carry exactly one ``X-Context-Narrowed`` header, equal to the echo of + *narrowing* (``<read,...>;<write>``)? The value received is never shown anywhere.""" + values = resp.headers.get_all(HEADER_NARROWED) or [] + return len(values) == 1 and values[0].strip() == narrowing.echo() + + def redact_secret(text: Any, secret: str | None) -> str: """``text`` with every exact occurrence of ``secret`` replaced by ``[REDACTED]``. @@ -363,6 +394,20 @@ def store_action(resp: dict[str, Any]) -> str: return "stored" if resp.get("success") else "unknown" +def _in_order(asked: Sequence[str], entries: Sequence[Any]) -> list[Mapping[str, Any]]: + """The entries of a multi-id get, checked to answer *asked* one by one in order: one object per + id whose ``id`` is the id asked or, for a block found by an id prefix, starts with it (ids + compared without case). Anything else raises: a list that does not line up is never returned.""" + if len(entries) != len(asked): + raise CtxApiError("get: the answer does not list one entry per id asked") + out: list[Mapping[str, Any]] = [] + for wanted, entry in zip(asked, entries, strict=True): + if not isinstance(entry, dict) or not str(entry.get("id") or "").lower().startswith(wanted.lower()): + raise CtxApiError("get: an entry of the answer does not answer the id asked at its place") + out.append(entry) + return out + + def store_block_id(resp: dict[str, Any]) -> str: if not isinstance(resp, dict): return "" @@ -397,12 +442,38 @@ def __init__( self._key = api_key self._timeout = timeout self._synthesis_timeout = synthesis_timeout - # Per-request scope narrowing (access groups): sent with every call and checked against the - # server's echo on every answer (CtxApiError code "narrowing_lost"). S1: kept, not yet sent. + # Per-request scope narrowing (access groups, design 02 §4.5): the same headers on every call, + # fixed for the client's life, and the server's echo checked on every successful answer. Once + # an answer lacks the right echo the client is off for good (``narrowing_lost``). self._narrowing = narrowing + self._narrowing_lost = False # The server registry's type names (``query_types``), read once per client. self._type_names: frozenset[str] | None = None + @property + def base_url(self) -> str: + """The base URL requests go to (no trailing slash).""" + return self._base + + @property + def key_digest(self) -> str: + """The key as caches may name it (:func:`narrowing.key_digest`), never the key itself.""" + return key_digest(self._key) + + @property + def narrowing(self) -> Narrowing | None: + """The narrowing this client sends, ``None`` for an unnarrowed client.""" + return self._narrowing + + @property + def narrowing_lost(self) -> bool: + """True once an answer came without the right echo: the client sends nothing more.""" + return self._narrowing_lost + + def narrowing_lost_error(self) -> CtxApiError: + """The error every call of a client that lost its narrowing raises, before any connection.""" + return CtxApiError(NARROWING_LOST_TEXT, code=NARROWING_LOST) + # -- low-level ----------------------------------------------------------- def _redact(self, text: Any) -> str: @@ -433,16 +504,30 @@ def _http_failure(self, exc: urllib.error.HTTPError) -> CtxApiError: return CtxApiError(message, status=exc.code, code=code) def _request( - self, method: str, path: str, payload: dict[str, Any] | None = None, timeout: float | None = None + self, + method: str, + path: str, + payload: dict[str, Any] | None = None, + timeout: float | None = None, + *, + unnarrowed: bool = False, ) -> dict[str, Any]: + """One call. A narrowed client sends its narrowing headers (``unnarrowed``: not, for the + unnarrowed ``whoami`` of a proof) and takes a successful answer only with the matching + ``X-Context-Narrowed`` echo; answers outside 2xx carry none and keep their own error.""" if self._url_refused: raise CtxApiError(BASE_URL_REFUSED) + if self._narrowing_lost: + raise self.narrowing_lost_error() + narrowing = None if unnarrowed else self._narrowing url = f"{self._base}{path}" headers = { "X-Context-Key": self._key, "Content-Type": "application/json", "Accept": "application/json", } + if narrowing is not None: + headers.update(narrowing.headers()) data = json.dumps(payload).encode("utf-8") if payload is not None else None req = urllib.request.Request(url, data=data, headers=headers, method=method) # noqa: S310 — http(s) only, see __init__ t = timeout if timeout is not None else self._timeout @@ -456,6 +541,13 @@ def _request( failure: CtxApiError | None = None try: with _urlopen(req, timeout=t) as resp: + if narrowing is not None and not _echo_matches(resp, narrowing): + # The server or a proxy on the way answered without the narrowing: whatever + # the body holds is discarded unread, and the client is off from now on. + self._narrowing_lost = True + raise CtxApiError( + f"{NARROWING_LOST_TEXT} ({method} {path})", status=resp.status, code=NARROWING_LOST + ) raw = resp.read().decode("utf-8", "replace") try: parsed = json.loads(raw) @@ -516,8 +608,10 @@ def _request( # -- API ------------------------------------------------------------- - def whoami(self) -> dict[str, Any]: - return self._request("GET", "/api/whoami") + def whoami(self, timeout: float | None = None, *, unnarrowed: bool = False) -> dict[str, Any]: + """``unnarrowed``: the same key without the narrowing headers (the unnarrowed half of a + proof, ``narrowing.whoami_raw``; a key that requires narrowing answers ``whoami`` either way).""" + return self._request("GET", "/api/whoami", timeout=timeout, unnarrowed=unnarrowed) def query( self, @@ -644,5 +738,52 @@ def get_blocks(self, ids: Sequence[str], timeout: float | None = None) -> list[M """The blocks *ids* (1 to 16), in order, with one ``get`` carrying ``ids`` (ctx with the multi-id get); against a server that answers that with 400, one ``get`` per id within the same bound. A block that cannot be had is an entry with ``error`` (and ``code``), never an - exception for the whole call; a transient failure raises. S1 stub: no blocks.""" - return [] + exception for the whole call; a transient failure raises, and so does an answer that does + not list one entry per id in the order asked — never a partial list. No ids: no request; + more than 16: ``ValueError`` before any request.""" + asked = [str(block_id) for block_id in ids] + if not asked: + return [] + if len(asked) > MAX_GET_IDS or not all(block_id.strip() for block_id in asked): + raise ValueError(f"get_blocks takes 1 to {MAX_GET_IDS} ids, none of them empty") + end = _monotonic() + (timeout if timeout is not None else self._timeout) + try: + answer = self._request("POST", "/api/manage", {"action": "get", "ids": asked}, timeout=timeout) + except CtxApiError as exc: + if exc.status != 400 or exc.code in NARROWING_REFUSALS: + raise + # ctx without the multi-id get reads no ``id`` and refuses the call with 400. + return _in_order(asked, [self._get_one_entry(block_id, end) for block_id in asked]) + listed = answer.get("blocks") if isinstance(answer, dict) else None + if is_failure_envelope(answer) or not isinstance(listed, list): + code = response_code(answer) + if code not in REJECT_CODES: + code = self._redact(code) # an answer with success: true is not redacted by _request + raise CtxApiError(f"get: the answer lists no blocks{f' [{code}]' if code else ''}", code=code) + # An entry for a block ctx cannot give is a failure of its own: its texts are redacted like a + # failure envelope's (the single-get fallback gets that from ``_request``); blocks stay as read. + return [redact_deep(entry, self._key) if "error" in entry else entry for entry in _in_order(asked, listed)] + + def _get_one_entry(self, block_id: str, end: float) -> Mapping[str, Any]: + """One id of :meth:`get_blocks` against ctx without the multi-id get, within the call's bound: + the block, or an entry with ``id``, ``code`` and ``error`` for an id ctx cannot give (not + found, out of reach, a malformed id: 200 without the block or 400).""" + left = end - _monotonic() + if left <= 0: + raise CtxApiError("connection error: timed out") # what the bound ends a call with + try: + answer = self._request("POST", "/api/manage", {"action": "get", "id": block_id}, timeout=left) + except CtxApiError as exc: + if exc.status != 400 or exc.code in NARROWING_REFUSALS: + raise + return {"id": block_id, "code": exc.code or "invalid_id", "error": str(exc)} + block = answer.get("block") if isinstance(answer, dict) else None + if not is_failure_envelope(answer) and isinstance(block, dict): + return block + if is_failure_envelope(answer) and isinstance(answer, dict): + return { + "id": block_id, + "code": response_code(answer) or "not_found", + "error": str(answer.get("error") or "block not found")[:300], + } + raise CtxApiError("get: the answer carries no block") diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py index cb727351b..679c0fef8 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py @@ -1,20 +1,20 @@ -"""Per-request scope narrowing on the client side and the proof of a group binding (contract, S1). +"""Per-request scope narrowing on the client side and the proof of a group binding (design 02 §4.5). A narrowed client sends ``X-Context-Read-Scopes`` (and ``X-Context-Write-Scope``) on every call and expects the server's echo ``X-Context-Narrowed: <read,...>;<write>`` on every answer. A binding is proven by ``whoami`` answers: one narrowed, and for restricted groups one unnarrowed of the same key. Only the raw answers are remembered (per base URL, key digest and header set: 60 s after success, 15 s after failure); every binding evaluates the rules E2 to E5 and E7 itself, so a proof for one -group never satisfies another's stricter expectation. - -S1 state: the data forms are final, the functions are inert stubs (nothing calls them yet). The -client cluster (P-A) fills them in. +group never satisfies another's stricter expectation (BP-21). """ from __future__ import annotations +import copy import hashlib -from collections.abc import Mapping +import threading +import time +from collections.abc import Iterable, Mapping from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -30,6 +30,20 @@ PROOF_TTL_FAILED_S = 15.0 # The ctx label column is VARCHAR(100); a longer label hashes the profile part. LABEL_MAX = 100 +# The proof store drops expired answers whenever it has grown to this many entries, and then again +# at twice the entries left: it never holds much more than the (URL, key, header set) triples asked +# in the last minute, at the cost of one pass per doubling. +PROOF_PRUNE_MIN = 256 + +# E7 (design 02 §3.3): the core toolsets that read files or run commands (hermes-agent +# ``tools/toolsets.py``) and the prefix of the bundles that contain them (``hermes-*``). +E7_FILE_TOOLSETS = frozenset({"terminal", "file", "code_execution", "debugging", "delegation"}) +E7_BUNDLE_PREFIX = "hermes-" +# The names of ``.env`` variables that hold a ctx key (design 02 §3.1 ``key``): the profile's +# standard key and every ``CTX_KEY_<...>``. For E7 every one of them but the server's own +# ``CTX_KEY_<scope_id>_<...>`` is a foreign key a file tool could read. +_STANDARD_KEY_NAMES = frozenset({"CTX_KEY", "CTX_API_KEY"}) +_KEY_NAME_PREFIXES = ("CTX_KEY_", "CTX_API_KEY_") @dataclass(frozen=True) @@ -91,25 +105,258 @@ def key_digest(api_key: str) -> str: def expected_label(platform: str, scope_id: str, profile: str) -> str: """The label a restricted group's key carries (E4): ``hermes:<platform>:<scope_id>:<profile>``; past 100 characters ``#`` and 16 hex characters of SHA-256 of the profile name replace the - profile part. S1 stub: ``""``.""" - return "" + profile part. A label still longer than that (an unusually long platform or server id) fits no + key, so E4 fails for it.""" + label = f"hermes:{platform}:{scope_id}:{profile}" + if len(label) <= LABEL_MAX: + return label + return f"hermes:{platform}:{scope_id}:#{hashlib.sha256(str(profile).encode('utf-8')).hexdigest()[:16]}" + + +# -- proof store: raw whoami answers per (base URL, key digest, header set) ------------------------ + + +@dataclass(frozen=True) +class _Proof: + """One remembered ``whoami``: the raw answer, or the failure as (message, status, code).""" + + expires: float + answer: Mapping[str, Any] | None = None + failure: tuple[str, int | None, str] | None = None + + +_PROOFS: dict[tuple[str, str, str], _Proof] = {} +_PROOFS_LOCK = threading.Lock() +_next_prune = PROOF_PRUNE_MIN +# Slots whose whoami is on its way: the callers that find one wait for it instead of asking too. +_ASKING: dict[tuple[str, str, str], threading.Event] = {} + + +def _remember(slot: tuple[str, str, str], proof: _Proof) -> None: + global _next_prune + with _PROOFS_LOCK: + _PROOFS[slot] = proof + if len(_PROOFS) >= _next_prune: + now = time.monotonic() + for stale in [s for s, p in _PROOFS.items() if p.expires <= now]: + del _PROOFS[stale] + _next_prune = max(PROOF_PRUNE_MIN, 2 * len(_PROOFS)) def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping[str, Any]: """The raw ``whoami`` answer of *client* (narrowed: with its headers; else the same key without - them), from the proof store or the server within *budget_s*; a failure is remembered 15 s and - raised as ``CtxApiError``. S1 stub: an empty answer.""" - return {} + them), from the proof store or the server within *budget_s* (the call's whole bound, its one + 429 retry included); a failure is remembered 15 s and raised as ``CtxApiError``. + The store is a state of the credentials, not of a binding: its slot is (base URL, key digest, + header set), so every binding with the same key and narrowing reads the same raw answer and + judges it itself (:func:`evaluate`). Callers that miss the store together ask once: the others + wait for that answer within their own budget. Only answers of the server are remembered: a client + that is off after a lost narrowing refuses without asking, and a budget used up before the call + is the caller's; neither touches the store. ``ValueError`` for a narrowed proof of a client + without a narrowing.""" + from .client import NARROWING_LOST, CtxApiError, is_failure_envelope, response_code -def evaluate(raw_narrowed: Mapping[str, Any], raw_unnarrowed: Mapping[str, Any] | None, expect: Expect) -> VerifyResult: - """E2 to E5 and E7 over raw answers, pure, without network. S1 stub: not proven.""" - return VerifyResult(ok=False, failed=("E5",), detail={"E5": "narrowing is not available"}) + narrowing = client.narrowing + if narrowed and narrowing is None: + raise ValueError("a narrowed proof needs a client built with a narrowing") + if client.narrowing_lost: + raise client.narrowing_lost_error() + slot = (client.base_url, client.key_digest, narrowing.echo() if narrowed and narrowing else "") + deadline = time.monotonic() + budget_s + while True: + with _PROOFS_LOCK: + proof = _PROOFS.get(slot) + fresh = proof is not None and proof.expires > time.monotonic() + asking = None if fresh else _ASKING.get(slot) + if not fresh and asking is None: + asking = _ASKING[slot] = threading.Event() + break + if fresh: + if proof.failure is not None: + message, status, code = proof.failure + raise CtxApiError(message, status=status, code=code) + return copy.deepcopy(dict(proof.answer or {})) + left = deadline - time.monotonic() + if left <= 0 or not asking.wait(left): + raise CtxApiError("connection error: timed out") # this caller's budget, not the server's answer + try: + if budget_s <= 0: + raise CtxApiError("connection error: timed out") # nothing sent, nothing remembered + try: + answer = client.whoami(timeout=budget_s, unnarrowed=not narrowed) + if is_failure_envelope(answer): + error = answer.get("error") if isinstance(answer, dict) else None + raise CtxApiError( + f"whoami answered no identity: {str(error or 'no answer')[:300]}", code=response_code(answer) + ) + except CtxApiError as exc: + # A refusal of the client itself (another thread lost the narrowing meanwhile) carries no + # status; an answer without the echo carries the answer's status and is remembered. + if not (exc.code == NARROWING_LOST and exc.status is None): + failure = (str(exc), exc.status, exc.code) + _remember(slot, _Proof(expires=time.monotonic() + PROOF_TTL_FAILED_S, failure=failure)) + raise + _remember(slot, _Proof(expires=time.monotonic() + PROOF_TTL_OK_S, answer=copy.deepcopy(dict(answer)))) + return copy.deepcopy(dict(answer)) + finally: + with _PROOFS_LOCK: + _ASKING.pop(slot, None) + asking.set() def reset_proofs() -> None: - """Forget every remembered ``whoami`` answer (tests, ``access check``). S1 stub: no-op.""" - return None + """Forget every remembered ``whoami`` answer (tests, ``access check``).""" + global _next_prune + with _PROOFS_LOCK: + _PROOFS.clear() + _next_prune = PROOF_PRUNE_MIN + + +# -- the rules, pure ------------------------------------------------------------------------------ + + +def _scopes(value: Any) -> tuple[str, ...] | None: + """A list of scope names as a tuple, ``None`` when it is not a list of strings.""" + if not isinstance(value, list) or not all(isinstance(item, str) for item in value): + return None + return tuple(value) + + +def _foreign_keys(env_names: Iterable[str], scope_id: str) -> list[str]: + """The ctx key variables of *env_names* that are not the server's own key: every one but a single + ``CTX_KEY_<scope_id>_...`` (the profile's key for this server). A second variable of the same + server belongs to another profile (or is a leftover of a renamed one), so then all of them count.""" + own = f"CTX_KEY_{str(scope_id).upper()}_" + keys = [ + str(name) for name in env_names if str(name) in _STANDARD_KEY_NAMES or str(name).startswith(_KEY_NAME_PREFIXES) + ] + mine = [name for name in keys if name.startswith(own)] + return keys if len(mine) > 1 else [name for name in keys if not name.startswith(own)] + + +def evaluate(raw_narrowed: Mapping[str, Any], raw_unnarrowed: Mapping[str, Any] | None, expect: Expect) -> VerifyResult: + """E2 to E5 and E7 over raw answers, pure, without network (design 02 §3.3). + + E5 (every binding): the narrowed answer reports exactly the narrowing sent. E2: the tenant, when + expected, in every answer; restricted (``strict``) also ``admin: false``, ``role: member`` and + ``scope_narrowing: required`` in the unnarrowed answer (a narrowed answer always reports member and + no admin). E3: the group's write scope is the key's home; restricted also the key's write set + exactly ``{write}``, its unnarrowed read set exactly ``read ∪ {write}`` and ``confirm_writes`` + off; unrestricted the read set within the key's. E4: the label, when expected, and always for + restricted groups. E7 (restricted): no foreign ctx key in the ``.env`` while the platform's + toolsets read files or run commands. Restricted groups need an unnarrowed answer that reports no + narrowing (and is of the same key, when both answers name it); without one E2 to E4 fail. A + missing or malformed field fails its rule. + + A restricted group is proven through its read narrowing, ``Narrowing(read=<group read>)`` without + a write scope, with ``write`` naming the group's write scope (a strict expectation that carries a + narrowing with a write scope fails E3: E3 needs the group's read set, which a write client's + narrowing does not carry). The write and the store client of a binding prove their own narrowing + with ``strict=False`` (E5, and E3's home scope for the write client) next to that group proof.""" + broken: dict[str, list[str]] = {} + + def fail(rule: str, text: str) -> None: + broken.setdefault(rule, []).append(text) + + narrowed = raw_narrowed if isinstance(raw_narrowed, Mapping) else {} + unnarrowed = raw_unnarrowed if isinstance(raw_unnarrowed, Mapping) else None + read = tuple(expect.narrowing.read) + write = expect.write + answers = [narrowed] if unnarrowed is None else [narrowed, unnarrowed] + + # E5: the narrowing the server applied is the one sent. + applied = narrowed.get("narrowed") + if not isinstance(applied, Mapping): + fail("E5", "the narrowed whoami reports no narrowing (ctx without per-request narrowing)") + else: + if _scopes(applied.get("read")) != read: + fail("E5", f"narrowed read scopes {','.join(read)}") + if applied.get("write") != (expect.narrowing.write or ""): + fail("E5", f"narrowed write scope {expect.narrowing.write or '(none)'}") + + # The unnarrowed answer of a restricted group must be one: E2 to E4 judge the key itself. + key_answer: Mapping[str, Any] | None = unnarrowed + if expect.strict and ( + unnarrowed is None + or "narrowed" not in unnarrowed + or unnarrowed.get("narrowed") is not None + or _other_key(narrowed, unnarrowed) + ): + missing = "an unnarrowed whoami of the key" + fail("E2", missing) + fail("E3", missing) + fail("E4", missing) + key_answer = None + + # E2: tenant, and for restricted groups no admin, member role, narrowing required. + if expect.tenant is None: + if expect.strict: + fail("E2", "a tenant for the group") + elif any(answer.get("tenant_slug") != expect.tenant for answer in answers): + fail("E2", f"tenant {expect.tenant}") + if expect.strict and key_answer is not None: + if key_answer.get("admin") is not False: + fail("E2", "admin false") + if key_answer.get("role") != "member": + fail("E2", "role member") + if key_answer.get("scope_narrowing") != "required": + fail("E2", "scope_narrowing required") + + # E3: the write scope is the key's home; restricted: the key's sets exactly the group's. + if write is None: + if expect.strict: + fail("E3", "a write scope for the group") + elif any(answer.get("home_scope") != write for answer in answers): + fail("E3", f"home scope {write}") + if expect.strict: + if expect.narrowing.write is not None: + fail("E3", "the group proven through its read narrowing (no write scope in it)") + if write is not None and write in read: + fail("E3", f"write scope {write} outside the read scopes") + if key_answer is not None and write is not None: + if _scopes(key_answer.get("write_scopes")) is None or set(key_answer["write_scopes"]) != {write}: + fail("E3", f"write scopes exactly {write}") + wanted = {*read, write} + if _scopes(key_answer.get("read_scopes")) is None or set(key_answer["read_scopes"]) != wanted: + fail("E3", f"read scopes exactly {','.join(sorted(wanted))}") + if key_answer.get("confirm_writes") is not False: + fail("E3", "confirm_writes false") + elif unnarrowed is not None: + known = _scopes(unnarrowed.get("read_scopes")) + if known is None or not set(read) <= set(known): + fail("E3", f"read scopes within the key's: {','.join(read)}") + + # E4: the label names the server and the serving profile. + if expect.label is None: + if expect.strict: + fail("E4", "a label for the key") + else: + labelled = [key_answer] if expect.strict else answers + if any(answer is not None and answer.get("label") != expect.label for answer in labelled): + fail("E4", f"label {expect.label}") + + # E7: no foreign ctx key in the profile's .env while its tools read files or run commands. + if expect.strict: + foreign = _foreign_keys(expect.env_names, expect.scope_id) + tools = [ + name + for name in expect.platform_toolsets + if name in E7_FILE_TOOLSETS or str(name).startswith(E7_BUNDLE_PREFIX) + ] + if foreign and tools: + fail("E7", f"no ctx key of another server or profile next to the toolsets {','.join(sorted(tools))}") + + if not broken: + return VerifyResult(ok=True) + failed = tuple(rule for rule in ("E2", "E3", "E4", "E5", "E7") if rule in broken) + return VerifyResult(ok=False, failed=failed, detail={rule: "; ".join(broken[rule]) for rule in failed}) + + +def _other_key(narrowed: Mapping[str, Any], unnarrowed: Mapping[str, Any]) -> bool: + """Do the two answers name different keys (``api_key_id``, when both carry one)?""" + one, two = narrowed.get("api_key_id"), unnarrowed.get("api_key_id") + return bool(one) and bool(two) and one != two __all__ = [ diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py index fc032c8d1..af4ee303d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -4,7 +4,6 @@ S1_PENDING = frozenset( { - "P-A", "P-B", "P-C", "P-D", diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py index 3f7d2a70f..ac19558dd 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py @@ -254,3 +254,432 @@ def test_get_blocks_falls_back_to_one_get_per_id_on_400(fake_ctx): blocks = client.get_blocks(ids) assert [b.get("title") for b in blocks] == ["b0", "b1", "b2"] assert fake_ctx.count("/api/manage", "get") == 1 + len(ids) + + +# -- S2 (P-A): the negative probes of design 02 §7.3 the S1 tests did not state -------------------- + + +def test_reject_vocabulary_has_the_narrowing_codes(): + """The server's narrowing refusals are codes of the closed vocabulary: kept verbatim, never retried.""" + for code in ("scope_denied", "scope_narrowing_invalid", "scope_narrowing_route", "scope_narrowing_required"): + assert code in _client.REJECT_CODES, code + + +@pytest.mark.s1_green +def test_client_without_narrowing_sends_the_headers_of_0_19_1(fake_ctx, monkeypatch): + """Guard: without a narrowing every request carries exactly the three headers it carried before.""" + _keys(fake_ctx) + sent = [] + original = _client._urlopen + + def spy(req, *, timeout): + sent.append(sorted(name.lower() for name, _ in req.header_items())) + return original(req, timeout=timeout) + + monkeypatch.setattr(_client, "_urlopen", spy) + client = CtxClient(fake_ctx.url, OPS_KEY, timeout=5) + client.search("rules") + client.whoami() + client.get_block("no-such-block") + client.query("rules") + assert len(sent) == 4 + assert all(names == ["accept", "content-type", "x-context-key"] for names in sent), sent + + +def test_after_narrowing_lost_the_client_sends_nothing_more(fake_ctx): + """D3 §3.3: an answer without the right echo is an error and the client is off from then on.""" + _keys(fake_ctx) + fake_ctx.echo_wrong = True + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError) as first: + client.search("rules") + assert first.value.code == "narrowing_lost" + text = str(first.value) + assert MEMBER_KEY not in text and "x;y" not in text, "the message names no key and no value it received" + fake_ctx.echo_wrong = False + asked = fake_ctx.count() + for call in (lambda: client.search("rules"), client.whoami, lambda: client.get_blocks(["any-id"])): + with pytest.raises(CtxApiError) as again: + call() + assert again.value.code == "narrowing_lost" + assert fake_ctx.count() == asked, "nothing is sent once the narrowing was lost" + + +def test_a_refusal_keeps_its_own_code_and_is_not_a_lost_narrowing(fake_ctx): + """Answers outside 2xx carry no echo (contract §5) and keep their own error; a 429 is retried.""" + _keys(fake_ctx) + outside = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(B,))) + with pytest.raises(CtxApiError) as caught: + outside.search("plans") + assert caught.value.code == "scope_denied" and caught.value.status == 403 + assert fake_ctx.requests()[-1].read_header == B + fake_ctx.throttle["/api/search"] = 1 + inside = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + assert inside.search("rules").get("success") is True, "a 429 without echo is retried, not lost" + + +def test_a_narrowed_proof_needs_a_narrowed_client(fake_ctx): + _keys(fake_ctx) + with pytest.raises(ValueError): + _nar.whoami_raw(CtxClient(fake_ctx.url, OPS_KEY, timeout=5), narrowed=True, budget_s=3) + assert fake_ctx.count() == 0 + + +def test_successful_proof_is_remembered_60_s_then_asked_again(fake_ctx, monkeypatch): + _keys(fake_ctx, narrowing="required") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + clock = [time.monotonic()] + monkeypatch.setattr(time, "monotonic", lambda: clock[0]) + first = _nar.whoami_raw(client, narrowed=True, budget_s=3) + clock[0] += _nar.PROOF_TTL_OK_S - 1 + assert _nar.whoami_raw(client, narrowed=True, budget_s=3) == first + assert fake_ctx.count("/api/whoami") == 1, "a success is remembered" + clock[0] += 2 + assert _nar.whoami_raw(client, narrowed=True, budget_s=3).get("narrowed") == {"read": [K], "write": ""} + assert fake_ctx.count("/api/whoami") == 2, "after 60 s the server is asked again" + + +def test_the_proof_store_is_per_server_key_and_header_set(fake_ctx): + from fakes.ctx_server import FakeCtx + + _keys(fake_ctx, narrowing="required") + one = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + two = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K, M), write=M)) + assert _nar.whoami_raw(one, narrowed=True, budget_s=3).get("narrowed") == {"read": [K], "write": ""} + assert _nar.whoami_raw(two, narrowed=True, budget_s=3).get("narrowed") == {"read": [K, M], "write": M} + assert fake_ctx.count("/api/whoami", narrowed=True) == 2, "another header set asks the server itself" + _nar.whoami_raw(one, narrowed=False, budget_s=3) + _nar.whoami_raw(two, narrowed=False, budget_s=3) + assert fake_ctx.count("/api/whoami", narrowed=False) == 1, "a key has one unnarrowed answer" + ops = CtxClient(fake_ctx.url, OPS_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + assert _nar.whoami_raw(ops, narrowed=False, budget_s=3).get("home_scope") == "t:d111-ops" + assert fake_ctx.count("/api/whoami", narrowed=False) == 2, "another key asks the server itself" + other = FakeCtx().start() + try: + other.add_key(secret=MEMBER_KEY, tenant="u", home="u:x", allowed=(K,), scope_narrowing="required") + there = CtxClient(other.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + assert _nar.whoami_raw(there, narrowed=False, budget_s=3).get("tenant_slug") == "u" + assert other.count("/api/whoami") == 1, "another server asks the server itself" + finally: + other.stop() + + +def test_narrowed_whoami_without_echo_is_lost_and_remembered(fake_ctx): + _keys(fake_ctx, narrowing="required") + fake_ctx.echo_missing = True + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError) as caught: + _nar.whoami_raw(client, narrowed=True, budget_s=3) + assert caught.value.code == "narrowing_lost" + fake_ctx.echo_missing = False + fresh = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError) as again: + _nar.whoami_raw(fresh, narrowed=True, budget_s=3) + assert again.value.code == "narrowing_lost", "the remembered failure keeps its code" + assert fake_ctx.count("/api/whoami") == 1 + + +def test_a_lost_client_leaves_the_proof_store_alone(fake_ctx): + """A client that is off refuses locally; that refusal is no answer of the server and is not remembered.""" + _keys(fake_ctx, narrowing="required") + fake_ctx.echo_missing = True + lost = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError): + lost.search("rules") + fake_ctx.echo_missing = False + with pytest.raises(CtxApiError) as caught: + _nar.whoami_raw(lost, narrowed=False, budget_s=3) + assert caught.value.code == "narrowing_lost" + fresh = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + assert _nar.whoami_raw(fresh, narrowed=False, budget_s=3).get("home_scope") == M + + +def _unrestricted(**overrides): + values = { + "narrowing": Narrowing(read=(K,)), + "strict": False, + "tenant": None, + "label": None, + "env_names": ("CTX_KEY", "CTX_KEY_222_OPS"), + "platform_toolsets": ("terminal", "file"), + "scope_id": "111", + "write": None, + } + values.update(overrides) + return Expect(**values) + + +def test_an_unrestricted_binding_is_proven_by_the_narrowed_answer(fake_ctx): + _keys(fake_ctx) + narrowed = fake_ctx.whoami_answer(OPS_KEY, (K,), "") + proven = _nar.evaluate(narrowed, None, _unrestricted()) + assert proven.ok, f"E2 to E4 in full and E7 are for restricted groups: {proven}" + tenant = _nar.evaluate(narrowed, None, _unrestricted(tenant="other")) + assert not tenant.ok and tenant.failed == ("E2",) + key = fake_ctx.whoami_answer(OPS_KEY) + assert _nar.evaluate(narrowed, key, _unrestricted()).ok + beyond = _nar.evaluate(narrowed, dict(key, read_scopes=["t:d111-ops"]), _unrestricted()) + assert not beyond.ok and beyond.failed == ("E3",), "the read set lies within the key's" + ops = "t:d111-ops" + chain = fake_ctx.whoami_answer(OPS_KEY, (ops,), ops) + assert _nar.evaluate(chain, None, _unrestricted(narrowing=Narrowing(read=(ops,), write=ops), write=ops)).ok + store = fake_ctx.whoami_answer(OPS_KEY, (K,), K) + not_home = _nar.evaluate(store, None, _unrestricted(narrowing=Narrowing(read=(K,), write=K), write=K)) + assert not not_home.ok and not_home.failed == ("E3",), "the chain's scope is the key's home" + assert _nar.evaluate(store, None, _unrestricted(narrowing=Narrowing(read=(K,), write=K))).ok + + +@pytest.mark.parametrize( + ("change", "rules"), + [ + ("no_unnarrowed", ("E2", "E3", "E4")), + ("unnarrowed_is_narrowed", ("E2", "E3", "E4")), + ("write_set", ("E3",)), + ("read_set_short", ("E3",)), + ("confirm_writes", ("E3",)), + ("no_write", ("E3",)), + ("no_label", ("E4",)), + ("tenant_between_answers", ("E2",)), + ("no_tenant", ("E2",)), + ("write_in_read", ("E3",)), + ("narrowed_write", ("E5",)), + ("admin_missing", ("E2",)), + ("confirm_writes_missing", ("E3",)), + ("write_scopes_missing", ("E3",)), + ("other_key", ("E2", "E3", "E4")), + ], +) +def test_strict_expectation_holds_on_every_part(fake_ctx, change, rules): + _keys(fake_ctx, narrowing="required") + narrowed, unnarrowed = _baseline_ok(fake_ctx) + narrowed, unnarrowed = dict(narrowed), dict(unnarrowed) + expect = _expect() + if change == "no_unnarrowed": + unnarrowed = None + elif change == "unnarrowed_is_narrowed": + unnarrowed = dict(narrowed) + elif change == "write_set": + unnarrowed["write_scopes"] = [M, K] + elif change == "read_set_short": + unnarrowed["read_scopes"] = [M] + elif change == "confirm_writes": + unnarrowed["confirm_writes"] = True + elif change == "no_write": + expect = _expect(write=None) + elif change == "no_label": + expect = _expect(label=None) + elif change == "tenant_between_answers": + narrowed["tenant_slug"] = "u" + elif change == "no_tenant": + expect = _expect(tenant=None) + elif change == "write_in_read": + narrowed = dict(fake_ctx.whoami_answer(MEMBER_KEY, (K, M), "")) + expect = _expect(narrowing=Narrowing(read=(K, M))) + elif change == "narrowed_write": + narrowed["narrowed"] = {"read": [K], "write": M} + elif change == "admin_missing": + del unnarrowed["admin"] + elif change == "confirm_writes_missing": + del unnarrowed["confirm_writes"] + elif change == "write_scopes_missing": + del unnarrowed["write_scopes"] + elif change == "other_key": + narrowed["api_key_id"], unnarrowed["api_key_id"] = "key-a", "key-b" + result = _nar.evaluate(narrowed, unnarrowed, expect) + assert not result.ok + assert result.failed == rules, result + assert all(rule in result.detail for rule in rules) + + +@pytest.mark.parametrize( + ("env_names", "toolsets", "ok"), + [ + (("CTX_KEY_111_MEMBERS", "CTX_BASE_URL", "OPENAI_API_KEY"), ("web", "file", "terminal"), True), + (("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS"), ("web",), True), + (("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS"), ("web", "hermes-discord"), False), + (("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS"), ("delegation",), False), + (("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS"), ("debugging",), False), + (("CTX_KEY_111_MEMBERS", "CTX_KEY"), ("terminal",), False), + (("CTX_KEY_111_MEMBERS", "CTX_API_KEY"), ("code_execution",), False), + (("CTX_KEY_111_MEMBERS", "CTX_KEY_1111_MEMBERS"), ("file",), False), + (("CTX_KEY_111_MEMBERS", "CTX_KEY_111_MODS"), ("file",), False), + (("CTX_KEY_111_MEMBERS", "CTX_KEY_111_MODS"), ("web",), True), + (("CTX_KEY_1111_MEMBERS",), ("file",), False), + ], +) +def test_e7_judges_foreign_ctx_keys_against_file_tools(fake_ctx, env_names, toolsets, ok): + _keys(fake_ctx, narrowing="required") + narrowed, unnarrowed = _raws(fake_ctx) + result = _nar.evaluate(narrowed, unnarrowed, _expect(env_names=env_names, platform_toolsets=toolsets)) + assert result.ok is ok, result + assert ok or result.failed == ("E7",) + + +def test_get_blocks_takes_at_most_16_ids_and_sends_nothing_for_none(fake_ctx): + _keys(fake_ctx) + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(ValueError): + client.get_blocks([f"id-{i}" for i in range(17)]) + assert client.get_blocks([]) == [] + assert fake_ctx.count() == 0 + + +def test_get_blocks_fallback_lists_a_block_it_cannot_have_as_an_entry(fake_ctx): + _keys(fake_ctx) + fake_ctx.without_c4 = True + there = fake_ctx.add_block(K, "one", "1") + elsewhere = fake_ctx.add_block(B, "plans", "bravo secret") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + blocks = client.get_blocks([there, "missing-id", elsewhere]) + assert [b.get("id") for b in blocks] == [there, "missing-id", elsewhere] + assert blocks[0].get("title") == "one" + assert blocks[1].get("code") == "not_found" and blocks[2].get("code") == "not_found" + assert "bravo secret" not in str(blocks) + + +def test_get_blocks_raises_a_refused_narrowing_instead_of_falling_back(fake_ctx): + """A 400 about the narrowing itself holds for every id: no fallback, no list of error entries.""" + _keys(fake_ctx) + block = fake_ctx.add_block(K, "one", "1") + doubled = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K, K))) + with pytest.raises(CtxApiError) as caught: + doubled.get_blocks([block]) + assert caught.value.code == "scope_narrowing_invalid" + assert fake_ctx.count("/api/manage", "get") == 1 + + +def test_get_blocks_never_returns_a_partial_list(fake_ctx): + _keys(fake_ctx) + ids = [fake_ctx.add_block(K, f"b{i}", str(i)) for i in range(3)] + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + fake_ctx.throttle["manage:get"] = 2 + with pytest.raises(CtxApiError): + client.get_blocks(ids) + fake_ctx.without_c4 = True + fake_ctx.latency["manage:get"] = 0.3 + started = time.monotonic() + with pytest.raises(CtxApiError): + client.get_blocks(ids, timeout=0.8) + assert time.monotonic() - started < 1.5, "the fallback holds the call's one bound" + + +def test_get_blocks_redacts_the_key_in_the_entries_of_blocks_it_cannot_have(fake_ctx, monkeypatch): + """An entry's error text reaches status files and logs (P-D): the key never travels with it.""" + _keys(fake_ctx) + monkeypatch.setattr( + fake_ctx, + "_get_one", + lambda block_id, read_set: {"id": block_id, "code": "not_found", "error": f"no block for {MEMBER_KEY}"}, + ) + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + blocks = client.get_blocks(["some-id"]) + assert blocks[0].get("code") == "not_found" + assert MEMBER_KEY not in str(blocks) + + +@pytest.mark.parametrize("fault", ["reversed", "short"]) +def test_get_blocks_refuses_an_answer_that_does_not_match_the_ids(fake_ctx, monkeypatch, fault): + _keys(fake_ctx) + ids = [fake_ctx.add_block(K, f"b{i}", str(i)) for i in range(2)] + original = fake_ctx._manage + + def answer(key, action, body, read_set, echo): + status, payload, echoed = original(key, action, body, read_set, echo) + listed = payload.get("blocks") + if isinstance(listed, list): + payload = dict(payload, blocks=listed[::-1] if fault == "reversed" else listed[:-1]) + return status, payload, echoed + + monkeypatch.setattr(fake_ctx, "_manage", answer) + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError): + client.get_blocks(ids) + + +def test_get_blocks_redacts_the_key_in_a_code_of_an_answer_without_blocks(fake_ctx, monkeypatch): + _keys(fake_ctx) + monkeypatch.setattr( + fake_ctx, + "_manage", + lambda key, action, body, read_set, echo: (200, {"success": True, "code": MEMBER_KEY}, echo), + ) + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError) as caught: + client.get_blocks(["some-id"]) + assert MEMBER_KEY not in str(caught.value) and MEMBER_KEY not in caught.value.code + + +# -- after the review: the proof of a restricted binding, the store under load, the echo's form ---- + + +def test_a_restricted_group_is_proven_through_its_read_narrowing_and_each_client_by_its_echo(fake_ctx): + """The strict proof needs the group's read set, which only the read narrowing carries; the write + client proves its own narrowing next to it without the strict rules.""" + _keys(fake_ctx, narrowing="required") + assert _nar.evaluate(*_raws(fake_ctx), _expect()).ok, "the group proof" + writer = Narrowing(read=(M,), write=M) + answer = fake_ctx.whoami_answer(MEMBER_KEY, (M,), M) + assert _nar.evaluate(answer, None, _expect(narrowing=writer, strict=False, label=None)).ok, "the write client" + misuse = _nar.evaluate(answer, fake_ctx.whoami_answer(MEMBER_KEY), _expect(narrowing=writer)) + assert not misuse.ok and "E3" in misuse.failed and "read narrowing" in misuse.detail["E3"] + + +def test_callers_that_miss_the_store_together_ask_once(fake_ctx): + import threading + + _keys(fake_ctx, narrowing="required") + fake_ctx.latency["/api/whoami"] = 0.3 + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + answers = [] + threads = [ + threading.Thread(target=lambda: answers.append(_nar.whoami_raw(client, narrowed=True, budget_s=3))) + for _ in range(5) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + assert len(answers) == 5 and all(a.get("narrowed") == {"read": [K], "write": ""} for a in answers) + assert fake_ctx.count("/api/whoami") == 1 + + +def test_a_spent_budget_is_not_remembered(fake_ctx): + _keys(fake_ctx, narrowing="required") + client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + with pytest.raises(CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=0) + assert fake_ctx.count() == 0 + assert _nar.whoami_raw(client, narrowed=True, budget_s=3).get("narrowed") == {"read": [K], "write": ""} + + +def test_a_refusal_of_the_client_itself_is_not_remembered(fake_ctx, monkeypatch): + """Another thread may lose the narrowing between the check and the call: that refusal is local.""" + _keys(fake_ctx, narrowing="required") + racing = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + + def refuse(**_kwargs): + raise racing.narrowing_lost_error() + + monkeypatch.setattr(racing, "whoami", refuse) + with pytest.raises(CtxApiError) as caught: + _nar.whoami_raw(racing, narrowed=False, budget_s=3) + assert caught.value.code == "narrowing_lost" + fresh = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) + assert _nar.whoami_raw(fresh, narrowed=False, budget_s=3).get("home_scope") == M + + +def test_the_echo_is_exactly_one_matching_header(): + import http.client + import types + + def answer(*values): + headers = http.client.HTTPMessage() + for value in values: + headers[_nar.HEADER_NARROWED] = value # a second assignment adds a second header + return types.SimpleNamespace(headers=headers) + + narrowing = Narrowing(read=(K, M), write=M) + assert _client._echo_matches(answer(f"{K},{M};{M}"), narrowing) + assert not _client._echo_matches(answer(f"{K},{M};{M}", f"{K},{M};{M}"), narrowing) + assert not _client._echo_matches(answer(), narrowing) + assert not _client._echo_matches(answer(f"{K};{M}"), narrowing) From a1b60e5c2435f981270afe5635360b0f7f599a21 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 01:31:40 +0100 Subject: [PATCH 04/65] =?UTF-8?q?fix(ctx=5Fcheckpoint):=20access=20groups?= =?UTF-8?q?=20(P-B)=20=E2=80=94=20the=20fields=20register=20on=20a=20Herme?= =?UTF-8?q?s=20that=20has=20them,=20their=20forms=20are=20checked=20before?= =?UTF-8?q?=20any=20secret,=20and=20one=20pure=20table=20decides=20off,=20?= =?UTF-8?q?the=20profile's=20connection=20or=20a=20group=20binding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit register() registers the twelve access-group fields when the public class hermes_cli.plugins.PluginContext has register_access_fields; a Hermes without it is asked nothing. memory/access.py fills the S1 contract of cluster P-B: the group's access context (with the group's platform for forks), the one definition of "restricted", the field forms, the settings from config.yaml only (an unknown mode is off), the E7 inputs, the monotone markers under flock, and decide(), the table of design 02 §4.2. Strict where evidence is partial: governed_unbound never opens a profile a restricted group runs in, and a messaging session without its group is off once the profile saw a governed session. The P-B row is removed from S1_PENDING; test_access_pb_rules.py adds the negatives S1 could not state. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/__init__.py | 13 +- .../plugin/ctx_checkpoint/memory/access.py | 911 ++++++++++++++++-- .../ctx_checkpoint/tests/fakes/s1_pending.py | 1 - .../tests/test_access_pb_rules.py | 692 +++++++++++++ 4 files changed, 1561 insertions(+), 56 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_rules.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index b5c638dc9..e87118548 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -47,6 +47,7 @@ from typing import Any from .config_schema import FIELDS as _FORM_FIELDS +from .memory import access as _access from .memory import checkpoint as _cp from .memory import status as _st from .memory.client import CtxApiError @@ -1369,9 +1370,19 @@ def _prompt_grant(self, fields: list[dict[str, Any]], server: str) -> dict[str, def register(ctx) -> None: - """Memory plugin entry point: the provider plus the bundled ``ctx-memory`` skill.""" + """Memory plugin entry point: the provider plus the bundled ``ctx-memory`` skill; on a Hermes + with access groups also the fields ctx_checkpoint adds to them.""" call_mcp, plugin_id = _host_call_mcp(ctx) ctx.register_memory_provider(CtxCheckpointMemoryProvider(call_mcp=call_mcp, plugin_id=plugin_id or PLUGIN_ID)) + # Access-group fields: detected on the public class (the collector answers every register_*); + # a host without them is asked nothing. The core keeps them only while this is the home's + # active provider. A failure here must never cost the provider; it is named, because without + # the fields the core refuses every restricted group whose profile carries this provider. + if _access.access_supported(): + try: + ctx.register_access_fields({name: dict(spec) for name, spec in _access.SCHEMA.items()}) + except Exception as exc: + logger.warning("ctx_checkpoint: access-group fields not registered: %s", exc) register_skill = getattr(ctx, "register_skill", None) if callable(register_skill) and _SKILL_PATH.is_file(): try: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py index 11654f786..eef9ac278 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -1,4 +1,4 @@ -"""Access groups: the fields ctx_checkpoint adds to them and the binding decision (contract, S1). +"""Access groups: the fields ctx_checkpoint adds to them and the binding decision. Hermes' access groups (``gateway.access_groups``) run each sender of a governed server in the profile of the first group that matches. A plugin adds fields to those groups @@ -6,31 +6,67 @@ (``initialize(scope_id=, access_group=, access_group_restricted=, access_fields=, restricted_profile=)``) and, inside a turn, through ``gateway.access_groups.current_access()``. -This module holds the schema of ctx_checkpoint's twelve fields, the detection of that host surface -and the pure decision which connection a session gets (``off``, the profile's own, or a group -binding). S1 state: the data forms are final, the functions are inert stubs; nothing in the plugin -calls them yet, so the plugin behaves as 0.19.1. The decision cluster (P-B) fills them in. +This module holds the schema of ctx_checkpoint's twelve fields, the detection of that host surface, +the forms of the fields, the profile's settings and markers, and the pure decision which connection +a session gets (``off``, the profile's own, or a group binding; design 02 §4.2). On a Hermes without +the access groups nothing here registers or binds anything, and a profile that never saw a governed +session behaves as 0.19.1. + +Every host surface is reached through the published plugin API only: ``hermes_cli.plugins: +PluginContext`` (detection), ``hermes_cli.config`` and ``hermes_constants`` (settings), +``agent.secret_scope`` (the ``.env`` tokenizer), ``gateway.session_context:get_session_env`` (a +fork's parent platform) and ``gateway.access_groups:current_access`` (the turn's group). Nothing +decides from ``os.environ``. """ from __future__ import annotations -from collections.abc import Mapping -from dataclasses import dataclass, field +import ast +import copy +import json +import logging +import os +import re +import sys +import tempfile +import threading +import time +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass, field, replace +from datetime import datetime, timezone +from pathlib import Path from types import MappingProxyType from typing import Any, Literal +from urllib.parse import urlsplit + +from .config import derive_profile_name + +try: + import fcntl +except ImportError: # Windows: marker writers are serialized within one process only + fcntl = None # type: ignore[assignment] + +logger = logging.getLogger(__name__) # The namespace is the plugin id ``memory.provider`` selects the provider by. NAMESPACE = "ctx_checkpoint" # The hook the core fires before a governed server's turn (gateway/access_prompt.py). HOOK_NAME = "access_group_fields" -# Platforms of a local, interactive session (``ungoverned: local`` admits them; forks only when -# their parent session was local). # The profile's markers (``read_markers``, ``raise_markers``, ``reset_markers``), under the home. MARKERS_FILE = "ctx_state/access-mode.json" +# Platforms of a local, interactive session (``ungoverned: local`` admits them; forks only when +# their parent session was local). LOCAL_PLATFORMS = frozenset({"cli", "tui", "desktop", "local", "codex", "acp", "gui"}) +# Platforms that are no chat with other people (design 02 §3.2: cron, the API server, webhooks). +# Row 7 of the decision closes every other platform without an access group once the profile saw a +# governed session; an unknown platform counts as messaging (like Hermes' own default-deny list of +# non-messaging surfaces, gateway/session_context.py). +NON_MESSAGING_PLATFORMS = frozenset({"cron", "api_server", "webhook"}) + # ``memory.ctx_checkpoint.*`` keys of config.yaml this axis reads (never from ctx.json), with defaults. SETTINGS_DEFAULTS: Mapping[str, Any] = MappingProxyType( { @@ -44,6 +80,49 @@ "verify_timeout_s": 3, # 1 .. 10 } ) +UNGOVERNED_MODES = ("auto", "profile", "local", "off") +GOVERNED_UNBOUND_MODES = ("profile", "off") +RESTRICTED_ALLOW_ITEMS = ("recall", "capture") +# Integer settings and their bounds (a value outside is clamped, a non-number is the default). +_SETTINGS_BOUNDS: Mapping[str, tuple[int, int]] = MappingProxyType( + { + "base_cache_s": (60, 86_400), + "base_cache_entries": (64, 65_536), + "base_timeout_s": (1, 10), + "base_workers": (1, 32), + "verify_timeout_s": (1, 10), + } +) +# What applies while the profile's config.yaml cannot be read: nothing beyond the defaults is +# allowed, and no session without an access group keeps the profile's connection. +_UNREADABLE_SETTINGS: Mapping[str, Any] = MappingProxyType( + {**SETTINGS_DEFAULTS, "ungoverned": "off", "governed_unbound": "off", "restricted_allow": ()} +) + +# Field forms (design 02 §3.1). ctx: go/internal/handler/tenant_manage.go slugPattern and +# scopeNamePattern; Hermes: hermes_cli/access_fields.py ENV_NAME. +_SLUG = r"[a-z0-9](?:[a-z0-9-]{0,22}[a-z0-9])?" +SLUG_PATTERN = re.compile(rf"^{_SLUG}$") +SCOPE_PATTERN = re.compile(rf"^({_SLUG}):({_SLUG})$") +ENV_NAME_PATTERN = re.compile(r"^[A-Z][A-Z0-9_]{0,63}$") +_KEY_NAME = re.compile(r"^(?:CTX_KEY|CTX_API_KEY|CTX_KEY_[A-Z0-9_]+)$") +_BASE_URL_NAME = re.compile(r"^(?:CTX_BASE_URL|CTX_BASE_URL_[A-Z0-9_]+)$") +_SERVER_PART = re.compile(r"^[A-Z0-9]+$") +_BLOCK_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") +READ_MAX = 8 +BASE_BLOCKS_MAX = 16 +BASE_MAX_CHARS_RANGE = (256, 8000) +BASE_MAX_CHARS_DEFAULT = 4000 + +# The marker file is a few hundred bytes; anything far larger is not ours and counts as unreadable. +_MARKERS_MAX_BYTES = 64 * 1024 +_MARKERS_LOCK_FILE = "access-mode.lock" +_MARKERS_LOCK_WAIT_S = 5.0 +_PROCESS_MARKERS_LOCK = threading.Lock() + +# Values of settings already warned about (a misspelt mode is named once per process, not per build). +_WARNED: set[tuple[str, str]] = set() +_WARNED_MAX = 64 def _spec(kind: str, description: str) -> Mapping[str, str]: @@ -134,8 +213,10 @@ class AccessContext: @dataclass(frozen=True) class GroupFields: - """The group's fields, parsed and with their forms checked (``parse_fields``); defaults applied - for the group's strictness.""" + """The group's fields, parsed and with their forms checked (``parse_fields``). ``""``/``()`` is + "not set"; ``recall``/``capture`` stay ``None`` when not set (their effective value needs the + profile's ``restricted_allow``). ``store`` is ``write`` when not set and ``""`` for restricted + groups (they never store).""" key: str base_url: str @@ -171,7 +252,8 @@ class Markers: class Decision: """What ``initialize`` binds: ``off`` (no ctx at all), ``profile`` (the profile's own connection, as 0.19.1) or ``group`` (a group binding from ``fields``). ``reason`` names the row of the - decision table and the cause; ``strict``: the group counts as restricted.""" + decision table and the cause (no value of a field); ``context`` is set exactly when the session + serves an access group (rows 2 to 4), ``strict``: that group counts as restricted.""" kind: Literal["off", "profile", "group"] reason: str @@ -180,81 +262,729 @@ class Decision: strict: bool = False +# -- the host surface ------------------------------------------------------------------------------ + + def access_supported() -> bool: """V8b: the host has the core's access-group fields and hook, read on the public class - ``hermes_cli.plugins.PluginContext`` (a memory provider's ``ctx`` answers every ``register_*``). - S1 stub: ``False``.""" - return False + ``hermes_cli.plugins.PluginContext``. A memory provider's ``ctx`` is a collector that answers + every ``register_*`` call, so the instance it hands over says nothing.""" + try: + from hermes_cli.plugins import PluginContext + except Exception: + return False + return callable(getattr(PluginContext, "register_access_fields", None)) def current_access() -> AccessContext | None: - """V8a/V6a: the access group serving the current turn, through the published - ``gateway.access_groups.current_access`` (imported at call time; ``None`` when the host lacks it, - outside a turn, or for a server that is not governed), with this plugin's namespace only. - S1 stub: ``None``.""" - return None + """V6a: the access group serving the current turn, through the published + ``gateway.access_groups.current_access``, with this plugin's namespace only (a deep copy). + + ``None`` when the host lacks it, outside a turn, for a server that is not governed, or when the + call fails (the core passes ``initialize`` no group then either). The module is looked up in + ``sys.modules``, not imported: only a loaded module can have bound a turn's group (the core + imports it for every agent build and every governed turn), a process that never loaded it pays + nothing, and a Hermes without access groups has none (the core reads ``gateway.run`` the same + way, ``gateway/access_groups.py`` ``_live_runner``).""" + module = sys.modules.get("gateway.access_groups") + reader = getattr(module, "current_access", None) if module is not None else None + if not callable(reader): + return None + try: + access = reader() + except Exception: + logger.debug("ctx_checkpoint: the access group of this turn is unreadable", exc_info=True) + return None + if access is None: + return None + try: + fields_for = getattr(access, "fields_for", None) + mine = fields_for(NAMESPACE) if callable(fields_for) else (getattr(access, "fields", None) or {}).get(NAMESPACE) + restricted = getattr(access, "restricted", None) + profile = getattr(access, "profile", None) + return AccessContext( + platform=str(access.platform), + scope_id=str(access.scope_id), + group=str(access.group), + profile=str(profile) if profile else None, + restricted=restricted if isinstance(restricted, bool) else None, + admin=getattr(access, "admin", False) is True, + fields=_frozen_copy(mine), + ) + except Exception: + logger.debug("ctx_checkpoint: the access group of this turn has an unknown form", exc_info=True) + return None def session_parent_platform() -> str | None: """The platform of the session a fork was built in: ``HERMES_SESSION_PLATFORM`` through the published ``gateway.session_context.get_session_env``, and only when the name is not in ``os.environ`` (else ``get_session_env`` answers with the process value, which says nothing about - the session); ``None`` when unknown. The ``parent_platform`` of ``decide``. S1 stub: ``None``.""" - return None + the session); ``None`` when unknown. The ``parent_platform`` of ``decide``.""" + if "HERMES_SESSION_PLATFORM" in os.environ: + return None + try: + from gateway.session_context import get_session_env + + value = get_session_env("HERMES_SESSION_PLATFORM", "") + except Exception: + return None + value = str(value or "").strip().lower() + return value or None def context_from_init(init_kwargs: Mapping[str, Any]) -> AccessContext | None: """The access group ``initialize`` was told about (``platform``, ``scope_id``, ``access_group``, ``access_group_restricted``, ``access_fields``, ``agent_identity``); ``None`` without - ``access_group``. S1 stub: ``None``.""" - return None + ``access_group``. A restriction that did not arrive as a bool is unknown (``None``); fields that + are no mapping are none (``decide`` refuses them before).""" + init = init_kwargs if isinstance(init_kwargs, Mapping) else {} + group = init.get("access_group") + if not isinstance(group, str) or not group: + return None + restricted = init.get("access_group_restricted") + scope_id = init.get("scope_id") + identity = init.get("agent_identity") + return AccessContext( + platform=str(init.get("platform") or ""), + scope_id=str(scope_id) if scope_id is not None else "", + group=group, + profile=identity if isinstance(identity, str) and identity else None, + restricted=restricted if isinstance(restricted, bool) else None, + fields=_frozen_copy(init.get("access_fields")), + ) + + +def _frozen_copy(raw: Any) -> Mapping[str, Any]: + return MappingProxyType(copy.deepcopy(dict(raw))) if isinstance(raw, Mapping) else MappingProxyType({}) + + +# -- strictness and the fields ----------------------------------------------------------------------- def is_strict(context: AccessContext | None, *, restricted_profile: bool | None, markers: Markers) -> bool: - """The one definition of "restricted" (design 02 §3.3): the group's ``restricted``; unknown counts - as restricted when the profile is restricted or the marker ``restricted_seen`` is set; in the hook - (no profile knowledge) unknown counts as restricted. S1 stub: ``True``.""" - return True + """The one definition of "restricted" (design 02 §3.3): the group's ``restricted`` when it is + known; else restricted unless the profile is known not to be restricted (``restricted_profile`` + exactly ``False``) and the marker ``restricted_seen`` is not set. In the hook (no profile + knowledge, ``restricted_profile=None``) an unknown restriction is restricted.""" + if context is not None and isinstance(context.restricted, bool): + return context.restricted + return restricted_profile is not False or markers.restricted_seen def parse_fields(raw: Mapping[str, Any], *, scope_id: str, strict: bool) -> GroupFields | FieldError: - """The group's fields with their forms checked before any secret is read or request sent: ``key`` - and ``base_url`` name ctx variables (restricted: ``CTX_KEY_<scope_id>_...``), scopes match the ctx - scope pattern, bounds hold; with ``strict`` the rules of E1. S1 stub: a ``FieldError``.""" - return FieldError(field="*", reason="access groups are not available") + """The group's fields with their forms checked before any secret is read or request sent (design + 02 §3.1): ``key`` and ``base_url`` name ctx variables (restricted: ``CTX_KEY_<scope_id>_...``), + scopes match ``<slug>:<name>`` without repeats, bounds hold, and an unknown field fails; with + ``strict`` the rules of E1 (``key``, ``tenant``, ``read``, ``write`` set, ``write`` not in + ``read``, every scope in ``tenant``). The first broken field in schema order is named, never its + value. The ``https`` of ``base_url``'s value is ``valid_base_url``'s, once the variable is read.""" + if not isinstance(raw, Mapping): + return FieldError("*", "the fields are not a mapping") + for name in raw: + if name not in SCHEMA: + return FieldError(str(name), "unknown field") + values: dict[str, Any] = {} + for name in SCHEMA: + checked = _FIELD_CHECKS[name](raw.get(name), scope_id=scope_id, strict=strict) + if isinstance(checked, FieldError): + return checked + values[name] = checked + if strict: + problem = _strict_problem(values) + if problem is not None: + return problem + write = values["write"] + return GroupFields( + key=values["key"], + base_url=values["base_url"], + tenant=values["tenant"], + read=values["read"], + write=write, + store="" if strict else (values["store"] or write), + recall=values["recall"], + capture=values["capture"], + base_blocks=values["base_blocks"], + base_max_chars=values["base_max_chars"], + base_rev=values["base_rev"], + enabled=values["enabled"], + ) + + +def _strict_problem(values: Mapping[str, Any]) -> FieldError | None: + """E1 on the parsed forms: what a restricted group must set, and that its scopes stay apart.""" + for name in ("key", "tenant", "read", "write"): + if not values[name]: + return FieldError(name, "required for restricted groups") + tenant = values["tenant"] + for name, scopes in (("read", values["read"]), ("write", (values["write"],))): + if any(scope.split(":", 1)[0] != tenant for scope in scopes): + return FieldError(name, "a scope outside the group's tenant") + if values["write"] in values["read"]: + return FieldError("write", "must not be one of 'read' for restricted groups") + return None + + +def _check_key(value: Any, *, scope_id: str, strict: bool) -> str | FieldError: + if value is None: + return "" + if not isinstance(value, str) or not ENV_NAME_PATTERN.match(value) or not _KEY_NAME.match(value): + return FieldError("key", "not a ctx key variable (CTX_KEY, CTX_API_KEY or CTX_KEY_<...>)") + if strict: + prefix = restricted_key_prefix(scope_id) + if prefix is None: + return FieldError("key", "the server id cannot be part of a variable name") + if not value.startswith(prefix) or len(value) == len(prefix): + return FieldError("key", "restricted groups name CTX_KEY_<server id>_<...> of their own server") + return value + + +def restricted_key_prefix(scope_id: str) -> str | None: + """``CTX_KEY_<SERVER>_``: how a restricted group's key variable starts (rule E1; E7 reads other + servers' keys by the same form). ``None`` when the server id is not letters and digits only.""" + part = str(scope_id or "").upper() + return f"CTX_KEY_{part}_" if _SERVER_PART.match(part) else None + + +def _check_base_url(value: Any, **_: Any) -> str | FieldError: + if value is None: + return "" + if not isinstance(value, str) or not ENV_NAME_PATTERN.match(value) or not _BASE_URL_NAME.match(value): + return FieldError("base_url", "not a ctx URL variable (CTX_BASE_URL or CTX_BASE_URL_<...>)") + return value + + +def valid_base_url(url: str) -> bool: + """A group's ctx server URL (the value ``base_url`` names): ``https`` with a host, without + credentials, whitespace, query or fragment. Checked after reading the variable, before the key is + read or a request is sent.""" + if not isinstance(url, str) or not url or url != url.strip() or any(ch.isspace() for ch in url): + return False + try: + parts = urlsplit(url) + port_ok = parts.port is None or parts.port > 0 + except ValueError: + return False + return ( + parts.scheme == "https" + and bool(parts.hostname) + and port_ok + and parts.username is None + and parts.password is None + and not parts.query + and not parts.fragment + ) + + +def _check_tenant(value: Any, **_: Any) -> str | FieldError: + if value is None: + return "" + if not isinstance(value, str) or not SLUG_PATTERN.match(value): + return FieldError("tenant", "not a tenant slug") + return value + + +def _check_read(value: Any, **_: Any) -> tuple[str, ...] | FieldError: + if value is None: + return () + if not isinstance(value, (list, tuple)) or not value or len(value) > READ_MAX: + return FieldError("read", f"a list of 1 to {READ_MAX} ctx scopes <slug>:<name>") + if not all(isinstance(scope, str) and SCOPE_PATTERN.match(scope) for scope in value): + return FieldError("read", f"a list of 1 to {READ_MAX} ctx scopes <slug>:<name>") + if len(set(value)) != len(value): + return FieldError("read", "a scope is named twice") + return tuple(value) + + +def _check_scope(name: str) -> Any: + def check(value: Any, **_: Any) -> str | FieldError: + if value is None: + return "" + if not isinstance(value, str) or not SCOPE_PATTERN.match(value): + return FieldError(name, "not a ctx scope <slug>:<name>") + return value + + return check + + +def _check_bool(name: str) -> Any: + def check(value: Any, **_: Any) -> bool | None | FieldError: + if value is None or isinstance(value, bool): + return value + return FieldError(name, "expected true or false") + + return check + + +def _check_base_blocks(value: Any, **_: Any) -> tuple[str, ...] | FieldError: + if value is None: + return () + if not isinstance(value, (list, tuple)) or len(value) > BASE_BLOCKS_MAX: + return FieldError("base_blocks", f"a list of up to {BASE_BLOCKS_MAX} block ids") + if not all(isinstance(item, str) and _BLOCK_ID.match(item) for item in value): + return FieldError("base_blocks", f"a list of up to {BASE_BLOCKS_MAX} block ids") + if len(set(value)) != len(value): + return FieldError("base_blocks", "a block id is named twice") + return tuple(value) + + +def _check_base_max_chars(value: Any, **_: Any) -> int | FieldError: + if value is None: + return BASE_MAX_CHARS_DEFAULT + low, high = BASE_MAX_CHARS_RANGE + if not isinstance(value, int) or isinstance(value, bool) or not low <= value <= high: + return FieldError("base_max_chars", f"a whole number from {low} to {high}") + return value + + +def _check_base_rev(value: Any, **_: Any) -> int | FieldError: + if value is None: + return 0 + if not isinstance(value, int) or isinstance(value, bool) or value < 0: + return FieldError("base_rev", "a whole number from 0") + return value + + +def _check_enabled(value: Any, **_: Any) -> bool | FieldError: + if value is None: + return True + if isinstance(value, bool): + return value + return FieldError("enabled", "expected true or false") + + +_FIELD_CHECKS: Mapping[str, Any] = MappingProxyType( + { + "key": _check_key, + "base_url": _check_base_url, + "tenant": _check_tenant, + "read": _check_read, + "write": _check_scope("write"), + "store": _check_scope("store"), + "recall": _check_bool("recall"), + "capture": _check_bool("capture"), + "base_blocks": _check_base_blocks, + "base_max_chars": _check_base_max_chars, + "base_rev": _check_base_rev, + "enabled": _check_enabled, + } +) + + +# -- the profile's settings and E7 inputs ------------------------------------------------------------ + + +def _same_home(home: str) -> bool: + try: + from hermes_constants import get_hermes_home + + return os.path.realpath(str(home)) == os.path.realpath(str(get_hermes_home())) + except Exception: + return False + + +def _profile_config(hermes_home: str) -> Mapping[str, Any] | None: + """The profile's config.yaml as Hermes reads it; ``None`` when it cannot be read or parsed. The + home that is the current one (``initialize``, the hook in the serving profile's scope) goes + through ``load_config_readonly`` (Hermes' behavioral read: cached on the file signature, its + last good copy while an edit breaks the file); another home (operator tools) is read once with + ``read_user_config_raw``. A missing file is an empty config.""" + try: + from hermes_cli import config as hermes_config + + if _same_home(hermes_home): + data = hermes_config.load_config_readonly() + else: + data = hermes_config.read_user_config_raw(Path(hermes_home) / "config.yaml") + except FileNotFoundError: + return {} + except Exception: + logger.debug("ctx_checkpoint: config.yaml of %s is unreadable", hermes_home, exc_info=True) + return None + if not isinstance(data, Mapping) or getattr(data, "read_error", None) is not None: + return None + return data + + +def _plugin_section(config: Mapping[str, Any]) -> Mapping[str, Any] | None: + """``memory.ctx_checkpoint``; ``{}`` when not written, ``None`` when it (or ``memory``) has + another form than a mapping.""" + memory = config.get("memory") + if memory is None: + return {} + if not isinstance(memory, Mapping): + return None + section = memory.get(NAMESPACE) + if section is None: + return {} + return section if isinstance(section, Mapping) else None + + +def _warn_once(key: str, shown: str, text: str) -> None: + if (key, shown) in _WARNED: + return + if len(_WARNED) < _WARNED_MAX: + _WARNED.add((key, shown)) + logger.warning(text) + + +def _mode(section: Mapping[str, Any], key: str, allowed: tuple[str, ...]) -> str: + """A mode setting; YAML 1.1 reads a bare ``off`` as ``false``. Anything else unknown is ``off`` + (the strict mode), named once in a WARNING.""" + if key not in section or section[key] is None: + return str(SETTINGS_DEFAULTS[key]) + value = section[key] + if value is False: + return "off" + text = value.strip().lower() if isinstance(value, str) else "" + if text in allowed: + return text + _warn_once( + key, + repr(value)[:40], + f"ctx_checkpoint: memory.{NAMESPACE}.{key} is not one of {', '.join(allowed)}; it counts as off", + ) + return "off" + + +def _restricted_allow(section: Mapping[str, Any]) -> tuple[str, ...]: + value = section.get("restricted_allow") + if value is None: + return () + if not isinstance(value, (list, tuple)): + _warn_once( + "restricted_allow", + type(value).__name__, + f"ctx_checkpoint: memory.{NAMESPACE}.restricted_allow is not a list; restricted groups get" + " neither recall nor capture", + ) + return () + items = {str(item).strip().lower() for item in value if isinstance(item, str)} + return tuple(item for item in RESTRICTED_ALLOW_ITEMS if item in items) + + +def _bounded_int(section: Mapping[str, Any], key: str) -> int: + low, high = _SETTINGS_BOUNDS[key] + value = section.get(key) + if isinstance(value, bool) or not isinstance(value, (int, float)) or value != value: + return int(SETTINGS_DEFAULTS[key]) + return int(max(low, min(high, value))) def load_settings(hermes_home: str) -> Mapping[str, Any]: - """``memory.ctx_checkpoint.*`` of this axis from the home's config.yaml only (``ctx.json`` never - sets them), bounded, unknown values replaced by the defaults. S1 stub: the defaults.""" - return SETTINGS_DEFAULTS + """``memory.ctx_checkpoint.*`` of this axis from the home's config.yaml only (``ctx.json`` and + the Settings → Plugins form never set them). Bounded: numbers are clamped to their range (a + non-number is the default), an unknown mode is ``off``, ``restricted_allow`` keeps only + ``recall``/``capture``. A config.yaml that cannot be read, or a ``memory``/``memory.ctx_checkpoint`` + that is no mapping, gives the strict settings (no session without an access group keeps the + profile's connection).""" + config = _profile_config(hermes_home) + section = _plugin_section(config) if config is not None else None + if section is None: + return _UNREADABLE_SETTINGS + settings: dict[str, Any] = { + "ungoverned": _mode(section, "ungoverned", UNGOVERNED_MODES), + "governed_unbound": _mode(section, "governed_unbound", GOVERNED_UNBOUND_MODES), + "restricted_allow": _restricted_allow(section), + } + for key in _SETTINGS_BOUNDS: + settings[key] = _bounded_int(section, key) + return MappingProxyType(settings) + + +def _platform_toolsets(config: Mapping[str, Any], platform: str) -> tuple[str, ...] | None: + """``platform_toolsets.<platform>`` as saved (a list, or the ``"[...]"`` text older Hermes wrote, + as ``hermes_cli.toolset_validation`` reads it); ``None`` when it is no saved list.""" + saved = config.get("platform_toolsets") + value = saved.get(platform) if isinstance(saved, Mapping) else None + if isinstance(value, str) and value.strip().startswith("["): + try: + value = ast.literal_eval(value.strip()) + except (ValueError, SyntaxError): + return None + if not isinstance(value, (list, tuple)): + return None + return tuple(str(item) for item in value) + + +def e7_inputs(hermes_home: str, platform: str) -> tuple[tuple[str, ...], tuple[str, ...]] | None: + """What rule E7 judges, read without network from the profile at *hermes_home*: the variable + NAMES in its ``.env`` (values are dropped at once; through Hermes' one ``.env`` tokenizer + ``agent.secret_scope.load_env_file``) and the toolset list ``platform_toolsets.<platform>`` of its + config.yaml, exactly as configured. ``None`` when the config or the ``.env`` cannot be read + (``load_env_file`` answers an unreadable file with no names) or the config names no list for the + platform, which fails E7 (the one reader P-C, P-D and P-E share). No ``.env`` is no names.""" + config = _profile_config(hermes_home) + if config is None: + return None + toolsets = _platform_toolsets(config, str(platform or "")) + if toolsets is None: + return None + env_path = Path(hermes_home) / ".env" + try: + with env_path.open("rb"): + pass + except FileNotFoundError: + return (), toolsets + except OSError: + logger.debug("ctx_checkpoint: the .env of %s is unreadable", hermes_home, exc_info=True) + return None + try: + from agent.secret_scope import load_env_file + + names = tuple(load_env_file(env_path)) + except Exception: + logger.debug("ctx_checkpoint: the .env of %s is unreadable", hermes_home, exc_info=True) + return None + return names, toolsets + + +# -- markers ----------------------------------------------------------------------------------------- + + +def _markers_path(hermes_home: str) -> Path: + return Path(hermes_home) / MARKERS_FILE def read_markers(hermes_home: str) -> Markers: - """The markers of ``<home>/ctx_state/access-mode.json``; a missing file is no marker, an - unreadable one counts as both set. S1 stub: no marker.""" - return Markers() + """The markers of ``<home>/ctx_state/access-mode.json``. A missing file is no marker; a file that + cannot be read, does not parse, or holds anything but ``false`` for a marker counts as that + marker set.""" + path = _markers_path(hermes_home) + try: + with path.open("rb") as handle: + raw = handle.read(_MARKERS_MAX_BYTES + 1) + except FileNotFoundError: + return Markers() + except OSError: + return Markers(restricted_seen=True, governed_seen=True) + try: + data = json.loads(raw.decode("utf-8")) if len(raw) <= _MARKERS_MAX_BYTES else None + except (UnicodeDecodeError, ValueError): + data = None + if not isinstance(data, dict): + return Markers(restricted_seen=True, governed_seen=True) + return Markers( + restricted_seen=data.get("restricted_seen") is not False, + governed_seen=data.get("governed_seen") is not False, + ) + + +@contextmanager +def _markers_lock(directory: Path) -> Iterator[None]: + """Serialize the markers' read-modify-write across threads and processes (a lost update would + lower a marker another writer raised). Raises ``OSError`` when the lock cannot be held within + the wait: nothing writes the markers unserialized.""" + with _PROCESS_MARKERS_LOCK: + if fcntl is None: + yield + return + directory.mkdir(parents=True, exist_ok=True) + fd = os.open(str(directory / _MARKERS_LOCK_FILE), os.O_RDWR | os.O_CREAT, 0o600) + try: + deadline = time.monotonic() + _MARKERS_LOCK_WAIT_S + while True: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= deadline: + raise OSError("the access-group marker lock is busy") from None + time.sleep(0.01) + yield + finally: + os.close(fd) # releases the lock + + +def _write_markers(path: Path, markers: Markers) -> None: + state = { + "restricted_seen": markers.restricted_seen, + "governed_seen": markers.governed_seen, + "since": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + } + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".access-mode-", dir=str(path.parent)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(state, handle) + os.chmod(tmp, 0o600) + os.replace(tmp, path) + except Exception: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def _marker_flags(flags: Mapping[str, bool]) -> dict[str, bool]: + unknown = set(flags) - {"restricted_seen", "governed_seen"} + if unknown: + raise ValueError(f"unknown marker: {', '.join(sorted(unknown))}") + return {name: value is True for name, value in flags.items()} def raise_markers(hermes_home: str, **flags: bool) -> None: """Set the named markers (``restricted_seen=True``, ``governed_seen=True``), only from false to - true, atomically; ``False`` never lowers one (only ``access reset-marker`` does). S1 stub: no-op.""" - return None + true, atomically, and only when one changes; ``False`` never lowers one (only ``access + reset-marker`` does). A marker that cannot be written (or whose lock cannot be held) is a + WARNING, never an exception: the decision of this build stands, and the next build that sees + the same session raises it again.""" + wanted = {name for name, value in _marker_flags(flags).items() if value} + if not wanted or all(getattr(read_markers(hermes_home), name) for name in wanted): + return # markers only rise: one already set needs no lock and no write + path = _markers_path(hermes_home) + try: + with _markers_lock(path.parent): + current = read_markers(hermes_home) + raised = Markers( + restricted_seen=current.restricted_seen or "restricted_seen" in wanted, + governed_seen=current.governed_seen or "governed_seen" in wanted, + ) + if raised != current: + _write_markers(path, raised) + except Exception: + logger.warning("ctx_checkpoint: the access-group marker file %s could not be written", path, exc_info=True) def reset_markers(hermes_home: str, *, restricted: bool = False, governed: bool = False) -> None: """Lower the named markers (``access reset-marker``, the only way down), atomically; the other - marker stays. File: ``MARKERS_FILE`` under the home, JSON ``{"restricted_seen": bool, - "governed_seen": bool, "since": "<ISO 8601 UTC of the last change>"}``. S1 stub: no-op.""" - return None + marker stays as read (an unreadable file counts as both set). File: ``MARKERS_FILE`` under the + home, JSON ``{"restricted_seen": bool, "governed_seen": bool, "since": "<ISO 8601 UTC of the + last change>"}``. Raises ``OSError`` when the file cannot be written or its lock cannot be held + (an operator command).""" + if not (restricted or governed): + return + path = _markers_path(hermes_home) + with _markers_lock(path.parent): + current = read_markers(hermes_home) + _write_markers( + path, + Markers( + restricted_seen=current.restricted_seen and not restricted, + governed_seen=current.governed_seen and not governed, + ), + ) -def e7_inputs(hermes_home: str, platform: str) -> tuple[tuple[str, ...], tuple[str, ...]] | None: - """What rule E7 judges, read without network from the profile at *hermes_home*: the variable - NAMES in its ``.env`` (never a value) and the toolset list ``platform_toolsets.<platform>`` of its - config.yaml, exactly as configured. ``None`` when either cannot be read, which fails E7 (the one - reader P-C, P-D and P-E share). S1 stub: ``None``.""" - return None +def seen_markers(init_kwargs: Mapping[str, Any], decision: Decision) -> dict[str, bool]: + """The markers an agent build raises (``raise_markers(home, **seen_markers(init, decision))``, + design 02 §4.2 below the table): ``governed_seen`` for every session that serves an access group + (rows 2 to 4), ``restricted_seen`` for ``restricted_profile: true`` and for every session of a + restricted group, bound or not. Nothing here ever lowers a marker.""" + flags: dict[str, bool] = {} + if decision.context is not None: + flags["governed_seen"] = True + if init_kwargs.get("restricted_profile") is True or (decision.context is not None and decision.strict): + flags["restricted_seen"] = True + return flags + + +# -- the decision ------------------------------------------------------------------------------------ + + +def _fork(init: Mapping[str, Any]) -> bool: + return init.get("agent_context") == "subagent" or init.get("platform") == "subagent" + + +def _session_platform(init: Mapping[str, Any], parent_platform: str | None) -> str | None: + """The platform the session is used on: a fork's parent session's (unknown: ``None``), else the + one ``initialize`` names.""" + platform = parent_platform if _fork(init) else init.get("platform") + return platform.strip().lower() if isinstance(platform, str) and platform.strip() else None + + +def _local(init: Mapping[str, Any], parent_platform: str | None) -> bool: + """A local, interactive session: a primary (or its memory flush) on a local platform, or a fork of + one. Cron and unknown agent contexts are not.""" + agent_context = init.get("agent_context") or "primary" + if agent_context not in ("primary", "flush", "subagent"): + return False + return _session_platform(init, parent_platform) in LOCAL_PLATFORMS + + +def _messaging(init: Mapping[str, Any], parent_platform: str | None) -> bool: + platform = _session_platform(init, parent_platform) + return platform is None or platform not in LOCAL_PLATFORMS | NON_MESSAGING_PLATFORMS + + +def _ungoverned( + init: Mapping[str, Any], parent_platform: str | None, settings: Mapping[str, Any], markers: Markers, row: int +) -> Decision: + mode = settings.get("ungoverned") + if mode == "auto": + if not markers.governed_seen: + return Decision("profile", f"row {row}: ungoverned auto, the profile saw no governed session") + mode = "local" + if mode == "profile": + return Decision("profile", f"row {row}: ungoverned profile") + if mode == "local": + if _local(init, parent_platform): + return Decision("profile", f"row {row}: ungoverned local, a local session") + return Decision("off", f"row {row}: ungoverned local, not a local session") + return Decision("off", f"row {row}: ungoverned off") + + +def _governed_unbound( + context: AccessContext, settings: Mapping[str, Any], open_profile: bool, row: int, why: str +) -> Decision: + """A governed group that binds nothing of its own: ``governed_unbound``. The profile's connection + only where the profile is known to serve no restricted group (``restricted_profile`` exactly + false, no ``restricted_seen``): there the core's promise holds that a provider in a restricted + profile reads and writes nothing without the group's own fields (V6).""" + if settings.get("governed_unbound") == "profile" and open_profile: + return Decision("profile", f"row {row}: {why}; governed_unbound profile", context=context) + if settings.get("governed_unbound") == "profile": + return Decision("off", f"row {row}: {why}; a restricted group runs in this profile", context=context) + return Decision("off", f"row {row}: {why}; governed_unbound off", context=context) + + +def _group(context: AccessContext, strict: bool, settings: Mapping[str, Any], open_profile: bool, row: int) -> Decision: + """Rows 2 and 3 (and 4 through them) for the group in *context*.""" + raw = context.fields + if not raw: + if strict: + return Decision("off", f"row {row}: restricted group without fields", context=context, strict=True) + return _governed_unbound(context, settings, open_profile, row, "group without fields") + if raw.get("enabled") is False: + return Decision("off", f"row {row}: enabled is false", context=context, strict=strict) + parsed = parse_fields(raw, scope_id=context.scope_id, strict=strict) + if isinstance(parsed, FieldError): + return Decision("off", f"row {row}: field {parsed.field}: {parsed.reason}", context=context, strict=strict) + if not parsed.key: # restricted groups never get here: E1 needs the key + return _governed_unbound(context, settings, open_profile, row, "group without a key") + return Decision("group", f"row {row}: group binding", context=context, fields=parsed, strict=strict) + + +def _with_group_platform( + context: AccessContext, current: AccessContext | None, parent_platform: str | None, init: Mapping[str, Any] +) -> AccessContext: + """The access kwargs name no platform: ``initialize``'s is the agent's (a ``delegate_task`` child + has ``subagent``). The group's platform is the turn's when ``current`` is the same group, else a + fork's parent session's (``""`` when unknown: no label of a server matches it).""" + if current is not None and (current.scope_id, current.group) == (context.scope_id, context.group): + return replace(context, platform=current.platform) + if _fork(init): + return replace(context, platform=parent_platform or "") + return context + + +def _home_profiles(init: Mapping[str, Any]) -> set[str]: + names = {derive_profile_name(str(init.get("hermes_home") or ""))} + identity = init.get("agent_identity") + if isinstance(identity, str) and identity: + names.add(identity) + return names + + +def _flag(init: Mapping[str, Any], key: str) -> bool | None: + value = init.get(key) + return value if isinstance(value, bool) else None + + +def _access_kwargs_passed(init: Mapping[str, Any]) -> bool: + """The core passes ``access_group`` and ``restricted_profile`` to every ``initialize`` (V5).""" + return "access_group" in init and "restricted_profile" in init def decide( @@ -265,20 +995,90 @@ def decide( markers: Markers, v8: bool, ) -> Decision: - """The decision table of design 02 §4.2 (first matching row): pure, no network, no files. - ``current``: ``current_access()`` at the build; ``parent_platform``: the copied session variable - ``HERMES_SESSION_PLATFORM`` of a fork (only when it is not in ``os.environ``). S1 stub: the - profile's own connection, as 0.19.1.""" - return Decision(kind="profile", reason="access groups are not available") + """The decision table of design 02 §4.2 (first matching row): pure, no network, no files, no + secret. ``current``: ``current_access()`` at the build; ``parent_platform``: the copied session + variable ``HERMES_SESSION_PLATFORM`` of a fork (``session_parent_platform()``); ``settings``: + ``load_settings`` (an unknown mode decides as ``off``); ``markers``: ``read_markers``; ``v8``: + ``access_supported()``. ``governed_unbound: profile`` opens the profile's connection only in a + profile known to serve no restricted group (``restricted_profile`` false, no ``restricted_seen``). + + 1. no access-group fields on the host: ``restricted_seen`` or ``restricted_profile`` true ⇒ + off; a named group binds nothing (restricted off, else ``governed_unbound``); else + ``ungoverned``; + 2. ``access_group`` with fields: the group binding (``enabled: false``, a broken field ⇒ off; + no ``key``: restricted off, else ``governed_unbound``); fields that are no mapping ⇒ off; + 3. ``access_group`` without fields: restricted ⇒ off, else ``governed_unbound``; + 4. no ``access_group`` but a turn's group (``current``) of this home's profile (or of none) ⇒ as + rows 2 and 3 with its fields; of another profile ⇒ off; + 5. ``restricted_profile`` true ⇒ off; 6. ``restricted_seen`` ⇒ off; + 7. a session on a messaging platform (a fork: its parent's; unknown counts as messaging) in a + profile with ``governed_seen``, or on a host that registers fields but passes no access + kwargs ⇒ off; an ``access_group`` of ``None`` is no proof the server is not governed (the + core passes none when it cannot read the turn's group); + 8. ``ungoverned``: ``profile``; ``local`` (local platforms, forks of local sessions); ``off``; + ``auto`` = ``profile`` until ``governed_seen``, then ``local``. + + The context of rows 2 to 4 carries the group's platform (the turn's, or a fork's parent's). + Which markers the build raises: ``seen_markers``.""" + init: Mapping[str, Any] = init_kwargs if isinstance(init_kwargs, Mapping) else {} + restricted_profile = _flag(init, "restricted_profile") + open_profile = restricted_profile is False and not markers.restricted_seen + group = init.get("access_group") + has_group = group is not None and group != "" + if not v8: + # No fields on this host, so no group binding. A host that still names a group or a restricted + # profile (access kwargs without the field registry) gets nothing more than rows 3 and 5 give. + if markers.restricted_seen: + return Decision("off", "row 1: a restricted group ran in this profile, the host has no access groups") + if restricted_profile is True: + return Decision("off", "row 1: a restricted group runs in this profile, the host has no fields") + if has_group: + context = context_from_init(init) if isinstance(group, str) else None + if context is None: + return Decision("off", "row 1: the access kwargs have an unknown form", strict=True) + context = _with_group_platform(context, current, parent_platform, init) + strict = is_strict(context, restricted_profile=restricted_profile, markers=markers) + return _group(replace(context, fields=MappingProxyType({})), strict, settings, open_profile, row=1) + return _ungoverned(init, parent_platform, settings, markers, row=1) + if has_group: + if not isinstance(group, str) or ( + init.get("access_fields") is not None and not isinstance(init.get("access_fields"), Mapping) + ): + return Decision("off", "row 2: the access kwargs have an unknown form", strict=True) + context = context_from_init(init) + if context is None: # unreachable: a non-empty str group always gives one + return Decision("off", "row 2: the access kwargs have an unknown form", strict=True) + context = _with_group_platform(context, current, parent_platform, init) + strict = is_strict(context, restricted_profile=restricted_profile, markers=markers) + return _group(context, strict, settings, open_profile, row=2 if context.fields else 3) + if current is not None: + strict = is_strict(current, restricted_profile=restricted_profile, markers=markers) + if current.profile is not None and current.profile not in _home_profiles(init): + return Decision("off", "row 4: the turn's group runs in another profile", context=current, strict=strict) + return _group(current, strict, settings, open_profile, row=4) + if restricted_profile is True: + return Decision("off", "row 5: a restricted group runs in this profile") + if markers.restricted_seen: + return Decision("off", "row 6: a restricted group ran in this profile") + if _messaging(init, parent_platform): + if markers.governed_seen: + return Decision("off", "row 7: a messaging session without its access group in a governed profile") + if not _access_kwargs_passed(init): + return Decision("off", "row 7: a messaging session on a host that passes no access kwargs") + return _ungoverned(init, parent_platform, settings, markers, row=8) __all__ = [ + "GOVERNED_UNBOUND_MODES", "HOOK_NAME", "LOCAL_PLATFORMS", "MARKERS_FILE", "NAMESPACE", + "NON_MESSAGING_PLATFORMS", + "RESTRICTED_ALLOW_ITEMS", "SCHEMA", "SETTINGS_DEFAULTS", + "UNGOVERNED_MODES", "AccessContext", "Decision", "FieldError", @@ -295,5 +1095,8 @@ def decide( "raise_markers", "read_markers", "reset_markers", + "restricted_key_prefix", + "seen_markers", "session_parent_platform", + "valid_base_url", ] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py index fc032c8d1..5e5143a7f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -5,7 +5,6 @@ S1_PENDING = frozenset( { "P-A", - "P-B", "P-C", "P-D", "P-E", diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_rules.py new file mode 100644 index 000000000..08ee061b3 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_rules.py @@ -0,0 +1,692 @@ +"""P-B beyond the S1 red tests (design 02 §7.3 row P-B, negatives S1 could not state): what each +protective row decides when its evidence is partial or malformed, the field forms the hook and the +binding share, the bounded settings, the markers under concurrency, the E7 inputs, and the core +imports ``hermes plugins validate`` reports.""" + +from __future__ import annotations + +import json +import logging +import threading +import time +from pathlib import Path + +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-B") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pb") +acc = ah.plugin_module(_PKG, "memory.access") + +K, M = "t:d111-k", "t:d111-members" +RESTRICTED_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M, "base_blocks": ["b1"]} +OPS_FIELDS = {"key": "CTX_KEY_OPS", "read": [K], "write": "t:d111-ops"} +OPS_NO_KEY = {"read": [K], "write": "t:d111-ops"} + + +def _settings(**overrides): + return {**dict(acc.SETTINGS_DEFAULTS), **overrides} + + +def _init(platform="discord", agent_context="primary", **v5): + return {"platform": platform, "agent_context": agent_context, "hermes_home": "/h/profiles/members", **v5} + + +def _decide(init, *, current=None, parent=None, markers=None, v8=True, **settings): + return acc.decide(init, current, parent, _settings(**settings), markers or acc.Markers(), v8) + + +def _group_init(fields, *, restricted=True, truth_filter=False, restricted_profile=False): + return _init( + **ah.v5_kwargs( + scope_id="111", + group="members", + group_restricted=restricted, + fields=fields, + truth_filter=truth_filter, + restricted_profile=restricted_profile, + ) + ) + + +# -- register(ctx) ------------------------------------------------------------------------------ + + +def test_registered_schema_is_plain_dicts_the_core_accepts(monkeypatch): + host = ah.install(monkeypatch, v8=True) + collector = host.collector() + _PKG.register(collector) + (schema,) = collector.access_fields + assert type(schema) is dict and all(type(spec) is dict for spec in schema.values()) + for name, spec in schema.items(): + # hermes_cli/access_fields.py: description up to MAX_TEXT (512) characters + assert len(spec["description"]) <= 512, name + + +def test_a_failing_field_registration_costs_neither_provider_nor_skill(monkeypatch, caplog): + host = ah.install(monkeypatch, v8=True) + collector = host.collector() + + def refuse(schema): + collector.calls.append(("register_access_fields", (schema,), {})) + raise ValueError("access group fields of ctx_checkpoint: refused") + + collector.register_access_fields = refuse + with caplog.at_level(logging.WARNING): + _PKG.register(collector) + assert collector.called("register_access_fields") == 1 + assert collector.called("register_memory_provider") == 1 + assert collector.called("register_skill") == 1 + # named: without the fields the core refuses every restricted group on this provider's profiles + warnings = [r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING] + assert len(warnings) == 1 and "access-group fields" in warnings[0] + + +@pytest.mark.s1_green +def test_access_supported_is_false_when_the_public_class_cannot_be_imported(monkeypatch): + ah.install(monkeypatch, v8=True) + monkeypatch.setitem(__import__("sys").modules, "hermes_cli.plugins", None) + assert acc.access_supported() is False + + +# -- current_access and the init kwargs --------------------------------------------------------- + + +def test_current_access_hands_out_a_copy_of_its_namespace(monkeypatch): + ah.install(monkeypatch, v8=True) + fields = {"read": [K], "write": M} + access = ah.make_access(fields=fields) + with ah.turn(access): + got = acc.current_access() + access.fields["ctx_checkpoint"]["read"].append("t:d222-k") # the core's copy changes later + assert got is not None and list(got.fields["read"]) == [K] + assert got.admin is False and got.profile == "members" + + +@pytest.mark.s1_green +def test_current_access_is_none_when_the_core_raises(monkeypatch): + host = ah.install(monkeypatch, v8=True) + + def broken(): + raise RuntimeError("table unreadable") + + monkeypatch.setattr(host.module, "current_access", broken) + assert acc.current_access() is None + + +def test_context_from_init_reads_a_dropped_restriction_as_unknown(): + init = _group_init(OPS_FIELDS, restricted=False, truth_filter=True) + assert "access_group_restricted" not in init and "restricted_profile" not in init + ctx = acc.context_from_init({**init, "agent_identity": "ops"}) + assert ctx is not None and ctx.restricted is None and ctx.profile == "ops" + decision = _decide(init) + assert decision.kind == "off" and decision.strict is True # the unrestricted-looking key fails E1 + + +# -- the decision table: protective rows with partial or malformed evidence ----------------------- + + +def test_decide_reads_no_secret_and_names_no_value(monkeypatch): + host = ah.install(monkeypatch, v8=True, secrets={"CTX_KEY_111_MEMBERS": "ctx_member_secret"}) + bound = _decide(_group_init(RESTRICTED_FIELDS)) + broken = _decide(_group_init({**RESTRICTED_FIELDS, "key": "CTX_KEY_222_MEMBERS"})) + assert bound.kind == "group" and broken.kind == "off" + assert host.secrets.total_reads() == 0 + assert "key" in broken.reason and "222" not in broken.reason + + +@pytest.mark.parametrize( + "malformed", + [ + {"access_group": "ops", "access_fields": [["key", "CTX_KEY_OPS"]]}, + {"access_group": "ops", "access_fields": "key=CTX_KEY_OPS"}, + {"access_group": ["ops"], "access_fields": {}}, + ], +) +def test_row2_access_kwargs_of_an_unknown_form_are_off(malformed): + """Even for a group known to be unrestricted, whose empty fields would follow + ``governed_unbound``: fields that are no mapping are no proof of "no fields".""" + init = _init(scope_id="111", access_group_restricted=False, restricted_profile=False, **malformed) + assert _decide(init, governed_unbound="profile").kind == "off" + well_formed = _init(scope_id="111", access_group_restricted=False, restricted_profile=False, access_group="ops") + assert _decide({**well_formed, "access_fields": {}}, governed_unbound="profile").kind == "profile" + + +def test_row2_an_unknown_field_is_off(): + decision = _decide(_group_init({**OPS_FIELDS, "keys": "CTX_KEY_OPS"}, restricted=False)) + assert decision.kind == "off" and "keys" in decision.reason + + +def test_row2_unrestricted_group_with_a_key_binds_unstrict(): + decision = _decide(_group_init(OPS_FIELDS, restricted=False)) + assert decision.kind == "group" and decision.strict is False + assert decision.fields is not None and decision.fields.store == "t:d111-ops" + + +def test_row4_a_turn_group_of_another_profile_is_off(): + current = acc.AccessContext("discord", "111", "ops", "ops", False, fields=OPS_FIELDS) + decision = _decide(_init(**ah.v5_kwargs()), current=current, governed_unbound="profile") + assert decision.kind == "off" and decision.context is current + + +def test_row4_a_turn_group_of_the_identity_profile_binds(): + current = acc.AccessContext("discord", "111", "ops", "ops", False, fields=OPS_FIELDS) + init = {**_init(**ah.v5_kwargs()), "agent_identity": "ops", "hermes_home": "/srv/hermes"} + assert _decide(init, current=current).kind == "group" + + +def test_row4_without_fields_restricted_off_unrestricted_governed_unbound(): + restricted = acc.AccessContext("discord", "111", "members", None, True) + unrestricted = acc.AccessContext("discord", "111", "ops", None, False) + init = _init(**ah.v5_kwargs()) + assert _decide(init, current=restricted, governed_unbound="profile").kind == "off" + assert _decide(init, current=unrestricted).kind == "off" + assert _decide(init, current=unrestricted, governed_unbound="profile").kind == "profile" + + +def test_row4_a_context_of_unknown_restriction_in_an_unknown_profile_is_strict(): + current = acc.AccessContext("discord", "111", "ops", None, None, fields=OPS_FIELDS) + decision = _decide(_init(), current=current) + assert decision.kind == "off" and decision.strict is True + + +def test_row5_comes_before_ungoverned_profile(): + init = _init(platform="cli", **ah.v5_kwargs(restricted_profile=True)) + assert _decide(init, ungoverned="profile").kind == "off" + + +def test_row7_holds_on_a_host_that_drops_false_values(): + init = _init(platform="discord", **ah.v5_kwargs(truth_filter=True)) + assert "access_group" not in init + assert _decide(init, markers=acc.Markers(governed_seen=True), ungoverned="profile").kind == "off" + + +@pytest.mark.parametrize( + ("platform", "agent_context", "parent", "kind"), + [ + ("subagent", "subagent", "discord", "off"), + ("subagent", "subagent", None, "off"), + ("curator", "subagent", "cli", "profile"), + ("irc", "primary", None, "off"), + ("", "primary", None, "off"), + ("cron", "cron", None, "profile"), + ("api_server", "primary", None, "profile"), + ("webhook", "primary", None, "profile"), + ], +) +def test_row7_closes_messaging_and_unknown_platforms_only(platform, agent_context, parent, kind): + init = _init(platform=platform, agent_context=agent_context, **ah.v5_kwargs()) + decision = _decide(init, parent=parent, markers=acc.Markers(governed_seen=True), ungoverned="profile") + assert decision.kind == kind, decision.reason + + +@pytest.mark.parametrize("parent", [None, "discord", "telegram"]) +def test_ungoverned_local_keeps_forks_of_unknown_or_messaging_sessions_off(parent): + init = _init(platform="subagent", agent_context="subagent", **ah.v5_kwargs()) + assert _decide(init, parent=parent, ungoverned="local").kind == "off" + + +def test_ungoverned_local_refuses_cron_on_a_local_platform_and_unknown_contexts(): + assert _decide(_init(platform="cli", agent_context="cron"), ungoverned="local").kind == "off" + assert _decide(_init(platform="cli", agent_context="review"), ungoverned="local").kind == "off" + assert _decide(_init(platform="cli", agent_context="flush"), ungoverned="local").kind == "profile" + + +@pytest.mark.parametrize("value", ["locl", "", None, True, "Profile "]) +def test_an_unknown_ungoverned_mode_decides_off_never_profile(value): + """``decide`` takes the settings as ``load_settings`` normalized them; anything else is off.""" + assert _decide(_init(platform="cli"), ungoverned=value).kind == "off" + + +def test_an_unknown_governed_unbound_mode_is_off(): + assert _decide(_group_init({}, restricted=False), governed_unbound="yes").kind == "off" + + +@pytest.mark.parametrize("platform", ["cli", "discord", "cron", "api_server"]) +@pytest.mark.parametrize("v8", [True, False]) +def test_without_access_kwargs_and_markers_the_defaults_keep_0_19_1(platform, v8): + """No access context: a Hermes without the core PR passes no access kwargs, one with it passes + them empty (``None``/``False``/``{}``, D5).""" + init = {"platform": platform, "agent_context": "cron" if platform == "cron" else "primary", "hermes_home": "/h"} + decision = _decide({**init, **(ah.v5_kwargs() if v8 else {})}, v8=v8) + assert decision.kind == "profile" and decision.context is None + + +@pytest.mark.parametrize(("platform", "kind"), [("discord", "off"), ("irc", "off"), ("cli", "profile")]) +def test_row7_a_host_with_fields_but_without_access_kwargs_closes_messaging(platform, kind): + """A host that registers fields (the core then trusts this provider in restricted profiles) but + tells ``initialize`` nothing about the group cannot have its messaging sessions placed.""" + init = {"platform": platform, "agent_context": "primary", "hermes_home": "/h"} + assert _decide(init, ungoverned="profile").kind == kind + + +def test_row6_holds_with_the_explicit_false_the_core_passes(): + init = _init(platform="cli", **ah.v5_kwargs(restricted_profile=False)) + assert init["restricted_profile"] is False + assert _decide(init, markers=acc.Markers(restricted_seen=True), ungoverned="profile").kind == "off" + + +@pytest.mark.parametrize( + ("fields", "restricted_profile", "markers"), + [ + ({}, True, acc.Markers()), + (OPS_NO_KEY, True, acc.Markers()), + ({}, False, acc.Markers(restricted_seen=True)), + ({}, None, acc.Markers()), + ], +) +def test_governed_unbound_never_opens_a_profile_that_serves_restricted_groups(fields, restricted_profile, markers): + """V6: in a profile a restricted group runs in, the provider reads and writes nothing without the + group's own fields; an unrestricted group there gets no profile connection either.""" + init = _group_init(fields, restricted=False) + if restricted_profile is None: + init.pop("restricted_profile") + else: + init["restricted_profile"] = restricted_profile + assert _decide(init, markers=markers, governed_unbound="profile").kind == "off" + open_init = {**_group_init(fields, restricted=False), "restricted_profile": False} + assert _decide(open_init, governed_unbound="profile").kind == "profile" + + +@pytest.mark.parametrize( + ("current", "parent", "platform"), + [ + (acc.AccessContext("discord", "111", "members", "members", True), None, "discord"), + (None, "discord", "discord"), + (None, None, ""), + (acc.AccessContext("telegram", "999", "other", "members", True), "discord", "discord"), + ], +) +def test_a_fork_binds_with_the_groups_platform_not_its_own(current, parent, platform): + """``delegate_task`` builds its child with ``platform="subagent"``; the access kwargs name none.""" + init = {**_group_init(RESTRICTED_FIELDS), "platform": "subagent", "agent_context": "subagent"} + decision = _decide(init, current=current, parent=parent) + assert decision.context is not None and decision.context.platform == platform + primary = _decide(_group_init(RESTRICTED_FIELDS), current=current, parent=parent) + assert primary.context is not None and primary.context.platform == "discord" + + +def test_row1_a_host_with_access_kwargs_but_without_fields_binds_nothing(): + """A core that passes the access kwargs but registers no fields (VB-13 "11a"): V8 is false.""" + restricted = _group_init(RESTRICTED_FIELDS, restricted=True) + unrestricted = _group_init(OPS_FIELDS, restricted=False) + assert _decide(restricted, v8=False, governed_unbound="profile").kind == "off" + assert _decide(unrestricted, v8=False).kind == "off" + assert _decide(unrestricted, v8=False, governed_unbound="profile").kind == "profile" + profile_only = _init(platform="cli", **ah.v5_kwargs(restricted_profile=True)) + assert _decide(profile_only, v8=False, ungoverned="profile").kind == "off" + + +def test_row1_auto_after_governed_seen_closes_messaging_on_a_host_without_v8(): + seen = acc.Markers(governed_seen=True) + assert _decide(_init(platform="discord"), v8=False, markers=seen).kind == "off" + assert _decide(_init(platform="cli"), v8=False, markers=seen).kind == "profile" + + +# -- the markers a build raises --------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("init", "current", "expected"), + [ + (_group_init(RESTRICTED_FIELDS), None, {"governed_seen": True, "restricted_seen": True}), + (_group_init({}, restricted=True), None, {"governed_seen": True, "restricted_seen": True}), + (_group_init(OPS_FIELDS, restricted=False), None, {"governed_seen": True}), + (_init(platform="cli", **ah.v5_kwargs(restricted_profile=True)), None, {"restricted_seen": True}), + (_init(platform="cli", **ah.v5_kwargs(restricted_profile=False)), None, {}), + ( + _init(**ah.v5_kwargs()), + acc.AccessContext("discord", "111", "ops", "ops", False, fields=OPS_FIELDS), + {"governed_seen": True}, + ), + ], +) +def test_seen_markers_follow_the_session_never_lower(init, current, expected): + decision = _decide(init, current=current) + assert acc.seen_markers(init, decision) == expected + assert all(value is True for value in acc.seen_markers(init, decision).values()) + + +# -- field forms ------------------------------------------------------------------------------------ + + +def test_an_empty_read_list_is_no_unset_read(): + """``read: []`` would read the key's whole read set if taken as "not set".""" + parsed = acc.parse_fields({"key": "CTX_KEY_OPS", "read": []}, scope_id="111", strict=False) + assert isinstance(parsed, acc.FieldError) and parsed.field == "read" + + +@pytest.mark.parametrize("name", ["CTX_KEY", "CTX_API_KEY", "CTX_KEY_OPS", "CTX_KEY_111_OPS_2"]) +def test_unrestricted_key_names(name): + assert isinstance(acc.parse_fields({"key": name}, scope_id="111", strict=False), acc.GroupFields) + + +@pytest.mark.parametrize("name", ["CTX_KEYX", "CTX_KEY_", "ctx_key", "OPENAI_API_KEY", "DISCORD_BOT_TOKEN", 7]) +def test_key_names_outside_ctx_are_refused(name): + parsed = acc.parse_fields({"key": name}, scope_id="111", strict=False) + assert isinstance(parsed, acc.FieldError) and parsed.field == "key" + + +@pytest.mark.parametrize( + ("scope_id", "key"), + [("111", "CTX_KEY_111_"), ("111", "CTX_KEY_1111_MEMBERS"), ("111", "CTX_KEY_MEMBERS"), ("a:b", "CTX_KEY_A_B_X")], +) +def test_restricted_key_must_name_its_own_server(scope_id, key): + parsed = acc.parse_fields({**RESTRICTED_FIELDS, "key": key}, scope_id=scope_id, strict=True) + assert isinstance(parsed, acc.FieldError) and parsed.field == "key" + + +@pytest.mark.parametrize("name", ["CTX_BASE_URL", "CTX_BASE_URL_EU"]) +def test_base_url_names(name): + assert isinstance(acc.parse_fields({"base_url": name}, scope_id="111", strict=False), acc.GroupFields) + + +@pytest.mark.parametrize("name", ["CTX_BASE_URLX", "CTX_KEY", "HOME_URL", "ctx_base_url"]) +def test_base_url_names_outside_ctx_are_refused(name): + parsed = acc.parse_fields({"base_url": name}, scope_id="111", strict=False) + assert isinstance(parsed, acc.FieldError) and parsed.field == "base_url" + + +@pytest.mark.parametrize( + ("change", "field"), + [ + ({"read": [K, K]}, "read"), + ({"read": []}, "read"), + ({"read": ["u:d111-k"]}, "read"), + ({"write": "u:d111-members"}, "write"), + ({"tenant": None}, "tenant"), + ({"write": None}, "write"), + ({"base_blocks": ["b1", "b1"]}, "base_blocks"), + ({"base_blocks": ["bad id"]}, "base_blocks"), + ({"base_max_chars": True}, "base_max_chars"), + ({"base_max_chars": 8001}, "base_max_chars"), + ({"base_rev": -1}, "base_rev"), + ({"enabled": "no"}, "enabled"), + ({"recall": 1}, "recall"), + ({"capture": "true"}, "capture"), + ], +) +def test_restricted_forms_name_the_broken_field(change, field): + parsed = acc.parse_fields({**RESTRICTED_FIELDS, **change}, scope_id="111", strict=True) + assert isinstance(parsed, acc.FieldError) and parsed.field == field, parsed + + +def test_restricted_groups_never_store_and_unset_values_stay_unset(): + parsed = acc.parse_fields({**RESTRICTED_FIELDS, "store": K}, scope_id="111", strict=True) + assert isinstance(parsed, acc.GroupFields) + assert parsed.store == "" and parsed.recall is None and parsed.capture is None and parsed.base_rev == 0 + open_parsed = acc.parse_fields({"key": "CTX_KEY_OPS"}, scope_id="111", strict=False) + assert isinstance(open_parsed, acc.GroupFields) and open_parsed.read == () and open_parsed.store == "" + + +@pytest.mark.parametrize( + ("url", "ok"), + [ + ("https://ctx.example.org", True), + ("https://ctx.example.org:8443/base", True), + ("http://ctx.example.org", False), + ("https://user:pass@ctx.example.org", False), + ("https://ctx.example.org/?k=v", False), + ("https://ctx.example.org/#x", False), + (" https://ctx.example.org", False), + ("https://", False), + ("https://ctx.example.org:0", False), + ("", False), + ], +) +def test_valid_base_url(url, ok): + assert acc.valid_base_url(url) is ok + + +# -- settings --------------------------------------------------------------------------------------- + + +def _config(home: Path, body: str) -> str: + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n" + body, encoding="utf-8") + return str(home) + + +def test_yaml_off_is_off_not_unknown(tmp_path, caplog): + with caplog.at_level(logging.WARNING): + settings = acc.load_settings(_config(tmp_path, " ungoverned: off\n governed_unbound: off\n")) + assert (settings["ungoverned"], settings["governed_unbound"]) == ("off", "off") + assert not caplog.records + + +def test_an_unknown_mode_is_off_with_one_warning(tmp_path, caplog): + home = _config(tmp_path, " ungoverned: locl-typo\n") + with caplog.at_level(logging.WARNING): + assert acc.load_settings(home)["ungoverned"] == "off" + assert acc.load_settings(home)["ungoverned"] == "off" + assert len([r for r in caplog.records if "ungoverned" in r.getMessage()]) == 1 + + +def test_restricted_allow_keeps_only_recall_and_capture(tmp_path): + settings = acc.load_settings(_config(tmp_path, " restricted_allow: [CAPTURE, bogus, recall]\n")) + assert settings["restricted_allow"] == ("recall", "capture") + scalar = tmp_path / "scalar" + scalar.mkdir() + assert acc.load_settings(_config(scalar, " restricted_allow: recall\n"))["restricted_allow"] == () + + +def test_numbers_are_clamped_and_non_numbers_are_defaults(tmp_path): + settings = acc.load_settings( + _config(tmp_path, " base_workers: 0\n base_cache_s: 'soon'\n verify_timeout_s: true\n") + ) + assert settings["base_workers"] == 1 + assert settings["base_cache_s"] == acc.SETTINGS_DEFAULTS["base_cache_s"] + assert settings["verify_timeout_s"] == acc.SETTINGS_DEFAULTS["verify_timeout_s"] + + +def test_a_missing_config_gives_the_defaults(tmp_path): + assert dict(acc.load_settings(str(tmp_path))) == dict(acc.SETTINGS_DEFAULTS) + + +def test_an_unreadable_config_gives_the_strict_settings(tmp_path): + (tmp_path / "config.yaml").write_text("memory: [unclosed\n", encoding="utf-8") + settings = acc.load_settings(str(tmp_path)) + assert (settings["ungoverned"], settings["governed_unbound"], settings["restricted_allow"]) == ("off", "off", ()) + + +@pytest.mark.parametrize( + ("text", "strict"), + [ + ("memory:\n ctx_checkpoint: local\n", True), + ("memory:\n ctx_checkpoint: [ungoverned, profile]\n", True), + ("memory: ctx_checkpoint\n", True), + ("memory:\n ctx_checkpoint:\n", False), + ("memory:\n", False), + ], +) +def test_a_settings_section_of_another_form_gives_the_strict_settings(tmp_path, text, strict): + (tmp_path / "config.yaml").write_text(text, encoding="utf-8") + settings = acc.load_settings(str(tmp_path)) + assert settings["ungoverned"] == ("off" if strict else "auto") + + +def test_the_plugins_form_and_ctx_json_set_nothing(tmp_path): + (tmp_path / "config.yaml").write_text( + "plugins:\n entries:\n ctx_checkpoint:\n settings:\n ungoverned: profile\n", encoding="utf-8" + ) + (tmp_path / "ctx.json").write_text(json.dumps({"governed_unbound": "profile"}), encoding="utf-8") + settings = acc.load_settings(str(tmp_path)) + assert (settings["ungoverned"], settings["governed_unbound"]) == ("auto", "off") + + +def test_the_current_home_is_read_through_hermes_config(_isolated_hermes_home): + home = _config(_isolated_hermes_home, " ungoverned: local\n base_workers: 99\n") + settings = acc.load_settings(home) + assert settings["ungoverned"] == "local" and settings["base_workers"] == 32 + + +# -- markers ---------------------------------------------------------------------------------------- + + +def test_raising_a_set_marker_writes_nothing(tmp_path): + home = str(tmp_path) + acc.raise_markers(home) + assert not (tmp_path / "ctx_state").exists() + acc.raise_markers(home, governed_seen=True) + path = tmp_path / "ctx_state" / "access-mode.json" + first = path.read_text(encoding="utf-8") + time.sleep(1.1) + acc.raise_markers(home, governed_seen=True) + assert path.read_text(encoding="utf-8") == first + assert json.loads(first)["governed_seen"] is True and json.loads(first)["restricted_seen"] is False + + +def test_concurrent_raises_lose_no_marker(tmp_path, monkeypatch): + home = str(tmp_path) + real = acc.read_markers + calls = {"n": 0} + + def slow_read(path_home): + markers = real(path_home) + calls["n"] += 1 + time.sleep(0.05) # widen the read-modify-write window + return markers + + monkeypatch.setattr(acc, "read_markers", slow_read) + threads = [ + threading.Thread(target=acc.raise_markers, args=(home,), kwargs={"restricted_seen": True}), + threading.Thread(target=acc.raise_markers, args=(home,), kwargs={"governed_seen": True}), + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert real(home) == acc.Markers(restricted_seen=True, governed_seen=True) + + +def test_an_unknown_marker_name_is_a_programming_error(tmp_path): + with pytest.raises(ValueError): + acc.raise_markers(str(tmp_path), restricted=True) + + +@pytest.mark.parametrize( + "content", + ["{}", '{"restricted_seen": "no", "governed_seen": 0}', "[]", '"x"', "{" + " " * 70_000 + "}"], +) +def test_marker_files_of_unknown_form_count_as_set(tmp_path, content): + (tmp_path / "ctx_state").mkdir() + (tmp_path / "ctx_state" / "access-mode.json").write_text(content, encoding="utf-8") + assert acc.read_markers(str(tmp_path)) == acc.Markers(restricted_seen=True, governed_seen=True) + + +def test_a_marker_path_that_is_no_file_counts_as_set(tmp_path): + (tmp_path / "ctx_state" / "access-mode.json").mkdir(parents=True) + assert acc.read_markers(str(tmp_path)) == acc.Markers(restricted_seen=True, governed_seen=True) + + +def test_an_unwritable_marker_is_a_warning_not_an_error(tmp_path, caplog, monkeypatch): + def full_disk(path, markers): + raise OSError(28, "No space left on device") + + monkeypatch.setattr(acc, "_write_markers", full_disk) + with caplog.at_level(logging.WARNING): + acc.raise_markers(str(tmp_path), restricted_seen=True) + assert any("marker" in r.getMessage() for r in caplog.records) + assert acc.read_markers(str(tmp_path)) == acc.Markers() + + +def test_a_marker_file_that_cannot_be_read_needs_no_raise(tmp_path, monkeypatch): + """An unreadable file already counts as both set: raising writes nothing over it.""" + (tmp_path / "ctx_state").write_text("a file where the directory belongs", encoding="utf-8") + monkeypatch.setattr(acc, "_write_markers", lambda path, markers: pytest.fail("no write expected")) + acc.raise_markers(str(tmp_path), restricted_seen=True, governed_seen=True) + + +@pytest.mark.skipif(acc.fcntl is None, reason="process lock only on this platform") +def test_a_busy_marker_lock_writes_nothing_unserialized(tmp_path, monkeypatch, caplog): + import fcntl + + monkeypatch.setattr(acc, "_MARKERS_LOCK_WAIT_S", 0.2) + (tmp_path / "ctx_state").mkdir() + holder = open(tmp_path / "ctx_state" / "access-mode.lock", "a+") # noqa: SIM115 - held across the calls + try: + fcntl.flock(holder.fileno(), fcntl.LOCK_EX) + with caplog.at_level(logging.WARNING): + acc.raise_markers(str(tmp_path), restricted_seen=True) + assert not (tmp_path / "ctx_state" / "access-mode.json").exists() + assert any("marker" in r.getMessage() for r in caplog.records) + with pytest.raises(OSError): + acc.reset_markers(str(tmp_path), governed=True) + finally: + holder.close() + acc.raise_markers(str(tmp_path), restricted_seen=True) + assert acc.read_markers(str(tmp_path)).restricted_seen is True + + +def test_reset_lowers_only_the_named_marker_even_from_an_unreadable_file(tmp_path): + (tmp_path / "ctx_state").mkdir() + (tmp_path / "ctx_state" / "access-mode.json").write_text("{broken", encoding="utf-8") + acc.reset_markers(str(tmp_path), restricted=True) + assert acc.read_markers(str(tmp_path)) == acc.Markers(restricted_seen=False, governed_seen=True) + acc.reset_markers(str(tmp_path), governed=True) + assert acc.read_markers(str(tmp_path)) == acc.Markers() + + +# -- E7 inputs -------------------------------------------------------------------------------------- + + +def _profile(home: Path, toolsets: str, env: str | None) -> str: + (home / "config.yaml").write_text(f"platform_toolsets:\n discord: {toolsets}\n", encoding="utf-8") + if env is not None: + (home / ".env").write_text(env, encoding="utf-8") + return str(home) + + +def test_e7_inputs_are_names_and_the_saved_list(tmp_path): + env = "CTX_KEY_111_MEMBERS=ctx_secret_one\nexport CTX_KEY_222_MEMBERS='ctx_secret_two'\n# CTX_KEY_333_X=y\n" + got = acc.e7_inputs(_profile(tmp_path, "[web, file]", env), "discord") + assert got == (("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS"), ("web", "file")) + assert "ctx_secret" not in repr(got) + + +def test_e7_inputs_read_the_text_form_older_hermes_saved(tmp_path): + got = acc.e7_inputs(_profile(tmp_path, '\'["web", "terminal"]\'', ""), "discord") + assert got == ((), ("web", "terminal")) + + +def test_e7_inputs_without_a_saved_list_or_a_readable_config_fail(tmp_path): + assert acc.e7_inputs(_profile(tmp_path, "[web]", None), "telegram") is None + assert acc.e7_inputs(_profile(tmp_path, "hermes-discord", None), "discord") is None + broken = tmp_path / "broken" + broken.mkdir() + (broken / "config.yaml").write_text("platform_toolsets: [unclosed\n", encoding="utf-8") + assert acc.e7_inputs(str(broken), "discord") is None + + +def test_e7_inputs_with_an_unreadable_env_fail(tmp_path): + """Hermes' tokenizer answers an unreadable ``.env`` with no names; E7 must not see "no keys".""" + home = _profile(tmp_path, "[web]", None) + (tmp_path / ".env").mkdir() + assert acc.e7_inputs(home, "discord") is None + + +def test_e7_inputs_without_an_env_file_have_no_names(tmp_path): + assert acc.e7_inputs(_profile(tmp_path, "[web]", None), "discord") == ((), ("web",)) + + +# -- the core imports hermes plugins validate reports ------------------------------------------------ + +# ``hermes plugins validate`` for ctx_checkpoint 0.19.1 (pinned Hermes): these private core modules +# and nothing else. Access groups reach the host through the published plugin API only. +BASELINE_PRIVATE_IMPORT_MODULES = frozenset( + { + "tools.mcp_tool_registration", + "plugins.memory.config_schema", + "tools.interrupt", + "hermes_cli.mcp_config", + } +) + + +@pytest.mark.s1_green +def test_validate_reports_no_private_core_import_beyond_0_19_1(): + private_imports = pytest.importorskip("hermes_cli.plugin_validate_private_imports") + findings = private_imports.private_import_findings(ah.PLUGIN_DIR) + assert len(findings) <= 12, findings + modules = {line.split(" ", 1)[1].rsplit(".", 1)[0] for line in findings} + assert modules <= BASELINE_PRIVATE_IMPORT_MODULES, findings From 17a89c103f56f0b8802562df288113e860e1c20b Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 02:32:26 +0100 Subject: [PATCH 05/65] =?UTF-8?q?chore(ctx=5Fcheckpoint):=20S2=20P-G=20?= =?UTF-8?q?=E2=80=94=20a=20checkpoint=20chain=20plans=20its=20rate=20windo?= =?UTF-8?q?w=20below=20the=20write=20limit=20the=20server=20reports=20for?= =?UTF-8?q?=20its=20key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Design 02 §7.3 row P-G (CC-7), built against the S1 contract. window_writes keeps 0.19.1's window (max_parts parts, at most 95, plus manifest and head) and lowers it to the reported whoami.rate_limit_write less the headroom 0.19.1 leaves of ctx's default limit (100 - 97 = 3, RATE_WINDOW_HEADROOM), never below one write; ChainWriter plans every run with its rate_limit_write. ctx counts writes per key and every writer of the process with that key shares one server entry, so a run reports its writer's limit to the entry, and the entry keeps every window planned on it below the limit last reported for the key — also the window of a writer that knows none and of a run that started before the report. Only a positive int is a limit: a server without the field, 0 or less (ctx: unlimited) and any other value leave the window as it was, and a limit at or over the default never raises it. A chain bound to a limit of 40 is paced at 37 writes a window and never refused, where it planned 97 and ran into ctx's refusals before; without a tighter limit every call, its arguments and every wait are the same as without the field. The cluster's red S1 test is switched on; tests added for the real chain path, two sessions of one key, the headroom, the floor of one write and the values that are no limit. Typed chore, not feat: the user-facing docs come with P-F; the integrator's squash carries the type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ctx_checkpoint/memory/checkpoint.py | 83 ++++- .../ctx_checkpoint/tests/fakes/s1_pending.py | 1 - .../tests/test_access_pg_window.py | 318 ++++++++++++++++++ 3 files changed, 383 insertions(+), 19 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py index 578378cdb..c58de0b78 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py @@ -82,14 +82,18 @@ MIN_PART_TEXT_BYTES = 4 * 1024 # Root session id as a title token: at most this many characters of [A-Za-z0-9_.-]. ROOT_TOKEN_MAX = 48 -# Server write rate limit: 100 writes per key over a sliding 60 s window -# (query.rate_limit_write, go/internal/config/config.go:870; counted over context_access_log, -# go/internal/store/blocks.go CheckRateLimitByAction). A chain writes at most max_parts parts -# plus its manifest and head inside one window — what 0.9.0 wrote in one burst — and paces the -# rest into the next windows (0.10.0); the gap to 100 is headroom for facts, the memory mirror -# and other sessions on the same key. +# Server write rate limit: 100 writes per key over a sliding 60 s window by default +# (query.rate_limit_write, go/internal/config/config.go:900, overridable per tenant; counted over +# context_access_log, go/internal/store/blocks.go CheckRateLimitByAction). A chain writes at most +# max_parts parts plus its manifest and head inside one window — what 0.9.0 wrote in one burst — +# and paces the rest into the next windows (0.10.0); the gap to 100 is headroom for facts, the +# memory mirror and other sessions on the same key. A server that reports the key's limit +# (whoami.rate_limit_write) lowers the window to that limit less the same headroom +# (window_writes). DEFAULT_MAX_PARTS = 80 MAX_PARTS_CEILING = 95 +RATE_LIMIT_WRITE_DEFAULT = 100 +RATE_WINDOW_HEADROOM = RATE_LIMIT_WRITE_DEFAULT - (MAX_PARTS_CEILING + 2) RATE_WINDOW_S = 60.0 # Slack on top of a window before a write that waits for it: ctx books a REST write after # answering it, a few milliseconds after the client saw the answer. @@ -106,11 +110,23 @@ def window_writes(max_parts: int, rate_limit_write: int | None = None) -> int: """Writes one chain plans inside one rate window: ``max_parts`` parts (at most - ``MAX_PARTS_CEILING``) plus manifest and head. ``rate_limit_write``: the write limit per 60 s the - server reports for the key (``whoami``; ctx with per-request narrowing), which the chain is to - follow (contract, S1: the chain cluster P-G makes it count and wires ``ChainWriter`` to it; - until then the reported limit is ignored).""" - return max(1, min(int(max_parts), MAX_PARTS_CEILING)) + 2 + ``MAX_PARTS_CEILING``) plus manifest and head, and no more than ``rate_limit_write`` less + ``RATE_WINDOW_HEADROOM``, never fewer than one. ``rate_limit_write``: the write limit per 60 s + the server reports for the key (``whoami.rate_limit_write``; ctx with per-request narrowing). + Only a positive int is a limit: None (a server without the field), 0 or less (ctx: unlimited) + and any other value leave the window as it is without the field, and a limit at or above + ``RATE_LIMIT_WRITE_DEFAULT`` never raises it.""" + planned = max(1, min(int(max_parts), MAX_PARTS_CEILING)) + 2 + cap = _limit_window(rate_limit_write) + return planned if cap is None else min(planned, cap) + + +def _limit_window(rate_limit_write: Any) -> int | None: + """The most writes a window may plan below a reported write limit (see ``window_writes``), or + None when the value is no limit.""" + if isinstance(rate_limit_write, bool) or not isinstance(rate_limit_write, int) or rate_limit_write <= 0: + return None + return max(1, rate_limit_write - RATE_WINDOW_HEADROOM) # How long (real seconds) a call waits for the answer of another call of the same entry before it @@ -993,6 +1009,28 @@ def __init__(self) -> None: # Until when (time.monotonic()) the recall's second query stays off for this entry: one of # them was abandoned while it held the entry (the provider's _session_digest_sources). self._recall_extra_off_until = 0.0 + # The write limit the server last reported for the entry's key (whoami.rate_limit_write, + # :meth:`report_write_limit`): ctx counts writes per key, so every window planned on the entry + # stays below it, also one a writer planned without knowing it. None: none reported. + self._write_limit: int | None = None + + def report_write_limit(self, rate_limit_write: Any) -> None: + """The write limit the server reported for the key; the latest report holds (a tenant's + limit can go up as well as down, and 0 or less is none). A value that is not an int (None: the + writer knows none) is no report and changes nothing.""" + if isinstance(rate_limit_write, bool) or not isinstance(rate_limit_write, int): + return + with self._cond: + self._write_limit = rate_limit_write + + def capped(self, window_writes: int) -> int: + """``window_writes`` below the write limit last reported for the key (unchanged without one).""" + with self._cond: + return self._capped(window_writes) + + def _capped(self, window_writes: int) -> int: + cap = _limit_window(self._write_limit) + return window_writes if cap is None else min(window_writes, cap) def type_to_send(self, name: str, wait_s: float = 0.0) -> str: """Whether a write names the block type ``name`` (GottZ/ctx#289): :data:`TYPE_ASK` (this write @@ -1110,6 +1148,7 @@ def register( planned by the runs before it that can still go before their deadlines (what its plan of windows must hold first).""" with self._cond: + window_writes = self._capped(window_writes) self._prune(now) ahead = len(self.booked) + self.writes_in_flight + self._ahead_of(None, now, window_writes) pending = max(0, int(planned_writes)) @@ -1222,6 +1261,7 @@ def admit( if reservation is not None: reservation.waiting = False if write: + window_writes = self._capped(window_writes) self._prune(now) used = len(self.booked) + self.writes_in_flight ahead = self._ahead_of(reservation, now, window_writes) @@ -1604,8 +1644,9 @@ class ChainWriter: every failure raises ``CtxCheckpointError``; the head is published LAST, so a partial failure never moves the stable head. - Paced (0.10.0): at most ``max_parts + 2`` writes inside one rate window; a longer chain - waits for the next window, and its deadline grows by one window for each window it needs. + Paced (0.10.0): at most ``max_parts + 2`` writes inside one rate window (fewer below a write + limit the server reports, ``rate_limit_write``); a longer chain waits for the next window, and + its deadline grows by one window for each window it needs. Since 0.17.0 (GottZ/ctx#299) the window and the error answers in a row are the server entry's (``entry``), shared by every chain of the process that writes through it. Idempotent: every title derives from the root and the transcript digest, so a retry meets @@ -1631,7 +1672,8 @@ class ChainWriter: # binds it before each checkpoint). None: every chain keeps a state of its own (before 0.17.0). entry: EntryState | None = field(default=None, repr=False) # The write limit per 60 s the server reports for the bound key (``whoami.rate_limit_write``; - # the binding sets it, ``window_writes`` follows it). S1 contract: kept, not yet read. + # the binding sets it, ``window_writes`` follows it; each run reports it to ``entry``, whose + # other writers then plan below it too). None: the window of a server without it. rate_limit_write: int | None = None _tool_evidence_warned: bool = field(default=False, init=False) @@ -1642,8 +1684,9 @@ def _notify(self, message: str) -> None: logger.debug("ctx checkpoint: notice failed", exc_info=True) def _window_writes(self) -> int: - """Writes of one chain inside one rate window: ``max_parts`` parts plus manifest and head.""" - return max(1, min(int(self.max_parts), MAX_PARTS_CEILING)) + 2 + """Writes of one chain inside one rate window: ``max_parts`` parts plus manifest and head, + below the write limit the server reported for the key (``window_writes``).""" + return window_writes(self.max_parts, self.rate_limit_write) # -- transport with budget, pacing and rate-limit waits -- @@ -2149,9 +2192,13 @@ def new_run( The run registers its planned writes at the entry (:meth:`EntryState.register`): they come after the writes booked or in flight there and after the planned writes of every run of the entry that started before, so the plan holds the windows all of those need together. The - caller ends the run with :meth:`_ChainRun.close` (``write`` does for its own run).""" - window_writes = self._window_writes() + caller ends the run with :meth:`_ChainRun.close` (``write`` does for its own run). + + The writer's ``rate_limit_write`` is reported to the entry, and the run plans below the limit + last reported for the key, whichever writer of the key reported it.""" entry = self.entry if self.entry is not None else EntryState() + entry.report_write_limit(self.rate_limit_write) + window_writes = entry.capped(self._window_writes()) # budget_s in the run is the effective one (messages name what the chain really had). run = _ChainRun( deadline=deadline, diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py index 7886cea04..220988e3c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -8,6 +8,5 @@ "P-D", "P-E", "P-F", - "P-G", } ) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py index 8e99e7c79..485477c12 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py @@ -3,6 +3,10 @@ from __future__ import annotations +import datetime as _dt +import json +import threading + import pytest from fakes import access_host as ah @@ -27,3 +31,317 @@ def test_server_without_the_field_keeps_todays_window(): def test_reported_limit_over_100_never_raises_the_window(): assert cp.window_writes(500, 1000) == min(500, cp.MAX_PARTS_CEILING) + 2 assert cp.window_writes(cp.MAX_PARTS_CEILING, 101) == cp.MAX_PARTS_CEILING + 2 + + +# -- S2: the window below a reported limit ----------------------------------------------------- + +# The window without a reported limit, as 0.19.1 computes it (``ChainWriter._window_writes``). +_TODAY = {max_parts: max(1, min(max_parts, cp.MAX_PARTS_CEILING)) + 2 for max_parts in (1, 3, 10, 80, 95, 96, 500)} + + +def test_the_headroom_is_what_todays_window_leaves_of_the_default_limit(): + """ctx's default write limit (query.rate_limit_write, go/internal/config/config.go:900) less the + most a chain plans per window today: the writes a window leaves to the key's other writers.""" + assert cp.RATE_LIMIT_WRITE_DEFAULT == 100 + assert cp.RATE_WINDOW_HEADROOM == cp.RATE_LIMIT_WRITE_DEFAULT - (cp.MAX_PARTS_CEILING + 2) == 3 + assert cp.window_writes(cp.MAX_PARTS_CEILING, cp.RATE_LIMIT_WRITE_DEFAULT) == cp.MAX_PARTS_CEILING + 2 + + +def test_a_reported_limit_of_40_keeps_the_chain_below_it_with_the_headroom(): + assert cp.window_writes(cp.MAX_PARTS_CEILING, 40) == 37 + assert cp.window_writes(cp.DEFAULT_MAX_PARTS, 40) == 37 + assert cp.window_writes(35, 40) == 37 + assert cp.window_writes(34, 40) == 36 + + +@pytest.mark.parametrize("limit", [1, 2, 3, 4]) +def test_a_limit_with_no_room_beyond_the_headroom_leaves_one_write_per_window(limit): + """A chain cannot plan fewer than one write per window (it would never end); one write never + exceeds a positive limit.""" + assert cp.window_writes(cp.MAX_PARTS_CEILING, limit) == 1 + + +def test_no_reported_limit_gets_a_window_over_it_or_over_todays(): + for max_parts, today in _TODAY.items(): + for limit in range(1, 301): + window = cp.window_writes(max_parts, limit) + assert 1 <= window <= today, (max_parts, limit, window) + assert window <= limit, (max_parts, limit, window) + if limit > cp.RATE_WINDOW_HEADROOM: + assert window <= limit - cp.RATE_WINDOW_HEADROOM, (max_parts, limit, window) + if limit >= cp.RATE_LIMIT_WRITE_DEFAULT: + assert window == today, (max_parts, limit, window) + + +@pytest.mark.s1_green +@pytest.mark.parametrize("reported", [None, 0, -1, -100, True, False, "40", 40.0, 40.5, [40], {"limit": 40}]) +def test_a_limit_that_is_absent_unlimited_or_not_an_int_leaves_todays_window(reported): + """ctx answers 0 for an unlimited key (store.WriteBudget, stage gates: ``<= 0`` = off); a bool is + no limit even though Python counts it as an int; any other form is not a reported limit.""" + for max_parts, today in _TODAY.items(): + assert cp.window_writes(max_parts, reported) == today, (max_parts, reported) + + +def test_the_writer_plans_its_runs_with_the_reported_limit(): + writer = cp.ChainWriter(client=None, rate_limit_write=40) + assert writer._window_writes() == 37 + run = writer.new_run(started=0.0, deadline=20.0, budget_s=20.0, planned_writes=82) + assert run.window_writes == 37 + assert run.planned_windows == 3 + assert cp.ChainWriter(client=None)._window_writes() == cp.DEFAULT_MAX_PARTS + 2 + assert cp.ChainWriter(client=None, rate_limit_write=0)._window_writes() == cp.DEFAULT_MAX_PARTS + 2 + + +# -- S2: the real chain write path (provider → ChainWriter → server entry) ---------------------- + +_CALL_LATENCY_S = 0.05 +_STORE_ANSWERS = json.loads((ah.PLUGIN_DIR / "memory" / "tests" / "mcp_answers.json").read_text(encoding="utf-8"))[ + "store" +] + + +class _Clock: + def __init__(self) -> None: + self.now = 1_000.0 + self.slept: list[float] = [] + + +class _CtxDouble: + """One ctx MCP server behind Hermes' dispatch (as ``tests/test_paced_idempotent_chain.py``): + ctx's write limit per key over a sliding 60 s window (``count >= limit`` refuses, + ``go/internal/handler/stage_gates.go``), an identical store books nothing, one call at a time.""" + + def __init__(self, clock: _Clock, *, write_limit: int) -> None: + self.clock = clock + self.write_limit = write_limit + self.rpc_lock = threading.Lock() + self.blocks: dict[tuple[str, str], dict] = {} + self.window: list[float] = [] + self.booked: list[float] = [] # every booking, never pruned + self.counter = 0 + self.refused = 0 + self.calls: list[str] = [] # every call as the JSON text of its tool and arguments + + def dispatch(self, name: str, args: dict, **_kwargs) -> str: + with self.rpc_lock: + self.clock.now += _CALL_LATENCY_S + tool = name.rsplit("__", 1)[-1] + self.calls.append(json.dumps([tool, args], ensure_ascii=False)) + answer = getattr(self, f"_{tool}")(args) + if "error" in answer: + return json.dumps({"error": answer["error"]}) + return json.dumps({"result": answer["result"]}) + + def _store(self, args: dict) -> dict: + key = (args["category"], args["title"]) + incoming = {"content": args["content"], "tags": list(args.get("tags") or []), "type": args.get("type")} + metadata = dict(args.get("metadata") or {}) + stored = self.blocks.get(key) + if stored is not None and all(stored[k] == v for k, v in incoming.items()) and stored["metadata"] == metadata: + return {"result": _STORE_ANSWERS["no_change"].format(title=args["title"], id=stored["id"], category=key[0])} + self.window = [t for t in self.window if t > self.clock.now - 60.0] + if len(self.window) >= self.write_limit: + self.refused += 1 + return {"error": f"Rate limit exceeded: max {self.write_limit} writes per 60 seconds"} + self.window.append(self.clock.now) + self.booked.append(self.clock.now) + if stored is None: + self.counter += 1 + stored = self.blocks[key] = {"id": f"019f7000-0000-7000-8000-{self.counter:012d}"} + stored.update(incoming, metadata=metadata, title=args["title"], category=args["category"]) + return { + "result": _STORE_ANSWERS["stored"].format(title=args["title"], id=stored["id"], category=args["category"]) + } + + def _search(self, args: dict) -> dict: + tags = set(args.get("tags") or []) + rows = [ + {"id": b["id"], "title": b["title"], "category": b["category"], "type": "checkpoint", "untrusted": True} + for b in self.blocks.values() + if args["query"] in b["title"] and tags <= set(b["tags"]) + ] + return {"result": json.dumps(rows[: int(args.get("limit") or 10)])} + + def _get(self, args: dict) -> dict: + for b in self.blocks.values(): + if b["id"] == args["id"]: + return {"result": json.dumps({k: b[k] for k in ("id", "title", "category", "content", "metadata")})} + return {"error": f"block not found: {args['id']}"} + + def parts(self) -> list[dict]: + return [b for b in self.blocks.values() if " part " in b["title"]] + + def busiest_window(self) -> int: + """Most writes ctx booked inside any 60 s window.""" + return max((sum(1 for t in self.booked if start - 60.0 < t <= start) for start in self.booked), default=0) + + +class _FrozenDatetime(_dt.datetime): + """The chain stamps its head with the wall clock; two runs compare byte for byte only without it.""" + + @classmethod + def now(cls, tz=None): + return cls(2026, 12, 6, 12, 0, 0, tzinfo=tz) + + +def _transcript(n_messages: int, tag: str = "m") -> list[dict]: + return [ + {"role": "user" if i % 2 == 0 else "assistant", "content": f"{tag}{i:04d} " + "w" * 900} + for i in range(n_messages) + ] + + +def _server(monkeypatch, *, write_limit: int) -> tuple[_CtxDouble, _Clock]: + """A fresh process (no server entry state yet) and one ctx double on a fake clock.""" + cp.reset_entry_states() + clock = _Clock() + + def sleep(seconds: float) -> None: + clock.slept.append(seconds) + clock.now += seconds + + monkeypatch.setattr(_PKG, "_monotonic", lambda: clock.now) + monkeypatch.setattr(_PKG, "_sleep", sleep) + monkeypatch.setattr(cp, "datetime", _FrozenDatetime) + return _CtxDouble(clock, write_limit=write_limit), clock + + +def _checkpoint( + server: _CtxDouble, session: str, reported, messages: int, notices: list[str], *, tag: str = "m", **config +): + """One checkpoint of ``messages`` one-part messages through an umbrella provider of the double's + key, its chain writer bound to the limit the server reported (``ChainWriter.rate_limit_write``, + set by the group binding; None: a writer that knows none). Returns the provider and the error.""" + provider = _PKG.CtxCheckpointMemoryProvider(config={"chunk_chars": 1_000, **config}, dispatch=server.dispatch) + provider.initialize(session, platform="cli", warning_callback=notices.append) + chain = provider._chain + + def bound_chain(): + # The binding sets the limit on the writer each checkpoint uses; so does the test, whatever + # builds or rebinds the writer in between. + writer = chain() + writer.rate_limit_write = reported + return writer + + provider._chain = bound_chain + try: + provider.on_pre_compress(_transcript(messages, tag), require_checkpoint=True) + except _PKG.CtxCheckpointError as exc: + return provider, exc + return provider, None + + +def _chain_against(monkeypatch, *, write_limit: int, reported, messages: int, **config) -> tuple: + """One checkpoint in a fresh process. Returns the server double, the waits, the notices and the + error (or None).""" + server, clock = _server(monkeypatch, write_limit=write_limit) + notices: list[str] = [] + _, error = _checkpoint(server, "session-pg", reported, messages, notices, **config) + return server, clock.slept, notices, error + + +@pytest.mark.parametrize(("limit", "messages"), [(40, 60), (10, 12)]) +def test_a_chain_bound_to_a_reported_limit_stays_below_it_in_every_window(monkeypatch, limit, messages): + """Server reports 40 (a tenant's overlay below the default): the chain used to plan up to 97 + writes a window, ran into ctx's refusals — error answers Hermes' breaker counts — and stopped + after two in a row. Bound to the limit it is paced below it and never refused.""" + server, slept, notices, error = _chain_against(monkeypatch, write_limit=limit, reported=limit, messages=messages) + assert server.refused == 0, f"ctx refused {server.refused} write(s) of the chain" + assert error is None, error + assert len(server.parts()) == messages + planned = limit - cp.RATE_WINDOW_HEADROOM + assert server.busiest_window() <= planned < limit + assert slept, "the chain did not wait for the next window" + assert notices and f"{planned} per minute" in notices[0], notices + + +@pytest.mark.s1_green +@pytest.mark.parametrize("reported", [0, -1, 100, 101, 1_000, True, False, "40", 40.0]) +def test_a_chain_without_a_tighter_reported_limit_writes_byte_for_byte_as_without_the_field(monkeypatch, reported): + """Server without the field (None), an unlimited key (0), a limit at or over the default, or a + value that is not a limit: the same calls with the same arguments and the same waits as 0.19.1.""" + config = {"max_parts": cp.MAX_PARTS_CEILING} + base, base_slept, base_notices, base_error = _chain_against( + monkeypatch, write_limit=1_000, reported=None, messages=120, **config + ) + assert base_error is None and base_slept and len(base.parts()) == 120 + server, slept, notices, error = _chain_against( + monkeypatch, write_limit=1_000, reported=reported, messages=120, **config + ) + assert error is None, error + assert server.calls == base.calls + assert server.booked == base.booked + assert slept == base_slept + assert notices == base_notices + + +# -- S2: the limit is the key's, so it is the server entry's ---------------------------------- +# ctx counts writes per key; every writer of the process with that key shares one server entry +# (``memory/provider.py`` ``_entry_key``). A writer that knows no limit (the profile's own connection +# on the same key, a writer built anew) and a run that started before the report must not plan the +# entry past the limit another writer of the key reported (fresh review, B-1). + + +def _writes_admitted(state, window: int) -> int: + """Writes the entry admits one after the other at one moment, each booked, for a run that + planned ``window`` writes a window.""" + admitted = 0 + while (ticket := state.admit(write=True, window_writes=window, now=0.0).ticket) is not None: + state.release(ticket, error=False, booked=True, now=0.0) + admitted += 1 + return admitted + + +def test_an_entry_keeps_every_window_below_the_limit_last_reported_for_its_key(): + reported = cp.EntryState() + reported.report_write_limit(40) + assert _writes_admitted(reported, cp.MAX_PARTS_CEILING + 2) == 37 + assert _writes_admitted(cp.EntryState(), cp.MAX_PARTS_CEILING + 2) == cp.MAX_PARTS_CEILING + 2 + + # A run that registers behind one planned with 0.19.1's window counts that one's slots below the limit. + state = cp.EntryState() + state.report_write_limit(40) + state.register(100, lambda: 30.0, now=0.0, window_writes=cp.MAX_PARTS_CEILING + 2) + _, ahead = state.register(5, lambda: 1_000.0, now=0.0, window_writes=cp.MAX_PARTS_CEILING + 2) + assert ahead == 37 + + +def test_the_latest_report_of_a_key_holds_and_a_value_that_is_no_int_changes_nothing(): + state = cp.EntryState() + state.report_write_limit(40) + for no_report in (None, True, False, "100", 100.0): + state.report_write_limit(no_report) + assert state.capped(97) == 37, no_report + state.report_write_limit(1_000) # the tenant's limit went up + assert state.capped(97) == 97 + state.report_write_limit(10) + assert state.capped(97) == 7 + state.report_write_limit(0) # unlimited + assert state.capped(97) == 97 + + +def test_a_writer_that_knows_no_limit_follows_the_one_its_key_reported(): + entry = cp.EntryState() + unbound = cp.ChainWriter(client=None, entry=entry) + assert unbound.new_run(started=0.0, deadline=20.0, budget_s=20.0, planned_writes=10).window_writes == 82 + bound = cp.ChainWriter(client=None, entry=entry, rate_limit_write=40) + assert bound.new_run(started=0.0, deadline=20.0, budget_s=20.0, planned_writes=10).window_writes == 37 + run = unbound.new_run(started=0.0, deadline=20.0, budget_s=20.0, planned_writes=82) + assert run.window_writes == 37 + assert run.planned_windows >= 3 + + +def test_two_sessions_of_one_key_stay_below_the_limit_one_of_them_reported(monkeypatch): + """A session bound with the reported limit 40, then a session of the same key whose writer knows + none: before, the second planned 82 writes a window on the entry the first had filled to 25 and + ran into ctx's refusals.""" + server, _ = _server(monkeypatch, write_limit=40) + notices: list[str] = [] + bound, error = _checkpoint(server, "session-bound", 40, 60, notices) + assert error is None, error + unbound, error = _checkpoint(server, "session-unbound", None, 60, notices, tag="u") + assert bound._chain().entry is unbound._chain().entry + assert server.refused == 0, f"ctx refused {server.refused} write(s) of the chains" + assert error is None, error + assert len(server.parts()) == 120 + assert server.busiest_window() <= 37 From 1245eed61db310734645d461fdfb73cb4ec74e95 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 02:48:40 +0100 Subject: [PATCH 06/65] =?UTF-8?q?fix(ctx=5Fcheckpoint):=20S2=20P-C=20?= =?UTF-8?q?=E2=80=94=20an=20access=20group=20reaches=20ctx=20only=20throug?= =?UTF-8?q?h=20its=20own=20proven=20binding,=20a=20session=20without=20one?= =?UTF-8?q?=20sends=20nothing,=20and=20a=20changed=20group=20or=20a=20lost?= =?UTF-8?q?=20narrowing=20turns=20the=20instance=20off?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The provider takes the access decision on every initialize (settings, markers, the decision table of P-B), raises the markers the build saw, and binds the group over REST with up to three narrowed clients whose proof (P-A's raw whoami answers) holds before any read or write; off sends nothing on any path. The trip wire compares the turn's access group and fields with the binding, a lost narrowing turns the whole instance off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/__init__.py | 59 +- .../ctx_checkpoint/memory/checkpoint.py | 11 +- .../plugin/ctx_checkpoint/memory/config.py | 5 +- .../plugin/ctx_checkpoint/memory/provider.py | 794 +++++++++++++++++- .../memory/tests/test_key_redaction.py | 10 +- .../plugin/ctx_checkpoint/memory/tools.py | 63 +- .../ctx_checkpoint/tests/fakes/s1_pending.py | 1 - .../tests/test_access_pc_binding.py | 664 ++++++++++++++- 8 files changed, 1535 insertions(+), 72 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index e87118548..386f0e29d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -813,8 +813,9 @@ def _entry_key(self) -> tuple[str, ...]: and one RPC lock, and with one ctx key one write window). A change of another field (a timeout) keeps the state; a changed route or key is another connection once Hermes reconnects. An OAuth entry is never adopted across profiles: it is keyed by the profile as - well. Only compared, never logged; the digest is no copy of the key the entry carries.""" - if self.transport == "rest": + well. Only compared, never logged; the digest is no copy of the key the entry carries. A + group binding writes over REST whatever the transport: its entry is the REST one.""" + if self.transport == "rest" or self._group is not None: return super()._entry_key() name = self._server_name() entry = _configured_server(_effective_config(), name) @@ -830,8 +831,12 @@ def _profile_secrets(self) -> tuple[str, ...]: def _connect(self) -> None: self._remember_secrets() - self._profile_keys = self._profile_secrets() - if self.transport == "rest": + # Access groups (design 02 §4.2 step 4): ``off`` binds and reads nothing (no key either); a + # group binding runs over REST whatever the transport (an MCP server entry carries fixed + # headers) and keeps the profile's keys for redaction; the engine does both. + kind = self._decision.kind if self._decision is not None else "profile" + self._profile_keys = () if kind == "off" else self._profile_secrets() + if self.transport == "rest" or kind != "profile": super()._connect() return name = self._server_name() @@ -855,6 +860,22 @@ def _connect(self) -> None: "on" if self.memory_enabled else "off", ) + def _group_base_url(self) -> str: + """The profile's ctx server for a group without ``base_url``: ``CTX_BASE_URL``, then + ``rest_base_url`` of this section (``ctx_base_url`` of ctx.json), then the origin of the MCP + server entry's URL (design 02 §3.1).""" + url = super()._group_base_url() + if url: + return url + from urllib.parse import urlsplit + + entry = _configured_server(_effective_config(), self._server_name()) + try: + parts = urlsplit(str(entry.get("url") or "")) + except ValueError: + return "" + return f"{parts.scheme}://{parts.netloc}" if parts.scheme in ("http", "https") and parts.netloc else "" + def _granted_call_mcp(self, tool: str) -> Callable[..., Any] | None: """Hermes' call_mcp for ``tool`` while the grant read before this checkpoint lists the entry and Hermes registered the tool (the entry's tool filter), else None.""" @@ -870,6 +891,9 @@ def _read_mcp_grant(self) -> bool: def is_available(self) -> bool: if self.transport == "rest": return super().is_available() + return self._mcp_available() or self._groups_available() + + def _mcp_available(self) -> bool: try: from hermes_cli.config import load_config @@ -1035,15 +1059,17 @@ def get_tool_schemas(self) -> list[dict[str, Any]]: def system_prompt_block(self) -> str: """The memory text (memory features on), then the checkpoint pointer once a head is known - for the session root — in both modes. Without either it is empty, as before 0.9.0.""" - if not self._active: + for the session root — in both modes. Without either it is empty, as before 0.9.0. A group + binding names the pointer only where its read tools read its write scope; a session the + access decision turned off gets nothing.""" + if not self._active or not self._access_gate(): return "" blocks = [] if self.memory_enabled: block = super().system_prompt_block() if block: blocks.append(f"{block}\nSkill: {self.name}:{SKILL_NAME} explains how to use the store well.") - pointer = self._checkpoint_pointer() + pointer = self._checkpoint_pointer() if self._chain_readable() else "" if pointer: blocks.append(pointer) return "\n\n".join(blocks) @@ -1054,10 +1080,23 @@ def _pointer_binding(self) -> str: """What a recorded head belongs to: transport, ctx server (MCP entry name or REST base URL) and chain category, as a digest. A head written through another binding is not named — its id would not resolve there, or the search would run in another category.""" - server = self._base_url if self.transport == "rest" else self._server_name() - raw = f"{self.transport}\0{server}\0{self._checkpoint_category()}" + group = self._group + rest = self.transport == "rest" or group is not None + server = self._base_url if rest else self._server_name() + raw = f"{'rest' if rest else self.transport}\0{server}\0{self._checkpoint_category()}" + if group is not None: # a group's head is its own: key, platform, server and group + context = group.context + key = hashlib.sha256(self._api_key.encode("utf-8")).hexdigest() + raw += f"\0{key}\0{context.platform}\0{context.scope_id}\0{context.group}" return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] + def _chain_readable(self) -> bool: + """Whether the session's model can read the chain it writes: always on the profile's + connection; a group binding only through its own read tools, and only when its read set + holds its write scope (the receipt and the pointer name a head only then).""" + group = self._group + return group is None or (self.memory_enabled and group.read_client is not None and group.write in group.read) + def _read_tools(self) -> _cp.ReadTools: """The read tools of this session, by the names the model sees: the plugin's own with memory features on (the block is withheld with them when Hermes gates the memory @@ -1071,6 +1110,8 @@ def _read_tools(self) -> _cp.ReadTools: return _cp.mcp_read_tools(mcp_tool_name(server, "get"), mcp_tool_name(server, "search")) def _receipt_read_path(self, head_id: str, root: str) -> str: + if not self._chain_readable(): + return "" return _cp.read_path(self._read_tools(), head_id=head_id, category=self._checkpoint_category()) def _checkpoint_pointer(self) -> str: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py index 578378cdb..cea55ac7c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py @@ -570,8 +570,9 @@ def redact_text(text: str, secret: str | Iterable[str] = ()) -> str: return _redact_checkpoint_secrets(_host_redact(text)) -# Codes the plugin's clients set themselves (``mcp_client``: staged write, abandoned call). -_CLIENT_CODES = frozenset({"confirm_writes", "timeout"}) +# Codes the plugin's clients set themselves (``mcp_client``: staged write, abandoned call; ``client``: +# an answer without the echo of the client's narrowing, after which the client sends nothing more). +_CLIENT_CODES = frozenset({"confirm_writes", "timeout", "narrowing_lost"}) # What an error text says when its redaction failed (it is withheld, never passed on raw). ERROR_WITHHELD = "(details withheld: redaction failed)" # A URL in an error text (``_shown_urls``): ``scheme://`` up to white space, a quote or an angle bracket. @@ -1627,6 +1628,10 @@ class ChainWriter: notify: Callable[[str], None] = lambda message: None # The bound ctx key(s), redacted from the transcript parts; never part of the repr. secret: str | tuple[str, ...] = field(default="", repr=False) + # The access group the chain is written for (``platform``, ``scope_id``, ``group``, ``profile``; + # design 02 §4.2 step 6): ``ctx_plugin.access`` of head and manifest, provenance and no right. + # None: a session of no access group (as before). + access: dict[str, str] | None = None # The process-wide state of the server entry the client writes to (entry_state; the provider # binds it before each checkpoint). None: every chain keeps a state of its own (before 0.17.0). entry: EntryState | None = field(default=None, repr=False) @@ -2371,6 +2376,8 @@ def _write_run( "port_of": UPSTREAM_REF, "redaction": (["bound-ctx-key"] if bound_secret_values(self.secret) else []) + list(REDACTION_PASSES), "checkpoint_id": checkpoint_id, + # where an access group's chain was written from (no right; absent without one) + **({"access": dict(self.access)} if self.access else {}), }, } diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/config.py b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py index 780fe36b7..af96f89d2 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/config.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py @@ -379,8 +379,9 @@ def _as_bool(value: Any, default: bool) -> bool: # CTX upsert without ``tags`` resets the block's tags to []. ORIGIN_SOURCE = "hermes" -# Agent-supplied tags with these prefixes are dropped — provenance must not be spoofable. -_RESERVED_TAG_PREFIXES = ("source:", "profile:", "hook:") +# Agent-supplied tags with these prefixes are dropped — provenance must not be spoofable. ``server:`` and +# ``group:`` name the access group a write came from (design 02 §4.2 step 6); only the plugin sets them. +_RESERVED_TAG_PREFIXES = ("source:", "profile:", "hook:", "server:", "group:") _MAX_TAG_LEN = 64 _MAX_AGENT_TAGS = 16 diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 492fa261f..b6c39bea4 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -21,21 +21,27 @@ from __future__ import annotations import hashlib +import json import logging import re import threading import time -from collections.abc import Callable +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any from agent.memory_provider import MemoryProvider +from . import access as _access from . import checkpoint as _cp from . import digest as _dg +from . import narrowing as _narrowing +from . import status as _status from .checkpoint import ChainWriter, CtxCheckpointError, redact_error_text -from .client import CtxApiError, CtxClient, response_code, store_action, store_block_id +from .client import RETRYABLE_CODES, CtxApiError, CtxClient, response_code, store_action, store_block_id from .config import ( + _MAX_TAG_LEN, CATEGORY_DIGEST, CATEGORY_LEARNINGS, CATEGORY_MEMORY, @@ -130,6 +136,99 @@ def spawn_context_thread( _PRUNED_HOMES: set = set() _PRUNE_LOCK = threading.Lock() +# Access groups (design 02 §4.2 step 5): a proof that failed on the network or on time — not on a +# rule — is asked again at most this often, and only in the background paths (``queue_prefetch``, +# the digest worker's ``sync_turn``); a proof that failed on a rule stays failed until the next agent +# build. What a session without a ctx binding names when a compaction requires a checkpoint. +PROOF_RETRY_S = 60.0 +NO_BINDING = "no ctx binding for this session" +# The agent tools that read through a group's read client, and the one that stores through its +# store client (offered to unrestricted groups only, design 02 §4.2 step 6). +READ_TOOLS = ("ctx_query", "ctx_search", "ctx_get") +STORE_TOOL = "ctx_store" + + +@dataclass +class _GroupBinding: + """A session's group binding (design 02 §4.2 steps 4 to 7): one key at one ctx server, the + group's scopes and up to three clients, each narrowed for the binding's life. Built in + ``initialize`` and never rebound; the provider reads and writes nothing through it before its + proof holds. ``read``/``write`` stay empty until they are known (an unrestricted group without + them takes the key's own); ``proven``/``refused``/``retry_at`` hold the state of the write and + the store client's own proofs (``"write"``, ``"store"``) and of the group proof (``"group"``).""" + + context: Any # access.AccessContext: platform, server, group, profile + strict: bool + profile: str + tenant: str + recall: bool + capture: bool + fields_read: tuple[str, ...] + fields_write: str + fields_store: str + read: tuple[str, ...] = () + write: str = "" + store: str = "" + read_client: CtxClient | None = None + write_client: CtxClient | None = None + store_client: CtxClient | None = None + label: str = "" + tenant_seen: str = "" + proven: set[str] = field(default_factory=set) + refused: dict[str, str] = field(default_factory=dict) + retry_at: dict[str, float] = field(default_factory=dict) + + def clients(self) -> tuple[CtxClient, ...]: + return tuple(c for c in (self.read_client, self.write_client, self.store_client) if c is not None) + + +def _plain(value: Any) -> Any: + """``value`` with every mapping a dict and every tuple a list (a stable JSON form).""" + if isinstance(value, Mapping): + return {str(k): _plain(v) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_plain(v) for v in value] + return value + + +def _fields_digest(fields: Any) -> str: + """The digest of a group's ctx_checkpoint fields the trip wire compares (design 02 §4.6).""" + canonical = json.dumps(_plain(fields or {}), sort_keys=True, ensure_ascii=False, default=str) + return hashlib.sha256(canonical.encode("utf-8", "surrogatepass")).hexdigest()[:32] + + +def _turn_key(context: Any) -> tuple[str, ...]: + """What a binding is bound to and a turn serves: platform, server, group, the group's restriction + and the digest of the fields (the core rebuilds the agent when any of them changes).""" + return ( + str(context.platform), + str(context.scope_id), + str(context.group), + str(context.restricted), + _fields_digest(context.fields), + ) + + +def _proof_transient(exc: CtxApiError) -> bool: + """A proof that failed on the network, on time or on the server (no answer, 5xx, 429), not on a + refusal of the key or its narrowing; only such a proof is asked again.""" + if exc.code and exc.code not in RETRYABLE_CODES: + return False + return exc.status is None or exc.status == 429 or exc.status >= 500 + + +def _proof_cause(exc: CtxApiError) -> str: + """A failed proof as a status line may name it: code and HTTP status, never the server's text.""" + parts = [f"code {exc.code}" if exc.code else "", f"status {exc.status}" if exc.status else ""] + return ", ".join(part for part in parts if part) or "no answer" + + +def _write_limit(info: Any) -> int | None: + """``whoami.rate_limit_write`` (writes per 60 s for this key, ctx with per-request narrowing): + a positive int, else None (an older server reports none).""" + value = info.get("rate_limit_write") if isinstance(info, Mapping) else None + return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None + class _PacedFactStore: """The client the required facts are stored through (GottZ/ctx#299, point 5): each store goes @@ -226,7 +325,21 @@ def __init__(self): self._chain_writer: ChainWriter | None = None self._last_manifest_by_root: dict[str, str] = {} # Binding of the last successful connect; the manifest cache belongs to it. - self._verified_binding: tuple[str, str, str, str] | None = None + self._verified_binding: tuple[str, ...] | None = None + # Access groups (design 02 §4.2-§4.6): the decision of the latest initialize (None before + # one: no access handling at all), the settings it was taken under, the group binding (None + # for the profile's connection and for off), what the binding is bound to for the trip wire, + # and why the instance is off for the rest of this agent ("" while it is not). + self._decision: Any = None + self._access_settings: Mapping[str, Any] = _access.SETTINGS_DEFAULTS + self._group: _GroupBinding | None = None + self._bound_turn: tuple[str, ...] | None = None + self._access_off = "" + self._access_lock = threading.RLock() + self._off_lock = threading.Lock() + # The write limit per 60 s the ctx server reports for the writing key (whoami + # ``rate_limit_write``); the chain writer follows it (P-G). + self._rate_limit_write: int | None = None self._last_chain_receipt = None # Why the latest chain write failed (None after a success or when no chain ran); the # umbrella records it with the outcome of each checkpoint. @@ -239,6 +352,9 @@ def __init__(self): self._compaction_pending = False self._idle_timer: threading.Timer | None = None self._idle_lock = threading.Lock() + # Counted up by every initialize: an idle timer armed under one binding never digests through + # the next one (a re-init can keep the session id and bind another access group). + self._binding_generation = 0 self._root_source = "" # -- Identity / availability -------------------------------------------- @@ -343,19 +459,34 @@ def _checkpoint_root(self) -> str: session switch of a compaction).""" return self._root_session_id or self._session_id or "unknown" - def _connect(self) -> None: - """Bind credentials and the client; sets ``_active``/``_client``. Default: REST.""" - # A re-initialization of the same instance must not keep the previous client, key, - # whoami identity or checkpoint writer — not even when it ends inactive below, or - # when env_secret raises (unscoped read under multiplexing) before the new values land. + def _drop_binding(self) -> None: + """Forget the current binding: no client, key, whoami identity or checkpoint writer stays, + and no group binding; the keys stay known for redaction.""" self._remember_secrets() self._active = False self._client = None self._chain_writer = None + self._group = None self._api_key = "" self._base_url = "" self._home_scope = "" self._whoami_label = "" + self._rate_limit_write = None + + def _connect(self) -> None: + """Bind credentials and the client; sets ``_active``/``_client``. Default: REST. The access + decision of ``initialize`` routes it: ``off`` binds nothing, ``group`` the group binding over + REST (whatever the transport), ``profile`` (and no decision) the profile's connection.""" + # A re-initialization of the same instance must not keep the previous client, key, + # whoami identity or checkpoint writer — not even when it ends inactive below, or + # when env_secret raises (unscoped read under multiplexing) before the new values land. + self._drop_binding() + decision = self._decision + if decision is not None and decision.kind == "off": + return + if decision is not None and decision.kind == "group": + self._bind_group(decision) + return self._api_key = env_secret("CTX_KEY") self._base_url = resolve_base_url(self._config.get("ctx_base_url")) self._active = bool(self._api_key and self._base_url) @@ -376,6 +507,7 @@ def _connect(self) -> None: raise CtxApiError(str(info.get("error") or "whoami failed")) self._home_scope = str(info.get("home_scope") or "") self._whoami_label = str(info.get("label") or "") + self._rate_limit_write = _write_limit(info) logger.info( "CTX memory provider connected (scope=%s, label=%s, profile=%s)", self._home_scope or "?", @@ -391,7 +523,26 @@ def _connect(self) -> None: self._client = None def is_available(self) -> bool: - """Env/config presence only — NO network calls.""" + """Env/config presence only — NO network calls. On a Hermes with access groups a profile + whose ``ungoverned`` is ``off`` or ``local`` is available without a connection of its own: + its access groups bring their keys (design 02 §4.2 step 9).""" + return self._profile_available() or self._groups_available() + + def _groups_available(self) -> bool: + """The profile uses ctx through access groups: the host has them (V8) and the profile's + ``memory.ctx_checkpoint.ungoverned`` is ``off`` or ``local``. Never the core's + ``gateway.access_groups`` config (its form is the core's). No network.""" + try: + if not _access.access_supported(): + return False + from hermes_constants import get_hermes_home + + return _access.load_settings(str(get_hermes_home())).get("ungoverned") in ("off", "local") + except Exception: + return False + + def _profile_available(self) -> bool: + """The profile's own REST connection is configured (0.19.1's availability).""" try: if not env_secret("CTX_KEY"): return False @@ -481,6 +632,14 @@ def get_status_config(self, provider_config: dict) -> dict: def initialize(self, session_id: str, **kwargs) -> None: from hermes_constants import get_hermes_home + # Step 0 (design 02 §4.2): the previous binding goes before anything is checked. Hermes keeps + # calling a provider whose initialize raised; nothing of the last binding may answer then. + self._drop_binding() + self._cancel_idle_timer() + self._binding_generation += 1 + self._decision = None + self._bound_turn = None + self._access_off = "the latest initialize did not finish" # A re-initialization starts a new binding: no recall cached (or still being warmed) # for the previous one is served under it. self._invalidate_prefetch() @@ -514,28 +673,39 @@ def initialize(self, session_id: str, **kwargs) -> None: # compression.checkpoint_required a gated chain would block every subagent # compaction with no path to success. self._write_enabled = self._agent_context not in {"cron", "flush", "subagent"} + self._decide_access(kwargs) self._connect() # A warm-up queued while this re-init ran still used the previous client: orphan it. self._invalidate_prefetch() - # The manifest cache only bridges a missing server head on the SAME binding; a - # manifest id from another profile, backend or key must never become a parent. Only - # verified bindings count: a failed re-init (inactive, no writes) keeps the cache for - # a later retry on the same binding. + self._note_verified_binding(previous_binding) + + def _note_verified_binding(self, previous_binding: tuple[str, ...] | None) -> None: + """The manifest cache only bridges a missing server head on the SAME binding; a manifest id + from another profile, backend, key or access group must never become a parent. Only verified + bindings count: a failed re-init (inactive, no writes) keeps the cache for a later retry on + the same binding.""" if self._active: binding = self._binding_identity() if binding != previous_binding: self._last_manifest_by_root = {} self._verified_binding = binding - def _binding_identity(self) -> tuple[str, str, str, str]: - """Profile home, backend, credential and whoami identity the provider is bound to. + def _binding_identity(self) -> tuple[str, ...]: + """Profile home, backend, credential, whoami identity and access group (platform, server, + group, the write client's narrowing) the provider is bound to. Only compared, never logged. The credential is its SHA-256 digest (``""`` without a key): the identity outlives the client, also an inactive re-init, and must not be a second copy of the key. """ key_digest = hashlib.sha256(self._api_key.encode("utf-8")).hexdigest() if self._api_key else "" - return (self._hermes_home, self._base_url, key_digest, self._whoami_label) + group = self._group + if group is None: + access: tuple[str, ...] = ("", "", "", "") + else: + writer = group.write_client.narrowing.echo() if group.write_client and group.write_client.narrowing else "" + access = (str(group.context.platform), str(group.context.scope_id), str(group.context.group), writer) + return (self._hermes_home, self._base_url, key_digest, self._whoami_label, *access) def _entry_key(self) -> tuple[str, ...]: """The server entry the checkpoint writes to (``checkpoint.entry_state``, GottZ/ctx#299): on @@ -544,6 +714,490 @@ def _entry_key(self) -> tuple[str, ...]: key_digest = hashlib.sha256(self._api_key.encode("utf-8")).hexdigest() if self._api_key else "" return ("rest", self._base_url, key_digest) + # -- Access groups (design 02 §4.2 to §4.6) --------------------------------------------- + + def _decide_access(self, kwargs: Mapping[str, Any]) -> None: + """Steps 1 and 2 of design 02 §4.2: the profile's settings and markers, the decision table + (``access.decide``) on this build's arguments and turn, then the markers the build raises + (``access.seen_markers``), all before anything is bound. A decision that cannot be taken is + ``off``.""" + home = self._hermes_home + init = dict(kwargs) + init.setdefault("hermes_home", home) + try: + settings = _access.load_settings(home) + markers = _access.read_markers(home) + decision = _access.decide( + init, + _access.current_access(), + _access.session_parent_platform(), + settings, + markers, + _access.access_supported(), + ) + _access.raise_markers(home, **_access.seen_markers(init, decision)) + except Exception as exc: # never a binding the table did not give + settings = _access.SETTINGS_DEFAULTS + decision = _access.Decision("off", f"the access decision failed ({type(exc).__name__})", strict=True) + self._access_settings = settings + self._decision = decision + context = self._access_context() + self._bound_turn = _turn_key(context) if context is not None else None + self._access_off = "" + if decision.kind != "off": + return + self._access_off = decision.reason + fields = decision.context.fields if decision.context is not None else None + configured = bool(fields) and fields.get("enabled") is not False + logger.log( + logging.WARNING if configured else logging.INFO, + "CTX provider off for this session (profile=%s, platform=%s): %s", + self._profile, + self._platform or "?", + decision.reason, + ) + self._record_access_state(decision.context, f"off: {decision.reason}") + + def _access_context(self) -> Any: + """The access group this session serves (``access.AccessContext``): a group binding, or a + governed group on the profile's connection; None for every other session and for ``off``.""" + decision = self._decision + return decision.context if decision is not None and decision.kind != "off" else None + + def _group_base_url(self) -> str: + """The ctx server of a group without ``base_url``: the profile's (``CTX_BASE_URL``, then the + settings' ``ctx_base_url``; the umbrella adds its MCP entry's origin).""" + return resolve_base_url(self._config.get("ctx_base_url")) + + def _bind_group(self, decision: Any) -> None: + """Steps 4 and 5 of design 02 §4.2 for a ``group`` decision: the group's server (``https`` + when a field names it) before its key, both read from the profile's secret scope, then the + group proof (:meth:`_prove_group`). ``recall``/``capture`` hold as set, unset they hold for + unrestricted groups only, and for restricted ones only when the profile's + ``restricted_allow`` names them.""" + context, fields, strict = decision.context, decision.fields, decision.strict + allow = tuple(self._access_settings.get("restricted_allow") or ()) + recall = (fields.recall if fields.recall is not None else not strict) and (not strict or "recall" in allow) + capture = (fields.capture if fields.capture is not None else not strict) and (not strict or "capture" in allow) + try: + if fields.base_url: + base_url = env_secret(fields.base_url) + if not _access.valid_base_url(base_url): + self._group_refused(context, "field base_url: its variable holds no https URL of a ctx server") + return + else: + base_url = self._group_base_url() + base_url = base_url.rstrip("/") + if not base_url: + self._group_refused(context, "no ctx server URL for the group (field base_url or the profile's)") + return + key = env_secret(fields.key) + except Exception as exc: # an unscoped read under multiplexing raises (host contract) + self._group_refused(context, f"the group's variables cannot be read ({type(exc).__name__})") + return + if not key: + self._group_refused(context, "field key: its variable is empty") + return + self._api_key = key + self._base_url = base_url + self._group = _GroupBinding( + context=context, + strict=strict, + profile=str(context.profile or self._profile), + tenant=fields.tenant, + recall=recall, + capture=capture, + fields_read=fields.read, + fields_write=fields.write, + fields_store=fields.store, + ) + self._prove_group(self._group) + + def _group_client(self, narrowing: Any) -> CtxClient: + return CtxClient( + self._base_url, + self._api_key, + timeout=float(self._config.get("api_timeout") or 10.0), + synthesis_timeout=float(self._config.get("synthesis_timeout") or 90.0), + narrowing=narrowing, + ) + + def _resolve_group(self, group: _GroupBinding, budget: float) -> str: + """The group's read set, write and store scope and its clients (``""``), or why it cannot + bind. An unrestricted group that names no ``read``/``write`` takes the key's: the key's home + scope is the write scope, the key's read set without it the read set (one unnarrowed + ``whoami``, raised as ``CtxApiError`` when it fails).""" + read, write = group.fields_read, group.fields_write + if not (read and write): + raw = _narrowing.whoami_raw(self._group_client(None), narrowed=False, budget_s=budget) + home, scopes = raw.get("home_scope"), raw.get("read_scopes") + if not isinstance(home, str) or not home or not isinstance(scopes, list): + return "the key's whoami names no home scope or read scopes" + write = write or home + read = read or tuple(str(scope) for scope in scopes if scope != write) + if len(read) > _access.READ_MAX: + return f"the key reads more than {_access.READ_MAX} scopes; name the group's in field read" + group.read, group.write = tuple(read), write + group.store = "" if group.strict else (group.fields_store or write) + group.read_client = self._group_client(_narrowing.Narrowing(read=group.read)) if group.read else None + group.write_client = ( + self._group_client(_narrowing.Narrowing(read=(write,), write=write)) if group.capture else None + ) + group.store_client = ( + self._group_client(_narrowing.Narrowing(read=(group.store,), write=group.store)) if group.store else None + ) + return "" + + def _prove_group(self, group: _GroupBinding) -> None: + """The group proof (design 02 §3.3, §4.2 step 5) within ``verify_timeout_s``: the read + narrowing's ``whoami`` and, for a restricted group, the key's unnarrowed one, judged by + ``narrowing.evaluate`` (E2 to E5, E7) with what this binding expects. The binding becomes + active, stays pending (no answer in time: asked again in the background) or goes off (a rule, + a refusal: until the next agent build). A group that reads nothing proves itself with its + writes (:meth:`_client_proven`).""" + context = group.context + deadline = self._now() + float(self._access_settings.get("verify_timeout_s") or 3) + + def left() -> float: + return max(0.0, deadline - self._now()) + + failed: list[str] = [] + detail: dict[str, str] = {} + try: + if not group.write: + why = self._resolve_group(group, left()) + if why: + self._group_refused(context, why, group=group) + return + if group.read_client is not None: + narrowed = _narrowing.whoami_raw(group.read_client, narrowed=True, budget_s=left()) + key_answer = ( + _narrowing.whoami_raw(group.read_client, narrowed=False, budget_s=left()) if group.strict else None + ) + e7 = _access.e7_inputs(self._hermes_home, str(context.platform)) if group.strict else ((), ()) + expect = _narrowing.Expect( + narrowing=group.read_client.narrowing, + strict=group.strict, + tenant=group.tenant or None, + label=_narrowing.expected_label(str(context.platform), str(context.scope_id), group.profile) + if group.strict + else None, + env_names=tuple(e7[0]) if e7 else (), + platform_toolsets=tuple(e7[1]) if e7 else (), + scope_id=str(context.scope_id), + write=group.write if group.strict else None, + ) + result = _narrowing.evaluate(narrowed, key_answer, expect) + failed, detail = list(result.failed), dict(result.detail) + if e7 is None: + failed.append("E7") + detail["E7"] = "the profile's .env and its saved toolset list for the platform must be readable" + answer = key_answer if key_answer is not None else narrowed + group.label = str(answer.get("label") or "") + group.tenant_seen = str(narrowed.get("tenant_slug") or "") + except CtxApiError as exc: + if _proof_transient(exc): + group.retry_at["group"] = self._now() + PROOF_RETRY_S + if self._group is not group: + return # re-initialized meanwhile + reason = f"proof pending: the ctx server gave no answer ({_proof_cause(exc)})" + logger.warning("CTX access group not bound yet (profile=%s): %s", self._profile, reason) + self._record_access_state(context, f"off: {reason}") + return + self._group_refused(context, f"the ctx server refused the proof ({_proof_cause(exc)})", group=group) + return + except Exception as exc: # a malformed answer or a host failure: no binding on it + self._group_refused(context, f"the proof failed ({type(exc).__name__})", group=group) + return + if failed: + self._group_refused(context, ", ".join(failed), rules=detail, group=group) + return + with self._access_lock: + if self._group is not group or self._access_off: + return # re-initialized or turned off meanwhile + group.proven.add("group") + self._client = group.read_client + self._home_scope = group.write + self._whoami_label = group.label + self._active = True + logger.info( + "CTX access group bound (profile=%s, platform=%s, server=%s, group=%s, restricted=%s, read=%d scope(s), " + "recall=%s, capture=%s)", + self._profile, + context.platform, + context.scope_id, + context.group, + group.strict, + len(group.read), + group.recall, + group.capture, + ) + self._record_access_state(context, "bound") + + def _group_refused( + self, + context: Any, + reason: str, + *, + rules: Mapping[str, str] | None = None, + group: _GroupBinding | None = None, + ) -> None: + """A group that does not bind: off for the rest of this agent, with the reason (never a key + value) in the log and the binding's status file. ``group``: the binding the proof was for; a + proof that ends after a re-initialization changes nothing of the new binding.""" + if group is not None and self._group is not group: + return + self._access_off = f"group binding refused: {reason}" + self._active = False + self._client = None + logger.warning( + "CTX access group not bound (profile=%s, platform=%s, server=%s, group=%s): %s%s", + self._profile, + getattr(context, "platform", "?"), + getattr(context, "scope_id", "?"), + getattr(context, "group", "?"), + reason, + "".join(f"; {rule}: expected {text}" for rule, text in (rules or {}).items()), + ) + self._record_access_state(context, f"off: {reason}", rules=rules) + self._group = None + + def _retry_group_proof(self) -> None: + """A group proof the network or the time failed, asked again at most every + :data:`PROOF_RETRY_S` (background paths only: ``queue_prefetch``, the digest worker).""" + group = self._group + if group is None or self._access_off or "group" in group.proven: + return + with self._access_lock: + now = self._now() + if self._group is not group or "group" in group.proven or now < group.retry_at.get("group", 0.0): + return + group.retry_at["group"] = now + PROOF_RETRY_S + previous = self._verified_binding + self._prove_group(group) + self._note_verified_binding(previous) + self._invalidate_prefetch() + + def _client_proven(self, kind: str, client: Any) -> bool: + """The write (``"write"``) or the store client's (``"store"``) own proof before its first + write (design 02 §4.2 step 5): its narrowed ``whoami`` reports its narrowing (E5), names the + group's tenant when the group does (E2), and the write client's scope is the key's home + (E3). Once per binding; a network failure is asked again after :data:`PROOF_RETRY_S`, a + refusal never. The profile's connection was proven on connect (True).""" + group = self._group + if group is None: + return not self._access_off + if self._access_off or client is None or "group" not in group.proven: + return False + if client is not (group.write_client if kind == "write" else group.store_client): + return False # pinned to an earlier binding + with self._access_lock: + if kind in group.proven: + return True + if kind in group.refused or self._now() < group.retry_at.get(kind, 0.0): + return False + try: + raw = _narrowing.whoami_raw( + client, narrowed=True, budget_s=float(self._access_settings.get("verify_timeout_s") or 3) + ) + except CtxApiError as exc: + if _proof_transient(exc): + group.retry_at[kind] = self._now() + PROOF_RETRY_S + logger.warning( + "CTX %s client not proven yet (profile=%s): %s", kind, self._profile, _proof_cause(exc) + ) + return False + group.refused[kind] = f"the ctx server refused the proof ({_proof_cause(exc)})" + logger.warning("CTX %s client off (profile=%s): %s", kind, self._profile, group.refused[kind]) + return False + except Exception as exc: + group.refused[kind] = f"the proof failed ({type(exc).__name__})" + logger.warning("CTX %s client off (profile=%s): %s", kind, self._profile, group.refused[kind]) + return False + result = _narrowing.evaluate( + raw, + None, + _narrowing.Expect( + narrowing=client.narrowing, + strict=False, + tenant=group.tenant or None, + label=None, + env_names=(), + platform_toolsets=(), + scope_id=str(group.context.scope_id), + write=group.write if kind == "write" else None, + ), + ) + if not result.ok: + group.refused[kind] = ", ".join(result.failed) + logger.warning( + "CTX %s client off (profile=%s): %s", + kind, + self._profile, + "; ".join(f"{rule}: expected {text}" for rule, text in result.detail.items()), + ) + return False + group.proven.add(kind) + if kind == "write" and self._group is group: + self._rate_limit_write = _write_limit(raw) + return True + + def _access_gate(self) -> bool: + """Whether this instance may reach ctx now (design 02 §4.3, §4.6): it is not off, the turn + (when one runs) serves the access group and fields the agent was built for, and no narrowed + client lost its narrowing. A mismatch or a lost narrowing turns the instance off for the rest + of the agent, never rebinds it. Without an access decision (no ``initialize`` yet) there is + nothing to compare.""" + if self._access_off: + return False + if self._decision is None: + return True + current = _access.current_access() + if current is not None and _turn_key(current) != self._bound_turn: + self._turn_off("trip wire: this turn's access group or fields differ from the agent's binding") + return False + group = self._group + if group is not None and any(client.narrowing_lost for client in group.clients()): + self._turn_off("narrowing_lost: a ctx answer came without the echo of this binding's narrowing") + return False + return True + + def _turn_off(self, reason: str) -> None: + """Off for the rest of this agent (trip wire, lost narrowing): no client, no recall, no write. + Its own lock: a proof in flight (which holds the access lock) does not delay it.""" + with self._off_lock: + if self._access_off: + return + self._access_off = reason + self._active = False + self._client = None + self._chain_writer = None + logger.warning("CTX provider off for the rest of this agent (profile=%s): %s", self._profile, reason) + self._record_access_state(self._access_context(), f"off: {reason}") + self._invalidate_prefetch() + + def _record_access_state(self, context: Any, state: str, *, rules: Mapping[str, str] | None = None) -> None: + """The binding's state for ``hermes memory status`` and ``access status`` (``status.record_access``; + display only, never a key value), for sessions of an access group only. Never raises.""" + if context is None or not self._hermes_home: + return + group = self._group + result = { + "state": state, + "rules": dict(rules or {}), + "key_digest": _narrowing.key_digest(self._api_key) if self._api_key else "", + "tenant_slug": (group.tenant or group.tenant_seen) if group is not None else "", + "read": list(group.read) if group is not None else [], + "write": group.write if group is not None else "", + } + try: + _status.record_access( + self._hermes_home, + str(context.platform), + str(context.scope_id), + str(context.profile or self._profile), + result, + ) + except Exception: + logger.debug("CTX access status not recorded", exc_info=True) + + def _recall_allowed(self) -> bool: + """Recall before a turn: always on the profile's connection, a group only with ``recall``.""" + group = self._group + return group is None or group.recall + + def _writer_client(self) -> Any: + """The client automatic writes go through (chain, facts, digests, mirror), without network: + the profile's one client, or a proven group's write client (it exists with ``capture`` only); + None when nothing is written.""" + if self._access_off: + return None + group = self._group + if group is None: + return self._client + if "group" not in group.proven or "write" in group.refused: + return None + return group.write_client + + def _ready_writer(self) -> Any: + """:meth:`_writer_client` once its own proof holds (the group's write client proves itself + before its first write), else None.""" + client = self._writer_client() + return client if client is not None and self._client_proven("write", client) else None + + def _no_writer_reason(self) -> str: + """Why a compaction has no client to write through: ``inactive`` (0.19.1's word) on the + profile's connection, otherwise :data:`NO_BINDING` with the cause (no key value).""" + group = self._group + if self._access_off: + return f"{NO_BINDING} ({self._access_off})" + if group is None: + return "inactive" + if "group" not in group.proven: + return f"{NO_BINDING} (the group binding is not proven yet)" + if not group.capture: + return f"{NO_BINDING} (capture is off for this access group)" + if "write" in group.refused: + return f"{NO_BINDING} (write client: {group.refused['write']})" + return f"{NO_BINDING} (the write client is not proven yet)" + + def _tool_client(self, tool_name: str) -> tuple[Any, str]: + """The client an agent tool goes through, or None and why not (``""``: the provider is not + active): the profile's one client; a group's read client for the read tools and its store + client, once proven, for ``ctx_store`` (unrestricted groups only).""" + if not self._access_gate(): + return None, f"CTX is off for this session ({NO_BINDING})" + group = self._group + if not self._active: + return None, "" + if group is None: + return self._client, "" + if tool_name == STORE_TOOL: + client = group.store_client + if client is not None and self._client_proven("store", client): + return client, "" + return None, f"CTX tool {STORE_TOOL} is not available for this access group" + if tool_name in READ_TOOLS and self._client is not None: + return self._client, "" + return None, f"CTX tool {tool_name} is not available for this access group" + + def _offered_tools(self) -> tuple[str, ...] | None: + """The agent tools a group binding offers (``None``: the profile's connection, all of them).""" + group = self._group + if group is None: + return None + offered = READ_TOOLS if group.read_client is not None else () + if group.store_client is not None and "store" not in group.refused: + offered = (*offered, STORE_TOOL) + return offered + + def _write_tags(self, agent_tags: Any, hook: str) -> list[str]: + """The tags of one write: the agent's (reserved prefixes dropped), the origin tags and, for a + session of an access group, ``server:<platform>:<server>`` and ``group:<group>``.""" + tags = merge_tags(agent_tags, self._profile, hook) + context = self._access_context() + if context is not None: + for tag in (f"server:{context.platform}:{context.scope_id}", f"group:{context.group}"): + if len(tag) <= _MAX_TAG_LEN and tag not in tags: + tags.append(tag) + return tags + + def _access_metadata(self) -> dict[str, str] | None: + """``ctx_plugin.access`` of the chain: where it was written from (provenance, no rights).""" + context = self._access_context() + if context is None: + return None + return { + "platform": str(context.platform), + "scope_id": str(context.scope_id), + "group": str(context.group), + "profile": str(context.profile or self._profile), + } + + def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None: + """Per-turn tick: the trip wire (design 02 §4.6).""" + self._access_gate() + def _invalidate_prefetch(self) -> None: """Drop the pre-warmed recall and orphan warm-ups still in flight.""" with self._prefetch_lock: @@ -607,9 +1261,15 @@ def shutdown(self) -> None: # -- Agent tools (implementations in tools.py) ------------------------------ def get_tool_schemas(self) -> list[dict[str, Any]]: + """The four tools; none for a session the access decision turned off, and for a group + binding the read tools with a read client and ``ctx_store`` with a store client.""" from .tools import get_tool_schemas as _schemas - return _schemas() + if not self._access_gate(): + return [] + offered = self._offered_tools() + schemas = _schemas() + return schemas if offered is None else [schema for schema in schemas if schema.get("name") in offered] def handle_tool_call(self, tool_name: str, args: dict[str, Any], **kwargs) -> str: from .tools import handle_tool_call as _handle @@ -619,8 +1279,11 @@ def handle_tool_call(self, tool_name: str, args: dict[str, Any], **kwargs) -> st # -- Static prompt block --------------------------------------------------- def system_prompt_block(self) -> str: - if not self._active: + if not self._active or not self._access_gate(): return "" + offered = self._offered_tools() + if offered is not None: + return self._group_prompt_block(offered) lines = [ "# CTX Long-Term Memory", f"Active. Server: {display_url(self._base_url)} · scope: {self._home_scope or '?'}.", @@ -631,6 +1294,30 @@ def system_prompt_block(self) -> str: ] return "\n".join(lines) + def _group_prompt_block(self, offered: tuple[str, ...]) -> str: + """The block of a group binding: server, tenant and write scope, and only the tools offered.""" + group = self._group + if group is None or not offered: + return "" + described = { + "ctx_query": "ctx_query (recall, optional LLM synthesis)", + STORE_TOOL: "ctx_store (persist)", + "ctx_search": "ctx_search (lightweight)", + "ctx_get": "ctx_get (block detail)", + } + lines = [ + "# CTX Long-Term Memory", + f"Active for this access group. Server: {display_url(self._base_url)} · tenant: " + f"{group.tenant or group.tenant_seen or '?'} · write scope: {group.write or '?'}.", + "Tools: " + ", ".join(described[name] for name in described if name in offered) + ".", + ] + if STORE_TOOL in offered: + lines += [ + "Conventions: one fact per block (~1–1.5k chars); store curated facts, never raw dialog dumps.", + "Categories: infrastructure, decisions, projects, reference, learnings, agent-briefing, index.", + ] + return "\n".join(lines) + # -- Prefetch --------------------------------------------------------------- def prefetch(self, query: str, *, session_id: str = "") -> str: @@ -640,6 +1327,8 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: fresh pre-warmed cache entry when available, otherwise queries now. """ self._last_recall_count = 0 + if not self._access_gate() or not self._recall_allowed(): + return "" # One read: the gate and the recall see the same binding (a re-init after the gate # neither redirects this turn's query nor leaves a None for _recall to resolve). client = self._client @@ -669,9 +1358,15 @@ def recall_status(self): return RecallStatus(provider_label="CTX", count=self._last_recall_count) def queue_prefetch(self, query: str, *, session_id: str = "") -> None: - """Pre-warm the recall cache for the next turn (background worker).""" + """Pre-warm the recall cache for the next turn (background worker). A group proof the network + failed is asked again here first (at most every :data:`PROOF_RETRY_S`).""" + if not self._access_gate(): + return + self._retry_group_proof() if not self._active or not self._config.get("auto_recall", True) or not self._client: return + if not self._recall_allowed(): + return q = (query or "").strip() if not q: return @@ -988,7 +1683,7 @@ def _auto_store_result( "CTX %s store skipped: no client (profile=%s, %s/%s)", hook, self._profile, category, log_title ) return False, "" - tags = merge_tags(None, self._profile, hook) + tags = self._write_tags(None, hook) extra: dict[str, Any] = {} if metadata: extra["metadata"] = metadata @@ -1107,13 +1802,17 @@ def on_memory_write(self, action: str, target: str, content: str, metadata: dict 'add' and 'replace' upsert a block; 'remove' is not mirrored (CTX has no delete-by-key API — the old block stays, Dream mode can supersede). + A group binding mirrors through its write client (``capture``), proven before its first write. """ + if not self._access_gate(): + return + client = self._writer_client() if ( not self._active or not self._write_enabled or not self._config.get("auto_capture", True) or not self._config.get("auto_memory_mirror", True) - or not self._client + or not client ): return content = (content or "").strip() @@ -1122,9 +1821,10 @@ def on_memory_write(self, action: str, target: str, content: str, metadata: dict category = CATEGORY_MEMORY if target == "memory" else CATEGORY_USER prefix = "memory: " if target == "memory" else "user: " sensitivity = self._config.get("sensitivity_default") - client = self._client def _run() -> None: + if not self._client_proven("write", client): + return safe = self._redacted(content) if safe is None: return @@ -1200,7 +1900,10 @@ def _pre_compress( if wait_limit is not None: deadline = min(deadline, wait_limit) api_version = self.pre_compress_checkpoint_api_version - connected = bool(self._active and self._client) + # A group binding writes through its write client (``capture``), proven before its first + # write; a session the access decision or the trip wire turned off writes nothing. + client = self._ready_writer() if self._access_gate() else None + connected = bool(self._active and client) # The chain archives evidence in every agent context (labelled, never dropped); # facts stay behind the cron/flush/subagent write gate. chain_set = bool(self._config.get("checkpoint_chain", True)) @@ -1213,7 +1916,7 @@ def _pre_compress( if not (chain_on or facts_on): if require_checkpoint: reason = ( - "inactive" + self._no_writer_reason() if not connected else ( "checkpoint_chain disabled and facts write-gated for this agent context" @@ -1223,7 +1926,6 @@ def _pre_compress( ) raise CtxCheckpointError(f"CTX pre-compress checkpoint unavailable: {reason}") return "" - client = self._client # #299: the chain and the required facts after it write against the process-wide state of # this server entry (its error answers in a row, its booked writes of the window). entry = self._chain().entry = _cp.entry_state(self._entry_key()) @@ -1378,25 +2080,31 @@ def _join_receipt(chain_text: str, facts_text: str) -> str: return f"{chain_text}\n\n{facts_text}" if facts_text else chain_text def _chain(self) -> ChainWriter: - if self._chain_writer is None or self._chain_writer.client is not self._client: - profile = self._profile + """The chain writer of the current write client (:meth:`_writer_client`), with the tags and + the ``ctx_plugin.access`` provenance of the session's access group.""" + client = self._writer_client() + if self._chain_writer is None or self._chain_writer.client is not client: + write_tags = self._write_tags def _tags(base: list[str]) -> list[str]: - return merge_tags(list(base), profile, "checkpoint") + return write_tags(list(base), "checkpoint") self._chain_writer = ChainWriter( - client=self._client, + client=client, category=self._checkpoint_category(), sensitivity=str(self._config.get("checkpoint_sensitivity") or "personal"), chunk_chars=int(self._config.get("checkpoint_chunk_chars") or _cp.DEFAULT_CHUNK_CHARS), max_parts=int(self._config.get("checkpoint_max_parts") or _cp.DEFAULT_MAX_PARTS), api_timeout=float(self._config.get("api_timeout") or 10.0), tags_for=_tags, - profile=profile, + profile=self._profile, secret=self._bound_secrets(), notify=self._checkpoint_notice, + access=self._access_metadata(), **self._chain_writer_seams(), ) + # The write limit the writing key's whoami reported (P-G follows it; None: not reported). + self._chain_writer.rate_limit_write = self._rate_limit_write return self._chain_writer def _checkpoint_notice(self, message: str) -> None: @@ -1617,10 +2325,11 @@ def _store_facts( # -- P5: session digests per segment ------------------------------------------------ def _digest_enabled(self) -> bool: + """Digests are written (a group binding: through its write client, with ``capture``).""" return bool( self._active and self._write_enabled - and self._client + and self._writer_client() and self._config.get("auto_capture", True) and self._config.get("auto_session_digest", True) ) @@ -1647,6 +2356,8 @@ def on_session_end(self, messages: list[dict[str, Any]]) -> None: trigger = "compaction" if self._compaction_pending else "end" self._compaction_pending = False self._cancel_idle_timer() + if not self._access_gate(): + return if not self._digest_enabled(): if self._active: logger.info( @@ -1671,7 +2382,11 @@ def sync_turn( ) -> None: """No raw turn dump (curated blocks only). P5: counts exchanges since the last digest; rolling digest at ``digest_every_exchanges`` / ``digest_every_hours``, and (re)arms the - idle timer (``idle_digest_minutes``) on the host's background worker.""" + idle timer (``idle_digest_minutes``) on the host's background worker. A group proof the + network failed is asked again here first (at most every :data:`PROOF_RETRY_S`).""" + if not self._access_gate(): + return + self._retry_group_proof() if not self._digest_enabled() or messages is None: return try: @@ -1698,7 +2413,9 @@ def _arm_idle_timer(self, messages: list[dict[str, Any]]) -> None: with self._idle_lock: if self._idle_timer is not None: self._idle_timer.cancel() - timer = threading.Timer(minutes * 60.0, ctx_bound(self._on_idle), args=(snapshot, root)) + timer = threading.Timer( + minutes * 60.0, ctx_bound(self._on_idle), args=(snapshot, root, self._binding_generation) + ) timer.daemon = True timer.name = "ctx-idle-digest" self._idle_timer = timer @@ -1710,9 +2427,13 @@ def _cancel_idle_timer(self) -> None: self._idle_timer.cancel() self._idle_timer = None - def _on_idle(self, snapshot: list[dict[str, Any]], root: str) -> None: + def _on_idle(self, snapshot: list[dict[str, Any]], root: str, generation: int | None = None) -> None: + """The idle digest of the binding the timer was armed under (``generation``): after a + re-initialization it writes nothing, even for the same session root.""" with self._idle_lock: self._idle_timer = None + if generation is not None and generation != self._binding_generation: + return if root != (self._root_session_id or self._session_id or "unknown") or not self._digest_enabled(): return try: @@ -1765,7 +2486,7 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: if manifest_id: metadata["manifest_id"] = manifest_id sensitivity = self._config.get("sensitivity_default") - client = self._client + client = self._writer_client() entry = _cp.entry_state(self._entry_key()) logger.info( "CTX %s digest scheduled (profile=%s, trigger=%s, root=%s, seg=%d, exchanges=%d)", @@ -1778,6 +2499,9 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: ) def _run() -> None: + if not self._client_proven("write", client): # a group's write client proves itself first + state.release(new) + return safe = self._redacted(digest) ok, _bid = ( self._auto_store_result( diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_key_redaction.py b/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_key_redaction.py index 9f2895b51..0f8d34a8c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_key_redaction.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_key_redaction.py @@ -896,8 +896,9 @@ def slow_recall(*_a): def test_prefetch_queued_during_reinitialize_does_not_publish(tmp_path, ctx_env, fake_client_cls): - """A warm-up queued between the start of initialize() and _connect() still sees the - previous client; its result must not survive the re-init.""" + """A warm-up queued between the start of initialize() and _connect() finds no binding: the + previous one is dropped before anything else (access groups, design 02 §4.2 step 0), so nothing + is queued and no result survives the re-init.""" p = _init(tmp_path) ctx_env.setattr(p, "_recall", lambda *_a: ("<recall of alpha>", 1)) warm = [] @@ -906,14 +907,15 @@ def test_prefetch_queued_during_reinitialize_does_not_publish(tmp_path, ctx_env, def queue_mid_init(): p.queue_prefetch("same query") warm.append(p._queue_thread) - warm[-1].join(5.0) + if warm[-1] is not None: + warm[-1].join(5.0) prune() ctx_env.setattr(p, "_prune_state_once", queue_mid_init) ctx_env.setenv("CTX_KEY", KEY_B) ctx_env.setenv("CTX_BASE_URL", URL_B) p.initialize("sess-next", hermes_home=str(tmp_path / "profiles" / "beta"), agent_context="primary") - assert warm and not warm[0].is_alive() + assert warm == [None] assert p._prefetch_cache is None diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/tools.py b/integrations/hermes/plugin/ctx_checkpoint/memory/tools.py index 561f97fec..05f9f4d81 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/tools.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/tools.py @@ -46,6 +46,11 @@ "an agent produced it." ) +# The plugin's own provenance key in block metadata (``ctx_plugin``: writer, profile, and for an +# access group ``access``); the model does not write it, so a block cannot claim a group it was not +# written from (design 02 §4.2 step 6). +PLUGIN_METADATA_KEY = "ctx_plugin" + _TYPES_EXCLUDE_PROP = { "type": "array", "items": {"type": "string"}, @@ -194,21 +199,41 @@ def _safe(provider, text: Any) -> str: return redact_error_text(text, _bound_secrets(provider)) +def _tool_client(provider, tool_name: str) -> tuple[Any, str]: + """The client the tool goes through and, without one, why not (``""``: not active). The + provider picks it (``_tool_client``: a group binding reads through its read client and stores + through its store client); a provider without that pick has its one client.""" + pick = getattr(provider, "_tool_client", None) + if callable(pick): + return pick(tool_name) + return (provider._client, "") if provider._active and provider._client else (None, "") + + +def _write_tags(provider, agent_tags: Any, hook: str) -> list[str]: + """The tags of a write: the provider's (with the access group's ``server:``/``group:``) or the + origin tags alone.""" + tags_of = getattr(provider, "_write_tags", None) + if callable(tags_of): + return tags_of(agent_tags, hook) + return merge_tags(agent_tags, getattr(provider, "_profile", "default"), hook) + + def handle_tool_call(provider, tool_name: str, args: dict[str, Any], **kwargs) -> str: """Dispatch a tool call on behalf of the provider instance. Every error text in the result and in the log is redacted (:func:`_safe`); a DEBUG line carries the redacted traceback instead of ``exc_info``, whose rendering would chain the raw texts.""" - if not provider._active or not provider._client: - return tool_error("CTX provider is not active (check CTX_BASE_URL/CTX_KEY and server reachability)") + client, refusal = _tool_client(provider, tool_name) + if client is None: + return tool_error(refusal or "CTX provider is not active (check CTX_BASE_URL/CTX_KEY and server reachability)") try: if tool_name == "ctx_query": - return _tool_query(provider, args) + return _tool_query(provider, client, args) if tool_name == "ctx_store": - return _tool_store(provider, args) + return _tool_store(provider, client, args) if tool_name == "ctx_search": - return _tool_search(provider, args) + return _tool_search(provider, client, args) if tool_name == "ctx_get": - return _tool_get(provider, args) + return _tool_get(provider, client, args) except CtxApiError as exc: text = _safe(provider, exc) if exc.code: @@ -263,12 +288,12 @@ def _trust_fields(entry: dict[str, Any], item: dict[str, Any]) -> bool: return False -def _tool_query(provider, args: dict[str, Any]) -> str: +def _tool_query(provider, client, args: dict[str, Any]) -> str: text = str(args.get("text") or "").strip() if not text: return tool_error("text is required") synthesize = bool(args.get("synthesize")) - data = provider._client.query( + data = client.query( text, synthesize=synthesize, include_content=True, types_exclude=_types_exclude_arg(provider, args) ) if not data.get("success"): @@ -296,7 +321,7 @@ def _tool_query(provider, args: dict[str, Any]) -> str: return json.dumps(result, ensure_ascii=False) -def _tool_store(provider, args: dict[str, Any]) -> str: +def _tool_store(provider, client, args: dict[str, Any]) -> str: category = str(args.get("category") or "").strip() title = str(args.get("title") or "").strip() content = str(args.get("content") or "").strip() @@ -323,15 +348,21 @@ def _tool_store(provider, args: dict[str, Any]) -> str: code="reserved_metadata", retryable=False, ) + if PLUGIN_METADATA_KEY in metadata: + return tool_error( + f"metadata key '{PLUGIN_METADATA_KEY}' is the plugin's own provenance and cannot be written", + code="reserved_metadata", + retryable=False, + ) if metadata: extra["metadata"] = metadata profile = getattr(provider, "_profile", "default") - data = provider._client.store( + data = client.store( category, title, content, sensitivity=sensitivity or provider._config.get("sensitivity_default"), - tags=merge_tags(args.get("tags"), profile, "tool"), + tags=_write_tags(provider, args.get("tags"), "tool"), **extra, ) if not data.get("success"): @@ -367,7 +398,7 @@ def _tool_store(provider, args: dict[str, Any]) -> str: return json.dumps(result, ensure_ascii=False) -def _tool_search(provider, args: dict[str, Any]) -> str: +def _tool_search(provider, client, args: dict[str, Any]) -> str: query = str(args.get("query") or "").strip() if not query: return tool_error("query is required") @@ -377,9 +408,7 @@ def _tool_search(provider, args: dict[str, Any]) -> str: # Named types are what the caller asked for: the configured default exclusion (checkpoint among # it) does not apply to them unless types_exclude is given. types_exclude = [] if types and args.get("types_exclude") is None else _types_exclude_arg(provider, args) - data = provider._client.search( - query, category=category, tags=tags or None, types=types or None, types_exclude=types_exclude - ) + data = client.search(query, category=category, tags=tags or None, types=types or None, types_exclude=types_exclude) if not data.get("success"): return tool_error(f"CTX search failed: {_safe(provider, data.get('error') or 'unknown error')}") results = [] @@ -402,11 +431,11 @@ def _tool_search(provider, args: dict[str, Any]) -> str: return json.dumps(out, ensure_ascii=False) -def _tool_get(provider, args: dict[str, Any]) -> str: +def _tool_get(provider, client, args: dict[str, Any]) -> str: block_id = str(args.get("block_id") or "").strip() if not block_id: return tool_error("block_id is required") - data = provider._client.get_block(block_id) + data = client.get_block(block_id) if not data.get("success"): return tool_error(f"CTX get failed: {_safe(provider, data.get('error') or 'unknown error')}") # The block is passed on whole: its untrusted_origin goes in checked (#295). diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py index 7886cea04..49e9d99c3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -4,7 +4,6 @@ S1_PENDING = frozenset( { - "P-C", "P-D", "P-E", "P-F", diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py index 05fc79e9d..6e1cd9a18 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py @@ -95,7 +95,12 @@ def test_changed_fields_under_a_cached_agent_turn_the_binding_off(world): def test_member_layout_binds_and_recall_never_reads_the_write_scope(world): _fake, _host, home = world - _write_settings(home, " restricted_allow: [recall]\n") + # A restricted profile carries a saved toolset list for the platform (the core's check R2); E7 + # reads it (``access.e7_inputs``), and without one E7 fails (an unknown list counts as unsafe). + (home / "config.yaml").write_text( + "platform_toolsets:\n discord: [web]\nmemory:\n ctx_checkpoint:\n restricted_allow: [recall]\n", + encoding="utf-8", + ) fields = {**MEMBER_FIELDS, "recall": True} provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) text = provider.prefetch("rules?") @@ -108,7 +113,7 @@ def test_member_layout_binds_and_recall_never_reads_the_write_scope(world): def test_swapped_fields_are_off_e3(world): fake, _host, home = world swapped = {**MEMBER_FIELDS, "read": [A_MEMBERS], "write": A_K, "recall": True} - _write_settings(home, " restricted_allow: [recall]\n") + _config(home, settings=" restricted_allow: [recall]\n") # a saved toolset list: only E3 can fail provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=swapped)) assert fake.count("/api/whoami") >= 1, "the proof asked the server" fake.reset_counters() @@ -117,6 +122,7 @@ def test_swapped_fields_are_off_e3(world): def test_restricted_recall_without_restricted_allow_stays_off(world): fake, _host, home = world + _config(home) # a saved toolset list, no restricted_allow: the group binds, its recall stays off fields = {**MEMBER_FIELDS, "recall": True} provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields)) assert fake.count("/api/whoami", narrowed=True) == 1, "the group is proven" @@ -174,3 +180,657 @@ def test_group_and_server_tags_are_reserved_for_the_plugin(): tags = _cfg.merge_tags(["server:discord:999", "group:admins", "topic"], "members", "tool") assert "topic" in tags assert not [t for t in tags if t.startswith(("server:", "group:"))] + + +# -- S2: the negatives of design 02 §7.3 row P-C beyond the S1 tests ---------------------------------- +# Same fake ctx server and host surface. ``_acc``/``_nar``/``_prov`` are the plugin copy's modules. + +_acc = ah.plugin_module(_PKG, "memory.access") +_nar = ah.plugin_module(_PKG, "memory.narrowing") +_prov = ah.plugin_module(_PKG, "memory.provider") +_cp = ah.plugin_module(_PKG, "memory.checkpoint") +_st = ah.plugin_module(_PKG, "memory.status") +CtxCheckpointError = _PKG.CtxCheckpointError +MEMBER_TOOLSETS = "platform_toolsets:\n discord: [web]\n" + + +def _config(home, *, toolsets=MEMBER_TOOLSETS, settings=""): + (home / "config.yaml").write_text( + toolsets + "memory:\n ctx_checkpoint:\n" + (settings or " {}\n"), encoding="utf-8" + ) + + +def _messages(n=6, tag="t"): + return [ + {"role": "user" if i % 2 == 0 else "assistant", "content": f"{tag} line {i:03d} " + tag * 120} for i in range(n) + ] + + +def _settle(provider): + for name in ("_write_thread", "_queue_thread"): + thread = getattr(provider, name, None) + if thread is not None: + thread.join(10.0) + + +def _stored(fake): + """(scope, tags, metadata) of every block a store request created, in order.""" + created = [] + for row in fake.requests("/api/store"): + title = str(row.body.get("title") or "") + for block in fake.blocks.values(): + if block["title"] == title: + created.append((block["scope"], tuple(block["tags"]), block["metadata"])) + break + return created + + +def _ctx_reads(host): + return {name: n for name, n in host.secrets.reads.items() if name.startswith("CTX") and n} + + +@pytest.fixture +def member_home(world): + fake, host, home = world + _config(home, settings=" restricted_allow: [recall]\n") + return fake, host, home + + +def _member(home, fields=None, **extra): + return _provider( + home, + **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields or MEMBER_FIELDS), + **extra, + ) + + +def test_an_off_session_reaches_ctx_on_no_path_and_reads_no_ctx_secret(world): + """V6: a restricted profile, its group without fields — every entry point, nothing reaches ctx.""" + fake, host, home = world + host.secrets.reads.clear() + provider = _provider( + home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, restricted_profile=True) + ) + messages = _messages() + assert provider.prefetch("plans?") == "" + provider.queue_prefetch("plans?") + provider.on_turn_start(1, "plans?") + provider.sync_turn("q", "a", messages=messages) + assert provider.on_pre_compress(messages) == "" + with pytest.raises(CtxCheckpointError, match="no ctx binding for this session"): + provider.on_pre_compress(messages, require_checkpoint=True) + provider.on_session_end(messages) + provider.on_memory_write("add", "memory", "a fact worth keeping") + for tool in ("ctx_query", "ctx_search", "ctx_get", "ctx_store"): + result = provider.handle_tool_call( + tool, {"text": "x", "query": "x", "block_id": "b", "category": "c", "title": "t", "content": "c"} + ) + assert '"error"' in result + assert provider.get_tool_schemas() == [] and provider.system_prompt_block() == "" + _settle(provider) + assert fake.count() == 0, [(r.path, r.action) for r in fake.requests()] + assert _ctx_reads(host) == {} + + +def test_restricted_capture_without_restricted_allow_writes_nothing(member_home): + fake, _host, home = member_home + provider = _member(home, {**MEMBER_FIELDS, "capture": True}) + assert provider._active, "the group is bound (its read client)" + fake.reset_counters() + messages = _messages() + assert provider.on_pre_compress(messages) == "" + with pytest.raises(CtxCheckpointError, match="capture is off for this access group"): + provider.on_pre_compress(messages, require_checkpoint=True) + provider.on_memory_write("add", "memory", "a member's fact") + provider.sync_turn("q", "a", messages=messages) + provider.on_session_end(messages) + _settle(provider) + assert fake.count("/api/store") == 0 and fake.count() == 0 + + +def test_restricted_capture_with_restricted_allow_writes_only_the_group_scope_tagged(member_home, monkeypatch): + fake, _host, home = member_home + _config(home, settings=" restricted_allow: [recall, capture]\n") + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _member(home, {**MEMBER_FIELDS, "capture": True}) + receipt = provider.on_pre_compress(_messages(), require_checkpoint=True) + assert receipt, "the chain was written" + stored = _stored(fake) + assert stored and {scope for scope, _tags, _meta in stored} == {A_MEMBERS} + assert all({"server:discord:111", "group:members"} <= set(tags) for _scope, tags, _meta in stored) + stores = fake.requests("/api/store") + assert {(r.read_header, r.write_header) for r in stores} == {(A_MEMBERS, A_MEMBERS)} + heads = [meta for _scope, _tags, meta in stored if (meta.get("ctx_plugin") or {}).get("checkpoint_id")] + access = {"platform": "discord", "scope_id": "111", "group": "members", "profile": "members"} + assert heads and all(meta["ctx_plugin"].get("access") == access for meta in heads) + writer_proofs = [r for r in fake.requests("/api/whoami") if r.write_header == A_MEMBERS] + assert len(writer_proofs) == 1, "the write client proved itself once, before its first write" + assert provider._chain_writer.rate_limit_write == fake.rate_limit_write, "the chain follows the reported limit" + + +def test_an_operator_group_stores_into_store_and_its_chain_stays_in_its_home(world, monkeypatch): + fake, _host, home = world + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _provider( + home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields={**OPS_FIELDS, "store": A_K}) + ) + assert "ctx_store" in [s["name"] for s in provider.get_tool_schemas()] + provider.handle_tool_call( # the fake answers a store without "success"; what it stored is what counts + "ctx_store", + {"category": "reference", "title": "ops note", "content": "c", "tags": ["server:discord:999", "group:x", "t"]}, + ) + assert {(r.read_header, r.write_header) for r in fake.requests("/api/store")} == {(A_K, A_K)} + note = next(block for block in fake.blocks.values() if block["title"] == "ops note") + assert note["scope"] == A_K + assert "server:discord:999" not in note["tags"] and "group:x" not in note["tags"] and "t" in note["tags"] + assert {"server:discord:111", "group:ops"} <= set(note["tags"]) + before = len(fake.blocks) + assert provider.on_pre_compress(_messages(tag="o"), require_checkpoint=True) + chain = [block for block in list(fake.blocks.values())[before:]] + assert chain and {block["scope"] for block in chain} == {A_OPS}, "the chain goes to the key's home, not store" + + +def test_a_key_without_the_right_to_write_turns_off_the_write_client_only(world): + fake, _host, home = world + fields = {**OPS_FIELDS, "write": A_MEMBERS} # the ops key reads/writes no A_MEMBERS + v5 = ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields) + # Each automatic write proves the write client before its first store: a digest first, a mirror first. + first_digest = _provider(home, **v5) + first_digest.on_session_end(_messages(10)) + _settle(first_digest) + first_mirror = _provider(home, **v5) + first_mirror.on_memory_write("add", "memory", "a fact") + _settle(first_mirror) + assert fake.count("/api/store") == 0 + provider = _provider(home, **v5) + assert "alpha knowledge" in provider.prefetch("rules?"), "the read client stays" + with pytest.raises(CtxCheckpointError, match="write client"): + provider.on_pre_compress(_messages(), require_checkpoint=True) + fake.reset_counters() + assert provider.on_pre_compress(_messages()) == "" + provider.on_memory_write("add", "memory", "a fact") + _settle(provider) + assert fake.count("/api/store") == 0 and fake.count("/api/whoami") == 0, "refused once, never asked again" + assert "alpha knowledge" in provider.prefetch("rules?") + + +def test_e7_binds_without_a_foreign_key_next_to_file_tools(member_home): + fake, _host, home = member_home + (home / ".env").write_text("CTX_KEY_111_MEMBERS=x\n", encoding="utf-8") + _config(home, toolsets="platform_toolsets:\n discord: [web, file]\n", settings=" restricted_allow: [recall]\n") + provider = _member(home, {**MEMBER_FIELDS, "recall": True}) + text = provider.prefetch("rules?") + assert "alpha knowledge" in text and "what another member said" not in text + assert {r.key_digest for r in fake.requests()} == {digest(MEMBER_KEY)} + + +def test_a_fork_built_in_the_turn_of_a_group_writes_into_the_groups_write_scope(world, monkeypatch): + fake, _host, home = world + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + turn = ah.make_access(group="ops", profile="members", restricted=False, fields=OPS_FIELDS) + with ah.turn(turn): + fork = Provider(config={"transport": "rest", "memory": True}) + fork.initialize( + "fork-1", hermes_home=str(home), platform="subagent", agent_context="subagent", **ah.v5_kwargs() + ) + assert fork.on_pre_compress(_messages(tag="f"), require_checkpoint=True) + stored = _stored(fake) + assert stored and {scope for scope, _tags, _meta in stored} == {A_OPS} + assert {r.key_digest for r in fake.requests()} == {digest(OPS_A_KEY)} + + +def test_an_initialize_that_raises_leaves_nothing_bound(world, monkeypatch): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + assert "alpha knowledge" in provider.prefetch("plans?") + + def broken(_home): + raise OSError("ctx.json unreadable") + + monkeypatch.setattr(provider, "_load_config", broken) + with pytest.raises(OSError): + provider.initialize("s-2", hermes_home=str(home), platform="discord", **ah.v5_kwargs()) + fake.reset_counters() + assert provider.prefetch("plans?") == "" and provider.get_tool_schemas() == [] + assert '"error"' in provider.handle_tool_call("ctx_query", {"text": "plans?"}) + assert fake.count() == 0 + + +def test_availability_without_a_profile_key_needs_the_host_and_ungoverned_off_or_local(world, monkeypatch): + fake, host, home = world + host.secrets.set_base({"CTX_BASE_URL": fake.url}) + monkeypatch.setenv("HERMES_HOME", str(home)) + _write_settings(home, " ungoverned: auto\n") + assert Provider(config={"transport": "rest"}).is_available() is False + _write_settings(home, ' ungoverned: "off"\n') + assert Provider(config={"transport": "rest"}).is_available() is True + assert Provider(config={"transport": "mcp"}).is_available() is True, "groups run over REST on an MCP profile" + ah.install(monkeypatch, v8=False, secrets={"CTX_BASE_URL": fake.url}) + assert Provider(config={"transport": "rest"}).is_available() is False, "no access groups on this host" + + +def test_the_trip_wire_also_runs_at_turn_start_and_in_tool_calls(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + same = ah.make_access(group="ops", profile="members", restricted=False, fields=OPS_FIELDS) + with ah.turn(same): + provider.on_turn_start(1, "plans?") + assert "alpha knowledge" in provider.prefetch("plans?"), "the same group and fields keep the binding" + other = ah.make_access(group="mods", profile="members", restricted=False, fields=OPS_FIELDS) + fake.reset_counters() + with ah.turn(other): + provider.on_turn_start(2, "plans?") + assert '"error"' in provider.handle_tool_call("ctx_query", {"text": "plans?"}) + assert provider.get_tool_schemas() == [] and provider.system_prompt_block() == "" + assert fake.count() == 0 + + +def test_a_turn_of_a_governed_group_on_a_profile_connection_turns_it_off(world): + fake, _host, home = world + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize("cli-1", hermes_home=str(home), platform="cli", agent_context="primary", **ah.v5_kwargs()) + assert "alpha knowledge" in provider.prefetch("plans?"), "a local session on the profile's connection" + fake.reset_counters() + with ah.turn(ah.make_access(group="ops", profile="members", restricted=False, fields=OPS_FIELDS)): + assert provider.prefetch("plans?") == "" + assert provider.get_tool_schemas() == [] and fake.count() == 0 + + +def test_a_lost_narrowing_turns_the_whole_instance_off(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + fake.echo_missing = True + assert provider.prefetch("plans?") == "" + fake.echo_missing = False + fake.reset_counters() + assert provider.prefetch("plans?") == "" + provider.on_memory_write("add", "memory", "a fact") + with pytest.raises(CtxCheckpointError, match="narrowing_lost"): + provider.on_pre_compress(_messages(), require_checkpoint=True) + assert '"error"' in provider.handle_tool_call("ctx_search", {"query": "plans"}) + assert provider.get_tool_schemas() == [] + _settle(provider) + assert fake.count() == 0, "no client of the binding sends anything after one lost its narrowing" + + +def test_the_build_raises_the_markers_and_a_later_session_without_its_group_is_off(world): + fake, _host, home = world + assert _acc.read_markers(str(home)) == _acc.Markers(False, False) + _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + assert _acc.read_markers(str(home)) == _acc.Markers(restricted_seen=False, governed_seen=True) + _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True)) + assert _acc.read_markers(str(home)) == _acc.Markers(restricted_seen=True, governed_seen=True) + fake.reset_counters() + for platform in ("discord", "cli"): # rows 6/7: a restricted group ran in this profile + later = _provider(home, platform=platform, **ah.v5_kwargs()) + assert later.prefetch("plans?") == "" and later.get_tool_schemas() == [] + assert fake.count() == 0 + + +def test_a_restricted_profile_without_a_group_raises_restricted_seen(world): + _fake, _host, home = world + _provider(home, platform="cli", **ah.v5_kwargs(restricted_profile=True)) + assert _acc.read_markers(str(home)).restricted_seen is True + + +def test_without_access_context_the_profile_connection_is_that_of_0_19_1(world, monkeypatch): + """Guard (green before P-C): a Hermes without the core PR binds the profile's key, unnarrowed.""" + fake, _host, home = world + ah.install(monkeypatch, v8=False, secrets={"CTX_KEY": PROFILE_KEY, "CTX_BASE_URL": fake.url}) + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize("s-1", hermes_home=str(home), platform="discord", agent_context="primary") + text = provider.prefetch("plans?") + assert "alpha knowledge" in text and "bravo knowledge" in text + assert {(r.read_header, r.write_header) for r in fake.requests()} == {(None, None)} + assert {r.key_digest for r in fake.requests()} == {digest(PROFILE_KEY)} + assert len(provider.get_tool_schemas()) == 4 and "scope: t:main" in provider.system_prompt_block() + + +def test_an_unknown_restriction_decides_strictly(world): + fake, host, home = world + kwargs = ah.v5_kwargs(scope_id="111", group="ops", fields=OPS_FIELDS, restricted_profile=True) + kwargs["access_group_restricted"] = "no" # not a bool: unknown, which counts as restricted + host.secrets.reads.clear() + provider = _provider(home, **kwargs) + assert provider.prefetch("plans?") == "" and fake.count() == 0 and _ctx_reads(host) == {} + + +def test_a_proof_without_answer_is_asked_again_in_the_background_once_a_minute(world, monkeypatch): + fake, _host, home = world + clock = [1000.0] + monkeypatch.setattr(_PKG, "_monotonic", lambda: clock[0]) + fake.throttle["/api/whoami"] = 4 + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + assert not provider._active and provider.prefetch("plans?") == "" + fake.throttle.clear() + _nar.reset_proofs() # the failure the proof store keeps 15 s + fake.reset_counters() + provider.queue_prefetch("plans?") + provider.sync_turn("q", "a", messages=_messages()) + _settle(provider) + assert fake.count() == 0, "not before a minute" + clock[0] += _prov.PROOF_RETRY_S + 1 + provider.queue_prefetch("plans?") + _settle(provider) + assert provider._active and fake.count("/api/whoami") == 1 + assert "alpha knowledge" in provider.prefetch("plans?") + + +def test_a_base_url_field_must_name_an_https_url_before_the_key_is_read(world, monkeypatch): + fake, _host, home = world + secrets = {"CTX_KEY": PROFILE_KEY, "CTX_BASE_URL": fake.url, "CTX_BASE_URL_A": fake.url} + secrets["CTX_KEY_111_OPS"] = OPS_A_KEY + host = ah.install(monkeypatch, v8=True, secrets=secrets) + fields = {**OPS_FIELDS, "base_url": "CTX_BASE_URL_A"} # its value is the fake's http:// URL + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + assert provider.prefetch("plans?") == "" + assert host.secrets.reads["CTX_KEY_111_OPS"] == 0 and host.secrets.reads["CTX_KEY"] == 0 + assert fake.count() == 0 + + +def test_an_unrestricted_group_without_read_and_write_takes_the_keys_own(world): + fake, _host, home = world + fields = {"key": "CTX_KEY_111_OPS"} + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + text = provider.prefetch("rules?") + assert "alpha knowledge" in text and "bravo knowledge" not in text + assert {r.read_header for r in fake.requests("/api/query")} == {A_K} + assert provider._group.write == A_OPS and provider._group.read == (A_K,) + + +def test_the_prompt_block_names_tenant_and_write_scope_and_only_the_offered_tools(member_home): + _fake, _host, home = member_home + block = _member(home, {**MEMBER_FIELDS, "recall": True}).system_prompt_block() + assert "tenant: t" in block and f"write scope: {A_MEMBERS}" in block + assert "ctx_query" in block and "ctx_store" not in block + + +def test_a_group_binding_runs_over_rest_on_an_mcp_profile(world): + fake, _host, home = world + provider = Provider(config={"transport": "mcp", "memory": True}) + provider.initialize( + "s-1", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS), + ) + assert "alpha knowledge" in provider.prefetch("plans?") + assert provider._entry_key()[0] == "rest" + assert {r.key_digest for r in fake.requests()} == {digest(OPS_A_KEY)} + + +def test_the_binding_identity_names_the_group_and_another_group_drops_the_manifest_cache(world): + _fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + ops = provider._binding_identity() + assert "ops" in ops and OPS_A_KEY not in repr(ops) + provider._last_manifest_by_root = {"s-1": "manifest-of-ops"} + provider.initialize( + "s-1", + hermes_home=str(home), + platform="discord", + **ah.v5_kwargs(scope_id="111", group="mods", group_restricted=False, fields=OPS_FIELDS), + ) + assert provider._binding_identity() != ops and provider._last_manifest_by_root == {} + + +ENTRY_POINTS = { + "prefetch": lambda p: p.prefetch("plans?"), + "queue_prefetch": lambda p: p.queue_prefetch("plans?"), + "sync_turn": lambda p: p.sync_turn("q", "a", messages=_messages(10)), + "on_pre_compress": lambda p: p.on_pre_compress(_messages(10)), + "on_session_end": lambda p: p.on_session_end(_messages(10)), + "on_memory_write": lambda p: p.on_memory_write("add", "memory", "a fact worth keeping"), + "handle_tool_call": lambda p: p.handle_tool_call("ctx_query", {"text": "plans?"}), + "get_tool_schemas": lambda p: p.get_tool_schemas(), + "system_prompt_block": lambda p: p.system_prompt_block(), + "on_turn_start": lambda p: p.on_turn_start(1, "plans?"), +} + + +@pytest.mark.parametrize("engine", [False, True], ids=["umbrella", "engine"]) +@pytest.mark.parametrize("entry", sorted(ENTRY_POINTS)) +def test_each_entry_point_runs_the_trip_wire_itself(world, monkeypatch, entry, engine): + """Each entry point checks the turn's group on its own: called alone in a turn of another group it + sends nothing, and the instance is off afterwards (the umbrella and the engine provider alike).""" + fake, _host, home = world + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + monkeypatch.setattr(_cp, "host_compaction_wait_s", lambda: None) + v5 = ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS) + if engine: + provider = _prov.CtxMemoryProvider() + provider.initialize("s-1", hermes_home=str(home), platform="discord", agent_context="primary", **v5) + else: + provider = _provider(home, **v5) + provider.on_memory_write("add", "memory", "before the turn") # proves the write client + _settle(provider) + assert fake.count("/api/store") == 1, "bound, with a proven write client" + fake.reset_counters() + with ah.turn(ah.make_access(group="mods", profile="members", restricted=False, fields=OPS_FIELDS)): + result = ENTRY_POINTS[entry](provider) + _settle(provider) + assert result in (None, "", []) or '"error"' in str(result) + assert provider.prefetch("plans?") == "" and provider.get_tool_schemas() == [] + assert fake.count() == 0, [(r.path, r.action) for r in fake.requests()] + + +def test_a_proof_that_ends_after_a_reinitialize_changes_nothing_of_the_new_binding(world): + _fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + stale = provider._group + provider.initialize( + "s-2", + hermes_home=str(home), + platform="discord", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS), + ) + _fake.keys[OPS_A_KEY].active = False # the stale proof is refused (401) + _nar.reset_proofs() + provider._prove_group(stale) + assert provider._active and not provider._access_off, "the new binding stands" + assert provider._client_proven("write", stale.write_client) is False, "a pinned old client writes nothing" + + +def test_e7_fails_without_a_saved_toolset_list(world): + fake, _host, home = world + _write_settings(home, " restricted_allow: [recall]\n") # no platform_toolsets: unknown counts as unsafe + provider = _member(home, {**MEMBER_FIELDS, "recall": True}) + assert fake.count("/api/whoami") >= 1 + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_a_key_of_another_server_or_profile_is_off_e4(member_home): + fake, _host, home = member_home + fake.keys[MEMBER_KEY].label = "hermes:discord:222:members" + provider = _member(home, {**MEMBER_FIELDS, "recall": True}) + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_a_key_of_another_tenant_is_off_e2(member_home): + fake, host, home = member_home + fake.add_key( + secret="ctx_member_u", + tenant="t", + home="u:d111-members", + allowed=("u:d111-k",), + scope_narrowing="required", + label=MEMBER_LABEL, + ) + fake.add_block("u:d111-k", "U rules", "uniform knowledge") + host.secrets.set_base({**host.secrets.var.get(), "CTX_KEY_111_MEMBERS": "ctx_member_u"}) + fields = { + "key": "CTX_KEY_111_MEMBERS", + "tenant": "u", + "read": ["u:d111-k"], + "write": "u:d111-members", + "recall": True, + } + provider = _member(home, fields) + fake.reset_counters() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_a_write_scope_that_is_not_the_keys_home_is_refused_e3(world, monkeypatch): + """The ops key may write A_K (its write_scopes), but the chain of a group goes to the key's home + only: a group whose write scope is another writable scope gets no write client (BP-23).""" + fake, _host, home = world + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + fields = {**OPS_FIELDS, "read": [A_OPS], "write": A_K} + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + assert provider._active, "the read client is bound" + with pytest.raises(CtxCheckpointError, match="write client"): + provider.on_pre_compress(_messages(), require_checkpoint=True) + assert fake.count("/api/store") == 0 + + +def test_ctx_store_proves_its_store_client_first(world): + fake, _host, home = world + fields = {**OPS_FIELDS, "store": A_MEMBERS} # the ops key cannot write there + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + out = provider.handle_tool_call("ctx_store", {"category": "reference", "title": "t", "content": "c"}) + assert "not available for this access group" in out + assert fake.count("/api/store") == 0 + assert "ctx_store" not in [s["name"] for s in provider.get_tool_schemas()], "a refused store client is not offered" + + +def test_the_pointer_block_follows_the_binding(world, monkeypatch): + fake, _host, home = world + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + fields = {**OPS_FIELDS, "read": [A_K, A_OPS]} # an unrestricted group that reads its own chain + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + receipt = provider.on_pre_compress(_messages(tag="p"), require_checkpoint=True) + head = receipt.split("`")[1] + assert head in provider.system_prompt_block() + other = ah.make_access(group="mods", profile="members", restricted=False, fields=fields) + fake.reset_counters() + with ah.turn(other): + assert provider.system_prompt_block() == "" + assert fake.count() == 0 + + +def test_a_restricted_group_names_no_pointer_to_a_chain_it_cannot_read(member_home, monkeypatch): + _fake, _host, home = member_home + _config(home, settings=" restricted_allow: [recall, capture]\n") + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _member(home, {**MEMBER_FIELDS, "capture": True, "recall": True}) + receipt = provider.on_pre_compress(_messages(tag="m"), require_checkpoint=True) + head = receipt.split("`")[1] + block = provider.system_prompt_block() + assert block and head not in block + + +def test_the_client_code_of_a_lost_narrowing_is_named(): + def lost(): + raise _PKG.CtxApiError("lost", status=200, code="narrowing_lost") + + assert "[narrowing_lost]" in _cp._unanswered(lost) + + +def test_every_binding_records_its_state_without_a_key_value(world, monkeypatch): + _fake, _host, home = world + seen = [] + monkeypatch.setattr(_st, "record_access", lambda *args: seen.append(args)) + _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + _provider(home, **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True)) + assert [(a[1], a[2], a[3], a[4]["state"].split(":")[0]) for a in seen] == [ + ("discord", "111", "members", "bound"), + ("discord", "111", "members", "off"), + ] + assert seen[0][4]["key_digest"] == digest(OPS_A_KEY) and seen[0][4]["read"] == [A_K] + assert OPS_A_KEY not in repr(seen) and MEMBER_KEY not in repr(seen) + + +def test_a_bound_restricted_group_without_restricted_allow_gets_no_recall(world): + """Recall needs the group's ``recall`` and, restricted, the profile's ``restricted_allow`` (A02-N2): + the group is bound (its read tools are offered), its prefetch reads nothing.""" + fake, _host, home = world + _config(home) # a saved toolset list, no restricted_allow + provider = _member(home, {**MEMBER_FIELDS, "recall": True}) + assert "ctx_query" in [s["name"] for s in provider.get_tool_schemas()], "bound" + fake.reset_counters() + assert provider.prefetch("rules?") == "" + provider.queue_prefetch("rules?") + _settle(provider) + assert fake.count() == 0 + + +def test_an_idle_timer_of_one_binding_never_digests_through_the_next(world, monkeypatch): + """The same instance, the same session id, re-initialized for another group (a speaker change in a + shared thread): the idle digest the first binding armed writes nothing through the second.""" + fake, _host, home = world + _config(home, settings=" restricted_allow: [recall, capture]\n") + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + provider.sync_turn("q", "a", messages=_messages(12, tag="opsx")) + timer = provider._idle_timer + assert timer is not None, "the idle timer is armed" + members = ah.v5_kwargs( + scope_id="111", group="members", group_restricted=True, fields={**MEMBER_FIELDS, "capture": True} + ) + provider.initialize("s-1", hermes_home=str(home), platform="discord", agent_context="primary", **members) + fake.reset_counters() + timer.function(*timer.args) # the timer fires after all + _settle(provider) + timer.cancel() + assert fake.count("/api/store") == 0 and _stored(fake) == [] + + +A_MODS = "t:d111-mods" +MODS_KEY = "ctx_mods_a" + + +def test_another_group_of_the_same_session_is_named_no_head_of_the_first(world, monkeypatch): + """Two unrestricted groups that read their own chains, one session: each pointer names only the + head its own binding wrote (the recorded head is keyed by key, server and group).""" + fake, host, home = world + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + fake.add_key(secret=MODS_KEY, tenant="t", home=A_MODS, allowed=(A_K,)) + host.secrets.set_base({**host.secrets.var.get(), "CTX_KEY_111_MODS": MODS_KEY}) + ops = _provider( + home, + **ah.v5_kwargs( + scope_id="111", group="ops", group_restricted=False, fields={**OPS_FIELDS, "read": [A_K, A_OPS]} + ), + ) + head = ops.on_pre_compress(_messages(tag="o"), require_checkpoint=True).split("`")[1] + assert head in ops.system_prompt_block() + mods_fields = {"key": "CTX_KEY_111_MODS", "read": [A_K, A_MODS], "write": A_MODS} + mods = _provider(home, **ah.v5_kwargs(scope_id="111", group="mods", group_restricted=False, fields=mods_fields)) + assert mods._active and head not in mods.system_prompt_block() + + +def test_the_receipt_names_a_read_path_only_where_the_group_can_read_its_chain(member_home, monkeypatch): + _fake, _host, home = member_home + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + _config(home, settings=" restricted_allow: [recall, capture]\n") + member = _member(home, {**MEMBER_FIELDS, "capture": True, "recall": True}) + receipt = member.on_pre_compress(_messages(tag="m"), require_checkpoint=True) + assert receipt and "ctx_get" not in receipt and "Read:" not in receipt + ops = _provider( + home, + **ah.v5_kwargs( + scope_id="111", group="ops", group_restricted=False, fields={**OPS_FIELDS, "read": [A_K, A_OPS]} + ), + ) + assert "ctx_get" in ops.on_pre_compress(_messages(tag="o"), require_checkpoint=True) + + +def test_a_turn_of_the_same_group_with_another_restriction_trips(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + fake.reset_counters() + with ah.turn(ah.make_access(group="ops", profile="members", restricted=True, fields=OPS_FIELDS)): + assert provider.prefetch("plans?") == "" + assert provider.get_tool_schemas() == [] and fake.count() == 0 + + +def test_the_model_cannot_write_the_plugins_provenance_key(world): + fake, _host, home = world + provider = _provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=OPS_FIELDS)) + forged = {"ctx_plugin": {"access": {"platform": "discord", "scope_id": "222", "group": "admins"}}} + out = provider.handle_tool_call( + "ctx_store", {"category": "reference", "title": "t", "content": "c", "metadata": forged} + ) + assert "reserved_metadata" in out and fake.count("/api/store") == 0 From 0e2e384f039d650106d0d59a76eb8cb2f7b9bbea Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 02:43:36 +0100 Subject: [PATCH 07/65] =?UTF-8?q?chore(ctx=5Fcheckpoint):=20S2=20P-D=20?= =?UTF-8?q?=E2=80=94=20the=20access-group=20hook=20puts=20a=20group's=20ba?= =?UTF-8?q?se=20blocks=20into=20its=20prompt,=20cached=20per=20proven=20ex?= =?UTF-8?q?pectation,=20whole=20or=20not=20at=20all,=20off=20the=20gateway?= =?UTF-8?q?=20loop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The hook access_group_fields (registered on a Hermes with access groups) reads the group's ctx_checkpoint fields, checks their forms and, for a restricted or untold group, E1 before any secret or request; reads settings, URL (a named one must be https), key and E7 inputs on its own pool in the turn's copied context. The render cache key is the whole expectation (URL, key digest, fields, strictness, tenant, label, server, E7 inputs), so a hit sends nothing and never serves a text proven for another group. On a miss, in the same pool task, it proves the binding from raw whoami answers (E2-E5, E7), fetches the blocks with one multi-id get (per id without it), drops blocks outside read or in the write scope (E6) and renders them deterministically with the bound key replaced over the whole text before any cut and the chain's redaction after it. A transient failure, an unreadable secret or the end of the budget raises BaseBlocksUnavailable, never a partial text; the budget stays under half the core's plugins.hook_callback_timeout. The S1 tests of P-D are switched on; their world gets the saved toolset list every restricted profile has (core R2). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/__init__.py | 8 + .../ctx_checkpoint/memory/base_blocks.py | 671 +++++++++++++++++- .../ctx_checkpoint/tests/fakes/pd_extra.py | 55 ++ .../ctx_checkpoint/tests/fakes/s1_pending.py | 1 - .../tests/test_access_pd_base_blocks.py | 7 +- .../tests/test_access_pd_rules.py | 508 +++++++++++++ 6 files changed, 1227 insertions(+), 23 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/fakes/pd_extra.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_rules.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index e87118548..ed30c52b7 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -48,6 +48,7 @@ from .config_schema import FIELDS as _FORM_FIELDS from .memory import access as _access +from .memory import base_blocks as _base_blocks from .memory import checkpoint as _cp from .memory import status as _st from .memory.client import CtxApiError @@ -1383,6 +1384,13 @@ def register(ctx) -> None: ctx.register_access_fields({name: dict(spec) for name, spec in _access.SCHEMA.items()}) except Exception as exc: logger.warning("ctx_checkpoint: access-group fields not registered: %s", exc) + # Base blocks: the hook that puts a group's base blocks into its prompt (an ``async def``; its + # blocking work runs on its own pool). Same detection; a failure costs neither provider nor skill. + if _access.access_supported(): + try: + ctx.register_hook(_access.HOOK_NAME, _base_blocks.on_access_group_fields) + except Exception as exc: + logger.warning("ctx_checkpoint: base-block hook not registered: %s", exc) register_skill = getattr(ctx, "register_skill", None) if callable(register_skill) and _SKILL_PATH.is_file(): try: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index 865d80d08..fb1fcbe6f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -1,29 +1,86 @@ -"""Base blocks: ctx blocks whose content joins an access group's prompt (contract, S1). +"""Base blocks: ctx blocks whose content joins an access group's prompt (design 02 §4.4). The core fires the hook ``access_group_fields`` before a governed server's turn, in the serving profile (its secrets are readable), once per session, group and digest of the group's fields and prompt; it keeps answers (``None`` too) and asks again after a callback that raised or timed out. The callback is an ``async def`` (the core awaits it on the gateway loop under -``plugins.hook_callback_timeout``); the blocking work runs on this module's own thread pool, so a -slow ctx server holds neither the loop nor its default executor. Only whole answers: a transient -failure or the end of ``base_timeout_s`` raises ``BaseBlocksUnavailable``, never a partial text. -The callback takes every value from its arguments or ``current_access()``, never from a provider -instance (the active provider's hooks hang on an instance that is never initialized). - -S1 state: the forms are final, the functions are inert stubs, and nothing registers the hook yet. -The base-block cluster (P-D) fills them in. +``plugins.hook_callback_timeout``); the blocking work runs on this module's own thread pool, in a +copy of the turn's context (its profile and secret scope), so a slow ctx server holds neither the loop +nor its default executor. Only whole answers: a transient failure or the end of the budget raises +``BaseBlocksUnavailable``, never a partial text. The callback takes every value from its arguments +and the serving profile's home, never from a provider instance (the active provider's hooks hang on +an instance that is never initialized). + +Order of a call, each step before the next touches a secret or the network: + +1. the group's ``ctx_checkpoint`` fields, their forms and, for a restricted group (``restricted`` + true, or not told), the rules of E1 (``access.parse_fields``) — pure, on the loop; +2. the profile's settings and the core's hook timeout, on the pool, within the shortest budget a + profile can set; the call's budget is then ``base_timeout_s``, at most half the core's timeout; +3. the URL (a ``base_url`` field names an ``https`` value), then the key, then the E7 inputs of the + profile: the expectation the binding is judged by. The render cache key is that whole expectation + (URL, key digest, fields, strictness, tenant, label, server, E7 inputs), so a cached text is only + given to the expectation a proof passed for, and a hit costs no request; +4. on a miss, in the same pool task: the proof of the binding from raw ``whoami`` answers + (``narrowing.whoami_raw``, ``narrowing.evaluate``: E2 to E5, E7), then one fetch per cache key + (callers with the same key wait for it on the loop): ``get`` with the block ids through the read + narrowing, E6 per block, then ``render``. A text lives ``base_cache_s``; a key's changed rights + reach new sessions after that, those of a running session never (the core keeps its answer). """ from __future__ import annotations -from collections.abc import Mapping, Sequence +import asyncio +import concurrent.futures +import contextvars +import hashlib +import json +import logging +import threading +import time +from collections import OrderedDict +from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass from typing import Any +from urllib.parse import urlsplit + +from . import access, narrowing +from . import checkpoint as _cp +from .client import REJECT_CODES, CtxApiError, CtxClient, redact_secret +from .config import env_secret, load_ctx_config + +logger = logging.getLogger(__name__) # The heading the rendered text starts with (part of the deterministic form). HEADING = "## Knowledge for this conversation (ctx)" TRUNCATED_MARK = "…[truncated]" +# The core bounds an ``async def`` callback with ``plugins.hook_callback_timeout`` and, when it passes, +# skips the callback for 60 s in every session (hermes_cli/plugins_dispatch.py +# ``ainvoke_hook_callback``). The hook's own budget ends first: at most this share of the core's +# timeout, the rest is room for the loop to deliver the hook's own end before the core's. +CORE_TIMEOUT_SHARE = 0.5 +# The core's reading of ``plugins.hook_callback_timeout`` (hermes_cli/plugins.py +# ``_resolve_hook_callback_timeout``): absent or not a number = 30 s, above 600 s = 600 s, 0 = no bound. +CORE_TIMEOUT_DEFAULT_S = 30.0 +CORE_TIMEOUT_MAX_S = 600.0 +# The settings are read before the call's budget is known; they get the shortest budget a profile +# can set (``base_timeout_s`` from 1 s). +SETTINGS_BUDGET_S = 1.0 +# The pool size before any profile's ``base_workers`` was read. +DEFAULT_WORKERS = int(access.SETTINGS_DEFAULTS["base_workers"]) +# A block's title and content (the bound keys already replaced over the whole text) pass the chain's +# redaction cut to ``max_chars`` plus this many characters, the longest named value its rules judge +# (``checkpoint.MAX_VALUE_CHARS``): a value that starts inside the text that is kept is judged whole. +REDACT_SLACK = _cp.MAX_VALUE_CHARS +# Entry codes of a multi-id get that are no answer about the block (try again later). Every other +# code of ctx's closed vocabulary, and ``not_found``/``invalid_id``, says the block cannot be had. +_TRANSIENT_ENTRY_CODES = frozenset({"rate_limit", "write_conflict", "internal", "timeout"}) +_GONE_ENTRY_CODES = (frozenset(REJECT_CODES) | {"not_found", "invalid_id"}) - _TRANSIENT_ENTRY_CODES +# How many distinct refusals are named in a WARNING per process (a misconfigured group is named once, +# not on every session). +_WARNED_MAX = 256 + class BaseBlocksUnavailable(Exception): """A base block could not be fetched now (network, time, 429) or the budget ran out: the hook @@ -40,6 +97,537 @@ class BaseBlock: scope: str +@dataclass(frozen=True) +class _Request: + """What the hook was asked, its forms checked (steps 1 and 2 of the module text).""" + + platform: str + scope_id: str + group: str + profile: str + strict: bool + fields: access.GroupFields + + +@dataclass(frozen=True) +class _Expectation: + """What a binding is judged by, read without network: the render cache key (the whole + expectation), the URL and key, and the E7 inputs and label of a restricted group.""" + + key: tuple[Any, ...] + url: str + api_key: str + env_names: tuple[str, ...] + toolsets: tuple[str, ...] + label: str | None + + +@dataclass(frozen=True) +class _Plan: + """A proven binding's fetch: the render cache key and what the fetch needs.""" + + key: tuple[Any, ...] + client: CtxClient + ids: tuple[str, ...] + read: tuple[str, ...] + write: str + max_chars: int + redact: tuple[str, ...] + cache_s: int + cache_entries: int + + +# -- process state: the pool, the render cache and the fetches on their way ------------------------ + +_LOCK = threading.RLock() +_POOL: concurrent.futures.ThreadPoolExecutor | None = None +_POOL_SIZE = 0 +# Render cache: full key -> (expiry on ``_now()``, text); least recently used first. +_CACHE: OrderedDict[tuple[Any, ...], tuple[float, str]] = OrderedDict() +_CACHE_LIMIT = 0 +# Fetches on their way: full key -> (future, the deadline of the call that started it). +_INFLIGHT: dict[tuple[Any, ...], tuple[concurrent.futures.Future, float]] = {} +_WARNED: set[tuple[str, ...]] = set() +# The render cache's clock (a seam: the loop's own clock must stay the real one). +_now = time.monotonic + + +def _submit(workers: int, fn: Callable[..., Any], *args: Any) -> concurrent.futures.Future: + """*fn* on the hook's own pool, in a copy of the caller's context (the turn's profile and secret + scope are ContextVars). The pool grows to the largest ``base_workers`` a serving profile set; + a replaced pool finishes what it holds.""" + global _POOL, _POOL_SIZE + run = contextvars.copy_context().run + with _LOCK: + if _POOL is None or workers > _POOL_SIZE: + old = _POOL + _POOL_SIZE = max(int(workers), _POOL_SIZE, 1) + _POOL = concurrent.futures.ThreadPoolExecutor(max_workers=_POOL_SIZE, thread_name_prefix="ctx-base-blocks") + if old is not None: + old.shutdown(wait=False) + return _POOL.submit(run, fn, *args) + + +async def _wait(future: concurrent.futures.Future, timeout: float) -> Any: + """The result of a pool *future* within *timeout*, without tying the future to this waiter: a + waiter that gives up (its budget, a cancellation) cancels nothing another waiter waits for.""" + loop = asyncio.get_running_loop() + mine: asyncio.Future[Any] = loop.create_future() + + def settle(done: concurrent.futures.Future) -> None: + def deliver() -> None: + if mine.done(): + return + error = done.exception() + if error is not None: + mine.set_exception(error) + else: + mine.set_result(done.result()) + + try: + loop.call_soon_threadsafe(deliver) + except RuntimeError: # the waiter's loop closed meanwhile: nobody waits any more + pass + + future.add_done_callback(settle) + if timeout <= 0: + raise BaseBlocksUnavailable("the budget of the base-block hook ran out") + try: + return await asyncio.wait_for(mine, timeout) + except TimeoutError: + raise BaseBlocksUnavailable("the budget of the base-block hook ran out") from None + + +def _cached(key: tuple[Any, ...]) -> str | None: + with _LOCK: + entry = _CACHE.get(key) + if entry is None: + return None + if entry[0] <= _now(): + del _CACHE[key] + return None + _CACHE.move_to_end(key) + return entry[1] + + +def _remember(plan: _Plan, text: str) -> None: + """Keep *text* for ``base_cache_s``; the cache holds the largest ``base_cache_entries`` a serving + profile set, least recently used out first.""" + global _CACHE_LIMIT + with _LOCK: + _CACHE_LIMIT = max(_CACHE_LIMIT, plan.cache_entries) + _CACHE[plan.key] = (_now() + plan.cache_s, text) + _CACHE.move_to_end(plan.key) + while len(_CACHE) > _CACHE_LIMIT: + _CACHE.popitem(last=False) + + +def reset_state() -> None: + """Drop the render cache, the joined in-flight fetches and the thread pool (tests).""" + global _POOL, _POOL_SIZE, _CACHE_LIMIT + with _LOCK: + pool, _POOL, _POOL_SIZE = _POOL, None, 0 + _CACHE.clear() + _CACHE_LIMIT = 0 + _INFLIGHT.clear() + _WARNED.clear() + if pool is not None: + pool.shutdown(wait=False) + + +def _warn(key: tuple[str, ...], text: str, *args: Any) -> None: + with _LOCK: + if key in _WARNED: + return + if len(_WARNED) < _WARNED_MAX: + _WARNED.add(key) + logger.warning(text, *args) + + +# -- steps 1 and 2: forms, settings, budget ---------------------------------------------------------- + + +def _request_of( + platform: Any, scope_id: Any, group: Any, restricted: Any, profile: Any, fields: Any +) -> _Request | None: + """Steps 1 and 2, pure: ``None`` without this plugin's fields, with ``enabled: false``, without + base blocks or a key, or when a form (for a restricted group also E1) is broken.""" + own = fields.get(access.NAMESPACE) if isinstance(fields, Mapping) else None + if not isinstance(own, Mapping) or own.get("enabled") is False or not own.get("base_blocks"): + return None + context = access.AccessContext( + platform=str(platform or ""), + scope_id=str(scope_id or ""), + group=str(group or ""), + profile=str(profile) if profile else None, + restricted=restricted if isinstance(restricted, bool) else None, + ) + # The hook knows no profile-wide restriction: a group whose restriction is not told is restricted + # (``restricted_profile=None``; the markers cannot change that answer, so no file is read here). + strict = access.is_strict(context, restricted_profile=None, markers=access.Markers()) + parsed = access.parse_fields(own, scope_id=context.scope_id, strict=strict) + if isinstance(parsed, access.FieldError): + _warn( + ("fields", context.platform, context.scope_id, context.group, parsed.field), + "ctx_checkpoint: base blocks of access group %s (%s:%s) off: field %s: %s", + context.group, + context.platform, + context.scope_id, + parsed.field, + parsed.reason, + ) + return None + if not parsed.enabled or not parsed.base_blocks or not parsed.key: + return None + return _Request(context.platform, context.scope_id, context.group, str(profile or ""), strict, parsed) + + +def _core_hook_timeout() -> float: + """``plugins.hook_callback_timeout`` of the serving profile as the core reads it; ``0`` means the + core bounds no callback.""" + try: + from hermes_cli.config import load_config_readonly + + plugins = (load_config_readonly() or {}).get("plugins") + value = plugins.get("hook_callback_timeout") if isinstance(plugins, Mapping) else None + except Exception: + value = None + if value is None: + return CORE_TIMEOUT_DEFAULT_S + try: + timeout = float(value) + except (TypeError, ValueError): + return CORE_TIMEOUT_DEFAULT_S + if timeout != timeout or timeout < 0: + return CORE_TIMEOUT_DEFAULT_S + return min(timeout, CORE_TIMEOUT_MAX_S) + + +def _settings() -> tuple[str, Mapping[str, Any], float]: + """The serving profile's home, its settings and the core's hook timeout (on the pool).""" + from hermes_constants import get_hermes_home + + home = str(get_hermes_home()) + return home, access.load_settings(home), _core_hook_timeout() + + +def _budget_s(settings: Mapping[str, Any], core_timeout: float) -> float: + """The call's whole budget: ``base_timeout_s``, at most ``CORE_TIMEOUT_SHARE`` of the core's + hook timeout when the core bounds callbacks.""" + own = float(settings["base_timeout_s"]) + return min(own, core_timeout * CORE_TIMEOUT_SHARE) if core_timeout > 0 else own + + +# -- step 3: URL, key, proof ------------------------------------------------------------------------------ + + +def _secret(name: str) -> str: + """A variable of the serving profile's ``.env`` (``""`` when it is not set). A read that fails + (no secret scope bound for this turn) says nothing about the variable: ``BaseBlocksUnavailable``, + so the core asks again instead of keeping a ``None`` for the session.""" + try: + return env_secret(name) + except Exception: + raise BaseBlocksUnavailable("the serving profile's secrets cannot be read in this scope") from None + + +def _profile_base_url(home: str) -> str: + """The profile's ctx URL when a group names none (design 02 §3.1): ``CTX_BASE_URL``, then + ``memory.ctx_checkpoint.rest_base_url``, then ``ctx_base_url`` of ``ctx.json``, then the origin of + ``mcp_servers.<mcp_server>.url``.""" + url = _secret("CTX_BASE_URL") + if url: + return url.rstrip("/") + try: + from hermes_cli.config import load_config_readonly + + config = load_config_readonly() or {} + except Exception: + config = {} + memory = config.get("memory") if isinstance(config, Mapping) else None + section = memory.get(access.NAMESPACE) if isinstance(memory, Mapping) else None + section = section if isinstance(section, Mapping) else {} + rest = str(section.get("rest_base_url") or "").strip() + if rest: + return rest.rstrip("/") + try: + saved = str(load_ctx_config(home).get("ctx_base_url") or "").strip() + except Exception: + saved = "" + if saved: + return saved.rstrip("/") + servers = config.get("mcp_servers") if isinstance(config, Mapping) else None + entry = servers.get(str(section.get("mcp_server") or "ctx")) if isinstance(servers, Mapping) else None + raw = entry.get("url") if isinstance(entry, Mapping) else None + try: + parts = urlsplit(str(raw or "")) + except ValueError: + return "" + return f"{parts.scheme}://{parts.netloc}" if parts.scheme in ("http", "https") and parts.netloc else "" + + +def _refused(error: CtxApiError) -> bool: + """A failure that says this binding gets no text (a key or narrowing the server refuses, a lost + narrowing), as against one to try again later (network, time, 429, 5xx).""" + if error.code == "narrowing_lost" or error.status in (401, 403): + return True + return bool(error.code) and error.permanent + + +def _scope_list(value: Any) -> tuple[str, ...] | None: + if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value): + return None + return tuple(value) + + +def _left(deadline: float) -> float: + left = deadline - time.monotonic() + if left <= 0: + raise BaseBlocksUnavailable("the budget of the base-block hook ran out") + return left + + +def _expectation(request: _Request, home: str) -> _Expectation | None: + """Step 3 on the pool, without network: the URL (a named one must be ``https``), only then the + key, then the E7 inputs of a restricted group. ``None``: this binding gets no text.""" + fields = request.fields + if fields.base_url: + url = _secret(fields.base_url) + if not access.valid_base_url(url): + _warn( + ("base_url", request.platform, request.scope_id, request.group), + "ctx_checkpoint: base blocks of access group %s (%s:%s) off: %s is no https URL", + request.group, + request.platform, + request.scope_id, + fields.base_url, + ) + return None + else: + url = _profile_base_url(home) + if not url: + return None + key = _secret(fields.key) + if not key: + return None + env_names: tuple[str, ...] = () + toolsets: tuple[str, ...] = () + if request.strict: + inputs = access.e7_inputs(home, request.platform) + if inputs is None: # the profile's .env or toolset list cannot be judged: E7 fails + _warn( + ("e7", request.platform, request.scope_id, request.group), + "ctx_checkpoint: base blocks of access group %s (%s:%s) off: E7 (no readable toolset list" + " or .env in the profile)", + request.group, + request.platform, + request.scope_id, + ) + return None + env_names, toolsets = inputs + label = narrowing.expected_label(request.platform, request.scope_id, request.profile) if request.strict else None + e7 = hashlib.sha256(json.dumps([env_names, toolsets]).encode("utf-8")).hexdigest()[:32] + cache_key = ( + url.strip().rstrip("/"), + narrowing.key_digest(key), + fields.read, + fields.write, + fields.base_blocks, + fields.base_rev, + fields.base_max_chars, + request.strict, + fields.tenant, + label, + request.scope_id, + e7, + ) + return _Expectation(cache_key, url, key, env_names, toolsets, label) + + +def _prove(request: _Request, expected: _Expectation, settings: Mapping[str, Any], deadline: float) -> _Plan | None: + """Step 4's proof on the pool: raw ``whoami`` answers judged against the expectation. ``None``: this + binding gets no text; ``BaseBlocksUnavailable``: try again later.""" + fields = request.fields + url, key = expected.url, expected.api_key + verify = float(settings["verify_timeout_s"]) + try: + plain = CtxClient(url, key, timeout=verify) + raw_unnarrowed = None + read = fields.read + if request.strict or not read: + raw_unnarrowed = narrowing.whoami_raw(plain, narrowed=False, budget_s=min(verify, _left(deadline))) + if not read: + # An unrestricted group without ``read`` reads the key's read set without its write scope. + home_scope = raw_unnarrowed.get("home_scope") if isinstance(raw_unnarrowed, Mapping) else None + known = _scope_list(raw_unnarrowed.get("read_scopes") if isinstance(raw_unnarrowed, Mapping) else None) + own_write = fields.write or (home_scope if isinstance(home_scope, str) else "") + read = tuple(scope for scope in (known or ()) if scope != own_write) + if not read or len(read) > access.READ_MAX: + _warn( + ("read", request.platform, request.scope_id, request.group), + "ctx_checkpoint: base blocks of access group %s (%s:%s) off: the key reads %d scopes" + " besides its write scope; set 'read' (1 to %d)", + request.group, + request.platform, + request.scope_id, + len(read), + access.READ_MAX, + ) + return None + client = CtxClient(url, key, timeout=verify, narrowing=narrowing.Narrowing(read=read)) + raw_narrowed = narrowing.whoami_raw(client, narrowed=True, budget_s=min(verify, _left(deadline))) + except CtxApiError as exc: + if _refused(exc): + _warn( + ("proof", request.platform, request.scope_id, request.group, exc.code or str(exc.status)), + "ctx_checkpoint: base blocks of access group %s (%s:%s) off: ctx refused the binding (%s)", + request.group, + request.platform, + request.scope_id, + _cp.redact_error_text(exc, (key,)), + ) + return None + raise BaseBlocksUnavailable("the binding could not be proven now") from None + except ValueError: # a URL CtxClient does not take (no http(s), no host) + return None + expect = narrowing.Expect( + narrowing=narrowing.Narrowing(read=read), + strict=request.strict, + tenant=fields.tenant or None, + label=expected.label, + env_names=expected.env_names, + platform_toolsets=expected.toolsets, + scope_id=request.scope_id, + write=fields.write or None, + ) + verdict = narrowing.evaluate(raw_narrowed, raw_unnarrowed, expect) + if not verdict.ok: + _warn( + ("rules", request.platform, request.scope_id, request.group, *verdict.failed), + "ctx_checkpoint: base blocks of access group %s (%s:%s) off: %s", + request.group, + request.platform, + request.scope_id, + "; ".join(f"{rule}: {verdict.detail.get(rule, '')}" for rule in verdict.failed), + ) + return None + home_scope = raw_narrowed.get("home_scope") + write = fields.write or (home_scope if isinstance(home_scope, str) else "") + return _Plan( + key=expected.key, + client=client, + ids=fields.base_blocks, + read=read, + write=write, + max_chars=fields.base_max_chars, + redact=(key,), + cache_s=int(settings["base_cache_s"]), + cache_entries=int(settings["base_cache_entries"]), + ) + + +# -- step 4: fetch, E6, render ------------------------------------------------------------------------------- + + +def _fetch(plan: _Plan, deadline: float) -> str: + """One fetch of the plan's blocks through the read narrowing, E6 per block, the text rendered and + kept in the render cache. A transient failure or an entry that is no answer raises: never a + partial text.""" + try: + entries = plan.client.get_blocks(plan.ids, timeout=_left(deadline)) + except CtxApiError as exc: + raise BaseBlocksUnavailable( + "the base blocks are refused" if _refused(exc) else "the base blocks could not be fetched now" + ) from None + blocks: list[BaseBlock] = [] + skipped: dict[str, str] = {} + for asked, entry in zip(plan.ids, entries, strict=True): + if "error" in entry: + code = str(entry.get("code") or "") + if code not in _GONE_ENTRY_CODES: + raise BaseBlocksUnavailable(f"a base block could not be fetched now ({code or 'no code'})") + skipped[asked] = code + continue + scope = entry.get("scope") + # E6: a block of the group's read set, never of its write scope; a block without a scope of + # the read set counts as outside it (the server's narrowing is not the only guard). + if not isinstance(scope, str) or scope not in plan.read: + skipped[asked] = "outside read" + continue + if scope == plan.write: + skipped[asked] = "write scope (E6)" + continue + blocks.append( + BaseBlock( + id=str(entry.get("id") or asked), + title=str(entry.get("title") or ""), + content=str(entry.get("content") or ""), + scope=scope, + ) + ) + try: + text = render(blocks, plan.max_chars, redact=plan.redact) + except Exception: + raise BaseBlocksUnavailable("the base blocks could not be redacted") from None + if skipped: + logger.info( + "ctx_checkpoint: base blocks skipped: %s", + ", ".join(f"{block_id} ({reason})" for block_id, reason in sorted(skipped.items())), + ) + # A whole text that arrives after its waiter's budget is still kept: the next call is a hit. + _remember(plan, text) + return text + + +def _done(key: tuple[Any, ...], future: concurrent.futures.Future) -> None: + with _LOCK: + entry = _INFLIGHT.get(key) + if entry is not None and entry[0] is future: + del _INFLIGHT[key] + + +def _answer( + request: _Request, home: str, settings: Mapping[str, Any], deadline: float +) -> str | concurrent.futures.Future | None: + """Steps 3 and 4 in one pool task, so a call that proved its binding fetches at once instead of + queueing behind every other call's proof: ``None`` (no text for this binding), the text (cached + or fetched now), or the future of the same key's fetch already on its way (the loop awaits it; + a pool thread never waits for another). A fetch whose own deadline has passed is not joined: + it can only end without a text, so this call fetches itself.""" + expected = _expectation(request, home) + if expected is None: + return None + hit = _cached(expected.key) + if hit is not None: + return hit + plan = _prove(request, expected, settings, deadline) + if plan is None: + return None + with _LOCK: + hit = _cached(plan.key) + if hit is not None: + return hit + entry = _INFLIGHT.get(plan.key) + if entry is not None and entry[1] > time.monotonic(): + joined: concurrent.futures.Future | None = entry[0] + else: + joined = None + own: concurrent.futures.Future = concurrent.futures.Future() + _INFLIGHT[plan.key] = (own, deadline) + if joined is not None: + return joined + try: + text = _fetch(plan, deadline) + except BaseException as exc: + own.set_exception(exc) + raise + else: + own.set_result(text) + return text + finally: + _done(plan.key, own) + + async def on_access_group_fields( *, platform: str, @@ -54,21 +642,62 @@ async def on_access_group_fields( ) -> dict | None: """The hook callback: ``{"prompt": text}`` from the group's base blocks, or ``None``. ``restricted``: the group's (``None`` = unknown = restricted); ``fields``: every valid namespace - of the group (this plugin reads ``fields["ctx_checkpoint"]``). S1 stub: ``None``.""" - return None + of the group (this plugin reads ``fields["ctx_checkpoint"]``). The text depends on the group's + fields and the blocks only, never on ``session_key`` or ``user_id``.""" + started = time.monotonic() + request = _request_of(platform, scope_id, group, restricted, profile, fields) + if request is None: + return None + home, settings, core_timeout = await _wait(_submit(DEFAULT_WORKERS, _settings), SETTINGS_BUDGET_S) + workers = int(settings["base_workers"]) + deadline = started + _budget_s(settings, core_timeout) + answer = await _wait(_submit(workers, _answer, request, home, settings, deadline), deadline - time.monotonic()) + if isinstance(answer, concurrent.futures.Future): + answer = await _wait(answer, deadline - time.monotonic()) + return {"prompt": answer} if answer else None -def render(blocks: Sequence[BaseBlock], max_chars: int, *, redact: Sequence[str] = ()) -> str: - """The deterministic text of *blocks* (heading, then ``### <title>`` and content per block, in - list order), every value of *redact* removed, filled up to *max_chars*: the block that overflows - is cut with ``…[truncated]``, the rest dropped. S1 stub: ``""``.""" - return "" +# -- rendering ------------------------------------------------------------------------------------------------- -def reset_state() -> None: - """Drop the render cache, the joined in-flight fetches and the thread pool (tests). S1 stub: - no-op.""" - return None +def _clean(text: str, limit: int, redact: Sequence[str]) -> str: + """*text* as it may enter a prompt: every value of *redact* replaced over the whole text first + (a cut can then leave no piece of one), cut to *limit* plus ``REDACT_SLACK``, a leading piece of + a value at the cut masked, then the chain's redaction (host strict mode, the plugin's rules) over + what is kept. A text the cut shortened ends with ``…[truncated]``, also when the redaction made + it shorter than *limit*.""" + values = _cp.bound_secret_values(tuple(redact)) + for value in values: + text = redact_secret(text, value) + kept = text[: limit + REDACT_SLACK] + for value in values: + kept = _cp._mask_cut_secret(kept, value) + cleaned = _cp.redact_text(kept, values) + return cleaned + TRUNCATED_MARK if len(kept) < len(text) else cleaned + + +def render(blocks: Sequence[BaseBlock], max_chars: int, *, redact: Sequence[str] = ()) -> str: + """The deterministic text of *blocks* (heading, then ``### <title>`` and content per block, in + list order), every value of *redact* removed with the chain's redaction, filled up to + *max_chars*: the block that overflows is cut with ``…[truncated]``, the rest dropped. No blocks: + ``""``. The text depends on the blocks only (it enters the agent's signature).""" + if not blocks: + return "" + text = HEADING + for block in blocks: + title = " ".join(_clean(block.title, max_chars, redact).split()) or block.id + content = _clean(block.content, max_chars, redact).strip() + piece = f"\n### {title}\n{content}" if content else f"\n### {title}" + if len(text) + len(piece) <= max_chars: + text += piece + continue + room = max_chars - len(text) - len(TRUNCATED_MARK) + if room >= 0: + text = text + piece[:room] + TRUNCATED_MARK + else: # the text so far fits, the mark does not: it takes the last characters + text = text[: max_chars - len(TRUNCATED_MARK)] + TRUNCATED_MARK + break + return text __all__ = [ diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/pd_extra.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/pd_extra.py new file mode 100644 index 000000000..c9bc2ee6e --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/pd_extra.py @@ -0,0 +1,55 @@ +"""Additive fault switches of the base-block cluster (P-D) over the S1 fake ctx server, without +changing ``ctx_server.py``: they wrap one server object's answer function. + +- ``throttle_single_gets``: the next *n* single-id ``get`` calls (the per-id fallback against ctx + without the multi-id get) answer 429, while the multi-id ``get`` is left alone, so a transient + failure reaches the fallback (the S1 switch ``throttle`` counts every ``get`` and is used up by the + multi-id call first). +- ``entry_code``: the multi-id ``get`` answers the entry of *block_id* with an error entry carrying + *code* (a transient or unknown per-entry failure of C-4). +""" + +from __future__ import annotations + +from typing import Any + + +def _wrap(fake: Any, wrapper: Any) -> None: + inner = fake._answer + + def answer(method, path, action, body, secret, read_values, write_values): + return wrapper(inner, method, path, action, body, secret, read_values, write_values) + + fake._answer = answer + + +def throttle_single_gets(fake: Any, n: int) -> None: + left = {"n": int(n)} + + def wrapper(inner, method, path, action, body, secret, read_values, write_values): + if path == "/api/manage" and action == "get" and "ids" not in body and left["n"] > 0: + with fake.lock: + left["n"] -= 1 + return 429, {"success": False, "error": "rate limited", "code": "rate_limit"}, None + return inner(method, path, action, body, secret, read_values, write_values) + + _wrap(fake, wrapper) + + +def entry_code(fake: Any, block_id: str, code: str) -> None: + def wrapper(inner, method, path, action, body, secret, read_values, write_values): + status, payload, echo = inner(method, path, action, body, secret, read_values, write_values) + if path == "/api/manage" and action == "get" and isinstance(payload.get("blocks"), list): + payload = dict(payload) + payload["blocks"] = [ + {"id": block_id, "error": "try later", "code": code} + if isinstance(entry, dict) and entry.get("id") == block_id + else entry + for entry in payload["blocks"] + ] + return status, payload, echo + + _wrap(fake, wrapper) + + +__all__ = ["entry_code", "throttle_single_gets"] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py index 7886cea04..aeb7e8e88 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -5,7 +5,6 @@ S1_PENDING = frozenset( { "P-C", - "P-D", "P-E", "P-F", "P-G", diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py index 6c66188bc..1c7d0d1a7 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py @@ -26,12 +26,16 @@ K, M, B = "t:d111-k", "t:d111-members", "t:d222-k" MEMBER_KEY = "ctx_member_111_secret_value" LABEL = "hermes:discord:111:members" +# A restricted profile has a saved toolset list for its platform: the core admits no restricted group +# without one (R2, gateway/access_check.py), and E7 is judged on it (access.e7_inputs). +TOOLSETS = "platform_toolsets:\n discord: [web]\n" @pytest.fixture def world(fake_ctx, monkeypatch, _isolated_hermes_home): bb.reset_state() _nar.reset_proofs() + (_isolated_hermes_home / "config.yaml").write_text(TOOLSETS, encoding="utf-8") fake_ctx.add_key( secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL, role="member" ) @@ -184,7 +188,8 @@ async def main(): def test_budget_ends_in_unavailable_never_a_partial_text(world): fake, _host, ids, home = world - (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n base_timeout_s: 1\n", encoding="utf-8") + budget = "memory:\n ctx_checkpoint:\n base_timeout_s: 1\n" + (home / "config.yaml").write_text(TOOLSETS + budget, encoding="utf-8") fake.latency["manage:get"] = 5.0 started = time.monotonic() outcome = _call(_fields(ids, "one", "two")) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_rules.py new file mode 100644 index 000000000..3ee41e0a3 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_rules.py @@ -0,0 +1,508 @@ +"""P-D beyond the S1 tests (design 02 §4.4, §7.3 row P-D; S1 contract §5): a cached text is given only +to the expectation a proof passed for (a hit sends nothing), the render cache keeps its lifetime and its least recently +used entries, the budget stays under the core's hook timeout, the work runs on the hook's own pool +(not the loop's default executor), a transient failure in the per-id fallback or a transient entry +of the multi-id get gives no partial text, and the fields' values reach the text only through their +forms. Driven through the core's dispatcher form against the fake ctx server, as the S1 tests are.""" + +from __future__ import annotations + +import asyncio +import concurrent.futures +import threading +import time + +import pytest +from fakes import access_host as ah +from fakes import pd_extra + +pytestmark = pytest.mark.access_cluster("P-D") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pd_rules") +bb = ah.plugin_module(_PKG, "memory.base_blocks") +_nar = ah.plugin_module(_PKG, "memory.narrowing") + +K, M, OPS = "t:d111-k", "t:d111-members", "t:d111-ops" +MEMBER_KEY = "ctx_member_111_secret_value" +OPS_KEY = "ctx_operator_111_secret_value" +OPS_TWIN_KEY = "ctx_operator_twin_secret_value" +LABEL = "hermes:discord:111:members" +# A restricted profile has a saved toolset list for its platform (the core's R2); E7 needs it. +BASE_CONFIG = "platform_toolsets:\n discord: [web]\n" + + +@pytest.fixture +def world(fake_ctx, monkeypatch, _isolated_hermes_home): + bb.reset_state() + _nar.reset_proofs() + (_isolated_hermes_home / "config.yaml").write_text(BASE_CONFIG, encoding="utf-8") + fake_ctx.add_key( + secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL, role="member" + ) + fake_ctx.add_key(secret=OPS_KEY, tenant="t", home=OPS, allowed=(K, M), label="ops", role="member") + fake_ctx.add_key(secret=OPS_TWIN_KEY, tenant="t", home=OPS, allowed=(K, M), label="ops-twin", role="member") + ids = { + "one": fake_ctx.add_block(K, "House rules", "Be kind to each other."), + "two": fake_ctx.add_block(K, "FAQ", "Ask in #help."), + "member_note": fake_ctx.add_block(M, "Member chatter", "said by a member"), + "ops_note": fake_ctx.add_block(OPS, "Ops log", "written by an operator"), + } + host = ah.install( + monkeypatch, + v8=True, + secrets={ + "CTX_BASE_URL": fake_ctx.url, + "CTX_KEY_111_MEMBERS": MEMBER_KEY, + "CTX_KEY_222_MEMBERS": MEMBER_KEY, + "CTX_KEY_111_OPS": OPS_KEY, + "CTX_KEY_111_TWIN": OPS_TWIN_KEY, + "CTX_BASE_URL_111": fake_ctx.url, + }, + ) + yield fake_ctx, host, ids, _isolated_hermes_home + bb.reset_state() + _nar.reset_proofs() + + +def _member(ids, *names, **extra): + own = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M} + own["base_blocks"] = [ids.get(n, n) for n in names] + own.update(extra) + return {"ctx_checkpoint": own} + + +def _ops(ids, *names, key="CTX_KEY_111_OPS", **extra): + own = {"key": key} + own["base_blocks"] = [ids.get(n, n) for n in names] + own.update(extra) + return {"ctx_checkpoint": own} + + +def _call(fields, *, timeout=30.0, **overrides): + kwargs = ah.hook_kwargs(fields=fields, **overrides) + return asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, timeout=timeout, **kwargs)) + + +def _prompt(outcome): + assert outcome.answered, f"the hook failed: {outcome.error!r}" + assert isinstance(outcome.result, dict) and isinstance(outcome.result.get("prompt"), str), outcome.result + return outcome.result["prompt"] + + +def _gets(fake): + return fake.count("/api/manage", "get") + + +def _config(home, text): + (home / "config.yaml").write_text(BASE_CONFIG + text, encoding="utf-8") + + +# -- the render cache: one entry per proven expectation --------------------------------------------- + + +def test_a_cache_hit_sends_no_request(world): + fake, _host, ids, _home = world + first = _prompt(_call(_member(ids, "one"))) + fake.reset_counters() + _nar.reset_proofs() # even with no proof remembered: the entry is the proven expectation + assert _prompt(_call(_member(ids, "one"))) == first + assert fake.count() == 0 + + +def test_a_cached_text_is_given_only_to_the_expectation_it_was_proven_for(world): + fake, _host, ids, _home = world + assert "House rules" in _prompt(_call(_member(ids, "one"))) + assert _gets(fake) == 1 + # The same key value under another server's variable: same URL, key, read, write and blocks, + # so the same text would be cached for it, but the key is labelled for server 111 (E4). + other_server = _member(ids, "one", key="CTX_KEY_222_MEMBERS") + outcome = _call(other_server, scope_id="222") + assert outcome.answered and outcome.result is None + # Another serving profile of the same server: the label names the profile (E4). + outcome = _call(_member(ids, "one"), profile="mods") + assert outcome.answered and outcome.result is None + # An unrestricted group that expects another tenant (E2). + outcome = _call(_ops(ids, "one", tenant="x", read=[K]), restricted=False) + assert outcome.answered and outcome.result is None + assert _gets(fake) == 1, "no refused call fetched" + + +def test_a_cached_text_is_not_given_to_another_tenant_expectation(world): + fake, _host, ids, _home = world + assert "House rules" in _prompt(_call(_ops(ids, "one", tenant="t", read=[K]), restricted=False)) + outcome = _call(_ops(ids, "one", tenant="x", read=[K]), restricted=False) # only the tenant differs + assert outcome.answered and outcome.result is None + assert _gets(fake) == 1 + + +def test_the_text_never_depends_on_the_sender_or_the_session(world): + fake, _host, ids, _home = world + first = _prompt(_call(_member(ids, "one", "two"), user_id="1", session_key="agent:main:discord:group:111:1")) + second = _prompt(_call(_member(ids, "one", "two"), user_id="2", session_key="agent:main:discord:group:111:2")) + assert first == second and _gets(fake) == 1 + + +def test_two_keys_never_share_a_text(world): + fake, _host, ids, _home = world + leaked = fake.add_block(K, "Pasted", f"twin key {OPS_TWIN_KEY} and ops key {OPS_KEY}") + one = _prompt(_call(_ops(ids, leaked, read=[K]), restricted=False)) + twin = _prompt(_call(_ops(ids, leaked, key="CTX_KEY_111_TWIN", read=[K]), restricted=False)) + assert OPS_KEY not in one and OPS_TWIN_KEY not in twin + assert _gets(fake) == 2 + + +def test_another_field_state_is_another_text(world): + fake, _host, ids, _home = world + long_text = "x" * 600 + block = fake.add_block(K, "Long", long_text) + full = _prompt(_call(_member(ids, block))) + short = _prompt(_call(_member(ids, block, base_max_chars=300))) + assert long_text in full and len(short) <= 300 and short.endswith(bb.TRUNCATED_MARK) + in_order = _prompt(_call(_member(ids, "one", "two"))) + swapped_order = _prompt(_call(_member(ids, "two", "one"))) + assert in_order.index("### House rules") < in_order.index("### FAQ") + assert swapped_order.index("### FAQ") < swapped_order.index("### House rules") + assert _gets(fake) == 4 + + +def test_a_narrower_read_is_another_text(world): + _fake, _host, ids, _home = world + wide = _prompt(_call(_ops(ids, "one", "member_note", read=[K, M]), restricted=False)) + narrow = _prompt(_call(_ops(ids, "one", "member_note", read=[K]), restricted=False)) + assert "said by a member" in wide and "said by a member" not in narrow + + +def test_another_ctx_server_is_another_text(world): + from fakes.ctx_server import FakeCtx + + _fake, host, ids, _home = world + other = FakeCtx().start() + try: + other.add_key( + secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL, role="member" + ) + other.add_block(K, "House rules", "the other server's rules", block_id=ids["one"]) + first = _prompt(_call(_member(ids, "one"))) + host.secrets.set_base({"CTX_BASE_URL": other.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + second = _prompt(_call(_member(ids, "one"))) + finally: + other.stop() + assert "Be kind to each other." in first and "the other server's rules" in second + + +def test_a_fetch_past_its_deadline_is_not_joined(world, monkeypatch): + _fake, _host, ids, _home = world + stale: concurrent.futures.Future = concurrent.futures.Future() # outlived its call, never ends + + class Inflight(dict): + def get(self, key, default=None): + return super().get(key) or (stale, 0.0) + + monkeypatch.setattr(bb, "_INFLIGHT", Inflight()) + assert "House rules" in _prompt(_call(_member(ids, "one"))) + + +def test_render_cache_lives_base_cache_s(world, monkeypatch): + fake, _host, ids, _home = world + clock = [1_000.0] + monkeypatch.setattr(bb, "_now", lambda: clock[0]) + _prompt(_call(_member(ids, "one"))) + clock[0] += 899 + _prompt(_call(_member(ids, "one"))) + assert _gets(fake) == 1, "within base_cache_s (900) the text is cached" + clock[0] += 2 + _prompt(_call(_member(ids, "one"))) + assert _gets(fake) == 2, "after base_cache_s it is fetched again" + + +def test_render_cache_keeps_the_least_recently_used_base_cache_entries(world): + fake, _host, ids, home = world + _config(home, "memory:\n ctx_checkpoint:\n base_cache_entries: 64\n") + for rev in range(64): + _prompt(_call(_member(ids, "one", base_rev=rev))) + assert _gets(fake) == 64 + _prompt(_call(_member(ids, "one", base_rev=0))) # used again: now the most recent + _prompt(_call(_member(ids, "one", base_rev=64))) # the 65th entry evicts the least recent (1) + assert _gets(fake) == 65 + _prompt(_call(_member(ids, "one", base_rev=0))) + assert _gets(fake) == 65, "rev 0 was used last, it stays" + _prompt(_call(_member(ids, "one", base_rev=1))) + assert _gets(fake) == 66, "rev 1 was the least recently used, it left" + + +def test_a_failure_is_not_remembered_as_a_text(world, monkeypatch): + fake, _host, ids, home = world + _config(home, "memory:\n ctx_checkpoint:\n base_timeout_s: 1\n") + fake.latency["manage:get"] = 3.0 + outcome = _call(_member(ids, "one")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable) + fake.latency.clear() + assert "House rules" in _prompt(_call(_member(ids, "one"))) + + +# -- whole or not at all ---------------------------------------------------------------------------- + + +def test_a_transient_failure_in_the_per_id_fallback_is_unavailable(world): + fake, _host, ids, _home = world + fake.without_c4 = True + pd_extra.throttle_single_gets(fake, 4) + outcome = _call(_member(ids, "one", "two")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + singles = [row for row in fake.requests("/api/manage") if row.action == "get" and "id" in row.body] + assert singles, "the per-id fallback was reached" + + +@pytest.mark.parametrize("code", ["internal", "rate_limit", "something_new"]) +def test_a_transient_or_unknown_entry_of_the_multi_id_get_is_unavailable(world, code): + fake, _host, ids, _home = world + pd_extra.entry_code(fake, ids["two"], code) + outcome = _call(_member(ids, "one", "two")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + + +def test_a_missing_block_is_skipped_not_failed(world): + fake, _host, ids, _home = world + pd_extra.entry_code(fake, ids["two"], "not_found") + text = _prompt(_call(_member(ids, "one", "two"))) + assert "House rules" in text and "FAQ" not in text + + +@pytest.mark.parametrize("scope", [None, ["t:d111-k"], ""]) +def test_a_block_without_a_scope_of_the_read_set_is_refused(world, scope): + fake, _host, ids, _home = world + fake.leak_on_get = True + odd = fake.add_block(K, "No scope", "where from?") + fake.blocks[odd]["scope"] = scope + text = _prompt(_call(_member(ids, "one", odd))) + assert "House rules" in text and "where from?" not in text + + +def test_a_rule_failure_is_none_and_a_transient_proof_failure_is_unavailable(world): + fake, host, ids, home = world + host.secrets.set_base({"CTX_BASE_URL": fake.url, "CTX_KEY_111_MEMBERS": "ctx_unknown_key_value_000"}) + outcome = _call(_member(ids, "one")) + assert outcome.answered and outcome.result is None and _gets(fake) == 0, "a refused key is no text, for good" + _nar.reset_proofs() + host.secrets.set_base({"CTX_BASE_URL": fake.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + _config(home, "memory:\n ctx_checkpoint:\n base_timeout_s: 1\n") + fake.latency["/api/whoami"] = 3.0 + outcome = _call(_member(ids, "one")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert _gets(fake) == 0 + + +def test_e6_refuses_a_block_of_the_write_scope_even_when_read_names_it(world): + _fake, _host, ids, _home = world + # An unrestricted group may name its own write scope in 'read' (E1 forbids that for restricted + # groups only): then the server gives the block, and E6 alone keeps the group's own text out. + text = _prompt(_call(_ops(ids, "one", "ops_note", read=[K, OPS], write=OPS), restricted=False)) + assert "House rules" in text and "written by an operator" not in text + + +def test_a_transient_refusal_of_the_proof_is_unavailable_not_none(world): + fake, _host, ids, _home = world + fake.throttle["/api/whoami"] = 2 # 429, the client's one retry meets 429 again + outcome = _call(_member(ids, "one")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert _gets(fake) == 0 + + +def test_a_secret_that_cannot_be_read_is_unavailable_not_none(world, monkeypatch): + import agent.secret_scope as secret_scope + + fake, _host, ids, _home = world + + def unscoped(name, default=None): + raise RuntimeError("no secret scope bound") + + monkeypatch.setattr(secret_scope, "get_secret", unscoped) + outcome = _call(_member(ids, "one")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert fake.count() == 0 + + +# -- fields reach the text only through their forms ---------------------------------------------------- + + +def test_a_base_url_field_that_is_not_https_reads_no_key_and_sends_nothing(world): + fake, host, ids, _home = world + host.secrets.reads.clear() + outcome = _call(_member(ids, "one", base_url="CTX_BASE_URL_111")) + assert outcome.answered and outcome.result is None + assert host.secrets.reads["CTX_KEY_111_MEMBERS"] == 0 and fake.count() == 0 + + +def test_the_title_is_redacted_too(world): + fake, _host, ids, _home = world + leaky = fake.add_block(K, f"title {MEMBER_KEY}", "body") + text = _prompt(_call(_member(ids, leaky))) + assert "body" in text and MEMBER_KEY not in text + + +def test_the_chains_redaction_rules_apply_to_base_blocks(): + block = bb.BaseBlock("1", "Notes", "the password: Tr0ub4dor-and-3 and Bearer abcdefghijklmnopqrstuvwxyz0123", K) + out = bb.render([block], 4000) + assert "Tr0ub4dor-and-3" not in out and "abcdefghijklmnopqrstuvwxyz0123" not in out + + +@pytest.mark.parametrize("pad", [1, 16]) +def test_a_key_across_the_cut_leaves_no_piece_in_the_prompt(world, pad): + fake, _host, ids, _home = world + # Dense occurrences of the key (28 characters each): replacing them shortens the text by thousands + # of characters. A cut at 8000 + 1024 before the replacement would leave a piece of the key at its + # edge (7 characters after a pad of 1, 20 after 16), and the shortening would pull it into the + # prompt; a piece under 8 characters is not even one the cut-piece masking knows. + dense = fake.add_block(K, "Dense", "p" * pad + (MEMBER_KEY + " ") * 700) + text = _prompt(_call(_member(ids, dense, base_max_chars=8000))) + assert MEMBER_KEY[:7] not in text + + +def test_a_cut_the_redaction_shortened_still_ends_with_the_mark(monkeypatch): + monkeypatch.setattr(bb._cp, "redact_text", lambda text, secret=(): text[: len(text) // 4]) + out = bb.render([bb.BaseBlock("1", "Long", "a" * 20_000, K)], 8000) + assert out.endswith(bb.TRUNCATED_MARK) and len(out) <= 8000 + + +def test_an_unrestricted_group_without_read_reads_its_keys_set_without_its_write_scope(world): + fake, _host, ids, _home = world + text = _prompt(_call(_ops(ids, "one", "member_note", "ops_note"), restricted=False)) + assert "House rules" in text and "said by a member" in text and "written by an operator" not in text + narrowed = [row.read_header for row in fake.requests("/api/manage") if row.action == "get"] + assert narrowed == [f"{K},{M}"] + + +def test_an_unrestricted_key_that_reads_more_than_eight_scopes_without_read_is_none(world): + fake, host, ids, _home = world + wide = "ctx_wide_operator_secret_value" + fake.add_key(secret=wide, tenant="t", home=OPS, allowed=tuple(f"t:s{i}" for i in range(9)), label="wide") + host.secrets.set_base({"CTX_BASE_URL": fake.url, "CTX_KEY_111_WIDE": wide}) + outcome = _call(_ops(ids, "one", key="CTX_KEY_111_WIDE"), restricted=False) + assert outcome.answered and outcome.result is None and _gets(fake) == 0 + assert fake.count("/api/whoami", narrowed=True) == 0, "no narrowing past 8 scopes is sent" + + +def test_a_foreign_key_that_appears_next_to_file_tools_ends_a_cached_text(world): + _fake, _host, ids, home = world + (home / "config.yaml").write_text("platform_toolsets:\n discord:\n - file\n", encoding="utf-8") + (home / ".env").write_text("CTX_KEY_111_MEMBERS=x\n", encoding="utf-8") + assert "House rules" in _prompt(_call(_member(ids, "one"))) + (home / ".env").write_text("CTX_KEY_111_MEMBERS=x\nCTX_KEY_222_MEMBERS=y\n", encoding="utf-8") + outcome = _call(_member(ids, "one")) + assert outcome.answered and outcome.result is None + + +def test_a_restricted_group_with_a_foreign_key_next_to_file_tools_is_none(world): + fake, _host, ids, home = world + (home / "config.yaml").write_text("platform_toolsets:\n discord:\n - file\n", encoding="utf-8") + (home / ".env").write_text("CTX_KEY_111_MEMBERS=x\nCTX_KEY_222_MEMBERS=y\n", encoding="utf-8") + outcome = _call(_member(ids, "one")) + assert outcome.answered and outcome.result is None and _gets(fake) == 0 + (home / ".env").write_text("CTX_KEY_111_MEMBERS=x\n", encoding="utf-8") + assert "House rules" in _prompt(_call(_member(ids, "one"))) + + +def test_render_marks_a_cut_even_when_the_last_whole_block_leaves_no_room_for_the_mark(): + first = bb.BaseBlock("1", "A", "a" * 204, K) # heading 40 + "\\n### A\\n" 7 + 204 = 251 of 256 + second = bb.BaseBlock("2", "B", "b", K) + out = bb.render([first, second], 256) + assert len(out) == 256 and out.endswith(bb.TRUNCATED_MARK) and "### B" not in out + assert out == bb.render([first, second], 256) + + +def test_a_restricted_group_in_a_profile_without_a_saved_toolset_list_is_none(world): + fake, _host, ids, home = world + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n base_timeout_s: 4\n", encoding="utf-8") + outcome = _call(_member(ids, "one")) + assert outcome.answered and outcome.result is None and _gets(fake) == 0 + + +# -- the budget, the core's timeout and the hook's own pool ---------------------------------------------- + + +def test_the_budget_stays_under_the_core_hook_timeout(world): + fake, _host, ids, home = world + _config(home, "plugins:\n hook_callback_timeout: 2\n") + fake.latency["manage:get"] = 5.0 + started = time.monotonic() + outcome = _call(_member(ids, "one"), timeout=2.0) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), ( + f"the core's own timeout ended the callback: {outcome.error!r}" + ) + assert time.monotonic() - started < 1.6 + + +def test_the_loops_default_executor_is_not_used(world): + _fake, _host, ids, _home = world + kwargs = ah.hook_kwargs(fields=_member(ids, "one")) + + async def main(): + loop = asyncio.get_running_loop() + busy = concurrent.futures.ThreadPoolExecutor(max_workers=1) + loop.set_default_executor(busy) + release = threading.Event() + blocker = loop.run_in_executor(None, release.wait) + try: + return await ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs) + finally: + release.set() + await blocker + + assert "House rules" in _prompt(asyncio.run(main())) + + +def test_under_a_restart_a_proven_call_fetches_before_later_proofs(world): + # 40 groups at once on the default 4 workers, 0.25 s per request: their proofs alone take 5 s, + # past the 4 s budget. A fetch queued behind every other proof would never run in time; the call + # that proved its binding fetches at once, so the first calls get their text. + fake, host, _ids, _home = world + secrets = {"CTX_BASE_URL": fake.url} + calls = [] + for n in range(40): + sid = str(500 + n) + secret = f"ctx_member_{sid}_secret_value" + fake.add_key( + secret=secret, + tenant="t", + home=f"t:d{sid}-members", + allowed=(f"t:d{sid}-k",), + scope_narrowing="required", + label=f"hermes:discord:{sid}:members", + role="member", + ) + block = fake.add_block(f"t:d{sid}-k", f"Rules of {sid}", "be kind") + secrets[f"CTX_KEY_{sid}_MEMBERS"] = secret + own = {"key": f"CTX_KEY_{sid}_MEMBERS", "tenant": "t", "read": [f"t:d{sid}-k"], "write": f"t:d{sid}-members"} + calls.append(ah.hook_kwargs(scope_id=sid, fields={"ctx_checkpoint": {**own, "base_blocks": [block]}})) + host.secrets.set_base(secrets) + fake.latency["/api/whoami"] = 0.25 + fake.latency["manage:get"] = 0.25 + + async def main(): + return await asyncio.gather(*(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kw) for kw in calls)) + + outcomes = asyncio.run(main()) + assert sum(1 for outcome in outcomes if outcome.answered and outcome.result) >= 1 + assert all(outcome.answered or isinstance(outcome.error, bb.BaseBlocksUnavailable) for outcome in outcomes) + + +# -- registration ------------------------------------------------------------------------------------------ + + +def test_register_without_v8_registers_no_hook(monkeypatch): + host = ah.install(monkeypatch, v8=False) + collector = host.collector() + _PKG.register(collector) + assert collector.called("register_hook") == 0 and collector.called("register_memory_provider") == 1 + + +def test_a_failing_hook_registration_costs_neither_provider_nor_skill(monkeypatch): + host = ah.install(monkeypatch, v8=True) + collector = host.collector() + + def refuse(name, callback, **kwargs): + raise RuntimeError("no hooks here") + + collector.register_hook = refuse + _PKG.register(collector) + assert collector.called("register_memory_provider") == 1 and collector.called("register_skill") == 1 From 7d04ccb186f44ac27d4f0e095329dbf1d73dd50e Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 04:31:37 +0100 Subject: [PATCH 08/65] test(ctx_checkpoint): the list of shielded clusters names each of the two left once Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py index e89263cfa..ca9a050c2 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -6,7 +6,5 @@ { "P-E", "P-F", - "P-E", - "P-F", } ) From 392a84e2af7cbb7a6d8f130adce970b6e39c4aeb Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 04:49:32 +0100 Subject: [PATCH 09/65] fix(ctx_checkpoint): a key's reported write limit reaches the chain raw, so 0 lifts a cap an earlier report set The provider passed whoami.rate_limit_write on only when it was positive; an unlimited key (0) counted as "nothing reported" and the server entry kept the cap of an earlier report for the life of the process. The provider now passes any int on; window_writes and EntryState.report_write_limit stay the one judge of what is a limit. The fake ctx server reports ctx's default limit (100) instead of 97. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/provider.py | 8 +- .../ctx_checkpoint/tests/fakes/ctx_server.py | 2 +- .../tests/test_access_seam_write_limit.py | 88 +++++++++++++++++++ 3 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_write_limit.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index b6c39bea4..01f33bc0c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -224,10 +224,12 @@ def _proof_cause(exc: CtxApiError) -> str: def _write_limit(info: Any) -> int | None: - """``whoami.rate_limit_write`` (writes per 60 s for this key, ctx with per-request narrowing): - a positive int, else None (an older server reports none).""" + """``whoami.rate_limit_write`` (writes per 60 s for this key, ctx with per-request narrowing) as + reported: any int, ``0`` or less included (ctx: unlimited, which lifts a limit reported before); + None when the answer has no int there (an older server reports none). What counts as a limit is + judged in one place, ``checkpoint.window_writes`` and ``EntryState.report_write_limit``.""" value = info.get("rate_limit_write") if isinstance(info, Mapping) else None - return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None + return value if isinstance(value, int) and not isinstance(value, bool) else None class _PacedFactStore: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py index b702a7cce..dd09d1a10 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -113,7 +113,7 @@ def __init__(self) -> None: self.leak_on_get = False # get answers blocks outside the request's read set (E6 is the client's too) self.latency: dict[str, float] = {} # route key ("/api/whoami", "manage:get", ...) -> seconds self.throttle: dict[str, int] = {} # route key -> number of 429 answers still to give - self.rate_limit_write = 97 + self.rate_limit_write = 100 # ctx's default (query.rate_limit_write) self.max_keys = 50 self._server: ThreadingHTTPServer | None = None self._thread: threading.Thread | None = None diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_write_limit.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_write_limit.py new file mode 100644 index 000000000..d5ec8086d --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_write_limit.py @@ -0,0 +1,88 @@ +"""Seam P-C/P-G: the write limit a key's ``whoami`` reports reaches the chain as reported. ``0`` (ctx: +unlimited) is a report like any other and lifts a cap an earlier report of the same key set +(``checkpoint.EntryState.report_write_limit`` and ``window_writes`` are the one judge of what is a +limit). Before, the provider turned ``0`` into "nothing reported", so a key whose tenant limit went from +40 to unlimited stayed capped at 37 writes a window for the life of the process.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_write_limit") +_prov = ah.plugin_module(_PKG, "memory.provider") +_cp = ah.plugin_module(_PKG, "memory.checkpoint") +_nar = ah.plugin_module(_PKG, "memory.narrowing") +Provider = _PKG.CtxCheckpointMemoryProvider + +A_K, A_MEMBERS = "t:d111-k", "t:d111-members" +MEMBER_KEY = "ctx_member_111_seam" +MEMBER_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [A_K], "write": A_MEMBERS, "capture": True} + + +@pytest.mark.parametrize( + ("reported", "passed"), + [(40, 40), (100, 100), (0, 0), (-1, -1), (None, None), (True, None), (False, None), ("40", None), (40.0, None)], +) +def test_the_reported_write_limit_is_passed_on_raw(reported, passed): + info = {"success": True} if reported is None else {"success": True, "rate_limit_write": reported} + assert _prov._write_limit(info) == passed + assert _prov._write_limit(None) is None + + +@pytest.fixture +def member(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key( + secret=MEMBER_KEY, + tenant="t", + home=A_MEMBERS, + allowed=(A_K,), + scope_narrowing="required", + label="hermes:discord:111:members", + ) + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + home = tmp_path / "profiles" / "members" + home.mkdir(parents=True) + (home / "config.yaml").write_text( + "platform_toolsets:\n discord: [web]\nmemory:\n ctx_checkpoint:\n restricted_allow: [capture]\n", + encoding="utf-8", + ) + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + _nar.reset_proofs() + yield fake_ctx, home + _nar.reset_proofs() + + +def _checkpoint(home): + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize( + "s-1", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=MEMBER_FIELDS), + ) + messages = [{"role": "user" if i % 2 == 0 else "assistant", "content": f"line {i} " + "x" * 200} for i in range(6)] + assert provider.on_pre_compress(messages, require_checkpoint=True), "the chain was written" + return provider + + +def test_an_unlimited_report_lifts_the_cap_an_earlier_report_of_the_key_set(member): + fake, home = member + fake.rate_limit_write = 40 + provider = _checkpoint(home) + entry = _cp.entry_state(provider._entry_key()) + assert entry.capped(_cp.MAX_PARTS_CEILING + 2) == 40 - _cp.RATE_WINDOW_HEADROOM + + fake.rate_limit_write = 0 # the tenant's limit was lifted + _nar.reset_proofs() # a new proof (the store keeps a raw answer 60 s) + provider = _checkpoint(home) + assert provider._chain_writer.rate_limit_write == 0 + assert _cp.entry_state(provider._entry_key()) is entry + assert entry.capped(_cp.MAX_PARTS_CEILING + 2) == _cp.MAX_PARTS_CEILING + 2 + + +def test_the_fake_reports_ctx_s_default_write_limit(fake_ctx): + """The fake's default is ctx's (query.rate_limit_write, go/internal/config/config.go): a bound chain + in the fake plans as against a server with the default limit.""" + assert fake_ctx.rate_limit_write == _cp.RATE_LIMIT_WRITE_DEFAULT == 100 From 5ae9ffe8581c86c87ab0e9b18f65bae39758313f Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 04:55:41 +0100 Subject: [PATCH 10/65] fix(ctx_checkpoint): a group without base_url binds and gets its base blocks from one profile URL The group binding (initialize) and the base-block hook each resolved the profile's ctx server from the same sources in their own order; with a rest_base_url of blanks the binding took the MCP entry's origin and the hook ctx.json's URL, so one group could be proven against two servers. Both now call config.profile_base_url: the URL of the profile's own REST connection (CTX_BASE_URL, ctx.json under the memory.ctx_checkpoint overlay), then the origin of the MCP server entry. The engine alone still reads no config.yaml; the hook keeps raising BaseBlocksUnavailable when the secret scope is unreadable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/__init__.py | 19 +-- .../ctx_checkpoint/memory/base_blocks.py | 34 ++---- .../plugin/ctx_checkpoint/memory/config.py | 27 ++++- .../plugin/ctx_checkpoint/memory/provider.py | 12 +- .../tests/test_access_seam_profile_url.py | 109 ++++++++++++++++++ 5 files changed, 156 insertions(+), 45 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index a5ba68727..468cb0482 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -861,21 +861,10 @@ def _connect(self) -> None: "on" if self.memory_enabled else "off", ) - def _group_base_url(self) -> str: - """The profile's ctx server for a group without ``base_url``: ``CTX_BASE_URL``, then - ``rest_base_url`` of this section (``ctx_base_url`` of ctx.json), then the origin of the MCP - server entry's URL (design 02 §3.1).""" - url = super()._group_base_url() - if url: - return url - from urllib.parse import urlsplit - - entry = _configured_server(_effective_config(), self._server_name()) - try: - parts = urlsplit(str(entry.get("url") or "")) - except ValueError: - return "" - return f"{parts.scheme}://{parts.netloc}" if parts.scheme in ("http", "https") and parts.netloc else "" + def _profile_url_sources(self) -> tuple[Any, Any]: + """This section (its ``rest_base_url`` and ``mcp_server``) and Hermes' loaded ``mcp_servers``: + the sources of the profile's ctx server for a group without ``base_url`` (design 02 §3.1).""" + return self._section, _effective_config().get("mcp_servers") def _granted_call_mcp(self, tool: str) -> Callable[..., Any] | None: """Hermes' call_mcp for ``tool`` while the grant read before this checkpoint lists the entry diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index fb1fcbe6f..1573679cf 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -42,12 +42,12 @@ from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass from typing import Any -from urllib.parse import urlsplit from . import access, narrowing from . import checkpoint as _cp +from . import config as _config from .client import REJECT_CODES, CtxApiError, CtxClient, redact_secret -from .config import env_secret, load_ctx_config +from .config import env_secret, umbrella_section logger = logging.getLogger(__name__) @@ -332,38 +332,20 @@ def _secret(name: str) -> str: def _profile_base_url(home: str) -> str: - """The profile's ctx URL when a group names none (design 02 §3.1): ``CTX_BASE_URL``, then - ``memory.ctx_checkpoint.rest_base_url``, then ``ctx_base_url`` of ``ctx.json``, then the origin of - ``mcp_servers.<mcp_server>.url``.""" - url = _secret("CTX_BASE_URL") - if url: - return url.rstrip("/") + """The profile's ctx URL when a group names none: the one resolution the group binding takes too + (``config.profile_base_url``), from the serving profile's config.yaml as Hermes reads it now. A + secret that cannot be read in this scope says nothing about the URL: ``BaseBlocksUnavailable``.""" try: from hermes_cli.config import load_config_readonly config = load_config_readonly() or {} except Exception: config = {} - memory = config.get("memory") if isinstance(config, Mapping) else None - section = memory.get(access.NAMESPACE) if isinstance(memory, Mapping) else None - section = section if isinstance(section, Mapping) else {} - rest = str(section.get("rest_base_url") or "").strip() - if rest: - return rest.rstrip("/") + config = config if isinstance(config, Mapping) else {} try: - saved = str(load_ctx_config(home).get("ctx_base_url") or "").strip() + return _config.profile_base_url(home, umbrella_section(dict(config)), config.get("mcp_servers")) except Exception: - saved = "" - if saved: - return saved.rstrip("/") - servers = config.get("mcp_servers") if isinstance(config, Mapping) else None - entry = servers.get(str(section.get("mcp_server") or "ctx")) if isinstance(servers, Mapping) else None - raw = entry.get("url") if isinstance(entry, Mapping) else None - try: - parts = urlsplit(str(raw or "")) - except ValueError: - return "" - return f"{parts.scheme}://{parts.netloc}" if parts.scheme in ("http", "https") and parts.netloc else "" + raise BaseBlocksUnavailable("the serving profile's secrets cannot be read in this scope") from None def _refused(error: CtxApiError) -> bool: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/config.py b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py index af96f89d2..69b878868 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/config.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py @@ -18,9 +18,10 @@ import tempfile import threading import time -from collections.abc import Iterable +from collections.abc import Iterable, Mapping from pathlib import Path from typing import Any +from urllib.parse import urlsplit logger = logging.getLogger(__name__) @@ -342,6 +343,30 @@ def resolve_base_url(config_value: str = "") -> str: return raw.rstrip("/") +def profile_base_url(hermes_home: str, section: Any = None, servers: Any = None) -> str: + """The profile's ctx server, for an access group that names no ``base_url`` (design 02 §3.1): the + one resolution the group binding and the base-block hook share. The URL the profile's own REST + connection takes (``resolve_base_url``: ``CTX_BASE_URL``, then ``ctx_base_url`` of ``ctx.json`` + under the ``memory.ctx_checkpoint`` overlay, whose ``rest_base_url`` covers it as soon as it is + set, as in :func:`overlay_from_umbrella`), then the origin of the MCP server entry + ``servers[section.mcp_server or "ctx"]``. *section*: ``memory.ctx_checkpoint`` as the caller read + it (``None``: the engine without the umbrella, which reads no config.yaml); *servers*: the + profile's ``mcp_servers``. ``""`` when none names one. Raises what ``env_secret`` raises.""" + section = section if isinstance(section, Mapping) else {} + rest = section.get("rest_base_url") + configured = str(rest).strip() if rest else str(load_ctx_config(hermes_home).get("ctx_base_url") or "") + url = resolve_base_url(configured) + if url: + return url + entry = servers.get(str(section.get("mcp_server") or "ctx")) if isinstance(servers, Mapping) else None + raw = entry.get("url") if isinstance(entry, Mapping) else None + try: + parts = urlsplit(str(raw or "")) + except ValueError: + return "" + return f"{parts.scheme}://{parts.netloc}" if parts.scheme in ("http", "https") and parts.netloc else "" + + def _as_type_list(value: Any, default: list[str]) -> list[str]: """Block-type name list: list or comma string; ``[]`` is valid (= exclude nothing).""" if isinstance(value, str): diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 01f33bc0c..246578c13 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -35,6 +35,7 @@ from . import access as _access from . import checkpoint as _cp +from . import config as _cfg from . import digest as _dg from . import narrowing as _narrowing from . import status as _status @@ -767,9 +768,14 @@ def _access_context(self) -> Any: return decision.context if decision is not None and decision.kind != "off" else None def _group_base_url(self) -> str: - """The ctx server of a group without ``base_url``: the profile's (``CTX_BASE_URL``, then the - settings' ``ctx_base_url``; the umbrella adds its MCP entry's origin).""" - return resolve_base_url(self._config.get("ctx_base_url")) + """The ctx server of a group without ``base_url``: the profile's, the one resolution the + base-block hook takes too (``config.profile_base_url``) from :meth:`_profile_url_sources`.""" + return _cfg.profile_base_url(self._hermes_home, *self._profile_url_sources()) + + def _profile_url_sources(self) -> tuple[Any, Any]: + """``memory.ctx_checkpoint`` and ``mcp_servers`` of the profile for :meth:`_group_base_url`: + none for the engine, which reads no config.yaml (the umbrella passes its own).""" + return None, None def _bind_group(self, decision: Any) -> None: """Steps 4 and 5 of design 02 §4.2 for a ``group`` decision: the group's server (``https`` diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py new file mode 100644 index 000000000..95bcd5f83 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py @@ -0,0 +1,109 @@ +"""Seam P-C/P-D: the ctx server of a group that names no ``base_url`` is the profile's, resolved by one +function for the group binding (``initialize``) and the base-block hook (``config.profile_base_url``). +Before, each had its own order of the same sources; a ``rest_base_url`` of blanks made the binding take +the MCP entry's origin and the hook ``ctx.json``'s URL, so the two could prove one group against two +ctx servers. The one function follows the profile's own REST connection (``resolve_base_url`` over +``ctx.json`` under the ``memory.ctx_checkpoint`` overlay), then the MCP entry's origin.""" + +from __future__ import annotations + +import json + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_profile_url") +_cfg = ah.plugin_module(_PKG, "memory.config") +_bb = ah.plugin_module(_PKG, "memory.base_blocks") +_prov = ah.plugin_module(_PKG, "memory.provider") +Provider = _PKG.CtxCheckpointMemoryProvider + +MCP = "mcp_servers:\n ctx:\n url: https://mcp.example:8443/mcp\n" + + +def _home(tmp_path, monkeypatch, *, config="", ctx_json=None, secrets=None): + home = tmp_path / "profiles" / "members" + home.mkdir(parents=True) + (home / "config.yaml").write_text(config or "{}\n", encoding="utf-8") + if ctx_json is not None: + (home / "ctx.json").write_text(json.dumps({"ctx_base_url": ctx_json}), encoding="utf-8") + monkeypatch.setenv("HERMES_HOME", str(home)) + ah.install(monkeypatch, v8=True, secrets=secrets or {}) + return home + + +def _binding_url(home, provider_class=Provider): + """The URL the group binding of ``initialize`` takes for a group without ``base_url``.""" + provider = provider_class(config=None) if provider_class is Provider else provider_class() + provider._hermes_home = str(home) + provider._config = provider._load_config(str(home)) + return provider._group_base_url() + + +CASES = [ + pytest.param( + "memory:\n ctx_checkpoint:\n rest_base_url: https://rest.example/\n" + MCP, + "https://json.example", + {"CTX_BASE_URL": "https://env.example/"}, + "https://env.example", + id="the profile's CTX_BASE_URL", + ), + pytest.param( + "memory:\n ctx_checkpoint:\n rest_base_url: https://rest.example/\n" + MCP, + "https://json.example", + {}, + "https://rest.example", + id="rest_base_url over ctx.json", + ), + pytest.param(MCP, "https://json.example/", {}, "https://json.example", id="ctx.json"), + pytest.param(MCP, None, {}, "https://mcp.example:8443", id="the MCP entry's origin"), + pytest.param( + "memory:\n ctx_checkpoint:\n mcp_server: myctx\nmcp_servers:\n myctx:\n url: https://named.example/mcp\n" + " ctx:\n url: https://other.example/mcp\n", + None, + {}, + "https://named.example", + id="the entry mcp_server names", + ), + pytest.param( + "memory:\n ctx_checkpoint:\n rest_base_url: ' '\n" + MCP, + "https://json.example", + {}, + "https://mcp.example:8443", + id="rest_base_url of blanks covers ctx.json as for the profile's own connection", + ), + pytest.param("mcp_servers:\n ctx:\n command: ctx-mcp\n", None, {}, "", id="no URL anywhere"), +] + + +@pytest.mark.parametrize(("config", "ctx_json", "secrets", "expected"), CASES) +def test_binding_and_hook_take_the_same_profile_url(tmp_path, monkeypatch, config, ctx_json, secrets, expected): + home = _home(tmp_path, monkeypatch, config=config, ctx_json=ctx_json, secrets=secrets) + assert _binding_url(home) == expected + assert _bb._profile_base_url(str(home)) == expected + + +def test_binding_and_hook_resolve_through_one_function(tmp_path, monkeypatch): + home = _home(tmp_path, monkeypatch, config=MCP, ctx_json="https://json.example") + seen = [] + + def one(hermes_home, section=None, servers=None): + seen.append(hermes_home) + return "https://one.example" + + monkeypatch.setattr(_cfg, "profile_base_url", one, raising=False) + assert _binding_url(home) == "https://one.example" + assert _bb._profile_base_url(str(home)) == "https://one.example" + assert seen == [str(home), str(home)] + + +def test_the_engine_alone_reads_no_config_yaml_for_the_url(tmp_path, monkeypatch): + """The engine (``memory/`` without the umbrella) never read config.yaml: its profile URL is the + environment's, then ``ctx.json``'s, as before.""" + home = _home( + tmp_path, + monkeypatch, + config="memory:\n ctx_checkpoint:\n rest_base_url: https://rest.example\n" + MCP, + ctx_json="https://json.example/", + ) + assert _binding_url(home, _prov.CtxMemoryProvider) == "https://json.example" From 61c0f611043b69568e40bf0543fabf1066aab489 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 05:06:56 +0100 Subject: [PATCH 11/65] =?UTF-8?q?chore(ctx=5Fcheckpoint):=20S2=20P-E=20?= =?UTF-8?q?=E2=80=94=20hermes=20memory=20status=20is=20not=20connected=20w?= =?UTF-8?q?hile=20a=20group=20binding=20is=20off,=20and=20hermes=20ctx=5Fc?= =?UTF-8?q?heckpoint=20access=20status,=20check,=20provision=20and=20reset?= =?UTF-8?q?-marker=20run=20the=20access=20groups?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit status.py keeps one small file per binding (display fields only, written on change, 0600, outside the state pruning) and a record of messaging sessions without an access group; hermes memory status counts the bindings and is not ok while one is off for another reason than its own fields. access status shows each binding, its broken rules with the expected values and the revocation path; access check proves a group's fields (E1 to E7, the write client too) and warns of a standard key or a ctx MCP entry in a restricted profile, a tenant grant, a restricted profile that also serves sessions without their group, and ungoverned: profile in a governed profile; access provision names the scopes and the key variable, calls keyset-provision once with replace_label, adds the key as one .env line and sets ungoverned: local, nothing written when ctx refuses and repeatable after an abort; reset-marker needs the marker named. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/__init__.py | 3 +- .../ctx_checkpoint/memory/access_cli.py | 856 +++++++++++++++++- .../plugin/ctx_checkpoint/memory/cli.py | 18 +- .../plugin/ctx_checkpoint/memory/provider.py | 29 +- .../plugin/ctx_checkpoint/memory/status.py | 280 +++++- .../ctx_checkpoint/memory/tests/test_cli.py | 2 +- .../ctx_checkpoint/tests/fakes/s1_pending.py | 1 - .../tests/test_access_pe_rules.py | 559 ++++++++++++ 8 files changed, 1706 insertions(+), 42 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index 468cb0482..3f584cb23 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -1036,9 +1036,10 @@ def get_status_config(self, provider_config: dict) -> dict: from hermes_constants import get_hermes_home home = str(get_hermes_home()) - return _st.mcp_report(home) + report = _st.mcp_report(home) except Exception as exc: return {"summary": f"✗ status unavailable: {_st.redact_error(exc, self._profile_secrets())}", "ok": False} + return self._with_access_status(report, bool(_configured_server(_effective_config(), self._server_name()))) # -- memory-feature gates ------------------------------------------------------ diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 9455de6aa..cf2aa016a 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -1,51 +1,867 @@ -"""``hermes ctx_checkpoint access <status|check|provision|reset-marker>`` (contract, S1). +"""``hermes ctx_checkpoint access <status|check|provision|reset-marker>``. Operator tools for access-group bindings (design 02 §4.7): ``status`` reads the per-binding status files without network; ``check`` proves a group's fields (E1 to E7) and names every broken rule with -the expected value; ``provision`` computes scope names and the label, calls ctx's -``keyset-provision`` with ``replace_label`` and a tenant-admin key read from a named variable (never -stored), adds the new key to the target profile's ``.env`` and prints the ``/policy field`` lines +the expected value, then the configuration warnings; ``provision`` computes scope names and the +label, calls ctx's ``keyset-provision`` with ``replace_label`` and a tenant-admin key read from a named +variable (never stored), adds the new key to the profile's ``.env`` and prints the ``/policy`` lines (``--emit-yaml``: the whole group entry); ``reset-marker`` lowers the profile's markers. +Every command works on the home it is given (the CLI's: the profile ``hermes -p <profile>`` runs in). +The plugin never reads the core's ``gateway.access_groups`` (design 02 A02-L9): ``check`` takes the +group's fields as ``--field name=value``, as ``/policy field`` takes them. No key value is printed, +logged or written anywhere but the one ``.env`` line ``provision`` adds (mode 0600). + Naming (design 02 §3.4): a ctx scope name is 1 to 24 characters of lowercase letters, digits and -inner hyphens (ctx ``scopeNamePattern``). Group names may hold ``_`` and 32 characters: ``_`` becomes -``-``, the edges are cleaned, the text is cut; when the name was changed or cut, its last four -characters are a hash of the original. Collisions are refused. One tenant per operator: -``d<server id in base 36>-k`` and ``d<server id in base 36>-<group part of at most 9>``; one tenant -per community: ``k`` and ``<group>``. The key variable is ``CTX_KEY_<server id>_<PROFILE>`` (profile -upper-cased, ``-`` as ``_``), at most 64 characters (a hash suffix replaces the rest). - -S1 state: the forms are final, the functions are inert stubs, and ``memory/cli.py`` does not offer -``access`` yet. The tools cluster (P-E) fills them in and wires the subcommand. +inner hyphens (ctx ``scopeNamePattern``). Group names may hold ``_``, ``-`` and 32 characters: ``_`` +becomes ``-`` (so ``a_b`` and ``a-b`` are the same scope and refused as a collision), the edges are +cleaned, the text is cut; when the edges were cleaned or the text cut, its last four characters are +a hash of the original. One tenant per operator: ``d<server id in base 36>-k`` and +``d<server id in base 36>-<group part of at most 9>``; one tenant per community: ``k`` and +``<group>``. The key variable is ``CTX_KEY_<server id>_<PROFILE>`` (profile upper-cased, ``-`` as +``_``), at most 64 characters (a hash suffix replaces the rest). """ from __future__ import annotations +import argparse +import contextlib +import hashlib +import http.client +import io +import json +import os import re +import tempfile +import urllib.error +import urllib.request from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +from . import access, narrowing +from . import client as _client +from . import config as _config +from . import status as _status +from .config import derive_profile_name, env_secret, umbrella_section # ctx: go/internal/handler/tenant_manage.go scopeNamePattern (name part of <slug>:<name>). SCOPE_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,22}[a-z0-9])?$") # Hermes: hermes_cli/access_fields.py ENV_NAME. ENV_NAME = re.compile(r"^[A-Z][A-Z0-9_]{0,63}$") KNOWLEDGE = "k" +# Hermes: gateway/access_groups.py _GROUP_NAME and ID; a platform name; a profile name. +GROUP_NAME = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$") +NUMERIC_ID = re.compile(r"^[0-9]{1,20}$") +PLATFORM_NAME = re.compile(r"^[a-z0-9_]{1,32}$") +SERVER_ID = re.compile(r"^[A-Za-z0-9]{1,32}$") +PROFILE_NAME = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$") +# Characters of a group part per tenant layout (design 02 §3.4): one tenant per operator leaves 9 after +# ``d<server id in base 36>-`` (a 64-bit id is at most 13 base-36 digits), one per community all 24. +GROUP_PART_MAX = 9 +SCOPE_NAME_MAX = 24 +HASH_CHARS = 4 +# The server part of a scope name: ``d`` and the id in base 36 (14 characters at most). +SERVER_PART_MAX = 14 +# A ctx key as ``.env`` holds it unquoted (ctx mints hex); anything else is not written. +KEY_VALUE = re.compile(r"^[A-Za-z0-9_.~-]{16,512}$") +# Bound of one operator request (keyset-provision runs one transaction under the tenant's lock). +REQUEST_TIMEOUT_S = 30.0 +_BASE_URL_ENV = re.compile(r"^(?:CTX_BASE_URL|CTX_BASE_URL_[A-Z0-9_]+)$") +_STANDARD_KEYS = ("CTX_KEY", "CTX_API_KEY") +_BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz" +_REVOKE = ( + "To cut a group off at once: deactivate its key (ctx manage api-key-update with active=false); ctx checks the " + "key on every request, without a cache." +) + + +# -- names --------------------------------------------------------------------------------------- + + +def _base36(number: int) -> str: + out = "" + while True: + number, digit = divmod(number, 36) + out = _BASE36[digit] + out + if not number: + return out + + +def _hash(text: str, chars: int) -> str: + return _base36(int(hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest(), 16))[-chars:] + + +def _server_part(scope_id: str) -> str: + """``d`` and a numeric server id in base 36; another id lower-cased behind ``s``; a hash when + neither fits :data:`SERVER_PART_MAX`.""" + text = str(scope_id) + part = "d" + _base36(int(text)) if text.isascii() and text.isdigit() else "s" + text.lower() + if len(part) <= SERVER_PART_MAX and SCOPE_NAME.match(part): + return part + return "h" + _hash(text, SERVER_PART_MAX - 1) + + +def _group_part(group: str, budget: int) -> str: + """The scope-name part of a group: lower case, ``_`` as ``-``; when the edges had to be cleaned, + another character dropped or the text cut, the last four characters are a hash of the name.""" + plain = str(group).lower().replace("_", "-") + if len(plain) <= budget and SCOPE_NAME.match(plain): + return plain + kept = re.sub(r"[^a-z0-9-]", "", plain).strip("-")[: budget - HASH_CHARS].rstrip("-") + return kept + _hash(str(group), HASH_CHARS) def scope_layout(scope_id: str, groups: Sequence[str], *, per_community: bool = False) -> Mapping[str, str]: """The ctx scope name (name part, no slug) for the server's knowledge scope (key ``"k"``) and for - each group in *groups*; ``ValueError`` when two map to the same name. S1 stub: ``{}``.""" - return {} + each group in *groups*; ``ValueError`` when two map to the same name.""" + if per_community: + prefix, budget = "", SCOPE_NAME_MAX + else: + prefix, budget = f"{_server_part(scope_id)}-", GROUP_PART_MAX + layout: dict[str, str] = {KNOWLEDGE: f"{prefix}{KNOWLEDGE}"} + owner: dict[str, str | None] = {layout[KNOWLEDGE]: None} # None: the knowledge scope (a group may be "k") + for group in groups: + name = prefix + _group_part(str(group), budget) + if not SCOPE_NAME.match(name): + raise ValueError(f"group {group!r} gives no ctx scope name") + if name in owner and owner[name] != group: + other = "the knowledge scope" if owner[name] is None else f"group {owner[name]!r}" + raise ValueError(f"group {group!r} and {other} map to the same ctx scope {name}") + owner[name] = group + layout[str(group)] = name + return layout def key_env_name(scope_id: str, profile: str) -> str: """The ``.env`` variable holding a restricted group's key on server *scope_id* served by - *profile*. S1 stub: ``""``.""" - return "" + *profile*: ``CTX_KEY_<SERVER>_<PROFILE>`` (the form rule E1 asks of a restricted group's ``key``, + ``access.restricted_key_prefix``), cut with a hash suffix to 64 characters. ``ValueError`` when the + server id cannot be part of a variable name.""" + prefix = access.restricted_key_prefix(scope_id) + if prefix is None: + raise ValueError("the server id cannot be part of a variable name (letters and digits only)") + part = re.sub(r"[^A-Z0-9_]", "_", str(profile).upper()) + name = prefix + part + if len(name) > 64: + digest = hashlib.sha256(str(profile).encode("utf-8", "surrogatepass")).hexdigest()[:8].upper() + keep = 64 - len(prefix) - 1 - len(digest) + if keep < 1: + raise ValueError("the server id leaves no room for the profile in a variable name") + name = f"{prefix}{part[:keep].rstrip('_') or 'P'}_{digest}" + if not ENV_NAME.match(name) or len(name) <= len(prefix): + raise ValueError("the profile gives no variable name") + return name + + +# -- command line -------------------------------------------------------------------------------- + + +class _Usage(Exception): + """A wrong argument: printed with ``✗``, exit code 2, nothing sent or written.""" + + +def add_arguments(parser: argparse.ArgumentParser) -> None: + """The ``access`` subcommands on *parser* (``hermes ctx_checkpoint access`` and :func:`run_access`).""" + subs = parser.add_subparsers(dest="access_command") + status = subs.add_parser("status", help="Show every access-group binding of this profile (no network)") + status.add_argument("--server", help="Only this server, as <platform>:<server id>") + check = subs.add_parser("check", help="Prove a group's fields against ctx (E1 to E7) and warn of risky setups") + check.add_argument("--server", required=True, help="<platform>:<server id>") + check.add_argument("--profile", help="The profile serving the group (default: this profile)") + check.add_argument("--group", default="", help="The group's name (shown only)") + strictness = check.add_mutually_exclusive_group() + strictness.add_argument("--restricted", action="store_true", help="The group is restricted (default)") + strictness.add_argument("--unrestricted", action="store_true", help="The group is not restricted") + check.add_argument( + "--field", + action="append", + default=[], + metavar="NAME=VALUE", + help="A ctx_checkpoint field of the group as /policy field takes it (lists comma-separated); repeatable", + ) + provision = subs.add_parser("provision", help="Create a restricted group's ctx scopes and key and add the key") + provision.add_argument("--server", required=True, help="<platform>:<server id>") + provision.add_argument("--profile", help="The profile serving the group (default: this profile)") + provision.add_argument("--group", required=True, help="The group's name in gateway.access_groups") + provision.add_argument( + "--read", action="extend", nargs="+", default=[], metavar="SCOPE", help="More scopes the group reads" + ) + provision.add_argument("--admin-key-env", required=True, metavar="VAR", help="Variable holding a tenant-admin key") + provision.add_argument("--base-url-env", metavar="VAR", help="CTX_BASE_URL_<...>: another ctx server (https)") + provision.add_argument("--per-community", action="store_true", help="Scope names for a tenant of this server alone") + provision.add_argument("--roles", default="", help="Role ids of the group, for --emit-yaml and /policy group") + provision.add_argument("--users", default="", help="User ids of the group, for --emit-yaml and /policy group") + provision.add_argument("--emit-yaml", action="store_true", help="Also print the group entry with its fields") + reset = subs.add_parser("reset-marker", help="Lower this profile's markers (it served restricted/governed groups)") + reset.add_argument("--profile", help="The profile (shown; the markers are this profile's)") + reset.add_argument("--restricted", action="store_true", help="Lower restricted_seen") + reset.add_argument("--governed", action="store_true", help="Lower governed_seen") def run_access(argv: Sequence[str], *, hermes_home: str) -> int: - """Run ``access <argv...>`` for the home; the exit code. S1 stub: 2 (not available).""" - return 2 + """Run ``access <argv...>`` for the home; the exit code (2: wrong arguments).""" + parser = argparse.ArgumentParser(prog="hermes ctx_checkpoint access") + add_arguments(parser) + usage = io.StringIO() + try: + with contextlib.redirect_stderr(usage): + args = parser.parse_args(list(argv)) + except SystemExit as exit_: + print(usage.getvalue().strip()) + return int(exit_.code or 0) + return run_parsed(args, hermes_home=hermes_home) + + +def run_parsed(args: argparse.Namespace, *, hermes_home: str) -> int: + """Run the parsed ``access`` command (``hermes ctx_checkpoint access …`` parses on its own tree).""" + commands = {"status": _cmd_status, "check": _cmd_check, "provision": _cmd_provision, "reset-marker": _cmd_reset} + command = commands.get(getattr(args, "access_command", None) or "") + if command is None: + print("Usage: hermes ctx_checkpoint access <status|check|provision|reset-marker>") + return 2 + try: + return command(args, str(hermes_home)) + except _Usage as exc: + print(f"✗ {exc}") + return 2 + + +def _server(value: str | None) -> tuple[str, str]: + platform, colon, scope_id = str(value or "").partition(":") + if not (colon and PLATFORM_NAME.match(platform) and SERVER_ID.match(scope_id)): + raise _Usage("--server takes <platform>:<server id> (for example discord:123456789012345678)") + return platform, scope_id + + +def _profile(args: argparse.Namespace, home: str) -> str: + profile = getattr(args, "profile", None) or derive_profile_name(home) + if not PROFILE_NAME.match(profile): + raise _Usage("--profile takes a profile name") + if profile != derive_profile_name(home): + print(f" note: this runs in profile {derive_profile_name(home)} ({home}); its files are the ones used") + return profile + + +def _ids(text: str, option: str) -> list[str]: + items = [item.strip() for item in str(text or "").split(",") if item.strip()] + if not all(NUMERIC_ID.match(item) for item in items): + raise _Usage(f"{option} takes numeric ids, comma-separated") + return items + + +def _secret(name: str) -> str: + """A variable of the profile (its secret scope, then the process environment); never printed.""" + try: + value = env_secret(name) + except Exception: + value = "" + return value or os.environ.get(name, "").strip() + + +def _user_config(home: str) -> dict[str, Any]: + """The home's config.yaml as written (``{}`` when missing or unreadable).""" + try: + from hermes_cli.config import read_user_config_raw + + data = read_user_config_raw(Path(home) / "config.yaml") + except Exception: + return {} + return data if isinstance(data, dict) else {} + + +def _profile_url(home: str) -> str: + config = _user_config(home) + return _config.profile_base_url(home, umbrella_section(config), config.get("mcp_servers")) + + +def _env_names(home: str) -> tuple[str, ...]: + """The variable names of the home's ``.env`` (values dropped at once; Hermes' tokenizer).""" + path = Path(home) / ".env" + if not path.is_file(): + return () + try: + from agent.secret_scope import load_env_file + + return tuple(load_env_file(path)) + except Exception: + return () + + +# -- status -------------------------------------------------------------------------------------- + + +def _yes(value: bool) -> str: + return "yes" if value else "no" + + +def _cmd_status(args: argparse.Namespace, home: str) -> int: + server = _server(args.server) if args.server else None + markers = access.read_markers(home) + print(f"ctx_checkpoint access groups — profile {derive_profile_name(home)} ({home})") + print(f" markers: restricted_seen {_yes(markers.restricted_seen)}, governed_seen {_yes(markers.governed_seen)}") + rows = [row for row in _status.read_access(home) if server is None or (row["platform"], row["scope_id"]) == server] + if not rows: + print(" no access-group binding recorded" + (" for that server" if server else "")) + for row in rows: + kind = _status.access_class(row) + mark = {"bound": "✓", "unset": "·", "off": "✗"}[kind] + print(f" {mark} {row['platform']}:{row['scope_id']} · profile {row['profile']} · {row['state']}") + for rule, expected in (row.get("rules") or {}).items(): + print(f" {rule}: expected {expected}") + detail = [ + f"tenant {row.get('tenant_slug') or '?'}", + f"read {','.join(row.get('read') or []) or '?'}", + f"write {row.get('write') or '?'}", + f"key digest {row.get('key_digest') or '?'}", + f"since {row.get('since') or '?'}", + ] + print(f" {' · '.join(detail)}") + print(f" status file: {row['file']}") + seen = _status.read_sessions_without_access(home) + on_profile = sorted((platform, kinds["profile"]) for platform, kinds in seen.items() if "profile" in kinds) + if on_profile and server is None: + names = ", ".join(f"{platform} (since {since})" for platform, since in on_profile) + print( + f" ! messaging sessions without an access group ran on the profile's connection: {names}. They read " + "and write with the profile's own key; for a profile that serves Discord set " + "memory.ctx_checkpoint.ungoverned: local" + ) + print(f" {_REVOKE}") + return 0 + + +# -- check --------------------------------------------------------------------------------------- + + +def _field_value(name: str, text: str) -> Any: + """A ``--field`` value as ``/policy field`` types it by the schema (lists comma-separated).""" + kind = access.SCHEMA[name]["type"] + if kind == "list": + return [item.strip() for item in text.split(",") if item.strip()] + if kind == "bool": + lowered = text.strip().lower() + if lowered not in ("true", "false", "yes", "no", "on", "off", "1", "0"): + raise _Usage(f"field {name} takes true or false") + return lowered in ("true", "yes", "on", "1") + if kind == "int": + try: + return int(text) + except ValueError: + raise _Usage(f"field {name} takes a whole number") from None + return text + + +def _fields(items: Sequence[str]) -> dict[str, Any]: + fields: dict[str, Any] = {} + for item in items: + name, eq, value = str(item).partition("=") + name = name.strip().removeprefix(f"{access.NAMESPACE}.") + if not eq or name not in access.SCHEMA: + raise _Usage(f"--field takes <name>=<value> with a field of {access.NAMESPACE}: {', '.join(access.SCHEMA)}") + fields[name] = _field_value(name, value) + return fields + + +def _cmd_check(args: argparse.Namespace, home: str) -> int: + platform, scope_id = _server(args.server) + profile = _profile(args, home) + strict = not args.unrestricted + raw = _fields(args.field) + print( + f"access check — {platform}:{scope_id} · group {args.group or '?'} · profile {profile} · " + f"{'restricted' if strict else 'not restricted'}" + ) + parsed = access.parse_fields(raw, scope_id=scope_id, strict=strict) + proof: dict[str, Any] = {} + if isinstance(parsed, access.FieldError): + print(f" ✗ E1 field {parsed.field}: expected {parsed.reason}") + broken = 1 + elif not parsed.enabled: + print(" · enabled is false: this group gets no ctx, nothing to prove") + broken = 0 + elif not parsed.key: + print(" · no key: this group gets no ctx of its own (memory.ctx_checkpoint.governed_unbound decides)") + broken = 0 + else: + broken, proof = _prove(home, platform, scope_id, profile, strict, parsed) + warnings = _warnings(home, platform, strict, proof) + for warning in warnings: + print(f" ⚠ {warning}") + print( + f"result: {broken} {'rule' if broken == 1 else 'rules'} broken, " + f"{len(warnings)} {'warning' if len(warnings) == 1 else 'warnings'}" + ) + return 1 if broken else 0 + + +def _prove( + home: str, platform: str, scope_id: str, profile: str, strict: bool, fields: access.GroupFields +) -> tuple[int, dict[str, Any]]: + """The proof of the binding as the provider makes it (design 02 §4.2 step 5): URL, key, E7 inputs, + the narrowed and the unnarrowed ``whoami`` judged by ``narrowing.evaluate``, and the write client's + own proof when the group writes. Prints a line per rule; the broken count and the raw answers.""" + if fields.base_url: + url = _secret(fields.base_url) + if not access.valid_base_url(url): + print(f" ✗ base_url: expected an https URL of a ctx server in {fields.base_url}") + return 1, {} + else: + url = _profile_url(home) + if not url: + print(" ✗ base_url: expected a ctx server URL of the profile (CTX_BASE_URL or rest_base_url)") + return 1, {} + print(f" ctx server: {_status.display_url(url)}") + key = _secret(fields.key) + if not key: + print(f" ✗ key: expected the ctx key in {fields.key} of the profile's .env") + return 1, {} + inputs = access.e7_inputs(home, platform) if strict else ((), ()) + settings = access.load_settings(home) + budget = REQUEST_TIMEOUT_S + narrowing.reset_proofs() + try: + plain = _client.CtxClient(url, key, timeout=budget) + unnarrowed = narrowing.whoami_raw(plain, narrowed=False, budget_s=budget) + read, write = fields.read, fields.write + if not (read and write): # an unrestricted group takes what it does not name from the key + home_scope = unnarrowed.get("home_scope") + write = write or (home_scope if isinstance(home_scope, str) else "") + known = unnarrowed.get("read_scopes") + read = read or tuple(str(s) for s in (known if isinstance(known, list) else ()) if s != write) + if not read or len(read) > access.READ_MAX: + print(f" ✗ read: expected 1 to {access.READ_MAX} scopes; the key reads {len(read)} besides {write}") + return 1, {"unnarrowed": unnarrowed} + reader = _client.CtxClient(url, key, timeout=budget, narrowing=narrowing.Narrowing(read=tuple(read))) + narrowed = narrowing.whoami_raw(reader, narrowed=True, budget_s=budget) + except (_client.CtxApiError, ValueError) as exc: + print(f" ✗ proof: ctx gave no identity of the key ({_status.redact_error(exc, (key,))})") + return 1, {} + expect = narrowing.Expect( + narrowing=narrowing.Narrowing(read=tuple(read)), + strict=strict, + tenant=fields.tenant or None, + label=narrowing.expected_label(platform, scope_id, profile) if strict else None, + env_names=tuple(inputs[0]) if inputs else (), + platform_toolsets=tuple(inputs[1]) if inputs else (), + scope_id=scope_id, + write=write or None, + ) + verdict = narrowing.evaluate(narrowed, unnarrowed, expect) + failed = dict(verdict.detail) + if strict and inputs is None: + failed["E7"] = f"a readable .env and a saved toolset list platform_toolsets.{platform} in the profile" + for rule in ("E2", "E3", "E4", "E5", "E7"): + if rule in failed: + print(f" ✗ {rule}: expected {failed[rule]}") + held = [rule for rule in ("E2", "E3", "E4", "E5", "E7") if rule not in failed and (strict or rule in ("E3", "E5"))] + if held: + print(f" ✓ {' '.join(held)} hold") + broken = len(failed) + capture = fields.capture if fields.capture is not None else not strict + if capture and (not strict or "capture" in settings["restricted_allow"]): + broken += _prove_writer(url, key, write, fields.tenant, scope_id) + return broken, {"unnarrowed": unnarrowed, "tenant": fields.tenant, "read": read, "write": write} + + +def _prove_writer(url: str, key: str, write: str, tenant: str, scope_id: str) -> int: + """The write client's own proof (E5, E3's home scope): a group that writes needs it.""" + try: + writer = _client.CtxClient( + url, key, timeout=REQUEST_TIMEOUT_S, narrowing=narrowing.Narrowing(read=(write,), write=write) + ) + raw = narrowing.whoami_raw(writer, narrowed=True, budget_s=REQUEST_TIMEOUT_S) + except (_client.CtxApiError, ValueError) as exc: + print(f" ✗ write client: ctx refused the write narrowing ({_status.redact_error(exc, (key,))})") + return 1 + verdict = narrowing.evaluate( + raw, + None, + narrowing.Expect( + narrowing=narrowing.Narrowing(read=(write,), write=write), + strict=False, + tenant=tenant or None, + label=None, + env_names=(), + platform_toolsets=(), + scope_id=scope_id, + write=write, + ), + ) + for rule in verdict.failed: + print(f" ✗ {rule} (write client): expected {verdict.detail.get(rule, '')}") + return len(verdict.failed) + + +def _ctx_mcp_entries(config: Mapping[str, Any]) -> list[str]: + """``mcp_servers`` entries that reach ctx: the one ``memory.ctx_checkpoint.mcp_server`` names + (``ctx``) and every entry that signs in with a ctx key (``X-Context-Key``, a ``CTX_*`` variable).""" + servers = config.get("mcp_servers") + if not isinstance(servers, Mapping): + return [] + named = str(umbrella_section(dict(config)).get("mcp_server") or "ctx") + found = [] + for name, entry in servers.items(): + if not isinstance(entry, Mapping) or entry.get("enabled") is False: + continue + headers = entry.get("headers") + signs = isinstance(headers, Mapping) and any( + str(header).strip().lower() == "x-context-key" or "${CTX_" in str(value) or "${env:CTX_" in str(value) + for header, value in headers.items() + ) + if name == named or signs: + found.append(str(name)) + return sorted(found) + + +def _warnings(home: str, platform: str, strict: bool, proof: Mapping[str, Any]) -> list[str]: + """The setups design 02 §4.7 warns of (none of them is a rule a binding fails on).""" + markers = access.read_markers(home) + restricted = strict or markers.restricted_seen + config = _user_config(home) + out: list[str] = [] + if restricted: + standard = [name for name in _STANDARD_KEYS if name in _env_names(home)] + if standard: + out.append( + f"the profile's .env holds the standard key {', '.join(standard)} while the profile serves restricted " + "groups: a session without its access group (a direct message, a route into this profile) or an " + "older ctx_checkpoint reaches ctx with it. A restricted profile carries no standard key" + ) + for name in _ctx_mcp_entries(config): + out.append( + f"mcp_servers.{name} reaches ctx past the plugin while the profile serves restricted groups: the " + "model calls its tools with that entry's key, which no access group narrows. Remove it here" + ) + unnarrowed = proof.get("unnarrowed") + tenant = proof.get("tenant") or (unnarrowed.get("tenant_slug") if isinstance(unnarrowed, Mapping) else "") + if isinstance(unnarrowed, Mapping) and tenant and unnarrowed.get("tenant_slug") == tenant: + known = unnarrowed.get("read_scopes") + granted = sorted( + str(s) for s in (known if isinstance(known, list) else ()) if not str(s).startswith(f"{tenant}:") + ) + if granted: + out.append( + f"the key reads scopes of another tenant ({', '.join(granted)}): a tenant grant reaches every key of " + f"tenant {tenant}, so every restricted binding of the tenant fails E3 at once. Give tenants with " + "restricted groups no incoming grant" + ) + if restricted: + seen = _status.read_sessions_without_access(home) + if seen: + names = ", ".join(sorted(seen)) + out.append( + f"this profile also served messaging sessions without an access group ({names}): a profile of " + "restricted ctx groups is no catch-all route or member profile of a server that is not governed. " + "Give those sessions another profile" + ) + if access.load_settings(home).get("ungoverned") == "profile" and markers.governed_seen: + out.append( + "memory.ctx_checkpoint.ungoverned: profile in a profile that serves governed servers: /background, cron " + "and sessions without their access group take the profile's own connection (private recall can reach a " + "public channel). Set it to local" + ) + return out + + +# -- provision ----------------------------------------------------------------------------------- + + +def _atomic_write(path: Path, data: str) -> None: + """Replace *path* with *data* atomically, mode 0600 (the test seam of an abort).""" + target = Path(os.path.realpath(path)) + fd, tmp = tempfile.mkstemp(prefix=".env-", dir=str(target.parent)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(data) + os.chmod(tmp, 0o600) + os.replace(tmp, target) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(tmp) + raise + + +def _env_with(text: str, name: str, value: str) -> str: + """*text* (a ``.env``) with ``name=value``: the first line that sets *name* replaced, later ones + dropped, every other line as it was; appended when none sets it.""" + setter = re.compile(rf"^\s*(?:export\s+)?{re.escape(name)}\s*=") + out: list[str] = [] + done = False + for line in text.splitlines(keepends=True): + if setter.match(line): + if not done: + out.append(f"{name}={value}\n") + done = True + continue + out.append(line) + if not done: + if out and not out[-1].endswith("\n"): + out[-1] += "\n" + out.append(f"{name}={value}\n") + return "".join(out) + + +def _manage_once(url: str, key: str, payload: Mapping[str, Any]) -> dict[str, Any]: + """One ``POST /api/manage`` with *key*, without the client's 429 retry (a refused set wrote nothing; + asking again changes nothing). Errors are ``CtxApiError`` with the key redacted.""" + client = _client.CtxClient(url, key, timeout=REQUEST_TIMEOUT_S) + if client._url_refused: + raise _client.CtxApiError(_client.BASE_URL_REFUSED) + request = urllib.request.Request( # noqa: S310 — http(s) only (CtxClient checked the URL) + f"{client.base_url}/api/manage", + data=json.dumps(payload).encode("utf-8"), + headers={"X-Context-Key": key, "Content-Type": "application/json", "Accept": "application/json"}, + method="POST", + ) + failure: _client.CtxApiError | None = None + try: + with _client._urlopen(request, timeout=REQUEST_TIMEOUT_S) as answer: + raw = answer.read().decode("utf-8", "replace") + except urllib.error.HTTPError as exc: + failure = client._http_failure(exc) + except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException) as exc: + failure = _client.CtxApiError(f"connection error: {client._redact(exc)}") + except ValueError: + failure = _client.CtxApiError("invalid request: key or URL rejected before any connection") + if failure is not None: + raise failure + try: + data = json.loads(raw) + except ValueError: + return {"success": False, "error": "invalid JSON response from CTX"} + return data if isinstance(data, dict) else {"success": False, "error": "unexpected response shape from CTX"} + + +def _full(scope: str, slug: str) -> str: + return scope if ":" in scope else f"{slug}:{scope}" + + +def _policy_value(values: Any) -> str: + return ",".join(values) if isinstance(values, (list, tuple)) else str(values) + + +def _yaml(value: Any) -> str: + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, list): + return "[" + ", ".join(json.dumps(str(item)) for item in value) + "]" + return json.dumps(str(value)) + + +def _cmd_provision(args: argparse.Namespace, home: str) -> int: + platform, scope_id = _server(args.server) + profile = _profile(args, home) + group = str(args.group) + if not GROUP_NAME.match(group): + raise _Usage(f"--group takes a group name as gateway.access_groups names it ({GROUP_NAME.pattern})") + roles, users = _ids(args.roles, "--roles"), _ids(args.users, "--users") + try: + layout = scope_layout(scope_id, [group], per_community=args.per_community) + variable = key_env_name(scope_id, profile) + except ValueError as exc: + raise _Usage(str(exc)) from None + knowledge, own = layout[KNOWLEDGE], layout[group] + extra = [str(scope) for scope in args.read] + for scope in extra: + if not (SCOPE_NAME.match(scope) or access.SCOPE_PATTERN.match(scope)) or scope in (knowledge, own): + raise _Usage(f"--read takes other ctx scopes, <name> or <tenant>:<name> ({scope!r})") + if len(extra) + 1 > access.READ_MAX: + raise _Usage(f"a group reads at most {access.READ_MAX} scopes") + if not ENV_NAME.match(str(args.admin_key_env)): + raise _Usage("--admin-key-env takes a variable name") + if args.base_url_env is not None and not _BASE_URL_ENV.match(str(args.base_url_env)): + raise _Usage("--base-url-env takes CTX_BASE_URL or CTX_BASE_URL_<...>") + label = narrowing.expected_label(platform, scope_id, profile) + print(f"access provision — {platform}:{scope_id} · group {group} · profile {profile}") + env_path = Path(home) / ".env" + try: # the .env is read before ctx is asked: a key nobody can store is not created + before = env_path.read_text(encoding="utf-8") if env_path.exists() else "" + except (OSError, UnicodeDecodeError) as exc: + print(f" ✗ {env_path} cannot be read ({type(exc).__name__}); nothing was sent") + return 1 + if args.base_url_env: + url = _secret(args.base_url_env) + if not access.valid_base_url(url): + print(f" ✗ {args.base_url_env} holds no https URL of a ctx server; nothing was sent") + return 1 + else: + url = _profile_url(home) + admin_key = _secret(args.admin_key_env) + if not url or not admin_key: + missing = "the ctx server URL (CTX_BASE_URL or rest_base_url)" if not url else args.admin_key_env + print(f" ✗ {missing} is not set; nothing was sent") + return 1 + request = { + "action": "keyset-provision", + "data": { + "scopes": [knowledge, own], + "keys": [ + { + "label": label, + "home_scope": own, + "allowed_scopes": [knowledge, *extra], + "write_scopes": [], + "scope_narrowing": "required", + "replace_label": True, + } + ], + }, + } + try: + answer = _manage_once(url, admin_key, request) + except _client.CtxApiError as exc: + print(f" ✗ ctx refused the key set, nothing was created: {_status.redact_error(exc, (admin_key,))}") + return 1 + made = _made_key(answer, label, own) + if isinstance(made, str): + print( + f" ✗ {made}. A key may have been created at ctx; run the same command again: it replaces it " + "(replace_label), so one key stays active" + ) + return 1 + secret, slug, scopes = made + try: + _atomic_write(env_path, _env_with(before, variable, secret)) + except OSError as exc: + print( + f" ✗ the key was created at ctx but {env_path} could not be written ({type(exc).__name__}); run the same " + "command again: it replaces the key (replace_label), so one key stays active" + ) + return 1 + for entry in scopes: + print(f" ctx scope {entry.get('scope')} ({'created' if entry.get('created') else 'there already'})") + print( + f" key: {variable} in {env_path} (label {label}, key digest {narrowing.key_digest(secret)}); " + "an earlier key of this label is inactive now" + ) + rc = _ungoverned_local(home) + fields: dict[str, Any] = {"key": variable, "tenant": slug, "read": [_full(knowledge, slug)]} + fields["read"] += [_full(scope, slug) for scope in extra] + fields["write"] = _full(own, slug) + if args.base_url_env: + fields["base_url"] = args.base_url_env + print(f" {_REVOKE}") + _print_fields(platform, scope_id, profile, group, fields, roles, users, emit_yaml=args.emit_yaml) + return rc + + +def _made_key(answer: Mapping[str, Any], label: str, own: str) -> tuple[str, str, list[Mapping[str, Any]]] | str: + """The new key's plaintext, the tenant slug and the scopes of a ``keyset-provision`` answer, or + what is wrong with it.""" + keys, scopes = answer.get("keys"), answer.get("scopes") + if answer.get("success") is not True or not isinstance(keys, list) or len(keys) != 1: + return "ctx answered no key set" + entry = keys[0] if isinstance(keys[0], Mapping) else {} + home_scope = str(entry.get("home_scope") or "") + slug, _colon, name = home_scope.partition(":") + secret = entry.get("api_key") + if entry.get("label") != label or name != own or not access.SLUG_PATTERN.match(slug): + return "ctx answered a key of another label or scope" + if not isinstance(secret, str) or not KEY_VALUE.match(secret): + return "ctx answered a key the .env cannot hold" + return secret, slug, [s for s in (scopes if isinstance(scopes, list) else []) if isinstance(s, Mapping)] + + +def _ungoverned_local(home: str) -> int: + """``memory.ctx_checkpoint.ungoverned: local`` in the profile (``off`` stays): a profile that serves + a restricted group gives sessions without their group no connection but a local one (design 02 + §4.7, BP-14). Written into *home*'s config.yaml through Hermes' own config writer (comments and + every other key stay), then read back.""" + current = access.load_settings(home).get("ungoverned") + if current in ("local", "off"): + print(f" memory.ctx_checkpoint.ungoverned: {current} (kept)") + return 0 + try: + from hermes_cli.config import save_config + from hermes_constants import reset_hermes_home_override, set_hermes_home_override + + token = set_hermes_home_override(home) # Hermes' writer, pointed at this home for this call + try: + save_config({"memory": {access.NAMESPACE: {"ungoverned": "local"}}}, merge_existing=True) + finally: + reset_hermes_home_override(token) + except Exception as exc: + print( + f" ✗ memory.ctx_checkpoint.ungoverned: local was not written ({type(exc).__name__}); set it in config.yaml" + ) + return 1 + if access.load_settings(home).get("ungoverned") != "local": + print(" ✗ memory.ctx_checkpoint.ungoverned: local did not take; set it in config.yaml") + return 1 + print(f" memory.ctx_checkpoint.ungoverned: local (was {current})") + return 0 + + +def _print_fields( + platform: str, + scope_id: str, + profile: str, + group: str, + fields: Mapping[str, Any], + roles: list[str], + users: list[str], + *, + emit_yaml: bool, +) -> None: + pairs = " ".join(f"{access.NAMESPACE}.{name}={_policy_value(value)}" for name, value in fields.items()) + members = (f" roles={','.join(roles)}" if roles else "") + (f" users={','.join(users)}" if users else "") + print(" the group's fields in one write (an existing group):") + print(f" /policy field {group} server={scope_id} {pairs}") + print(" a new group with its fields in one write:") + print( + f" /policy group {group} server={scope_id} profile={profile} restricted=true" + f"{members or ' roles=<role ids>'} {pairs}" + ) + if not emit_yaml: + return + print("--- yaml") + print( + f'# one item of gateway.access_groups.{platform}."{scope_id}".groups (config.yaml): ' + "group and fields in one write" + ) + print(f"- name: {_yaml(group)}") + print(f" profile: {_yaml(profile)}") + print(" restricted: true") + if roles: + print(f" roles: {_yaml(roles)}") + if users: + print(f" users: {_yaml(users)}") + if not (roles or users): + print(' # roles: ["<role id>"] the group needs roles, users or users_from before it is saved') + print(" fields:") + print(f" {access.NAMESPACE}:") + for name, value in fields.items(): + print(f" {name}: {_yaml(value)}") + + +# -- reset-marker -------------------------------------------------------------------------------- + + +def _cmd_reset(args: argparse.Namespace, home: str) -> int: + if not (args.restricted or args.governed): + raise _Usage("name the marker to lower: --restricted, --governed or both") + _profile(args, home) + try: + access.reset_markers(home, restricted=args.restricted, governed=args.governed) + except OSError as exc: + print(f"✗ the markers of {home} were not written ({type(exc).__name__})") + return 1 + markers = access.read_markers(home) + print( + f"markers of {home}: restricted_seen {_yes(markers.restricted_seen)}, " + f"governed_seen {_yes(markers.governed_seen)}" + ) + return 0 -__all__ = ["ENV_NAME", "KNOWLEDGE", "SCOPE_NAME", "key_env_name", "run_access", "scope_layout"] +__all__ = [ + "ENV_NAME", + "KNOWLEDGE", + "SCOPE_NAME", + "add_arguments", + "key_env_name", + "run_access", + "run_parsed", + "scope_layout", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/cli.py index 76c02a176..74ba1bddc 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/cli.py @@ -1,4 +1,4 @@ -"""CLI commands of the ctx_checkpoint plugin: ``hermes ctx_checkpoint <status|sync|query|store|search|get>``. +"""CLI commands of the ctx_checkpoint plugin: ``hermes ctx_checkpoint <status|sync|query|store|search|get|access>``. Discovered by the host at argparse setup time (``register_cli``), before the provider is loaded. The host registers the plugin's parent package first, so the relative imports @@ -10,6 +10,9 @@ carry the provenance tags (``hook:cli``) and the configured sensitivity, and reads honour ``prefetch_types_exclude``. Error texts are printed redacted with the keys the provider binds (``CTX_KEY`` on REST and ``status.profile_ctx_keys``) and the checkpoint rules (#308). + +``access`` holds the operator tools of access groups (``memory/access_cli.py``): ``status``, ``check``, +``provision``, ``reset-marker``. """ from __future__ import annotations @@ -20,6 +23,7 @@ from pathlib import Path from typing import Any +from . import access_cli from .client import CtxApiError, CtxClient, store_action, store_block_id from .config import ( CATEGORY_MEMORY, @@ -47,7 +51,7 @@ _ENTRY_SEPARATOR = "§" _HOOK = "cli" PROVIDER_NAME = "ctx_checkpoint" -_SUBCOMMANDS = "status|sync|query|store|search|get" +_SUBCOMMANDS = "status|sync|query|store|search|get|access" _MCP_HINT = ( "✗ this command needs the REST transport (memory.ctx_checkpoint.transport: rest with CTX_KEY in .env). " "Over the default MCP transport the store is reached inside a session through the ctx MCP tools, " @@ -317,7 +321,13 @@ def cmd_get(args, home: Path, config: dict[str, Any]) -> int: return 0 +def cmd_access(args, home: Path, config: dict[str, Any]) -> int: + """``access …``: the operator tools of access groups, on this profile's home.""" + return access_cli.run_parsed(args, hermes_home=str(home)) + + _COMMANDS = { + "access": cmd_access, "status": cmd_status, "sync": cmd_sync, "query": cmd_query, @@ -386,3 +396,7 @@ def register_cli(subparser) -> None: p_get = subs.add_parser("get", help="Fetch a full block by id") p_get.add_argument("block_id", help="CTX block id (UUID)") p_get.set_defaults(func=ctx_command) + + p_access = subs.add_parser("access", help="Access groups: status, check, provision, reset-marker") + access_cli.add_arguments(p_access) + p_access.set_defaults(func=ctx_command) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 246578c13..355d13ba4 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -590,7 +590,26 @@ def save_config(self, values: dict[str, Any], hermes_home: str) -> None: def get_status_config(self, provider_config: dict) -> dict: """Feeds ``hermes memory status``. Must not raise. Error texts are redacted with the keys - the provider binds (the REST key and :meth:`_profile_secrets`, #308).""" + the provider binds (the REST key and :meth:`_profile_secrets`, #308). The profile's + access-group bindings join the report (:meth:`_with_access_status`).""" + status, configured = self._own_status_config(provider_config) + return self._with_access_status(status, configured) + + def _with_access_status(self, status: dict[str, Any], configured: bool) -> dict[str, Any]: + """*status* with the access-group bindings of the profile (``status.access_status``): not ok + while one is off. A profile that is meant to run without a connection of its own + (``ungoverned`` ``off`` or ``local``, none *configured*) is ok with every group bound.""" + try: + from hermes_constants import get_hermes_home + + home = self._hermes_home or str(get_hermes_home()) + own_optional = not configured and _access.load_settings(home).get("ungoverned") in ("off", "local") + return _status.access_status(status, home, own_expected=not own_optional) + except Exception: + return status + + def _own_status_config(self, provider_config: dict) -> tuple[dict[str, Any], bool]: + """The report of the profile's own connection, and whether one is configured.""" status: dict[str, Any] = {"summary": "✗ CTX not configured (set CTX_BASE_URL and CTX_KEY)", "ok": False} api_key = "" try: @@ -605,9 +624,9 @@ def get_status_config(self, provider_config: dict) -> dict: except Exception as exc: text = redact_error_text(exc, (api_key, *self._profile_secrets())) status["summary"] = f"✗ CTX config unreadable: {shorten(text, 140)}" - return status + return status, True if not (api_key and base): - return status + return status, False secrets = (api_key, *self._profile_secrets()) try: client = CtxClient(base, api_key, timeout=8.0) @@ -628,7 +647,7 @@ def get_status_config(self, provider_config: dict) -> dict: status["summary"] = f"✗ whoami failed: {shorten(cause, 140)} · {shown}" except Exception as exc: status["summary"] = f"✗ {shorten(redact_error_text(exc, secrets), 140)} · {shown}" - return status + return status, True # -- Lifecycle ------------------------------------------------------------ @@ -744,6 +763,8 @@ def _decide_access(self, kwargs: Mapping[str, Any]) -> None: decision = _access.Decision("off", f"the access decision failed ({type(exc).__name__})", strict=True) self._access_settings = settings self._decision = decision + if decision.context is None: # display only (``access status``, ``access check``) + _status.record_session_without_access(home, self._platform, self._agent_context, decision.kind) context = self._access_context() self._bound_turn = _turn_key(context) if context is not None else None self._access_off = "" diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py index 72569d56b..4e056f4f3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py @@ -504,8 +504,9 @@ def checkpoint_outcome( @contextmanager -def _state_lock(directory: Path) -> Iterator[None]: - """Exclusive lock of the outcome file's writers (see :data:`STATE_LOCK_FILE`); never raises.""" +def _state_lock(directory: Path, lock_file: str = STATE_LOCK_FILE) -> Iterator[None]: + """Exclusive lock of the outcome file's writers (see :data:`STATE_LOCK_FILE`; ``lock_file``: the + lock of another set of files in *directory*, the access-group status files); never raises.""" if fcntl is None: held = _PROCESS_STATE_LOCK.acquire(timeout=STATE_LOCK_WAIT_S) try: @@ -517,7 +518,7 @@ def _state_lock(directory: Path) -> Iterator[None]: fd = -1 try: directory.mkdir(parents=True, exist_ok=True) - fd = os.open(str(directory / STATE_LOCK_FILE), os.O_RDWR | os.O_CREAT, 0o600) + fd = os.open(str(directory / lock_file), os.O_RDWR | os.O_CREAT, 0o600) deadline = time.monotonic() + STATE_LOCK_WAIT_S while True: try: @@ -751,20 +752,273 @@ def mcp_report(hermes_home: str) -> dict[str, Any]: ) -# -- access groups (contract, S1) --------------------------------------------------------------- +# -- access groups ------------------------------------------------------------------------------ # One small file per binding under <home>/ctx_state/access/<platform>-<scope_id>-<profile>.json, -# written atomically and only when the state changes: ``bound`` or ``off: <reason>``, the rules -# checked (E1-E7), the key digest (16 hex), tenant slug, read, write, time, base blocks loaded and -# skipped with reason. Display only (``hermes memory status``, ``access status``): never read to -# bind, never a key value. The binding cluster (P-C) writes through ``record_access``; the tools -# cluster (P-E) owns the rest. +# written atomically (mode 0600) and only when what it shows changes: ``bound`` or ``off: <reason>``, +# the rules a proof broke with the value each expected, the key's digest (16 hex), tenant slug, read, +# write, the time of the last change. Display only (``hermes memory status``, ``hermes ctx_checkpoint +# access status``): never read to bind, never a key value (only the fields below are kept, texts pass +# the error redaction). The folder is below ``ctx_state``, so the state pruning (``digest. +# prune_state_dir``, top-level ``*.json`` only) never removes a binding's file. The binding (P-C) +# writes through ``record_access``. + +ACCESS_DIR = "access" +# Messaging sessions that served no access group, per platform and the connection they got (formerly +# DP-23): ``{platform: {"profile" | "off": <first seen>}}``. Not a ``*.json`` name, for the pruning. +ACCESS_SESSIONS_FILE = "access-sessions.state" +ACCESS_LOCK_FILE = "access.lock" +# A status file is a few hundred bytes; a far larger one is not ours and is skipped. +ACCESS_FILE_MAX_BYTES = 64 * 1024 +# Bounds of what a record keeps: scopes per list (a group reads at most 8), rules, platforms recorded. +ACCESS_LIST_MAX = 16 +ACCESS_SESSION_PLATFORMS_MAX = 64 +# ``hermes memory status`` names this many bindings that are off one by one, then counts the rest. +ACCESS_STATUS_LINES = 5 +_SAFE_NAME_PART = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.]{0,63}$") +_KEY_DIGEST_RE = re.compile(r"^[0-9a-f]{16}$") +_SCOPE_TEXT_RE = re.compile(r"^[A-Za-z0-9_:.-]{1,64}$") +_RULE_NAME_RE = re.compile(r"^[A-Za-z0-9_ -]{1,32}$") +# The reasons of the decision table (``access.decide``) for a group that gets no ctx by its own fields +# (no fields, ``enabled: false``, no key with ``governed_unbound: off``): a choice, not a fault. +_UNSET_STATE_RE = re.compile( + r"^off: row \d+: (?:restricted group without fields|enabled is false" + r"|group without (?:fields|a key); governed_unbound off)$" +) +# Sessions that are no messaging with other people: local and interactive, cron, the API server, +# webhooks, forks (their parent session was recorded). +_NOT_MESSAGING = frozenset({"cli", "tui", "desktop", "local", "codex", "acp", "gui", "cron", "api_server", "webhook"}) + + +def _now_text() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _name_part(text: str) -> str: + """A part of a status file name: as it is when it is plain letters, digits, ``_`` and ``.`` + (never ``.``/``..``), else ``h`` and 16 hex of its SHA-256 (no path can come of it).""" + import hashlib + + if _SAFE_NAME_PART.match(text) and text.strip(".") == text: + return text + return "h" + hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()[:16] + + +def access_file(hermes_home: str, platform: str, scope_id: str, profile: str) -> Path: + """The status file of one binding (see above).""" + name = "-".join(_name_part(str(part)) for part in (platform, scope_id, profile)) + return Path(hermes_home) / FACT_STATE_DIR / ACCESS_DIR / f"{name}.json" + + +def _display_text(value: Any) -> str: + return redact_error(value) if isinstance(value, str) else "" + + +def _scope_list(value: Any) -> list[str]: + if not isinstance(value, (list, tuple)): + return [] + return [str(item) for item in value[:ACCESS_LIST_MAX] if isinstance(item, str) and _SCOPE_TEXT_RE.match(item)] + + +def _access_fields(result: Mapping[str, Any]) -> dict[str, Any]: + """What a binding's record keeps of *result*: the display fields, each in its form, nothing else.""" + out: dict[str, Any] = {} + if "state" in result: + out["state"] = _display_text(result.get("state")) + if "rules" in result: + rules = result.get("rules") + out["rules"] = { + str(rule): _display_text(text) + for rule, text in list(rules.items() if isinstance(rules, Mapping) else ())[:ACCESS_LIST_MAX] + if isinstance(rule, str) and _RULE_NAME_RE.match(rule) + } + if "key_digest" in result: + digest = result.get("key_digest") + out["key_digest"] = digest if isinstance(digest, str) and _KEY_DIGEST_RE.match(digest) else "" + if "tenant_slug" in result: + tenant = result.get("tenant_slug") + out["tenant_slug"] = tenant if isinstance(tenant, str) and _SCOPE_TEXT_RE.match(tenant) else "" + if "read" in result: + out["read"] = _scope_list(result.get("read")) + if "write" in result: + write = result.get("write") + out["write"] = write if isinstance(write, str) and _SCOPE_TEXT_RE.match(write) else "" + return out + + +def _read_json_file(path: Path) -> dict[str, Any] | None: + """A small JSON object file; ``None`` when missing, too large, unreadable or not an object.""" + try: + with path.open("rb") as handle: + raw = handle.read(ACCESS_FILE_MAX_BYTES + 1) + except OSError: + return None + if len(raw) > ACCESS_FILE_MAX_BYTES: + return None + try: + data = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + return None + return data if isinstance(data, dict) else None + + +def _write_json_file(path: Path, data: Mapping[str, Any]) -> None: + """Replace *path* atomically with *data* (mode 0600); raises on failure, leaving no temp file.""" + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".access-", dir=str(path.parent)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(data, handle, ensure_ascii=False, sort_keys=True) + os.chmod(tmp, 0o600) + os.replace(tmp, path) + except Exception: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def _update_access( + hermes_home: str, platform: str, scope_id: str, profile: str, change: Callable[[dict[str, Any]], dict[str, Any]] +) -> None: + """Read a binding's record, apply *change*, write it back only when it changed (stamped ``since``), + under the lock of the access folder.""" + path = access_file(hermes_home, platform, scope_id, profile) + with _state_lock(path.parent, ACCESS_LOCK_FILE): + current = _read_json_file(path) or {} + record = change({key: value for key, value in current.items() if key != "since"}) + record.update(platform=str(platform), scope_id=str(scope_id), profile=str(profile)) + if record == {key: value for key, value in current.items() if key != "since"}: + return + record["since"] = _now_text() + _write_json_file(path, record) def record_access(hermes_home: str, platform: str, scope_id: str, profile: str, result: Mapping[str, Any]) -> None: - """Record the state of one binding (see above). S1 stub: no-op.""" - return None + """Record the state of one binding (see above): of *result* only ``state`` (``"bound"`` or + ``"off: <reason>"``), ``rules`` (rule → the expected value), ``key_digest`` (16 hex), + ``tenant_slug``, ``read`` and ``write`` are kept; the file is written only when they change. Never + raises: a status must not cost a binding.""" + if not hermes_home or not isinstance(result, Mapping): + return + fields = _access_fields(result) + try: + _update_access(hermes_home, platform, scope_id, profile, lambda record: {**record, **fields}) + except Exception: + logger.debug("ctx_checkpoint: access-group status not recorded", exc_info=True) def read_access(hermes_home: str) -> list[Mapping[str, Any]]: - """Every recorded binding of the home, sorted by platform, server and profile. S1 stub: none.""" - return [] + """Every recorded binding of the home, sorted by platform, server and profile, each with ``file`` + (its path below the home). A file that is unreadable, too large or not a record is skipped.""" + folder = Path(hermes_home) / FACT_STATE_DIR / ACCESS_DIR + try: + paths = [path for path in folder.iterdir() if path.suffix == ".json" and path.is_file()] + except OSError: + return [] + rows: list[dict[str, Any]] = [] + for path in paths: + record = _read_json_file(path) + if record is None or not all(isinstance(record.get(key), str) for key in ("platform", "scope_id", "profile")): + continue + if not isinstance(record.get("state"), str): + continue + record["file"] = f"{FACT_STATE_DIR}/{ACCESS_DIR}/{path.name}" + rows.append(record) + rows.sort(key=lambda row: (row["platform"], row["scope_id"], row["profile"])) + return rows + + +def access_class(row: Mapping[str, Any]) -> str: + """``bound``; ``unset`` (off because the group has no ctx by its own fields: a choice); or ``off`` + (every other reason: a broken rule, a refused or pending proof, a broken field, the trip wire).""" + state = str(row.get("state") or "") + if state == "bound": + return "bound" + return "unset" if _UNSET_STATE_RE.match(state) else "off" + + +def access_line(row: Mapping[str, Any]) -> str: + """One binding as a status line names it: server, profile and state.""" + return f"{row.get('platform')}:{row.get('scope_id')} (profile {row.get('profile')}): {row.get('state')}" + + +def access_status(status: dict[str, Any], hermes_home: str, *, own_expected: bool = True) -> dict[str, Any]: + """``hermes memory status`` with the profile's access-group bindings. Without a recorded binding + *status* comes back as it is. With one: ``access_groups`` counts them; every binding that is off + (not by its own fields) is named (``access_off``, ``access_off_2`` …) and makes the report not ok, + its summary led by the count — a profile is not "connected" while one of its groups is cut off. + *own_expected*: the profile needs a connection of its own (False: ``ungoverned`` is ``off`` or + ``local`` and no standard key is configured, so with every group bound the report is ok). Never + raises.""" + try: + rows = read_access(hermes_home) + except Exception: + return status + if not rows: + return status + classes = [access_class(row) for row in rows] + bound, unset = classes.count("bound"), classes.count("unset") + off = [row for row, kind in zip(rows, classes, strict=True) if kind == "off"] + out = dict(status) + counts = f"{bound} bound, {len(off)} off" + (f", {unset} without ctx by their fields" if unset else "") + out["access_groups"] = f"{counts} — `hermes ctx_checkpoint access status` shows each" + for index, row in enumerate(off[:ACCESS_STATUS_LINES]): + out["access_off" if index == 0 else f"access_off_{index + 1}"] = access_line(row) + if len(off) > ACCESS_STATUS_LINES: + out["access_off_more"] = f"{len(off) - ACCESS_STATUS_LINES} more off" + previous = str(status.get("summary") or "") + if off: + out["ok"] = False + out["summary"] = ( + f"✗ {len(off)} of {len(rows)} access-group bindings off · the profile's own connection: {previous}" + ) + elif bound and not own_expected: + out["ok"] = True + out["summary"] = ( + f"✓ access groups: {bound} bound · no connection of the profile's own (ungoverned: off or local)" + ) + return out + + +def record_session_without_access(hermes_home: str, platform: str, agent_context: str, connection: str) -> None: + """A messaging session that served no access group (a server not governed, a direct message, + ``/background``): *connection* is what it got, ``profile`` (the profile's own) or ``off``. Kept once + per platform and connection with the time first seen (``access status`` names it; ``access check`` + warns of it in a profile that serves restricted groups). Local sessions, cron, the API server, + webhooks and forks are not recorded. Never raises.""" + name = str(platform or "").strip().lower() + if ( + not hermes_home + or connection not in ("profile", "off") + or str(agent_context or "primary") != "primary" + or not name + or name in _NOT_MESSAGING + or name == "subagent" + or not _SAFE_NAME_PART.match(name) + ): + return + path = Path(hermes_home) / FACT_STATE_DIR / ACCESS_SESSIONS_FILE + try: + if connection in (read_sessions_without_access(hermes_home).get(name) or {}): + return # already known: no lock, no write + with _state_lock(path.parent, ACCESS_LOCK_FILE): + seen = read_sessions_without_access(hermes_home) + if connection in (seen.get(name) or {}): + return + if name not in seen and len(seen) >= ACCESS_SESSION_PLATFORMS_MAX: + return + seen.setdefault(name, {})[connection] = _now_text() + _write_json_file(path, seen) + except Exception: + logger.debug("ctx_checkpoint: session without an access group not recorded", exc_info=True) + + +def read_sessions_without_access(hermes_home: str) -> dict[str, dict[str, str]]: + """``{platform: {connection: first seen}}`` of :func:`record_session_without_access`.""" + data = _read_json_file(Path(hermes_home) / FACT_STATE_DIR / ACCESS_SESSIONS_FILE) or {} + return { + str(platform): {str(kind): str(since) for kind, since in kinds.items() if kind in ("profile", "off")} + for platform, kinds in data.items() + if isinstance(kinds, dict) + } diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_cli.py index 89f6e72c5..ac4cbdbc4 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_cli.py @@ -181,7 +181,7 @@ def test_status_shows_profile_and_settings(run, capsys): def test_unconfigured_and_usage_exit_codes(run, monkeypatch, capsys): assert run() == 2 - assert "Usage: hermes ctx_checkpoint <status|sync|query|store|search|get>" in capsys.readouterr().out + assert "Usage: hermes ctx_checkpoint <status|sync|query|store|search|get|access>" in capsys.readouterr().out monkeypatch.delenv("CTX_KEY") assert run("search", "x") == 1 assert "CTX not configured" in capsys.readouterr().out diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py index ca9a050c2..40343593f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -4,7 +4,6 @@ S1_PENDING = frozenset( { - "P-E", "P-F", } ) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py new file mode 100644 index 000000000..e1fa2d404 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -0,0 +1,559 @@ +"""P-E beyond the S1 tests (design 02 §3.6, §4.7, §7.3 row P-E): the per-binding status files and what +``hermes memory status`` makes of them, ``access status``/``check``/``provision``/``reset-marker`` +against the fake ctx server and the fake host surface, and the record of messaging sessions without an +access group (formerly DP-23).""" + +from __future__ import annotations + +import json +import os +import re +import stat + +import hermes_yaml +import pytest +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-E") + +_PKG = ah.load_plugin("ctx_checkpoint_access_pe_rules") +st = ah.plugin_module(_PKG, "memory.status") +cli = ah.plugin_module(_PKG, "memory.access_cli") +acc = ah.plugin_module(_PKG, "memory.access") +nar = ah.plugin_module(_PKG, "memory.narrowing") +Provider = _PKG.CtxCheckpointMemoryProvider + +ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_do_not_store" +PROFILE_KEY = "ctx_profile_key_of_the_operator" +MEMBER_KEY = "ctx_member_key_of_server_111" +A_K, A_MEMBERS = "t:d111-k", "t:d111-members" +LABEL = "hermes:discord:111:members" +BOUND = { + "state": "bound", + "rules": {}, + "key_digest": "0123456789abcdef", + "tenant_slug": "t", + "read": [A_K], + "write": A_MEMBERS, +} +OFF = {**BOUND, "state": "off: E4", "rules": {"E4": f"label {LABEL}"}} + + +def _text(root): + return "\n".join(p.read_text(encoding="utf-8", errors="replace") for p in root.rglob("*") if p.is_file()) + + +def _home(tmp_path, name="members", *, config="platform_toolsets:\n discord: [web]\n"): + home = tmp_path / "profiles" / name + home.mkdir(parents=True) + (home / "config.yaml").write_text(config, encoding="utf-8") + return home + + +def _run(home, *argv): + return cli.run_access(list(argv), hermes_home=str(home)) + + +# -- status files --------------------------------------------------------------------------------- + + +def test_a_binding_s_file_is_rewritten_only_when_its_state_changes(tmp_path): + st.record_access(str(tmp_path), "discord", "111", "members", OFF) + path = tmp_path / "ctx_state" / "access" / "discord-111-members.json" + first = path.stat() + assert stat.S_IMODE(first.st_mode) == 0o600 + st.record_access(str(tmp_path), "discord", "111", "members", dict(OFF)) + assert path.stat().st_ino == first.st_ino and path.stat().st_mtime_ns == first.st_mtime_ns + st.record_access(str(tmp_path), "discord", "111", "members", BOUND) + assert path.stat().st_ino != first.st_ino + (row,) = st.read_access(str(tmp_path)) + assert row["state"] == "bound" and row["rules"] == {} + + +def test_the_status_file_keeps_only_display_fields(tmp_path): + st.record_access( + str(tmp_path), + "discord", + "111", + "members", + {**OFF, "key_digest": "ctx_not_a_digest_but_a_key", "api_key": "ctx_api_key_value", "token": PROFILE_KEY}, + ) + (row,) = st.read_access(str(tmp_path)) + text = _text(tmp_path) + assert "ctx_api_key_value" not in text and PROFILE_KEY not in text and "ctx_not_a_digest" not in text + assert row["key_digest"] == "" and row["platform"] == "discord" and row["scope_id"] == "111" + + +@pytest.mark.parametrize("scope_id", ["../../escape", "a/b", "..", ""]) +def test_a_status_file_never_leaves_the_access_directory(tmp_path, scope_id): + st.record_access(str(tmp_path / "home"), "discord", scope_id, "members", OFF) + files = [p for p in tmp_path.rglob("*") if p.is_file() and p.suffix == ".json"] + assert len(files) == 1 and files[0].parent == tmp_path / "home" / "ctx_state" / "access" + (row,) = st.read_access(str(tmp_path / "home")) + assert row["scope_id"] == scope_id + + +def test_unreadable_and_foreign_status_files_are_skipped(tmp_path): + st.record_access(str(tmp_path), "discord", "111", "members", BOUND) + folder = tmp_path / "ctx_state" / "access" + (folder / "broken.json").write_text("{not json", encoding="utf-8") + (folder / "list.json").write_text("[1, 2]", encoding="utf-8") + (folder / "huge.json").write_text(json.dumps({"state": "x" * 100_000}), encoding="utf-8") + assert [row["scope_id"] for row in st.read_access(str(tmp_path))] == ["111"] + + +def test_bindings_are_listed_by_platform_server_and_profile(tmp_path): + for platform, scope_id, profile in (("slack", "9", "a"), ("discord", "222", "b"), ("discord", "111", "c")): + st.record_access(str(tmp_path), platform, scope_id, profile, BOUND) + rows = st.read_access(str(tmp_path)) + assert [(r["platform"], r["scope_id"], r["profile"]) for r in rows] == [ + ("discord", "111", "c"), + ("discord", "222", "b"), + ("slack", "9", "a"), + ] + + +# -- hermes memory status ----------------------------------------------------------------------------- + + +@pytest.fixture +def operator(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:main", label="operator", role="admin") + ah.install(monkeypatch, v8=True, secrets={"CTX_KEY": PROFILE_KEY, "CTX_BASE_URL": fake_ctx.url}) + home = _home(tmp_path, "operator") + monkeypatch.setenv("HERMES_HOME", str(home)) + return fake_ctx, home + + +@pytest.mark.s1_green +def test_memory_status_without_access_groups_is_as_before(operator): + _fake, _home = operator + status = Provider(config={"transport": "rest"}).get_status_config({}) + assert status["ok"] is True and status["summary"].startswith("✓ Connected") + assert not [key for key in status if key.startswith("access")] + + +def test_memory_status_is_not_connected_while_a_group_binding_is_off(operator): + _fake, home = operator + st.record_access(str(home), "discord", "111", "members", OFF) + st.record_access(str(home), "discord", "222", "members", BOUND) + status = Provider(config={"transport": "rest"}).get_status_config({}) + assert status["ok"] is False + assert not status["summary"].startswith("✓") and "1 of 2" in status["summary"] + assert "discord:111" in status["access_off"] and "E4" in status["access_off"] + assert "1 bound" in status["access_groups"] + + +def test_memory_status_on_mcp_is_not_connected_while_a_group_binding_is_off(operator, monkeypatch): + _fake, home = operator + (home / "config.yaml").write_text( + "memory:\n ctx_checkpoint:\n transport: mcp\nmcp_servers:\n ctx:\n url: http://127.0.0.1:1/mcp\n", + encoding="utf-8", + ) + monkeypatch.setattr(st, "probe_server", lambda name, entry, timeout: ["search", "get", "store"]) + provider = Provider(config={"transport": "mcp"}) + assert provider.get_status_config({})["ok"] is True + st.record_access(str(home), "discord", "111", "members", OFF) + status = provider.get_status_config({}) + assert status["ok"] is False and not status["summary"].startswith("✓") + assert "discord:111" in status["access_off"] + + +def test_memory_status_does_not_count_a_group_without_ctx_by_its_fields_as_a_fault(operator): + _fake, home = operator + for row, reason in enumerate( + ("enabled is false", "group without fields; governed_unbound off", "restricted group without fields"), start=2 + ): + st.record_access(str(home), "discord", str(row), "members", {**BOUND, "state": f"off: row {row}: {reason}"}) + st.record_access(str(home), "discord", "111", "members", BOUND) + status = Provider(config={"transport": "rest"}).get_status_config({}) + assert status["ok"] is True and status["summary"].startswith("✓") + assert "1 bound" in status["access_groups"] and "3 without ctx" in status["access_groups"] + + +def test_the_status_classes_follow_the_decision_table_s_own_reasons(): + """The reasons ``access.decide`` gives a group that has no ctx by its fields are the ones the status + counts as no fault; every other off is one.""" + context = acc.AccessContext("discord", "111", "members", "members", True) + unbound = acc.AccessContext("discord", "111", "ops", "ops", False) + settings = dict(acc.SETTINGS_DEFAULTS) + reasons = [ + acc.decide( + { + "access_group": "members", + "access_group_restricted": True, + "access_fields": {}, + "scope_id": "111", + "restricted_profile": True, + "platform": "discord", + }, + None, + None, + settings, + acc.Markers(), + True, + ).reason, + acc.decide( + { + "access_group": "ops", + "access_group_restricted": False, + "access_fields": {}, + "scope_id": "111", + "restricted_profile": False, + "platform": "discord", + }, + None, + None, + settings, + acc.Markers(), + True, + ).reason, + acc.decide( + { + "access_group": "members", + "access_group_restricted": True, + "scope_id": "111", + "platform": "discord", + "access_fields": {"enabled": False}, + "restricted_profile": True, + }, + None, + None, + settings, + acc.Markers(), + True, + ).reason, + ] + assert context and unbound + assert [st.access_class({"state": f"off: {reason}"}) for reason in reasons] == ["unset"] * 3 + assert st.access_class({"state": "bound"}) == "bound" + for fault in ( + "off: E4", + "off: proof pending: the ctx server gave no answer", + "off: row 2: field read: x", + "off: trip wire: …", + "off: row 2: group without fields; a restricted group runs in this profile", + ): + assert st.access_class({"state": fault}) == "off", fault + + +def test_memory_status_of_a_profile_without_its_own_key_is_healthy_when_its_groups_are_bound( + fake_ctx, monkeypatch, tmp_path +): + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url}) + home = _home(tmp_path, config="memory:\n ctx_checkpoint:\n ungoverned: local\n") + monkeypatch.setenv("HERMES_HOME", str(home)) + st.record_access(str(home), "discord", "111", "members", BOUND) + status = Provider(config={"transport": "rest"}).get_status_config({}) + assert status["ok"] is True and status["summary"].startswith("✓") and "1 bound" in status["summary"] + st.record_access(str(home), "discord", "222", "members", OFF) + status = Provider(config={"transport": "rest"}).get_status_config({}) + assert status["ok"] is False and not status["summary"].startswith("✓") + + +# -- access status ------------------------------------------------------------------------------------ + + +def test_access_status_names_the_rules_the_file_and_filters_by_server(tmp_path, capsys): + st.record_access(str(tmp_path), "discord", "111", "members", OFF) + st.record_access(str(tmp_path), "discord", "222", "members", BOUND) + assert _run(tmp_path, "status") == 0 + out = capsys.readouterr().out + assert f"E4: expected label {LABEL}" in out and "discord-111-members.json" in out and "discord:222" in out + assert _run(tmp_path, "status", "--server", "discord:222") == 0 + out = capsys.readouterr().out + assert "discord:222" in out and "discord:111" not in out + + +def test_a_messaging_session_on_the_profile_connection_is_recorded_once_and_named( + fake_ctx, monkeypatch, tmp_path, capsys +): + """Formerly DP-23: a Discord session without an access group that ran over the profile's own + connection (a server not governed, ``ungoverned: profile``) is named by ``access status``; a local + CLI session is not.""" + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:main") + ah.install(monkeypatch, v8=True, secrets={"CTX_KEY": PROFILE_KEY, "CTX_BASE_URL": fake_ctx.url}) + home = _home(tmp_path, "operator", config="memory:\n ctx_checkpoint:\n ungoverned: profile\n") + for platform in ("cli", "discord", "discord"): + provider = Provider(config={"transport": "rest"}) + provider.initialize("s", hermes_home=str(home), platform=platform, agent_context="primary", **ah.v5_kwargs()) + record = home / "ctx_state" / st.ACCESS_SESSIONS_FILE + assert json.loads(record.read_text(encoding="utf-8")).keys() == {"discord"} + assert _run(home, "status") == 0 + out = capsys.readouterr().out + assert "discord" in out and "ungoverned: local" in out and "cli" not in out.split("profile's connection", 1)[-1] + + +# -- access check ----------------------------------------------------------------------------------------- + +MEMBER = ["--server", "discord:111", "--profile", "members", "--group", "members", "--restricted"] +FIELDS = [ + "--field", + "key=CTX_KEY_111_MEMBERS", + "--field", + "tenant=t", + "--field", + f"read={A_K}", + "--field", + f"write={A_MEMBERS}", +] + + +@pytest.fixture +def member(fake_ctx, monkeypatch, tmp_path): + def build(**key): + spec = dict( + secret=MEMBER_KEY, tenant="t", home=A_MEMBERS, allowed=(A_K,), scope_narrowing="required", label=LABEL + ) + spec.update(key) + fake_ctx.add_key(**spec) + return fake_ctx + + host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + home = _home(tmp_path) + monkeypatch.setenv("HERMES_HOME", str(home)) + nar.reset_proofs() + yield build, host, home + nar.reset_proofs() + + +def test_check_of_a_proper_restricted_binding_passes_without_warnings(member, capsys): + build, _host, home = member + build() + assert _run(home, "check", *MEMBER, *FIELDS) == 0 + out = capsys.readouterr().out + assert "✗" not in out and "⚠" not in out and "E2" in out and "E7" in out + + +@pytest.mark.parametrize( + ("key", "rule", "expected"), + [ + ({"label": "hermes:discord:999:members"}, "E4", f"label {LABEL}"), + ({"role": "admin"}, "E2", "role member"), + ({"scope_narrowing": "optional"}, "E2", "scope_narrowing required"), + ({"allowed": (A_K, "t:d111-mods")}, "E3", f"read scopes exactly {A_K},{A_MEMBERS}"), + ({"tenant": "u"}, "E2", "tenant t"), + ], +) +def test_check_names_every_broken_rule_with_its_expected_value(member, capsys, key, rule, expected): + build, _host, home = member + build(**key) + assert _run(home, "check", *MEMBER, *FIELDS) == 1 + out = capsys.readouterr().out + assert re.search(rf"✗ {rule}\b.*expected .*{re.escape(expected)}", out), out + assert MEMBER_KEY not in out + + +def test_check_refuses_a_broken_field_before_any_secret_or_request(member, capsys): + build, host, home = member + fake = build() + host.secrets.reads.clear() + assert ( + _run( + home, + "check", + *MEMBER, + "--field", + "key=CTX_KEY", + "--field", + "tenant=t", + "--field", + f"read={A_K}", + "--field", + f"write={A_MEMBERS}", + ) + == 1 + ) + out = capsys.readouterr().out + assert "✗ E1" in out and "field key" in out and "CTX_KEY_<server id>" in out + assert fake.count() == 0 and not [n for n, c in host.secrets.reads.items() if n.startswith("CTX_KEY") and c] + + +def test_check_warns_of_a_standard_key_in_a_restricted_profile(member, capsys): + build, _host, home = member + build() + (home / ".env").write_text("CTX_KEY=x\n", encoding="utf-8") + assert _run(home, "check", *MEMBER, *FIELDS) == 0 + assert re.search(r"⚠ .*standard key CTX_KEY", capsys.readouterr().out) + + +def test_check_warns_of_a_ctx_mcp_entry_in_a_restricted_profile(member, capsys): + build, _host, home = member + build() + with open(home / "config.yaml", "a", encoding="utf-8") as handle: + handle.write("mcp_servers:\n ctx:\n url: https://ctx.example/mcp\n") + assert _run(home, "check", *MEMBER, *FIELDS) == 0 + assert re.search(r"⚠ .*mcp_servers\.ctx", capsys.readouterr().out) + + +def test_check_warns_of_a_tenant_grant(member, capsys): + build, _host, home = member + build(grants=("u:shared-k",)) + assert _run(home, "check", *MEMBER, *FIELDS) == 1 # E3 fails as well: the key reads more than the group + out = capsys.readouterr().out + assert re.search(r"⚠ .*u:shared-k.*tenant grant", out), out + + +def test_check_warns_of_sessions_without_an_access_group_in_a_restricted_profile(member, capsys): + build, _host, home = member + build() + st.record_session_without_access(str(home), "discord", "primary", "off") + assert _run(home, "check", *MEMBER, *FIELDS) == 0 + assert re.search(r"⚠ .*without an access group", capsys.readouterr().out) + + +def test_check_warns_of_ungoverned_profile_in_a_governed_profile(member, capsys): + build, _host, home = member + build() + with open(home / "config.yaml", "a", encoding="utf-8") as handle: + handle.write("memory:\n ctx_checkpoint:\n ungoverned: profile\n") + acc.raise_markers(str(home), governed_seen=True) + assert _run(home, "check", *MEMBER, *FIELDS) == 0 + assert re.search(r"⚠ .*ungoverned: profile", capsys.readouterr().out) + + +def test_check_of_an_unrestricted_group_in_an_open_profile_warns_of_no_standard_key( + fake_ctx, monkeypatch, tmp_path, capsys +): + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:d111-ops", allowed=(A_K,)) + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_OPS": PROFILE_KEY}) + home = _home(tmp_path, "ops") + (home / ".env").write_text("CTX_KEY=x\n", encoding="utf-8") + nar.reset_proofs() + argv = ["--server", "discord:111", "--profile", "ops", "--group", "ops", "--unrestricted"] + assert _run(home, "check", *argv, "--field", "key=CTX_KEY_111_OPS", "--field", f"read={A_K}") == 0 + assert "⚠" not in capsys.readouterr().out + + +# -- access provision ------------------------------------------------------------------------------------- + + +@pytest.fixture +def admin(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) + home = _home(tmp_path) + monkeypatch.setenv("HERMES_HOME", str(home)) + return fake_ctx, home + + +def _provision(home, *extra): + argv = ["provision", "--server", "discord:111", "--profile", "members", "--group", "members"] + return _run(home, *argv, "--admin-key-env", "CTX_ADMIN", *extra) + + +def _new_keys(fake): + return [k for k in fake.keys.values() if k.label.startswith("hermes:")] + + +def test_provision_writes_one_env_line_0600_and_keeps_every_other_line(admin, capsys): + fake, home = admin + before = "FOO=bar\n# a comment\nCTX_KEY_111_MEMBERS=old-value\nexport OTHER='x y'\nCTX_KEY_111_MEMBERS=older\n" + (home / ".env").write_text(before, encoding="utf-8") + os.chmod(home / ".env", 0o644) + assert _provision(home) == 0 + (key,) = [k for k in _new_keys(fake) if k.active] + after = (home / ".env").read_text(encoding="utf-8") + assert after == f"FOO=bar\n# a comment\nCTX_KEY_111_MEMBERS={key.secret}\nexport OTHER='x y'\n" + assert stat.S_IMODE((home / ".env").stat().st_mode) == 0o600 + out = capsys.readouterr().out + assert key.secret not in out and ADMIN_KEY not in out + + +def test_provision_after_an_abort_between_ctx_and_the_env_is_repeatable(admin, monkeypatch, capsys): + fake, home = admin + real = cli._atomic_write + + def broken(path, data): + raise OSError("disk full") + + monkeypatch.setattr(cli, "_atomic_write", broken) + assert _provision(home) == 1 + assert not (home / ".env").exists() + assert "again" in capsys.readouterr().out + monkeypatch.setattr(cli, "_atomic_write", real) + assert _provision(home) == 0 + active = [k for k in _new_keys(fake) if k.active] + assert len(active) == 1 and len(_new_keys(fake)) == 2 + assert (home / ".env").read_text(encoding="utf-8") == f"CTX_KEY_111_MEMBERS={active[0].secret}\n" + + +def test_provision_sends_only_what_ctx_decodes(admin): + fake, home = admin + assert _provision(home, "--read", "t:d111-extra") == 0 + (call,) = [r.body for r in fake.requests("/api/manage") if r.action == "keyset-provision"] + assert set(call) == {"action", "data"} and set(call["data"]) == {"scopes", "keys"} + (spec,) = call["data"]["keys"] + assert set(spec) == {"label", "home_scope", "allowed_scopes", "write_scopes", "scope_narrowing", "replace_label"} + assert spec["label"] == LABEL and spec["scope_narrowing"] == "required" and spec["write_scopes"] == [] + assert spec["replace_label"] is True and spec["home_scope"] in call["data"]["scopes"] + assert spec["allowed_scopes"][1:] == ["t:d111-extra"] + assert all(cli.SCOPE_NAME.match(name) for name in call["data"]["scopes"]) + + +def test_provision_sets_ungoverned_local_in_its_own_profile_and_keeps_off(admin): + _fake, home = admin + assert _provision(home) == 0 + assert acc.load_settings(str(home))["ungoverned"] == "local" + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n ungoverned: 'off'\n", encoding="utf-8") + assert _provision(home) == 0 + assert acc.load_settings(str(home))["ungoverned"] == "off" + + +def test_provision_emits_a_group_entry_the_core_and_the_plugin_take(admin, capsys): + _fake, home = admin + assert _provision(home, "--emit-yaml", "--roles", "222,333") == 0 + out = capsys.readouterr().out + fragment = out.split("--- yaml", 1)[1] + (group,) = hermes_yaml.safe_load(fragment) + assert set(group) == {"name", "profile", "restricted", "roles", "fields"}, "only what gateway.access_groups takes" + assert group["name"] == "members" and group["profile"] == "members" and group["restricted"] is True + assert group["roles"] == ["222", "333"] + fields = group["fields"]["ctx_checkpoint"] + parsed = acc.parse_fields(fields, scope_id="111", strict=True) + assert isinstance(parsed, acc.GroupFields), parsed + assert parsed.key == "CTX_KEY_111_MEMBERS" and parsed.tenant == "t" and parsed.write.startswith("t:d") + assert "/policy field members server=111 ctx_checkpoint.key=CTX_KEY_111_MEMBERS" in out + + +@pytest.mark.parametrize( + ("argv", "why"), + [ + (["--server", "discord:1-1", "--group", "members"], "--server"), + (["--server", "discord", "--group", "members"], "--server"), + (["--server", "discord:111", "--group", "Members!"], "--group"), + (["--server", "discord:111", "--group", "k", "--per-community"], "same ctx scope"), + ], +) +def test_provision_refuses_what_it_cannot_name_before_any_request(admin, argv, why, capsys): + fake, home = admin + assert _run(home, "provision", *argv, "--profile", "members", "--admin-key-env", "CTX_ADMIN") == 2 + assert why in capsys.readouterr().out + assert fake.count() == 0 and not (home / ".env").exists() + + +def test_provision_without_the_admin_key_sends_nothing(admin, monkeypatch, capsys): + fake, home = admin + monkeypatch.delenv("CTX_ADMIN") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake.url}) + assert _provision(home) == 1 + assert fake.count() == 0 and "CTX_ADMIN" in capsys.readouterr().out + + +def test_provision_per_community_names_k_and_the_group(admin): + fake, home = admin + assert _provision(home, "--per-community") == 0 + (call,) = [r.body for r in fake.requests("/api/manage") if r.action == "keyset-provision"] + assert call["data"]["scopes"] == ["k", "members"] + + +# -- reset-marker ------------------------------------------------------------------------------------------- + + +def test_reset_marker_needs_a_marker_named(tmp_path): + acc.raise_markers(str(tmp_path), restricted_seen=True, governed_seen=True) + assert _run(tmp_path, "reset-marker", "--profile", "members") == 2 + assert acc.read_markers(str(tmp_path)) == acc.Markers(True, True) + assert _run(tmp_path, "reset-marker", "--profile", "members", "--governed") == 0 + assert acc.read_markers(str(tmp_path)) == acc.Markers(True, False) From d2b94065a8a15df5a7ac55c7c030a41982730afa Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 05:11:08 +0100 Subject: [PATCH 12/65] fix(ctx_checkpoint): the operator sees per group whether the base-block hook delivered its text and, when not, why The hook records each group's outcome beside the binding's own state in the binding's status file: delivered (blocks loaded, skipped ones with their code, cut to base_max_chars), not delivered with the reason (a broken field, no key or URL, E7 inputs, ctx's refusal, the rules a proof broke with the expected values) or unavailable (asked again on a later turn). Never a block's content or a key. The records are written on a thread of their own after the answer, so the hook's answer never waits for them; the binding's state (P-C) and the base blocks keep each other. access status lists them per group, hermes memory status names groups without their base blocks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ctx_checkpoint/memory/access_cli.py | 7 +- .../ctx_checkpoint/memory/base_blocks.py | 111 +++++++++++++-- .../plugin/ctx_checkpoint/memory/status.py | 89 +++++++++++- .../tests/test_access_seam_base_status.py | 132 ++++++++++++++++++ 4 files changed, 321 insertions(+), 18 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index cf2aa016a..4702a4373 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -305,8 +305,9 @@ def _cmd_status(args: argparse.Namespace, home: str) -> int: print(" no access-group binding recorded" + (" for that server" if server else "")) for row in rows: kind = _status.access_class(row) - mark = {"bound": "✓", "unset": "·", "off": "✗"}[kind] - print(f" {mark} {row['platform']}:{row['scope_id']} · profile {row['profile']} · {row['state']}") + mark = {"bound": "✓", "unset": "·", "off": "✗"}.get(kind, "?") + state = row["state"] or "no binding state recorded yet" + print(f" {mark} {row['platform']}:{row['scope_id']} · profile {row['profile']} · {state}") for rule, expected in (row.get("rules") or {}).items(): print(f" {rule}: expected {expected}") detail = [ @@ -317,6 +318,8 @@ def _cmd_status(args: argparse.Namespace, home: str) -> int: f"since {row.get('since') or '?'}", ] print(f" {' · '.join(detail)}") + for group, entry in sorted(_status.base_block_groups(row).items()): + print(f" {_status.base_block_line(group, entry)}") print(f" status file: {row['file']}") seen = _status.read_sessions_without_access(home) on_profile = sorted((platform, kinds["profile"]) for platform, kinds in seen.items() if "profile" in kinds) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index 1573679cf..3bd5e6b84 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -46,6 +46,7 @@ from . import access, narrowing from . import checkpoint as _cp from . import config as _config +from . import status as _status from .client import REJECT_CODES, CtxApiError, CtxClient, redact_secret from .config import env_secret, umbrella_section @@ -150,6 +151,11 @@ class _Plan: _WARNED: set[tuple[str, ...]] = set() # The render cache's clock (a seam: the loop's own clock must stay the real one). _now = time.monotonic +# The thread that records each group's base-block outcome for ``access status`` (display only, never on +# an answer's path), and how many outcomes may wait for it before more are dropped. +_REPORTS: concurrent.futures.ThreadPoolExecutor | None = None +_REPORTS_WAITING = 0 +REPORTS_WAITING_MAX = 4096 def _submit(workers: int, fn: Callable[..., Any], *args: Any) -> concurrent.futures.Future: @@ -223,16 +229,70 @@ def _remember(plan: _Plan, text: str) -> None: def reset_state() -> None: - """Drop the render cache, the joined in-flight fetches and the thread pool (tests).""" - global _POOL, _POOL_SIZE, _CACHE_LIMIT + """Drop the render cache, the joined in-flight fetches and the thread pools (tests).""" + global _POOL, _POOL_SIZE, _CACHE_LIMIT, _REPORTS with _LOCK: pool, _POOL, _POOL_SIZE = _POOL, None, 0 + reports, _REPORTS = _REPORTS, None _CACHE.clear() _CACHE_LIMIT = 0 _INFLIGHT.clear() _WARNED.clear() if pool is not None: pool.shutdown(wait=False) + if reports is not None: + reports.shutdown(wait=False) + + +def _report(request: _Request, outcome: Mapping[str, Any]) -> None: + """Record *outcome* (``status.record_base_blocks``) for the request's group on the reports thread, + in a copy of the caller's context (the serving profile's home). Never blocks, never raises; an + outcome is dropped while :data:`REPORTS_WAITING_MAX` others wait.""" + global _REPORTS, _REPORTS_WAITING + run = contextvars.copy_context().run + with _LOCK: + if _REPORTS_WAITING >= REPORTS_WAITING_MAX: + return + if _REPORTS is None: + _REPORTS = concurrent.futures.ThreadPoolExecutor(max_workers=1, thread_name_prefix="ctx-base-status") + _REPORTS_WAITING += 1 + reports = _REPORTS + try: + reports.submit(run, _write_report, request, dict(outcome)) + except RuntimeError: # shut down meanwhile + with _LOCK: + _REPORTS_WAITING -= 1 + + +def _write_report(request: _Request, outcome: dict[str, Any]) -> None: + global _REPORTS_WAITING + try: + from hermes_constants import get_hermes_home + + home = str(get_hermes_home()) + _status.record_base_blocks(home, request.platform, request.scope_id, request.profile, request.group, outcome) + except Exception: + logger.debug("ctx_checkpoint: base-block outcome not recorded", exc_info=True) + finally: + with _LOCK: + _REPORTS_WAITING -= 1 + + +def wait_for_reports(timeout: float = 5.0) -> bool: + """Whether every outcome handed to the reports thread so far is recorded within *timeout* (tests).""" + with _LOCK: + reports = _REPORTS + if reports is None: + return True + try: + reports.submit(lambda: None).result(timeout) + except (concurrent.futures.TimeoutError, RuntimeError): + return False + return True + + +def _not_delivered(request: _Request, reason: str) -> None: + _report(request, {"state": f"not delivered: {reason}"}) def _warn(key: tuple[str, ...], text: str, *args: Any) -> None: @@ -266,7 +326,9 @@ def _request_of( # (``restricted_profile=None``; the markers cannot change that answer, so no file is read here). strict = access.is_strict(context, restricted_profile=None, markers=access.Markers()) parsed = access.parse_fields(own, scope_id=context.scope_id, strict=strict) + shown = _Request(context.platform, context.scope_id, context.group, str(profile or ""), strict, None) if isinstance(parsed, access.FieldError): + _not_delivered(shown, f"field {parsed.field}: {parsed.reason}") _warn( ("fields", context.platform, context.scope_id, context.group, parsed.field), "ctx_checkpoint: base blocks of access group %s (%s:%s) off: field %s: %s", @@ -277,7 +339,10 @@ def _request_of( parsed.reason, ) return None - if not parsed.enabled or not parsed.base_blocks or not parsed.key: + if not parsed.enabled or not parsed.base_blocks: + return None + if not parsed.key: + _not_delivered(shown, "the group names no key (field key)") return None return _Request(context.platform, context.scope_id, context.group, str(profile or ""), strict, parsed) @@ -384,13 +449,16 @@ def _expectation(request: _Request, home: str) -> _Expectation | None: request.scope_id, fields.base_url, ) + _not_delivered(request, f"field base_url: {fields.base_url} holds no https URL") return None else: url = _profile_base_url(home) if not url: + _not_delivered(request, "no ctx server URL (field base_url or the profile's)") return None key = _secret(fields.key) if not key: + _not_delivered(request, f"field key: {fields.key} is empty in the profile's .env") return None env_names: tuple[str, ...] = () toolsets: tuple[str, ...] = () @@ -405,6 +473,7 @@ def _expectation(request: _Request, home: str) -> _Expectation | None: request.platform, request.scope_id, ) + _not_delivered(request, "E7: the profile's .env or its toolset list for the platform is unreadable") return None env_names, toolsets = inputs label = narrowing.expected_label(request.platform, request.scope_id, request.profile) if request.strict else None @@ -455,6 +524,7 @@ def _prove(request: _Request, expected: _Expectation, settings: Mapping[str, Any len(read), access.READ_MAX, ) + _not_delivered(request, f"the key reads {len(read)} scopes besides its write scope; set field read") return None client = CtxClient(url, key, timeout=verify, narrowing=narrowing.Narrowing(read=read)) raw_narrowed = narrowing.whoami_raw(client, narrowed=True, budget_s=min(verify, _left(deadline))) @@ -468,9 +538,12 @@ def _prove(request: _Request, expected: _Expectation, settings: Mapping[str, Any request.scope_id, _cp.redact_error_text(exc, (key,)), ) + cause = ", ".join(part for part in (exc.code, f"HTTP {exc.status}" if exc.status else "") if part) + _not_delivered(request, f"ctx refused the binding ({cause or 'no code'})") return None raise BaseBlocksUnavailable("the binding could not be proven now") from None except ValueError: # a URL CtxClient does not take (no http(s), no host) + _not_delivered(request, "the ctx server URL is no http(s) URL with a host") return None expect = narrowing.Expect( narrowing=narrowing.Narrowing(read=read), @@ -492,6 +565,9 @@ def _prove(request: _Request, expected: _Expectation, settings: Mapping[str, Any request.scope_id, "; ".join(f"{rule}: {verdict.detail.get(rule, '')}" for rule in verdict.failed), ) + _not_delivered( + request, "; ".join(f"{rule}: expected {verdict.detail.get(rule, '')}" for rule in verdict.failed) + ) return None home_scope = raw_narrowed.get("home_scope") write = fields.write or (home_scope if isinstance(home_scope, str) else "") @@ -511,10 +587,10 @@ def _prove(request: _Request, expected: _Expectation, settings: Mapping[str, Any # -- step 4: fetch, E6, render ------------------------------------------------------------------------------- -def _fetch(plan: _Plan, deadline: float) -> str: +def _fetch(plan: _Plan, deadline: float, request: _Request) -> str: """One fetch of the plan's blocks through the read narrowing, E6 per block, the text rendered and - kept in the render cache. A transient failure or an entry that is no answer raises: never a - partial text.""" + kept in the render cache, its outcome recorded for the request's group. A transient failure or an + entry that is no answer raises: never a partial text.""" try: entries = plan.client.get_blocks(plan.ids, timeout=_left(deadline)) except CtxApiError as exc: @@ -558,6 +634,11 @@ def _fetch(plan: _Plan, deadline: float) -> str: ) # A whole text that arrives after its waiter's budget is still kept: the next call is a hit. _remember(plan, text) + if text: + outcome = {"state": "delivered", "loaded": len(blocks), "skipped": skipped} + _report(request, {**outcome, "cut": text.endswith(TRUNCATED_MARK)}) + else: + _report(request, {"state": "not delivered: none of the base blocks could be had", "skipped": skipped}) return text @@ -599,7 +680,7 @@ def _answer( if joined is not None: return joined try: - text = _fetch(plan, deadline) + text = _fetch(plan, deadline, request) except BaseException as exc: own.set_exception(exc) raise @@ -630,12 +711,16 @@ async def on_access_group_fields( request = _request_of(platform, scope_id, group, restricted, profile, fields) if request is None: return None - home, settings, core_timeout = await _wait(_submit(DEFAULT_WORKERS, _settings), SETTINGS_BUDGET_S) - workers = int(settings["base_workers"]) - deadline = started + _budget_s(settings, core_timeout) - answer = await _wait(_submit(workers, _answer, request, home, settings, deadline), deadline - time.monotonic()) - if isinstance(answer, concurrent.futures.Future): - answer = await _wait(answer, deadline - time.monotonic()) + try: + home, settings, core_timeout = await _wait(_submit(DEFAULT_WORKERS, _settings), SETTINGS_BUDGET_S) + workers = int(settings["base_workers"]) + deadline = started + _budget_s(settings, core_timeout) + answer = await _wait(_submit(workers, _answer, request, home, settings, deadline), deadline - time.monotonic()) + if isinstance(answer, concurrent.futures.Future): + answer = await _wait(answer, deadline - time.monotonic()) + except BaseBlocksUnavailable as exc: + _report(request, {"state": f"unavailable: {exc}; the core asks again on a later turn"}) + raise return {"prompt": answer} if answer else None diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py index 4e056f4f3..1bfa39cb6 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py @@ -772,6 +772,8 @@ def mcp_report(hermes_home: str) -> dict[str, Any]: # Bounds of what a record keeps: scopes per list (a group reads at most 8), rules, platforms recorded. ACCESS_LIST_MAX = 16 ACCESS_SESSION_PLATFORMS_MAX = 64 +# Groups whose base blocks one binding's record names (a server has at most 32 groups). +ACCESS_BASE_GROUPS_MAX = 32 # ``hermes memory status`` names this many bindings that are off one by one, then counts the rest. ACCESS_STATUS_LINES = 5 _SAFE_NAME_PART = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.]{0,63}$") @@ -908,6 +910,48 @@ def record_access(hermes_home: str, platform: str, scope_id: str, profile: str, logger.debug("ctx_checkpoint: access-group status not recorded", exc_info=True) +def record_base_blocks( + hermes_home: str, platform: str, scope_id: str, profile: str, group: str, outcome: Mapping[str, Any] +) -> None: + """Record what the base-block hook did for *group* of a binding, beside the binding's own state + (``record_access`` keeps it): ``state`` (``delivered``: the text is built and cached — a call that + ran out of time meanwhile gets it on its next turn; ``not delivered: <reason>``; ``unavailable: + <reason>``, asked again later), ``loaded`` (blocks fetched for the text), ``cut`` (the text reached + ``base_max_chars``) and ``skipped`` (block id → why it is not in the text). Never a block's content + or title, never a key. Written only when it changes (stamped ``at``); at most + :data:`ACCESS_BASE_GROUPS_MAX` groups per binding. Never raises.""" + if not hermes_home or not isinstance(outcome, Mapping) or not isinstance(group, str) or not group: + return + skipped = outcome.get("skipped") + entry = { + "state": _display_text(outcome.get("state")), + "loaded": outcome.get("loaded") if isinstance(outcome.get("loaded"), int) else 0, + "cut": outcome.get("cut") is True, + "skipped": { + str(block): _display_text(reason) + for block, reason in list(skipped.items() if isinstance(skipped, Mapping) else ())[:ACCESS_LIST_MAX] + if _SCOPE_TEXT_RE.match(str(block)) + }, + } + name = group[:64] + + def change(record: dict[str, Any]) -> dict[str, Any]: + groups = record.get("base_blocks") + groups = dict(groups) if isinstance(groups, Mapping) else {} + previous = groups.get(name) + if isinstance(previous, Mapping) and {k: v for k, v in previous.items() if k != "at"} == entry: + return record + if name not in groups and len(groups) >= ACCESS_BASE_GROUPS_MAX: + return record + groups[name] = {**entry, "at": _now_text()} + return {**record, "base_blocks": groups} + + try: + _update_access(hermes_home, platform, scope_id, profile, change) + except Exception: + logger.debug("ctx_checkpoint: base-block status not recorded", exc_info=True) + + def read_access(hermes_home: str) -> list[Mapping[str, Any]]: """Every recorded binding of the home, sorted by platform, server and profile, each with ``file`` (its path below the home). A file that is unreadable, too large or not a record is skipped.""" @@ -921,8 +965,9 @@ def read_access(hermes_home: str) -> list[Mapping[str, Any]]: record = _read_json_file(path) if record is None or not all(isinstance(record.get(key), str) for key in ("platform", "scope_id", "profile")): continue - if not isinstance(record.get("state"), str): + if not isinstance(record.get("state", ""), str): continue + record.setdefault("state", "") # only base blocks recorded so far record["file"] = f"{FACT_STATE_DIR}/{ACCESS_DIR}/{path.name}" rows.append(record) rows.sort(key=lambda row: (row["platform"], row["scope_id"], row["profile"])) @@ -930,14 +975,36 @@ def read_access(hermes_home: str) -> list[Mapping[str, Any]]: def access_class(row: Mapping[str, Any]) -> str: - """``bound``; ``unset`` (off because the group has no ctx by its own fields: a choice); or ``off`` - (every other reason: a broken rule, a refused or pending proof, a broken field, the trip wire).""" + """``bound``; ``unset`` (off because the group has no ctx by its own fields: a choice); ``off`` + (every other reason: a broken rule, a refused or pending proof, a broken field, the trip wire); or + ``unknown`` (no binding state recorded, only the base blocks of the hook).""" state = str(row.get("state") or "") if state == "bound": return "bound" + if not state: + return "unknown" return "unset" if _UNSET_STATE_RE.match(state) else "off" +def base_block_groups(row: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]: + """The base-block entries of a binding's record by group (``record_base_blocks``).""" + groups = row.get("base_blocks") + if not isinstance(groups, Mapping): + return {} + return {str(group): entry for group, entry in groups.items() if isinstance(entry, Mapping)} + + +def base_block_line(group: str, entry: Mapping[str, Any]) -> str: + """One group's base blocks as ``access status`` names them.""" + state = str(entry.get("state") or "?") + if state == "delivered": + state = f"delivered, {entry.get('loaded', 0)} loaded" + (", cut to base_max_chars" if entry.get("cut") else "") + skipped = entry.get("skipped") + if isinstance(skipped, Mapping) and skipped: + state += "; skipped: " + ", ".join(f"{block} ({why})" for block, why in sorted(skipped.items())) + return f"base blocks of {group}: {state} (since {entry.get('at') or '?'})" + + def access_line(row: Mapping[str, Any]) -> str: """One binding as a status line names it: server, profile and state.""" return f"{row.get('platform')}:{row.get('scope_id')} (profile {row.get('profile')}): {row.get('state')}" @@ -961,6 +1028,22 @@ def access_status(status: dict[str, Any], hermes_home: str, *, own_expected: boo bound, unset = classes.count("bound"), classes.count("unset") off = [row for row, kind in zip(rows, classes, strict=True) if kind == "off"] out = dict(status) + missing = [ + f"{row['platform']}:{row['scope_id']} {group}" + for row in rows + for group, entry in sorted(base_block_groups(row).items()) + if entry.get("state") != "delivered" + ] + if missing: + shown = ", ".join(missing[:ACCESS_STATUS_LINES]) + ( + f" and {len(missing) - ACCESS_STATUS_LINES} more" if len(missing) > ACCESS_STATUS_LINES else "" + ) + out["access_base_blocks"] = ( + f"✗ base blocks not delivered: {shown} — `hermes ctx_checkpoint access status` says why" + ) + rows = [row for row, kind in zip(rows, classes, strict=True) if kind != "unknown"] + if not rows: + return out counts = f"{bound} bound, {len(off)} off" + (f", {unset} without ctx by their fields" if unset else "") out["access_groups"] = f"{counts} — `hermes ctx_checkpoint access status` shows each" for index, row in enumerate(off[:ACCESS_STATUS_LINES]): diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py new file mode 100644 index 000000000..473636812 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py @@ -0,0 +1,132 @@ +"""Seam P-D/P-E/P-C: the operator sees per group whether the base-block hook delivered the group's text +and, when not, why — in the binding's status file next to the binding's own state, which the group +binding (P-C) keeps writing without dropping it. Never a block's content, never a key. The hook writes +it on a thread of its own, after its answer (display only; the answer never waits for it).""" + +from __future__ import annotations + +import asyncio +import time + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_base_status") +bb = ah.plugin_module(_PKG, "memory.base_blocks") +st = ah.plugin_module(_PKG, "memory.status") +cli = ah.plugin_module(_PKG, "memory.access_cli") +_nar = ah.plugin_module(_PKG, "memory.narrowing") + +K, M = "t:d111-k", "t:d111-members" +MEMBER_KEY = "ctx_member_111_status_secret" +LABEL = "hermes:discord:111:members" +SECRET_TEXT = "the house rules say: be kind" + + +@pytest.fixture +def world(fake_ctx, monkeypatch, _isolated_hermes_home): + bb.reset_state() + _nar.reset_proofs() + home = _isolated_hermes_home + (home / "config.yaml").write_text("platform_toolsets:\n discord: [web]\n", encoding="utf-8") + fake_ctx.add_key(secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL) + ids = { + "one": fake_ctx.add_block(K, "House rules", SECRET_TEXT), + "two": fake_ctx.add_block(K, "FAQ", "Ask in #help."), + "mine": fake_ctx.add_block(M, "Member chatter", "said by a member"), + } + host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + yield fake_ctx, host, ids, home + bb.reset_state() + _nar.reset_proofs() + + +def _fields(ids, *names, **extra): + own = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M, **extra} + own["base_blocks"] = [ids.get(name, name) for name in names] + return {"ctx_checkpoint": own} + + +def _call(fields, **overrides): + kwargs = ah.hook_kwargs(fields=fields, **overrides) + return asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, timeout=30.0, **kwargs)) + + +def _base(home, group="members"): + """The group's base-block entry of the binding (discord, 111, members), once the hook wrote it.""" + deadline = time.monotonic() + 5.0 + while True: + rows = [ + r + for r in st.read_access(str(home)) + if (r["platform"], r["scope_id"], r["profile"]) == ("discord", "111", "members") + ] + entry = ((rows[0].get("base_blocks") or {}).get(group)) if rows else None + if entry is not None or time.monotonic() > deadline: + return entry or {} + time.sleep(0.02) + + +def _files(home): + return "\n".join(p.read_text(encoding="utf-8") for p in (home / "ctx_state").rglob("*") if p.is_file()) + + +def test_a_delivered_text_is_recorded_with_its_skipped_blocks_and_no_content(world, capsys): + _fake, _host, ids, home = world + outcome = _call(_fields(ids, "one", "two", "gone-block-id", "mine")) + assert outcome.answered and SECRET_TEXT in outcome.result["prompt"] + entry = _base(home) + assert entry.get("state") == "delivered" and entry.get("loaded") == 2 + assert entry.get("skipped") == {"gone-block-id": "not_found", ids["mine"]: "not_found"} + assert SECRET_TEXT not in _files(home) and MEMBER_KEY not in _files(home) + assert cli.run_access(["status"], hermes_home=str(home)) == 0 + out = capsys.readouterr().out + assert "base blocks of members: delivered, 2 loaded" in out and "gone-block-id (not_found)" in out + + +def test_a_broken_rule_is_named_as_the_reason(world): + fake, _host, ids, home = world + fake.keys[MEMBER_KEY].label = "hermes:discord:999:members" + outcome = _call(_fields(ids, "one")) + assert outcome.answered and outcome.result is None + entry = _base(home) + assert entry.get("state", "").startswith("not delivered:") and "E4" in entry["state"], entry + + +def test_a_broken_field_is_named_without_a_request(world): + fake, _host, ids, home = world + outcome = _call({"ctx_checkpoint": {**_fields(ids, "one")["ctx_checkpoint"], "key": "CTX_KEY"}}) + assert outcome.answered and outcome.result is None + entry = _base(home) + assert entry.get("state", "").startswith("not delivered: field key"), entry + assert fake.count() == 0 + + +def test_a_transient_failure_is_recorded_as_unavailable(world, monkeypatch): + fake, _host, ids, home = world + fake.latency["manage:get"] = 2.0 + (home / "config.yaml").write_text( + "platform_toolsets:\n discord: [web]\nmemory:\n ctx_checkpoint:\n base_timeout_s: 1\n", encoding="utf-8" + ) + outcome = _call(_fields(ids, "one")) + assert not outcome.answered + entry = _base(home) + assert entry.get("state", "").startswith("unavailable:"), entry + + +def test_the_binding_s_state_and_the_base_blocks_keep_each_other(world): + _fake, _host, ids, home = world + bound = { + "state": "bound", + "rules": {}, + "key_digest": "0123456789abcdef", + "tenant_slug": "t", + "read": [K], + "write": M, + } + st.record_access(str(home), "discord", "111", "members", bound) + _call(_fields(ids, "one")) + assert _base(home).get("state") == "delivered" + st.record_access(str(home), "discord", "111", "members", {**bound, "state": "off: E4"}) + (row,) = st.read_access(str(home)) + assert row["state"] == "off: E4" and row["base_blocks"]["members"]["state"] == "delivered" From 51ee275215b8efcd57254cb6511ae1c4ee619e01 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 05:14:16 +0100 Subject: [PATCH 13/65] perf(ctx_checkpoint): the base-block hook's pool defaults to 32 threads Measured with the hook load script on the merged plugin (2 000 groups with 16 base blocks each, 200 ms on whoami and get, multi-id get, every session's hook at once after a restart): with 16 threads every group had its text after 28 turns, with 32 after 18, two runs each. The threads wait on the network; base_workers stays settable from 1 to 32. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/access.py | 2 +- .../tests/test_access_seam_base_workers.py | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py index eef9ac278..30f9b43f1 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -76,7 +76,7 @@ "base_cache_s": 900, # 60 .. 86400 "base_cache_entries": 2048, # 64 .. 65536 "base_timeout_s": 4, # 1 .. 10 - "base_workers": 4, # 1 .. 32 + "base_workers": 32, # 1 .. 32; measured: a restart of 2 000 groups at 200 ms is served in 18 turns, 28 with 16 "verify_timeout_s": 3, # 1 .. 10 } ) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py new file mode 100644 index 000000000..9b922693f --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py @@ -0,0 +1,25 @@ +"""Seam P-D/P-B: the base-block hook's own pool defaults to 32 threads (``base_workers``). Measured with +P-D's load script on the merged plugin (2 000 groups, 16 base blocks each, 200 ms on ``whoami`` and +``get``, multi-id get, a restart of every session at once, 30 turns): 16 threads gave every group its +text after 28 turns, 32 threads after 18 (two runs each); the threads wait on the network, so the default +is the measured upper end of the setting.""" + +from __future__ import annotations + +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_base_workers") +acc = ah.plugin_module(_PKG, "memory.access") +bb = ah.plugin_module(_PKG, "memory.base_blocks") + + +def test_the_base_block_pool_defaults_to_32_threads(tmp_path): + assert acc.SETTINGS_DEFAULTS["base_workers"] == 32 + assert bb.DEFAULT_WORKERS == 32, "the pool the first settings read runs on" + (tmp_path / "config.yaml").write_text("memory:\n ctx_checkpoint: {}\n", encoding="utf-8") + assert acc.load_settings(str(tmp_path))["base_workers"] == 32 + + +def test_a_profile_still_sets_fewer(tmp_path): + (tmp_path / "config.yaml").write_text("memory:\n ctx_checkpoint:\n base_workers: 4\n", encoding="utf-8") + assert acc.load_settings(str(tmp_path))["base_workers"] == 4 From 7cf8808d684f9f7a34d0988a2add3ee36279e410 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 05:18:33 +0100 Subject: [PATCH 14/65] fix(ctx_checkpoint): access provision sends no tenant-admin key over plain http to another host A profile URL of http:// to a host outside this computer and the local network would carry the tenant-admin key unencrypted; provision now refuses before any request (https, or a local host). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/access_cli.py | 6 ++++++ .../plugin/ctx_checkpoint/memory/base_blocks.py | 13 ------------- .../ctx_checkpoint/tests/test_access_pe_rules.py | 8 ++++++++ 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 4702a4373..efd1b5a02 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -690,6 +690,12 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: return 1 else: url = _profile_url(home) + if _status.insecure_http(url): + print( + f" ✗ {_status.display_url(url)} is http:// to a host outside this computer and the local network: " + "the tenant-admin key would travel unencrypted. Use https; nothing was sent" + ) + return 1 admin_key = _secret(args.admin_key_env) if not url or not admin_key: missing = "the ctx server URL (CTX_BASE_URL or rest_base_url)" if not url else args.admin_key_env diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index 3bd5e6b84..fe4719ae4 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -278,19 +278,6 @@ def _write_report(request: _Request, outcome: dict[str, Any]) -> None: _REPORTS_WAITING -= 1 -def wait_for_reports(timeout: float = 5.0) -> bool: - """Whether every outcome handed to the reports thread so far is recorded within *timeout* (tests).""" - with _LOCK: - reports = _REPORTS - if reports is None: - return True - try: - reports.submit(lambda: None).result(timeout) - except (concurrent.futures.TimeoutError, RuntimeError): - return False - return True - - def _not_delivered(request: _Request, reason: str) -> None: _report(request, {"state": f"not delivered: {reason}"}) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py index e1fa2d404..877723795 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -557,3 +557,11 @@ def test_reset_marker_needs_a_marker_named(tmp_path): assert acc.read_markers(str(tmp_path)) == acc.Markers(True, True) assert _run(tmp_path, "reset-marker", "--profile", "members", "--governed") == 0 assert acc.read_markers(str(tmp_path)) == acc.Markers(True, False) + + +def test_provision_sends_no_admin_key_over_plain_http_to_another_host(admin, monkeypatch, capsys): + _fake, home = admin + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": "http://ctx.invalid", "CTX_ADMIN": ADMIN_KEY}) + assert _provision(home) == 1 + out = capsys.readouterr().out + assert "https" in out and "nothing was sent" in out From c2724c4206c4a3e449f27f95e66619c2eb106ba1 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 05:45:18 +0100 Subject: [PATCH 15/65] =?UTF-8?q?fix(ctx=5Fcheckpoint):=20access=20tools?= =?UTF-8?q?=20after=20a=20fresh=20review=20=E2=80=94=20provision=20tells?= =?UTF-8?q?=20"unknown"=20from=20"refused",=20keeps=20lines=20written=20me?= =?UTF-8?q?anwhile,=20stays=20in=20its=20own=20profile,=20and=20the=20base?= =?UTF-8?q?-block=20status=20follows=20every=20path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From a fresh review of P-E and the seams: - provision: no answer, a 5xx or a proxy error says the set may exist and asks for the same command again (only a 4xx is "nothing created"); the .env line is merged into the file read again under a lock just before the write; another --profile than the one it runs in is refused (also for reset-marker); a key of other rights than asked for is not taken; a URL the client does not take sends nothing; a tenant-admin key found in the profile's .env and how running sessions get the new key are named. - hermes memory status is not ok with a status file it cannot read; access check names what it does not prove (base blocks, the store client). - base-block status: a group without base blocks keeps no stale entry, a cache hit or a joined fetch records the group as delivered; the pool starts at 4 threads and grows to the largest base_workers (default 32), so a profile that sets fewer gets fewer. - profile URL: the section's ctx_base_url counts as for the profile's own connection. - status records take no lock when nothing changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ctx_checkpoint/memory/access_cli.py | 100 ++++++++++++++-- .../ctx_checkpoint/memory/base_blocks.py | 41 +++++-- .../plugin/ctx_checkpoint/memory/config.py | 10 +- .../plugin/ctx_checkpoint/memory/status.py | 113 +++++++++++++----- .../tests/test_access_pe_rules.py | 94 +++++++++++++++ .../tests/test_access_seam_base_status.py | 41 ++++++- .../tests/test_access_seam_base_workers.py | 42 ++++++- .../tests/test_access_seam_profile_url.py | 7 ++ 8 files changed, 386 insertions(+), 62 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index efd1b5a02..fc884c55e 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -43,7 +43,7 @@ from . import client as _client from . import config as _config from . import status as _status -from .config import derive_profile_name, env_secret, umbrella_section +from .config import FACT_STATE_DIR, derive_profile_name, env_secret, umbrella_section # ctx: go/internal/handler/tenant_manage.go scopeNamePattern (name part of <slug>:<name>). SCOPE_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,22}[a-z0-9])?$") @@ -68,6 +68,8 @@ # Bound of one operator request (keyset-provision runs one transaction under the tenant's lock). REQUEST_TIMEOUT_S = 30.0 _BASE_URL_ENV = re.compile(r"^(?:CTX_BASE_URL|CTX_BASE_URL_[A-Z0-9_]+)$") +# Serializes this tool's writes of a profile's .env (in ctx_state/; Hermes' own writers take none). +ENV_LOCK_FILE = "env-provision.lock" _STANDARD_KEYS = ("CTX_KEY", "CTX_API_KEY") _BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz" _REVOKE = ( @@ -243,6 +245,34 @@ def _profile(args: argparse.Namespace, home: str) -> str: return profile +def _known_profile(home: str) -> str | None: + """The name of the profile at *home* where it is certain: a home ``…/profiles/<name>`` or the + account's default home (``default``); ``None`` for any other home.""" + parts = Path(home).expanduser().parts + if len(parts) >= 2 and parts[-2] == "profiles" and parts[-1]: + return parts[-1] + try: + from hermes_constants import account_default_hermes_home + + if os.path.realpath(home) == os.path.realpath(str(account_default_hermes_home())): + return "default" + except Exception: + return None + return None + + +def _own_profile_only(args: argparse.Namespace, home: str, command: str) -> None: + """A command that writes into the profile's files refuses to name another profile than the one it + runs in: the key, its label and ``ungoverned`` would land in the wrong profile.""" + known = _known_profile(home) + wanted = getattr(args, "profile", None) + if wanted and known and wanted != known: + raise _Usage( + f"this runs in profile {known} ({home}), not {wanted}: run it there, " + f"hermes -p {wanted} ctx_checkpoint access {command} …" + ) + + def _ids(text: str, option: str) -> list[str]: items = [item.strip() for item in str(text or "").split(",") if item.strip()] if not all(NUMERIC_ID.match(item) for item in items): @@ -388,6 +418,13 @@ def _cmd_check(args: argparse.Namespace, home: str) -> int: broken = 0 else: broken, proof = _prove(home, platform, scope_id, profile, strict, parsed) + unchecked = [] + if parsed.base_blocks: + unchecked.append("the base blocks (E6; `access status` shows what the hook did with them)") + if not strict and parsed.store and parsed.store != parsed.write: + unchecked.append("the store client of field store") + if unchecked: + print(f" · not checked here: {'; '.join(unchecked)}") warnings = _warnings(home, platform, strict, proof) for warning in warnings: print(f" ⚠ {warning}") @@ -605,6 +642,15 @@ def _env_with(text: str, name: str, value: str) -> str: return "".join(out) +def _write_env_line(home: str, env_path: Path, name: str, value: str) -> None: + """``name=value`` into the profile's ``.env``: read again and replaced under a lock just before the + write, so a line another writer added while ctx answered stays (the first read only proved the file + readable). Raises ``OSError``/``ValueError`` when it cannot be read or written.""" + with _status._state_lock(Path(home) / FACT_STATE_DIR, ENV_LOCK_FILE): + current = env_path.read_text(encoding="utf-8") if env_path.exists() else "" + _atomic_write(env_path, _env_with(current, name, value)) + + def _manage_once(url: str, key: str, payload: Mapping[str, Any]) -> dict[str, Any]: """One ``POST /api/manage`` with *key*, without the client's 429 retry (a refused set wrote nothing; asking again changes nothing). Errors are ``CtxApiError`` with the key redacted.""" @@ -654,6 +700,7 @@ def _yaml(value: Any) -> str: def _cmd_provision(args: argparse.Namespace, home: str) -> int: platform, scope_id = _server(args.server) + _own_profile_only(args, home, "provision") profile = _profile(args, home) group = str(args.group) if not GROUP_NAME.match(group): @@ -679,10 +726,16 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: print(f"access provision — {platform}:{scope_id} · group {group} · profile {profile}") env_path = Path(home) / ".env" try: # the .env is read before ctx is asked: a key nobody can store is not created - before = env_path.read_text(encoding="utf-8") if env_path.exists() else "" + if env_path.exists(): + env_path.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as exc: print(f" ✗ {env_path} cannot be read ({type(exc).__name__}); nothing was sent") return 1 + if args.admin_key_env in _env_names(home): + print( + f" ⚠ {args.admin_key_env} is in this profile's .env: a tenant-admin key in a profile that serves " + "groups is within reach of its tools; keep it in the shell's environment for this command only" + ) if args.base_url_env: url = _secret(args.base_url_env) if not access.valid_base_url(url): @@ -719,10 +772,21 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: } try: answer = _manage_once(url, admin_key, request) + except ValueError: # a URL CtxClient does not take (no http(s), no host) + print(f" ✗ {_status.display_url(url) or url!r} is no http(s) URL of a ctx server; nothing was sent") + return 1 except _client.CtxApiError as exc: - print(f" ✗ ctx refused the key set, nothing was created: {_status.redact_error(exc, (admin_key,))}") + cause = _status.redact_error(exc, (admin_key,)) + if exc.status is not None and 400 <= exc.status < 500: + print(f" ✗ ctx refused the key set, nothing was created: {cause}") + else: # no answer, or a server or proxy error: ctx may have committed the set + print( + f" ✗ no clear answer from ctx ({cause}): whether the key set was created is unknown, and the key " + "of an earlier run of this label may be inactive now. Run the same command again: it replaces " + "any key of this label (replace_label), so one key stays active and lands in the .env" + ) return 1 - made = _made_key(answer, label, own) + made = _made_key(answer, label, own, [_full_name(scope) for scope in (knowledge, *extra)]) if isinstance(made, str): print( f" ✗ {made}. A key may have been created at ctx; run the same command again: it replaces it " @@ -731,8 +795,8 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: return 1 secret, slug, scopes = made try: - _atomic_write(env_path, _env_with(before, variable, secret)) - except OSError as exc: + _write_env_line(home, env_path, variable, secret) + except (OSError, ValueError) as exc: print( f" ✗ the key was created at ctx but {env_path} could not be written ({type(exc).__name__}); run the same " "command again: it replaces the key (replace_label), so one key stays active" @@ -744,6 +808,10 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: f" key: {variable} in {env_path} (label {label}, key digest {narrowing.key_digest(secret)}); " "an earlier key of this label is inactive now" ) + print( + f" sessions bound with an earlier key of this label lose ctx until their agent is rebuilt; " + f"/policy field {group} server={scope_id} {access.NAMESPACE}.base_rev=<n+1> rebuilds them at once" + ) rc = _ungoverned_local(home) fields: dict[str, Any] = {"key": variable, "tenant": slug, "read": [_full(knowledge, slug)]} fields["read"] += [_full(scope, slug) for scope in extra] @@ -755,9 +823,17 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: return rc -def _made_key(answer: Mapping[str, Any], label: str, own: str) -> tuple[str, str, list[Mapping[str, Any]]] | str: +def _full_name(scope: str) -> str: + """A scope of the request as the answer names it, the slug left open (``*:<name>`` for a bare name).""" + return scope if ":" in scope else f"*:{scope}" + + +def _made_key( + answer: Mapping[str, Any], label: str, own: str, allowed: Sequence[str] +) -> tuple[str, str, list[Mapping[str, Any]]] | str: """The new key's plaintext, the tenant slug and the scopes of a ``keyset-provision`` answer, or - what is wrong with it.""" + what is wrong with it: one key, of the label, homed in the group's scope, with exactly the rights + asked for (*allowed* as :func:`_full_name` gives them, no write scope, narrowing required).""" keys, scopes = answer.get("keys"), answer.get("scopes") if answer.get("success") is not True or not isinstance(keys, list) or len(keys) != 1: return "ctx answered no key set" @@ -767,6 +843,13 @@ def _made_key(answer: Mapping[str, Any], label: str, own: str) -> tuple[str, str secret = entry.get("api_key") if entry.get("label") != label or name != own or not access.SLUG_PATTERN.match(slug): return "ctx answered a key of another label or scope" + asked = [name if not name.startswith("*:") else f"{slug}:{name[2:]}" for name in allowed] + if ( + entry.get("scope_narrowing") != "required" + or entry.get("write_scopes") != [] + or [str(scope) for scope in entry.get("allowed_scopes") or []] != asked + ): + return "ctx answered a key of other rights than asked for" if not isinstance(secret, str) or not KEY_VALUE.match(secret): return "ctx answered a key the .env cannot hold" return secret, slug, [s for s in (scopes if isinstance(scopes, list) else []) if isinstance(s, Mapping)] @@ -850,6 +933,7 @@ def _print_fields( def _cmd_reset(args: argparse.Namespace, home: str) -> int: if not (args.restricted or args.governed): raise _Usage("name the marker to lower: --restricted, --governed or both") + _own_profile_only(args, home, "reset-marker") _profile(args, home) try: access.reset_markers(home, restricted=args.restricted, governed=args.governed) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index fe4719ae4..665edff16 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -68,8 +68,10 @@ # The settings are read before the call's budget is known; they get the shortest budget a profile # can set (``base_timeout_s`` from 1 s). SETTINGS_BUDGET_S = 1.0 -# The pool size before any profile's ``base_workers`` was read. -DEFAULT_WORKERS = int(access.SETTINGS_DEFAULTS["base_workers"]) +# The pool size before any profile's ``base_workers`` was read (the settings stage runs on it); the pool +# then grows to the largest ``base_workers`` a serving profile set (default 32), so a profile that sets +# fewer gets fewer. +SETTINGS_WORKERS = 4 # A block's title and content (the bound keys already replaced over the whole text) pass the chain's # redaction cut to ``max_chars`` plus this many characters, the longest named value its rules judge # (``checkpoint.MAX_VALUE_CHARS``): a value that starts inside the text that is kept is judged whole. @@ -156,6 +158,10 @@ class _Plan: _REPORTS: concurrent.futures.ThreadPoolExecutor | None = None _REPORTS_WAITING = 0 REPORTS_WAITING_MAX = 4096 +# The state last handed to the reports thread per (platform, server, profile, group): a cache hit or a +# group without base blocks reports only when it differs (the hot paths stay one dict lookup). +_REPORTED: dict[tuple[str, str, str, str], str | None] = {} +REPORTED_MAX = 65_536 def _submit(workers: int, fn: Callable[..., Any], *args: Any) -> concurrent.futures.Future: @@ -234,6 +240,7 @@ def reset_state() -> None: with _LOCK: pool, _POOL, _POOL_SIZE = _POOL, None, 0 reports, _REPORTS = _REPORTS, None + _REPORTED.clear() _CACHE.clear() _CACHE_LIMIT = 0 _INFLIGHT.clear() @@ -244,27 +251,35 @@ def reset_state() -> None: reports.shutdown(wait=False) -def _report(request: _Request, outcome: Mapping[str, Any]) -> None: - """Record *outcome* (``status.record_base_blocks``) for the request's group on the reports thread, - in a copy of the caller's context (the serving profile's home). Never blocks, never raises; an - outcome is dropped while :data:`REPORTS_WAITING_MAX` others wait.""" +def _report(request: _Request, outcome: Mapping[str, Any] | None, *, changed_only: bool = False) -> None: + """Record *outcome* (``status.record_base_blocks``; ``None``: the group has no base blocks) for the + request's group on the reports thread, in a copy of the caller's context (the serving profile's + home). *changed_only*: only when the state differs from the one reported last in this process. + Never blocks, never raises; an outcome is dropped while :data:`REPORTS_WAITING_MAX` others wait.""" global _REPORTS, _REPORTS_WAITING run = contextvars.copy_context().run + slot = (request.platform, request.scope_id, request.profile, request.group) + state = None if outcome is None else str(outcome.get("state")) with _LOCK: + if changed_only and slot in _REPORTED and _REPORTED[slot] == state: + return if _REPORTS_WAITING >= REPORTS_WAITING_MAX: return + if len(_REPORTED) >= REPORTED_MAX: + _REPORTED.clear() + _REPORTED[slot] = state if _REPORTS is None: _REPORTS = concurrent.futures.ThreadPoolExecutor(max_workers=1, thread_name_prefix="ctx-base-status") _REPORTS_WAITING += 1 reports = _REPORTS try: - reports.submit(run, _write_report, request, dict(outcome)) + reports.submit(run, _write_report, request, None if outcome is None else dict(outcome)) except RuntimeError: # shut down meanwhile with _LOCK: _REPORTS_WAITING -= 1 -def _write_report(request: _Request, outcome: dict[str, Any]) -> None: +def _write_report(request: _Request, outcome: dict[str, Any] | None) -> None: global _REPORTS_WAITING try: from hermes_constants import get_hermes_home @@ -301,6 +316,9 @@ def _request_of( base blocks or a key, or when a form (for a restricted group also E1) is broken.""" own = fields.get(access.NAMESPACE) if isinstance(fields, Mapping) else None if not isinstance(own, Mapping) or own.get("enabled") is False or not own.get("base_blocks"): + # No base blocks for this group (any more): an entry an earlier outcome left is removed. + plain = _Request(str(platform or ""), str(scope_id or ""), str(group or ""), str(profile or ""), True, None) + _report(plain, None, changed_only=True) return None context = access.AccessContext( platform=str(platform or ""), @@ -327,6 +345,7 @@ def _request_of( ) return None if not parsed.enabled or not parsed.base_blocks: + _report(shown, None, changed_only=True) return None if not parsed.key: _not_delivered(shown, "the group names no key (field key)") @@ -699,15 +718,17 @@ async def on_access_group_fields( if request is None: return None try: - home, settings, core_timeout = await _wait(_submit(DEFAULT_WORKERS, _settings), SETTINGS_BUDGET_S) + home, settings, core_timeout = await _wait(_submit(SETTINGS_WORKERS, _settings), SETTINGS_BUDGET_S) workers = int(settings["base_workers"]) deadline = started + _budget_s(settings, core_timeout) answer = await _wait(_submit(workers, _answer, request, home, settings, deadline), deadline - time.monotonic()) if isinstance(answer, concurrent.futures.Future): answer = await _wait(answer, deadline - time.monotonic()) except BaseBlocksUnavailable as exc: - _report(request, {"state": f"unavailable: {exc}; the core asks again on a later turn"}) + _report(request, {"state": f"unavailable: {exc}; the core asks again on a later turn"}, changed_only=True) raise + if answer: # a cache hit or another call's fetch of the same text: this group has it too + _report(request, {"state": "delivered"}, changed_only=True) return {"prompt": answer} if answer else None diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/config.py b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py index 69b878868..aec58063c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/config.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py @@ -347,15 +347,15 @@ def profile_base_url(hermes_home: str, section: Any = None, servers: Any = None) """The profile's ctx server, for an access group that names no ``base_url`` (design 02 §3.1): the one resolution the group binding and the base-block hook share. The URL the profile's own REST connection takes (``resolve_base_url``: ``CTX_BASE_URL``, then ``ctx_base_url`` of ``ctx.json`` - under the ``memory.ctx_checkpoint`` overlay, whose ``rest_base_url`` covers it as soon as it is - set, as in :func:`overlay_from_umbrella`), then the origin of the MCP server entry + under the ``memory.ctx_checkpoint`` overlay of :func:`overlay_from_umbrella`, where the section's + ``ctx_base_url`` and, as soon as it is set, ``rest_base_url`` cover it), then the origin of the MCP + server entry ``servers[section.mcp_server or "ctx"]``. *section*: ``memory.ctx_checkpoint`` as the caller read it (``None``: the engine without the umbrella, which reads no config.yaml); *servers*: the profile's ``mcp_servers``. ``""`` when none names one. Raises what ``env_secret`` raises.""" section = section if isinstance(section, Mapping) else {} - rest = section.get("rest_base_url") - configured = str(rest).strip() if rest else str(load_ctx_config(hermes_home).get("ctx_base_url") or "") - url = resolve_base_url(configured) + configured = load_ctx_config(hermes_home, overlay=overlay_from_umbrella(dict(section))).get("ctx_base_url") + url = resolve_base_url(str(configured or "")) if url: return url entry = servers.get(str(section.get("mcp_server") or "ctx")) if isinstance(servers, Mapping) else None diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py index 1bfa39cb6..a030daf2c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/status.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py @@ -884,13 +884,24 @@ def _update_access( hermes_home: str, platform: str, scope_id: str, profile: str, change: Callable[[dict[str, Any]], dict[str, Any]] ) -> None: """Read a binding's record, apply *change*, write it back only when it changed (stamped ``since``), - under the lock of the access folder.""" + under the lock of the access folder. A record *change* leaves as it is takes no lock (every agent + build of a governed session records its binding; most of them change nothing).""" path = access_file(hermes_home, platform, scope_id, profile) - with _state_lock(path.parent, ACCESS_LOCK_FILE): - current = _read_json_file(path) or {} - record = change({key: value for key, value in current.items() if key != "since"}) + + def changed() -> dict[str, Any] | None: + current = {key: value for key, value in (_read_json_file(path) or {}).items() if key != "since"} + record = change(dict(current)) record.update(platform=str(platform), scope_id=str(scope_id), profile=str(profile)) - if record == {key: value for key, value in current.items() if key != "since"}: + return None if record == current else record + + if changed() is None: + return + with _state_lock(path.parent, ACCESS_LOCK_FILE): + record = changed() + if record is None: + return + if set(record) <= {"platform", "scope_id", "profile"}: # nothing left to show + path.unlink(missing_ok=True) return record["since"] = _now_text() _write_json_file(path, record) @@ -917,30 +928,44 @@ def record_base_blocks( (``record_access`` keeps it): ``state`` (``delivered``: the text is built and cached — a call that ran out of time meanwhile gets it on its next turn; ``not delivered: <reason>``; ``unavailable: <reason>``, asked again later), ``loaded`` (blocks fetched for the text), ``cut`` (the text reached - ``base_max_chars``) and ``skipped`` (block id → why it is not in the text). Never a block's content - or title, never a key. Written only when it changes (stamped ``at``); at most + ``base_max_chars``) and ``skipped`` (block id → why it is not in the text); *outcome* ``None`` removes + the group's entry (it has no base blocks any more). ``delivered`` says the text went to the core, + which drops a contribution that would take the group's prompt past 8 000 characters. Never a block's + content or title, never a key. Written only when it changes (stamped ``at``); at most :data:`ACCESS_BASE_GROUPS_MAX` groups per binding. Never raises.""" - if not hermes_home or not isinstance(outcome, Mapping) or not isinstance(group, str) or not group: + if not hermes_home or not isinstance(group, str) or not group: return - skipped = outcome.get("skipped") - entry = { - "state": _display_text(outcome.get("state")), - "loaded": outcome.get("loaded") if isinstance(outcome.get("loaded"), int) else 0, - "cut": outcome.get("cut") is True, - "skipped": { - str(block): _display_text(reason) - for block, reason in list(skipped.items() if isinstance(skipped, Mapping) else ())[:ACCESS_LIST_MAX] - if _SCOPE_TEXT_RE.match(str(block)) - }, - } name = group[:64] + entry: dict[str, Any] | None = None + if isinstance(outcome, Mapping): + entry = {"state": _display_text(outcome.get("state"))} + if isinstance(outcome.get("loaded"), int) and not isinstance(outcome.get("loaded"), bool): + entry["loaded"] = outcome["loaded"] + if outcome.get("cut") is True: + entry["cut"] = True + skipped = outcome.get("skipped") + if isinstance(skipped, Mapping) and skipped: + entry["skipped"] = { + str(block): _display_text(reason) + for block, reason in list(skipped.items())[:ACCESS_LIST_MAX] + if _SCOPE_TEXT_RE.match(str(block)) + } def change(record: dict[str, Any]) -> dict[str, Any]: groups = record.get("base_blocks") groups = dict(groups) if isinstance(groups, Mapping) else {} previous = groups.get(name) - if isinstance(previous, Mapping) and {k: v for k, v in previous.items() if k != "at"} == entry: - return record + if entry is None: # the group has no base blocks (any more): no entry + if name not in groups: + return record + groups.pop(name) + out = {key: value for key, value in record.items() if key != "base_blocks"} + return {**out, "base_blocks": groups} if groups else out + if isinstance(previous, Mapping): + kept = {k: v for k, v in previous.items() if k != "at"} + # The same state without the counts (a cache hit) keeps the counts the fetch recorded. + if kept == entry or ("loaded" not in entry and kept.get("state") == entry["state"]): + return record if name not in groups and len(groups) >= ACCESS_BASE_GROUPS_MAX: return record groups[name] = {**entry, "at": _now_text()} @@ -954,24 +979,38 @@ def change(record: dict[str, Any]) -> dict[str, Any]: def read_access(hermes_home: str) -> list[Mapping[str, Any]]: """Every recorded binding of the home, sorted by platform, server and profile, each with ``file`` - (its path below the home). A file that is unreadable, too large or not a record is skipped.""" + (its path below the home). A file that is unreadable, too large or not a record is skipped + (:func:`unreadable_access` names those).""" + return _scan_access(hermes_home)[0] + + +def unreadable_access(hermes_home: str) -> list[str]: + """The status files of the home that :func:`read_access` skips (unreadable, too large, no record).""" + return _scan_access(hermes_home)[1] + + +def _scan_access(hermes_home: str) -> tuple[list[dict[str, Any]], list[str]]: folder = Path(hermes_home) / FACT_STATE_DIR / ACCESS_DIR try: - paths = [path for path in folder.iterdir() if path.suffix == ".json" and path.is_file()] + paths = sorted(path for path in folder.iterdir() if path.suffix == ".json" and path.is_file()) except OSError: - return [] + return [], [] rows: list[dict[str, Any]] = [] + unreadable: list[str] = [] for path in paths: record = _read_json_file(path) - if record is None or not all(isinstance(record.get(key), str) for key in ("platform", "scope_id", "profile")): - continue - if not isinstance(record.get("state", ""), str): + if ( + record is None + or not all(isinstance(record.get(key), str) for key in ("platform", "scope_id", "profile")) + or not isinstance(record.get("state", ""), str) + ): + unreadable.append(f"{FACT_STATE_DIR}/{ACCESS_DIR}/{path.name}") continue record.setdefault("state", "") # only base blocks recorded so far record["file"] = f"{FACT_STATE_DIR}/{ACCESS_DIR}/{path.name}" rows.append(record) rows.sort(key=lambda row: (row["platform"], row["scope_id"], row["profile"])) - return rows + return rows, unreadable def access_class(row: Mapping[str, Any]) -> str: @@ -997,8 +1036,10 @@ def base_block_groups(row: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]: def base_block_line(group: str, entry: Mapping[str, Any]) -> str: """One group's base blocks as ``access status`` names them.""" state = str(entry.get("state") or "?") - if state == "delivered": - state = f"delivered, {entry.get('loaded', 0)} loaded" + (", cut to base_max_chars" if entry.get("cut") else "") + if state == "delivered" and isinstance(entry.get("loaded"), int): + state += f", {entry['loaded']} loaded" + if entry.get("cut"): + state += ", cut to base_max_chars" skipped = entry.get("skipped") if isinstance(skipped, Mapping) and skipped: state += "; skipped: " + ", ".join(f"{block} ({why})" for block, why in sorted(skipped.items())) @@ -1019,15 +1060,21 @@ def access_status(status: dict[str, Any], hermes_home: str, *, own_expected: boo ``local`` and no standard key is configured, so with every group bound the report is ok). Never raises.""" try: - rows = read_access(hermes_home) + rows, unreadable = _scan_access(hermes_home) except Exception: return status - if not rows: + if not rows and not unreadable: return status classes = [access_class(row) for row in rows] bound, unset = classes.count("bound"), classes.count("unset") off = [row for row, kind in zip(rows, classes, strict=True) if kind == "off"] out = dict(status) + if unreadable: # a binding that cannot be read may be one that is off + out["ok"] = False + out["summary"] = ( + f"✗ {len(unreadable)} access-group status files unreadable · own connection: {status.get('summary') or ''}" + ) + out["access_unreadable"] = f"✗ status files that cannot be read: {', '.join(unreadable[:ACCESS_STATUS_LINES])}" missing = [ f"{row['platform']}:{row['scope_id']} {group}" for row in rows @@ -1056,7 +1103,7 @@ def access_status(status: dict[str, Any], hermes_home: str, *, own_expected: boo out["summary"] = ( f"✗ {len(off)} of {len(rows)} access-group bindings off · the profile's own connection: {previous}" ) - elif bound and not own_expected: + elif bound and not own_expected and not unreadable: out["ok"] = True out["summary"] = ( f"✓ access groups: {bound} bound · no connection of the profile's own (ungoverned: off or local)" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py index 877723795..d3376be01 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -9,6 +9,7 @@ import os import re import stat +import time import hermes_yaml import pytest @@ -565,3 +566,96 @@ def test_provision_sends_no_admin_key_over_plain_http_to_another_host(admin, mon assert _provision(home) == 1 out = capsys.readouterr().out assert "https" in out and "nothing was sent" in out + + +# -- fresh review -------------------------------------------------------------------------------------------- + + +def test_provision_without_an_answer_says_the_set_may_exist_and_a_rerun_heals(admin, monkeypatch, capsys): + """No answer in time (the set may be committed, the earlier key of the label already inactive): the + output must not claim nothing was created, and the same command heals it.""" + fake, home = admin + fake.latency["manage:keyset-provision"] = 1.5 + monkeypatch.setattr(cli, "REQUEST_TIMEOUT_S", 0.5) + assert _provision(home) == 1 + out = capsys.readouterr().out + assert "nothing was created" not in out and "unknown" in out and "again" in out + time.sleep(1.3) # the fake's answer to the first call is on its way + fake.latency.clear() + monkeypatch.setattr(cli, "REQUEST_TIMEOUT_S", 30.0) + assert _provision(home) == 0 + (key,) = [k for k in _new_keys(fake) if k.active] + assert (home / ".env").read_text(encoding="utf-8") == f"CTX_KEY_111_MEMBERS={key.secret}\n" + + +def test_provision_keeps_a_line_another_writer_added_while_ctx_answered(admin, monkeypatch): + _fake, home = admin + (home / ".env").write_text("FIRST=1\n", encoding="utf-8") + real = cli._manage_once + + def answer_while_another_writes(url, key, payload): + answer = real(url, key, payload) + with open(home / ".env", "a", encoding="utf-8") as handle: + handle.write("WRITTEN_MEANWHILE=1\n") + return answer + + monkeypatch.setattr(cli, "_manage_once", answer_while_another_writes) + assert _provision(home) == 0 + text = (home / ".env").read_text(encoding="utf-8") + assert text.startswith("FIRST=1\nWRITTEN_MEANWHILE=1\nCTX_KEY_111_MEMBERS="), text + + +def test_provision_refuses_another_profile_than_the_one_it_runs_in(fake_ctx, monkeypatch, tmp_path, capsys): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + home = _home(tmp_path, "operator", config="memory:\n ctx_checkpoint:\n ungoverned: profile\n") + argv = ["provision", "--server", "discord:111", "--profile", "members", "--group", "members"] + assert _run(home, *argv, "--admin-key-env", "CTX_ADMIN") == 2 + assert "hermes -p members" in capsys.readouterr().out + assert fake_ctx.count() == 0 and not (home / ".env").exists() + assert acc.load_settings(str(home))["ungoverned"] == "profile" + + +def test_provision_of_a_url_the_client_does_not_take_sends_nothing(admin, monkeypatch, capsys): + _fake, home = admin + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": "ctx.example.com", "CTX_ADMIN": ADMIN_KEY}) + assert _provision(home) == 1 + assert "nothing was sent" in capsys.readouterr().out and not (home / ".env").exists() + + +def test_provision_takes_only_the_key_it_asked_for(admin, monkeypatch, capsys): + _fake, home = admin + real = cli._manage_once + + def loose(url, key, payload): + answer = real(url, key, payload) + answer["keys"][0]["scope_narrowing"] = "optional" + return answer + + monkeypatch.setattr(cli, "_manage_once", loose) + assert _provision(home) == 1 + assert "again" in capsys.readouterr().out and not (home / ".env").exists() + + +def test_provision_warns_of_the_admin_key_in_the_profile_s_env_and_of_running_sessions(admin, capsys): + _fake, home = admin + (home / ".env").write_text(f"CTX_ADMIN={ADMIN_KEY}\n", encoding="utf-8") + assert _provision(home) == 0 + out = capsys.readouterr().out + assert re.search(r"⚠ .*CTX_ADMIN", out) and ADMIN_KEY not in out + assert "base_rev" in out + + +def test_memory_status_is_not_ok_with_a_status_file_it_cannot_read(operator): + _fake, home = operator + st.record_access(str(home), "discord", "111", "members", BOUND) + (home / "ctx_state" / "access" / "discord-222-members.json").write_text("{broken", encoding="utf-8") + status = Provider(config={"transport": "rest"}).get_status_config({}) + assert status["ok"] is False and "discord-222-members.json" in status["access_unreadable"] + + +def test_check_names_what_it_does_not_prove(member, capsys): + build, _host, home = member + build() + assert _run(home, "check", *MEMBER, *FIELDS, "--field", "base_blocks=abc") == 0 + assert "not checked here" in capsys.readouterr().out diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py index 473636812..15faddbb6 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py @@ -90,7 +90,8 @@ def test_a_broken_rule_is_named_as_the_reason(world): outcome = _call(_fields(ids, "one")) assert outcome.answered and outcome.result is None entry = _base(home) - assert entry.get("state", "").startswith("not delivered:") and "E4" in entry["state"], entry + assert entry.get("state", "").startswith("not delivered:"), entry + assert f"E4: expected label {LABEL}" in entry["state"], "the rule with the value it expected" def test_a_broken_field_is_named_without_a_request(world): @@ -130,3 +131,41 @@ def test_the_binding_s_state_and_the_base_blocks_keep_each_other(world): st.record_access(str(home), "discord", "111", "members", {**bound, "state": "off: E4"}) (row,) = st.read_access(str(home)) assert row["state"] == "off: E4" and row["base_blocks"]["members"]["state"] == "delivered" + + +def _until(predicate, timeout=5.0): + deadline = time.monotonic() + timeout + while not predicate() and time.monotonic() < deadline: + time.sleep(0.02) + return predicate() + + +def _groups(home): + rows = [ + r + for r in st.read_access(str(home)) + if (r["platform"], r["scope_id"], r["profile"]) == ("discord", "111", "members") + ] + return dict(rows[0].get("base_blocks") or {}) if rows else {} + + +def test_a_group_whose_base_blocks_were_taken_away_keeps_no_stale_entry(world): + _fake, _host, ids, home = world + _call(_fields(ids, "one")) + assert _base(home).get("state") == "delivered" + assert _call(_fields(ids, "one", enabled=False)).result is None + assert _until(lambda: "members" not in _groups(home)), _groups(home) + _call(_fields(ids, "one")) + assert _until(lambda: "members" in _groups(home)) + assert _call(_fields(ids)).result is None # no base blocks any more + assert _until(lambda: "members" not in _groups(home)), _groups(home) + + +def test_a_second_group_with_the_same_fields_is_recorded_from_the_cache(world): + fake, _host, ids, home = world + assert _call(_fields(ids, "one")).answered + assert _base(home).get("state") == "delivered" + fake.reset_counters() + outcome = _call(_fields(ids, "one"), group="helpers") + assert outcome.answered and outcome.result and fake.count() == 0, "a cache hit" + assert _until(lambda: (_groups(home).get("helpers") or {}).get("state") == "delivered"), _groups(home) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py index 9b922693f..ad5f48cd2 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py @@ -2,24 +2,56 @@ P-D's load script on the merged plugin (2 000 groups, 16 base blocks each, 200 ms on ``whoami`` and ``get``, multi-id get, a restart of every session at once, 30 turns): 16 threads gave every group its text after 28 turns, 32 threads after 18 (two runs each); the threads wait on the network, so the default -is the measured upper end of the setting.""" +is the measured upper end of the setting. A profile that sets fewer gets fewer: the pool starts small +and grows to the largest ``base_workers`` a serving profile set.""" from __future__ import annotations +import asyncio + +import pytest from fakes import access_host as ah _PKG = ah.load_plugin("ctx_checkpoint_access_seam_base_workers") acc = ah.plugin_module(_PKG, "memory.access") bb = ah.plugin_module(_PKG, "memory.base_blocks") +_nar = ah.plugin_module(_PKG, "memory.narrowing") + +K, M = "t:d111-k", "t:d111-members" +MEMBER_KEY = "ctx_member_111_workers_secret" def test_the_base_block_pool_defaults_to_32_threads(tmp_path): assert acc.SETTINGS_DEFAULTS["base_workers"] == 32 - assert bb.DEFAULT_WORKERS == 32, "the pool the first settings read runs on" (tmp_path / "config.yaml").write_text("memory:\n ctx_checkpoint: {}\n", encoding="utf-8") assert acc.load_settings(str(tmp_path))["base_workers"] == 32 -def test_a_profile_still_sets_fewer(tmp_path): - (tmp_path / "config.yaml").write_text("memory:\n ctx_checkpoint:\n base_workers: 4\n", encoding="utf-8") - assert acc.load_settings(str(tmp_path))["base_workers"] == 4 +@pytest.fixture +def hook(fake_ctx, monkeypatch, _isolated_hermes_home): + bb.reset_state() + _nar.reset_proofs() + label = "hermes:discord:111:members" + fake_ctx.add_key(secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=label) + block = fake_ctx.add_block(K, "House rules", "Be kind.") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + fields = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M, "base_blocks": [block]} + + def call(settings: str) -> int: + bb.reset_state() + (_isolated_hermes_home / "config.yaml").write_text( + "platform_toolsets:\n discord: [web]\nmemory:\n ctx_checkpoint:\n" + settings, encoding="utf-8" + ) + kwargs = ah.hook_kwargs(fields={"ctx_checkpoint": fields}) + outcome = asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, timeout=30.0, **kwargs)) + assert outcome.answered and outcome.result, outcome + return bb._POOL_SIZE + + yield call + bb.reset_state() + _nar.reset_proofs() + + +def test_a_profile_s_base_workers_sizes_the_pool(hook): + assert hook(" base_workers: 4\n") == 4 + assert hook(" {}\n") == 32 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py index 95bcd5f83..8de2c6baf 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py @@ -72,6 +72,13 @@ def _binding_url(home, provider_class=Provider): "https://mcp.example:8443", id="rest_base_url of blanks covers ctx.json as for the profile's own connection", ), + pytest.param( + "memory:\n ctx_checkpoint:\n ctx_base_url: https://section.example/\n" + MCP, + "https://json.example", + {}, + "https://section.example", + id="the section's ctx_base_url over ctx.json as for the profile's own connection", + ), pytest.param("mcp_servers:\n ctx:\n command: ctx-mcp\n", None, {}, "", id="no URL anywhere"), ] From 8627a10d351dcee72f48b434459d143e56fabb72 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:08:39 +0100 Subject: [PATCH 16/65] fix(ctx_checkpoint): the access-group markers survive the state pruning, and no session ledger takes their name The monotone markers (ctx_state/access-mode.json) only rise; access reset-marker is the one way down. digest.prune_state_dir removed every top-level *.json untouched for state_retention_days (default 30), and set markers are never written again: after 30 days the first initialize of a process deleted them before it decided, so row 1 of the decision table (Hermes without the access groups, for example after a rollback) gave the profile's own connection instead of off, and ungoverned: auto went back to profile in a profile that serves governed servers. The pruning now keeps config.KEPT_STATE_FILES (compared case-insensitively). A fact ledger is ctx_state/<root>.json: a session whose root id is access-mode wrote its ledger over the markers file, or created one that counts as both markers set. _safe_root now gives such a root its hash suffix, as it does for every root it has to change. access.MARKERS_FILE is built from config (same value). New tests hold every path that deletes or overwrites under ctx_state/, including the real entrance (initialize prunes before it decides) and that only access reset-marker calls reset_markers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/access.py | 7 +- .../plugin/ctx_checkpoint/memory/config.py | 15 +- .../plugin/ctx_checkpoint/memory/digest.py | 8 +- .../tests/test_access_seam_marker_keep.py | 182 ++++++++++++++++++ 4 files changed, 205 insertions(+), 7 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_marker_keep.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py index 30f9b43f1..03a4774a2 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -40,7 +40,7 @@ from typing import Any, Literal from urllib.parse import urlsplit -from .config import derive_profile_name +from .config import FACT_STATE_DIR, MARKERS_FILE_NAME, derive_profile_name try: import fcntl @@ -54,8 +54,9 @@ # The hook the core fires before a governed server's turn (gateway/access_prompt.py). HOOK_NAME = "access_group_fields" -# The profile's markers (``read_markers``, ``raise_markers``, ``reset_markers``), under the home. -MARKERS_FILE = "ctx_state/access-mode.json" +# The profile's markers (``read_markers``, ``raise_markers``, ``reset_markers``), under the home +# (``ctx_state/access-mode.json``; the state pruning keeps it, ``config.KEPT_STATE_FILES``). +MARKERS_FILE = f"{FACT_STATE_DIR}/{MARKERS_FILE_NAME}" # Platforms of a local, interactive session (``ungoverned: local`` admits them; forks only when # their parent session was local). diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/config.py b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py index aec58063c..e12f85b87 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/config.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py @@ -126,6 +126,13 @@ def untrusted_origin_note(origin: str) -> str: # cumulative ``fact_hashes`` list in chain head/manifest metadata lives in checkpoint.py. FACT_STATE_DIR = "ctx_state" FACT_LEDGER_MAX = 500 # keys per root (FIFO) +# The access-group markers (``access.MARKERS_FILE``): they only rise, and only ``access reset-marker`` +# lowers them (design 02 §3.6). Files of ``ctx_state/`` that belong to no session: the state pruning +# keeps them and no session's ledger takes their name (compared case-insensitively, as a +# case-insensitive file system would). +MARKERS_FILE_NAME = "access-mode.json" +KEPT_STATE_FILES = frozenset({MARKERS_FILE_NAME}) + # P5: session digests per segment. Plan thresholds: ≥ 4 exchanges since the last digest, # rolling digest after 40 exchanges or 6 h; idle digest after 6 h without a turn. @@ -834,10 +841,16 @@ def extract_salient_facts( # --------------------------------------------------------------------------- +def kept_state_file(name: str) -> bool: + """Whether *name* (a file name under ``ctx_state/``) is one of :data:`KEPT_STATE_FILES`.""" + folded = str(name).casefold() + return any(folded == kept.casefold() for kept in KEPT_STATE_FILES) + + def _safe_root(root: str) -> str: raw = str(root or "unknown") safe = re.sub(r"[^A-Za-z0-9_.-]", "_", raw)[:80] - if safe != raw: + if safe != raw or kept_state_file(f"{safe}.json"): # a ledger never takes the markers' name safe += "-" + hashlib.sha256(raw.encode("utf-8")).hexdigest()[:8] return safe diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/digest.py b/integrations/hermes/plugin/ctx_checkpoint/memory/digest.py index 9b599bb0a..e54db852a 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/digest.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/digest.py @@ -27,7 +27,7 @@ from typing import Any from urllib.parse import quote -from .config import FACT_STATE_DIR, _safe_root +from .config import FACT_STATE_DIR, _safe_root, kept_state_file logger = logging.getLogger(__name__) @@ -234,7 +234,9 @@ def _get(row_id: str) -> dict[str, Any] | None: def prune_state_dir(hermes_home: str, max_age_days: float, *, now: float | None = None) -> int: """Delete ``ctx_state`` files (ledgers, digest states, stale temp files) not modified for - ``max_age_days``. 0/negative = off. Returns the number of removed files. Never raises.""" + ``max_age_days``. 0/negative = off. Returns the number of removed files. Never raises. The + access-group markers (``config.KEPT_STATE_FILES``) are no session's state and stay: set markers + are never written again, so their age says nothing.""" if not hermes_home or not max_age_days or max_age_days <= 0: return 0 base = Path(hermes_home) / FACT_STATE_DIR @@ -248,7 +250,7 @@ def prune_state_dir(hermes_home: str, max_age_days: float, *, now: float | None return 0 for entry in entries: name = entry.name - if not (name.endswith(".json") or name.startswith((".ledger-", ".digest-"))): + if not (name.endswith(".json") or name.startswith((".ledger-", ".digest-"))) or kept_state_file(name): continue try: if entry.is_file() and entry.stat().st_mtime < cutoff: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_marker_keep.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_marker_keep.py new file mode 100644 index 000000000..cfc22f133 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_marker_keep.py @@ -0,0 +1,182 @@ +"""Seam P-B/P-E: the monotone access-group markers (``ctx_state/access-mode.json``, design 02 §3.6, +A02-L11) survive every path that deletes or overwrites files under ``ctx_state/``. Only ``access +reset-marker`` lowers them. + +The paths, each held here or where named: + +- ``digest.prune_state_dir`` (``state_retention_days``, default 30, run by the first ``initialize`` of a + process per home, before the access decision): it removed every top-level ``*.json`` untouched for the + retention, and set markers are never written again. Afterwards row 1 of the decision table (a Hermes + without the core PR, for example after a rollback) gave the profile's own connection instead of + ``off``, and ``ungoverned: auto`` went back to ``profile`` in a profile that serves governed servers. +- ``config.FactLedger`` writes ``ctx_state/<root>.json``: a session whose root id is ``access-mode`` + wrote its ledger over the markers file (and, with no markers set, created one that counts as both + set: a profile cut off ctx by a session id). +- ``access.reset_markers``: called by ``access reset-marker`` only (held below). +- Error paths of ``access.raise_markers`` (unreadable file, full disk, busy lock): never lower a marker + (``tests/test_access_pb_rules.py``, the marker tests from ``test_marker_files_of_unknown_form_count_as_set`` + to ``test_reset_lowers_only_the_named_marker_even_from_an_unreadable_file``). +- The access status files (``ctx_state/access/``, ``ctx_state/access-sessions.state``) and the outcome + file (``ctx_state/checkpoint-status.state``) have their own names; the pruning keeps them (held below + and in ``tests/test_settings_and_status.py::test_the_outcome_file_survives_state_pruning``). +""" + +from __future__ import annotations + +import ast +import os +import time +from pathlib import Path + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_marker_keep") +acc = ah.plugin_module(_PKG, "memory.access") +cfg = ah.plugin_module(_PKG, "memory.config") +dg = ah.plugin_module(_PKG, "memory.digest") +Provider = _PKG.CtxCheckpointMemoryProvider + +DAYS = cfg.DEFAULT_STATE_RETENTION_DAYS + + +def _age(path: Path, days: float) -> None: + stale = time.time() - days * 86400 + os.utime(path, (stale, stale)) + + +def _markers(home: Path) -> Path: + return home / acc.MARKERS_FILE + + +def test_the_pruning_keeps_the_markers(tmp_path): + acc.raise_markers(str(tmp_path), restricted_seen=True, governed_seen=True) + ledger = tmp_path / "ctx_state" / "old-root.json" + ledger.write_text("{}", encoding="utf-8") + _age(_markers(tmp_path), DAYS + 1) + _age(ledger, DAYS + 1) + + removed = dg.prune_state_dir(str(tmp_path), DAYS) + + assert removed == 1 and not ledger.exists(), "the pruning still removes an old ledger" + assert _markers(tmp_path).is_file() + assert acc.read_markers(str(tmp_path)) == acc.Markers(restricted_seen=True, governed_seen=True) + + +@pytest.mark.parametrize("name", ["ACCESS-MODE.JSON", "Access-Mode.json"]) +def test_the_pruning_keeps_the_markers_under_another_case(tmp_path, name): + """A case-insensitive file system lists the file under the case it was created with.""" + state = tmp_path / "ctx_state" + state.mkdir() + path = state / name + path.write_text('{"restricted_seen": true, "governed_seen": true}', encoding="utf-8") + _age(path, DAYS + 1) + assert dg.prune_state_dir(str(tmp_path), DAYS) == 0 and path.is_file() + + +def test_the_pruning_keeps_the_access_status_files(tmp_path): + state = tmp_path / "ctx_state" + (state / "access").mkdir(parents=True) + kept = [ + state / "access" / "discord-111-members.json", + state / "access-sessions.state", + state / "access-mode.lock", + state / "access.lock", + ] + for path in kept: + path.write_text("{}", encoding="utf-8") + _age(path, DAYS + 1) + _age(state / "access", DAYS + 1) + dg.prune_state_dir(str(tmp_path), DAYS) + assert all(path.exists() for path in kept) + + +def test_row_one_stays_off_after_the_pruning(tmp_path): + """Hermes without the core PR (rolled back after running with it): a profile that once served a + restricted group stays off on every path without the argument.""" + home = str(tmp_path) + acc.raise_markers(home, restricted_seen=True) + init = {"platform": "discord", "agent_context": "primary", "hermes_home": home} + settings = dict(acc.SETTINGS_DEFAULTS) + assert acc.decide(init, None, None, settings, acc.read_markers(home), False).kind == "off" + + _age(_markers(tmp_path), DAYS + 1) + dg.prune_state_dir(home, DAYS) + + assert acc.decide(init, None, None, settings, acc.read_markers(home), False).kind == "off" + + +def test_auto_stays_local_after_the_pruning(tmp_path): + """``ungoverned: auto`` in a profile that served a governed server: cron stays off.""" + home = str(tmp_path) + acc.raise_markers(home, governed_seen=True) + init = {"platform": "cron", "agent_context": "cron", "hermes_home": home} + settings = dict(acc.SETTINGS_DEFAULTS) + assert acc.decide(init, None, None, settings, acc.read_markers(home), True).kind == "off" + + _age(_markers(tmp_path), DAYS + 1) + dg.prune_state_dir(home, DAYS) + + assert acc.decide(init, None, None, settings, acc.read_markers(home), True).kind == "off" + + +def test_the_first_initialize_of_a_process_keeps_old_markers(monkeypatch, tmp_path, fake_ctx): + """The real entrance: ``initialize`` prunes (once per process and home) before it decides. A + messaging session on a Hermes without the core PR in a profile with ``restricted_seen`` is off, + also when the markers file is older than the retention (without it, the profile's own key).""" + fake_ctx.add_key(secret="ctx_profile_key_ops", tenant="t", home="t:ops") + ah.install(monkeypatch, v8=False, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY": "ctx_profile_key_ops"}) + home = tmp_path / "profiles" / "ops" + home.mkdir(parents=True) + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n ungoverned: auto\n", encoding="utf-8") + acc.raise_markers(str(home), restricted_seen=True) + _age(_markers(home), DAYS + 1) + + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize("s-old", hermes_home=str(home), platform="discord", agent_context="primary") + + assert acc.read_markers(str(home)).restricted_seen is True + assert provider._decision is not None and provider._decision.kind == "off" + assert provider._access_off and provider._client is None + + +@pytest.mark.parametrize("root", ["access-mode", "ACCESS-MODE", "Access-Mode"]) +def test_a_session_named_like_the_markers_keeps_its_ledger_apart(tmp_path, root): + home = str(tmp_path) + ledger = cfg.FactLedger(home, root) + ledger.add(["fact-key"]) + + assert not _markers(tmp_path).exists(), "no session creates the markers file" + assert acc.read_markers(home) == acc.Markers() + assert ledger.path.name.casefold() != Path(acc.MARKERS_FILE).name.casefold() + assert cfg.FactLedger(home, root).keys() == ["fact-key"], "the ledger is found again under its name" + + +def test_a_session_named_like_the_markers_leaves_set_markers_as_they_are(tmp_path): + home = str(tmp_path) + acc.raise_markers(home, restricted_seen=True) + before = _markers(tmp_path).read_bytes() + cfg.FactLedger(home, "access-mode").add(["fact-key"]) + assert _markers(tmp_path).read_bytes() == before + + +def test_the_markers_file_is_a_kept_state_file(): + path = Path(acc.MARKERS_FILE) + assert path.parent.as_posix() == cfg.FACT_STATE_DIR and path.name in cfg.KEPT_STATE_FILES + + +def test_only_the_reset_marker_command_lowers_a_marker(): + """``reset_markers`` is called from ``access reset-marker`` only; nothing else writes the file.""" + calls: dict[str, list[str]] = {} + for path in sorted(ah.PLUGIN_DIR.rglob("*.py")): + if "tests" in path.relative_to(ah.PLUGIN_DIR).parts: + continue + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Call): + func = node.func + name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "") + if name in ("reset_markers", "_write_markers"): + calls.setdefault(name, []).append(path.relative_to(ah.PLUGIN_DIR).as_posix()) + assert calls.get("reset_markers") == ["memory/access_cli.py"] + assert sorted(calls.get("_write_markers", [])) == ["memory/access.py", "memory/access.py"] From 3080ab19506b2b7bcbe5aa0fb79af7b6a1425ce6 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:15:36 +0100 Subject: [PATCH 17/65] fix(ctx_checkpoint): a status record that cannot be written leaves the access decision, the binding and the hook's answer as they are The provider records messaging sessions without an access group for access status and access check (display only). Its call in _decide_access stood outside any guard: whatever escaped the writer aborted initialize after the decision and before the binding, so the session lost ctx (off, "the latest initialize did not finish") for a status line. The call is guarded now. New tests hold every status writer in a decision, binding or hook path against the faults a profile home can have (a full disk, a file where the folder or file belongs, a lock that is a folder) and against a writer that raises: the session gets what it gets on a healthy disk (decision, reason, off state, client, bound scopes; the hook's prompt), and initialize returns. The writer of the binding's state and the hook's reports thread already held; only the session record did not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/provider.py | 5 +- .../tests/test_access_seam_display.py | 220 ++++++++++++++++++ 2 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_display.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 355d13ba4..03ef483d1 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -764,7 +764,10 @@ def _decide_access(self, kwargs: Mapping[str, Any]) -> None: self._access_settings = settings self._decision = decision if decision.context is None: # display only (``access status``, ``access check``) - _status.record_session_without_access(home, self._platform, self._agent_context, decision.kind) + try: # a display never breaks the build whose decision it shows + _status.record_session_without_access(home, self._platform, self._agent_context, decision.kind) + except Exception: + logger.debug("CTX session without an access group not recorded", exc_info=True) context = self._access_context() self._bound_turn = _turn_key(context) if context is not None else None self._access_off = "" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_display.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_display.py new file mode 100644 index 000000000..3bfcb2cbd --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_display.py @@ -0,0 +1,220 @@ +"""Seam P-C/P-D/P-E: what only shows (status files for ``hermes memory status`` and ``access status``) +neither changes nor breaks a decision, a binding or the base-block hook's answer. + +The writers P-E hung into those paths: ``status.record_session_without_access`` in the provider's access +decision (``_decide_access``), ``status.record_access`` through ``_record_access_state`` in the decision and +the group binding, and ``status.record_base_blocks`` through ``base_blocks._report`` in the hook. Each is +held here with the faults a profile home can have (a file where the folder or file belongs, a full disk) and +with the writer raising outright: the session gets what it gets with a healthy disk, nothing more, nothing +less, and ``initialize`` returns. +""" + +from __future__ import annotations + +import asyncio + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_display") +_prov = ah.plugin_module(_PKG, "memory.provider") +st = ah.plugin_module(_PKG, "memory.status") +bb = ah.plugin_module(_PKG, "memory.base_blocks") +_nar = ah.plugin_module(_PKG, "memory.narrowing") +Provider = _PKG.CtxCheckpointMemoryProvider + +PROFILE_KEY = "ctx_profile_key_display" +K, M = "t:d111-k", "t:d111-members" +MEMBER_KEY = "ctx_member_111_display" +LABEL = "hermes:discord:111:members" +MEMBER_FIELDS = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M} +WRONG_KEY = "ctx_member_111_display_wrong_label" +# A group whose proof fails (E4: the key's label names another profile) and one whose fields fail +# before any proof (a read scope outside the tenant): both are off with a state for the operator. +BINDINGS = { + "bound": MEMBER_FIELDS, + "off at the proof": {**MEMBER_FIELDS, "key": "CTX_KEY_111_WRONG"}, + "off at the fields": {**MEMBER_FIELDS, "tenant": "other"}, +} + + +def _full_disk(*_args, **_kwargs): + raise OSError(28, "No space left on device") + + +def _raise(*_args, **_kwargs): + raise RuntimeError("a display writer failed") + + +def _state(provider) -> tuple: + decision = provider._decision + group = provider._group + return ( + decision.kind if decision is not None else None, + decision.reason if decision is not None else None, + provider._access_off, + provider._active, + provider._client is not None, + None if group is None else (group.read, group.write), + ) + + +# -- the access decision: a messaging session that serves no access group -------------------------- + + +@pytest.fixture +def plain(fake_ctx, monkeypatch, tmp_path): + """A Hermes without the core PR, a Discord session on the profile's own connection.""" + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:ops") + ah.install(monkeypatch, v8=False, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY": PROFILE_KEY}) + _nar.reset_proofs() + + def make(name: str): + home = tmp_path / "profiles" / name + home.mkdir(parents=True) + (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n ungoverned: auto\n", encoding="utf-8") + return home + + yield make + _nar.reset_proofs() + + +def _plain_session(home): + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize("s-display", hermes_home=str(home), platform="discord", agent_context="primary") + return provider + + +def test_a_healthy_disk_records_the_session_and_connects(plain): + home = plain("healthy") + provider = _plain_session(home) + assert _state(provider)[:5] == ("profile", provider._decision.reason, "", True, True) + assert st.read_sessions_without_access(str(home)).get("discord", {}).get("profile") + + +@pytest.mark.parametrize("fault", ["writer raises", "full disk", "file is a folder", "lock is a folder"]) +def test_a_failing_session_record_changes_nothing_of_the_decision(plain, monkeypatch, fault): + expected = _state(_plain_session(plain("healthy"))) + home = plain("faulty") + state = home / "ctx_state" + if fault == "writer raises": + monkeypatch.setattr(st, "record_session_without_access", _raise) + elif fault == "full disk": + monkeypatch.setattr(st, "_write_json_file", _full_disk) + elif fault == "file is a folder": + (state / st.ACCESS_SESSIONS_FILE).mkdir(parents=True) + else: + (state / st.ACCESS_LOCK_FILE).mkdir(parents=True) + + provider = _plain_session(home) # returns: the display does not break initialize + + assert _state(provider) == expected + if fault in ("full disk", "file is a folder"): + assert not st.read_sessions_without_access(str(home)), "nothing was recorded" + + +# -- the group binding: its state for the operator --------------------------------------------------- + + +@pytest.fixture +def member(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL) + fake_ctx.add_key( + secret=WRONG_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL + "-else" + ) + secrets = {"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY, "CTX_KEY_111_WRONG": WRONG_KEY} + ah.install(monkeypatch, v8=True, secrets=secrets) + _nar.reset_proofs() + + def make(name: str): + home = tmp_path / name / "profiles" / "members" # the profile is "members" (E4's label) + home.mkdir(parents=True) + (home / "config.yaml").write_text("platform_toolsets:\n discord: [web]\n", encoding="utf-8") + return home + + yield make + _nar.reset_proofs() + + +def _member_session(home, fields=MEMBER_FIELDS): + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize( + "s-member", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="members", group_restricted=True, fields=fields), + ) + return provider + + +@pytest.mark.parametrize("binding", sorted(BINDINGS)) +@pytest.mark.parametrize("fault", ["writer raises", "full disk", "folder is a file"]) +def test_a_failing_binding_record_changes_nothing_of_the_binding(member, monkeypatch, binding, fault): + fields = BINDINGS[binding] + healthy = member("healthy") + expected = _state(_member_session(healthy, fields)) + assert (expected[0], bool(expected[2])) == { + "bound": ("group", False), + "off at the proof": ("group", True), + "off at the fields": ("off", True), + }[binding] + assert st.read_access(str(healthy)), "a healthy disk records the binding's state" + home = member("faulty") + if fault == "writer raises": + monkeypatch.setattr(st, "record_access", _raise) + elif fault == "full disk": + monkeypatch.setattr(st, "_write_json_file", _full_disk) + else: + (home / "ctx_state").mkdir() + (home / "ctx_state" / st.ACCESS_DIR).write_text("a file where the folder belongs", encoding="utf-8") + + assert _state(_member_session(home, fields)) == expected + + +# -- the base-block hook: its outcome for the operator ------------------------------------------------ + + +@pytest.fixture +def world(fake_ctx, monkeypatch, _isolated_hermes_home): + bb.reset_state() + _nar.reset_proofs() + home = _isolated_hermes_home + (home / "config.yaml").write_text("platform_toolsets:\n discord: [web]\n", encoding="utf-8") + fake_ctx.add_key(secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL) + block = fake_ctx.add_block(K, "House rules", "be kind") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + yield {"ctx_checkpoint": {**MEMBER_FIELDS, "base_blocks": [block]}} + bb.reset_state() + _nar.reset_proofs() + + +def _call(fields): + kwargs = ah.hook_kwargs(fields=fields) + return asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, timeout=30.0, **kwargs)) + + +class _NoThread: + def submit(self, *_args, **_kwargs): + raise RuntimeError("can't start new thread") + + def shutdown(self, *_args, **_kwargs): + return None + + +@pytest.mark.parametrize("fault", ["writer raises", "full disk", "no reports thread"]) +def test_a_failing_base_block_record_changes_nothing_of_the_answer(world, monkeypatch, fault): + expected = _call(world) + assert expected.answered and "be kind" in expected.result["prompt"] + bb.reset_state() + _nar.reset_proofs() + if fault == "writer raises": + monkeypatch.setattr(st, "record_base_blocks", _raise) + elif fault == "full disk": + monkeypatch.setattr(st, "_write_json_file", _full_disk) + else: + monkeypatch.setattr(bb, "_REPORTS", _NoThread()) + + outcome = _call(world) + + assert (outcome.answered, outcome.result, outcome.error) == (True, expected.result, None) From ea4434d88419df2a641a2689a835b75bc411d0fa Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:21:48 +0100 Subject: [PATCH 18/65] test(ctx_checkpoint): S3 runs against a real ctxd with scope narrowing and against Hermes with access groups Two opt-in test modules for the access-group binding, run against the real counterparts instead of the fakes; both skip in the workflow's umbrella suite. test_s3_real_ctxd.py (CTX_S3_URL, CTX_S3_ADMIN_KEY: a throwaway ctxd on an empty database): access provision through keyset-provision, the strict proof against the real whoami with every broken rule failing closed, a lost echo or lost narrowing headers ending the client, a group reading only its read set and writing only its write scope, the base-block hook asking once with ids and leaving out what the group may not read, the write limit read from whoami, an incoming tenant grant turning a restricted binding off; CTX_S3_SERVER=before-c1 checks that a server without narrowing binds nothing. test_s3_core_contract.py with s3_core_child.py (CTX_S3_HERMES_SRC: a Hermes tree with access groups): fields and hook register in every served profile, all five access values reach initialize, the hook runs with restricted in the serving profile's secret scope and ends before the core's timeout, /background, delegate_task and the memory worker see the group, R7 admits a restricted profile exactly when the group carries the fields; a strict xfail pins that a delegate child of a CLI session is off under ungoverned: local. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ctx_checkpoint/tests/s3_core_child.py | 724 +++++++++++ .../tests/test_s3_core_contract.py | 247 ++++ .../ctx_checkpoint/tests/test_s3_real_ctxd.py | 1086 +++++++++++++++++ 3 files changed, 2057 insertions(+) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py b/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py new file mode 100644 index 000000000..9f5cd0d2e --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py @@ -0,0 +1,724 @@ +"""Child process of ``test_s3_core_contract.py``: ctx_checkpoint inside Hermes with access groups (the +core PR), through Hermes' own entry points. Not a pytest module. + +Hermes binds its plugin registry, field registry and hook table at import, so every scenario runs in a +process of its own: ``HOME`` and ``HERMES_HOME`` point into a fresh directory (the default profile +``<root>/.hermes`` and the profile ``members`` under it), the plugin is copied into each profile's +``plugins/`` and loaded by Hermes' discovery, and ctx is the fake server of ``tests/fakes/ctx_server.py`` +on 127.0.0.1 (no other network). What is real: discovery and ``register()``, the access-group table read +from config.yaml, admission (``GatewayRunner._handle_message``), the baseline check of a restricted +profile (``gateway.access_check``), the profile runtime and secret scope +(``gateway.run._async_profile_runtime_scope``), pre-agent setup (``run_preagent_setup`` → ``turn_prompt`` +→ ``ainvoke_hook_callback``), the agent build (``run_agent.AIAgent`` → ``MemoryManager`` → +``initialize``), ``/background`` (``_run_background_task``) and the sub-agent build of ``delegate_task`` +(``agent.subagents.spawn._build_child_agent``). Stubbed: the model client (``OpenAI``), tool schemas, the +session store and the steps of setup around the prompt (as Hermes' own tests of these paths stub them). + +Usage: ``python -B s3_core_child.py <scenario> <root>``; the last line of the output is a JSON summary. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import os +import shutil +import sys +import threading +import time +from pathlib import Path +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +TESTS = Path(__file__).resolve().parent +PLUGIN = TESTS.parent +GUILD = "100000000000000001" +OWNER, MEMBER = "200000000000000002", "300000000000000003" +CHAT = "700000000000000007" +K, M_SCOPE, B_SCOPE = "t:d1-k", "t:d1-members", "t:d2-k" +KEY_VAR = f"CTX_KEY_{GUILD}_MEMBERS" +MEMBER_KEY = "ctx_member_s3_secret_value_0001" +DEFAULT_KEY = "ctx_default_s3_secret_value_0002" # the same variable name in the default profile's .env +LABEL = f"hermes:discord:{GUILD}:members" +ACCESS_KEYS = ("scope_id", "access_group", "access_group_restricted", "access_fields", "restricted_profile") +UNSET = "<absent>" + + +def _yaml(data: Any) -> str: + import hermes_yaml as yaml + + return yaml.safe_dump(data) + + +class World: + """The homes, the fake ctx server and the spies of one scenario.""" + + def __init__( + self, + root: Path, + *, + members_fields: Any = "default", + hook_timeout: float | None = None, + latency: dict[str, float] | None = None, + checkpoint_required: bool = False, + members_extra: dict[str, Any] | None = None, + ) -> None: + sys.path.insert(0, str(TESTS)) + from fakes.ctx_server import FakeCtx + + self.root = root + self.home = Path(os.environ["HERMES_HOME"]) + self.members = self.home / "profiles" / "members" + self.members.mkdir(parents=True, exist_ok=True) + self.fake = FakeCtx().start() + self.fake.add_key( + secret=MEMBER_KEY, + tenant="t", + home=M_SCOPE, + allowed=(K,), + scope_narrowing="required", + label=LABEL, + role="member", + ) + self.fake.add_key( + secret=DEFAULT_KEY, + tenant="t", + home=B_SCOPE, + allowed=(), + scope_narrowing="required", + label=f"hermes:discord:{GUILD}:default", + role="member", + ) + self.ids = { + "one": self.fake.add_block(K, "House rules", "Be kind to each other."), + "foreign": self.fake.add_block(B_SCOPE, "Server B notes", "bravo-foreign-text"), + "own": self.fake.add_block(M_SCOPE, "Member chatter", "said by a member"), + } + if latency: + self.fake.latency.update(latency) + fields = members_fields + if fields == "default": + fields = { + "ctx_checkpoint": { + "key": KEY_VAR, + "tenant": "t", + "read": [K], + "write": M_SCOPE, + "base_blocks": [self.ids["one"], self.ids["foreign"], self.ids["own"]], + } + } + operators = {"name": "operators", "users": [OWNER], "profile": "default", "restricted": False, "admin": True} + members = {"name": "members", "roles": [GUILD], "profile": "members", "prompt": "Be brief."} + if fields is not None: + members["fields"] = fields + self.groups = [operators, members] + root_config = { + "gateway": {"multiplex_profiles": True, "access_groups": {"discord": {GUILD: {"groups": self.groups}}}}, + "memory": {"provider": "ctx_checkpoint", "ctx_checkpoint": {"ungoverned": "off"}}, + } + # The restricted profile of Hermes' documented recipe (tests/gateway/test_access_check.py ``_recipe``), + # with ctx_checkpoint as its memory provider and no default key (``ungoverned: off``). + members_config: dict[str, Any] = { + "platform_toolsets": {"discord": []}, + "platform_toolsets_exact": ["discord"], + "context_references": {"enabled": False}, + "gateway": {"strict": True, "trust_recent_files": False, "media_delivery_caches": "none"}, + "discord": {"history_backfill": False}, + "terminal": {"cwd": str(self.members / "workspace")}, + "memory": { + "provider": "ctx_checkpoint", + "memory_enabled": False, + "user_profile_enabled": False, + "ctx_checkpoint": {"ungoverned": "off"}, + }, + "approvals": {"mode": "manual"}, + } + if hook_timeout is not None: + members_config["plugins"] = {"hook_callback_timeout": hook_timeout} + if checkpoint_required: + members_config["compression"] = {"checkpoint_required": True} + root_config["compression"] = {"checkpoint_required": True} + for key, value in (members_extra or {}).items(): + members_config[key] = value + # R6 refuses a working directory inside a git repository rooted outside the profile's home; a run + # from a checkout lies in one. A marker makes the workspace its own root (a real ~/.hermes has none). + (self.members / "workspace" / ".git").mkdir(parents=True, exist_ok=True) + (self.home / "config.yaml").write_text(_yaml(root_config), encoding="utf-8") + (self.members / "config.yaml").write_text(_yaml(members_config), encoding="utf-8") + (self.home / ".env").write_text(f"CTX_BASE_URL={self.fake.url}\n{KEY_VAR}={DEFAULT_KEY}\n", encoding="utf-8") + (self.members / ".env").write_text(f"CTX_BASE_URL={self.fake.url}\n{KEY_VAR}={MEMBER_KEY}\n", encoding="utf-8") + for home in (self.home, self.members): + shutil.copytree( + PLUGIN, home / "plugins" / "ctx_checkpoint", ignore=shutil.ignore_patterns("tests", "__pycache__") + ) + self.hook_calls: list[dict[str, Any]] = [] + self.inits: list[dict[str, Any]] = [] + self.patches: list[Any] = [] + self._spy() + + # -- spies (record, then call the real thing) --------------------------------------------------- + + def _spy(self) -> None: + from agent.memory_manager import MemoryManager + from hermes_cli.plugins import PluginManager + + calls, inits = self.hook_calls, self.inits + real_ainvoke = PluginManager.ainvoke_hook_callback + + async def ainvoke(manager, hook, callback, **kwargs): + started = time.monotonic() + answered, result = await real_ainvoke(manager, hook, callback, **kwargs) + calls.append( + { + "hook": hook, + "callback": getattr(callback, "__module__", "?") + "." + getattr(callback, "__name__", "?"), + "restricted": kwargs.get("restricted", UNSET), + "kwargs": sorted(kwargs), + "profile": kwargs.get("profile"), + "group": kwargs.get("group"), + "fields": sorted(kwargs.get("fields") or {}), + "answered": answered, + "prompt": (result or {}).get("prompt") if isinstance(result, dict) else None, + "seconds": round(time.monotonic() - started, 3), + } + ) + return answered, result + + real_init = MemoryManager.initialize_for_agent + + def initialize_for_agent(manager, *args, **kwargs): + out = real_init(manager, *args, **kwargs) + record = {key: _plain(kwargs.get(key, UNSET)) for key in ACCESS_KEYS} + record.update({key: kwargs.get(key, UNSET) for key in ("platform", "agent_context", "agent_identity")}) + record["thread"] = threading.current_thread().name + record["decisions"] = [_decision(p) for p in getattr(manager, "providers", [])] + inits.append(record) + return out + + for target, attr, value in ( + (PluginManager, "ainvoke_hook_callback", ainvoke), + (MemoryManager, "initialize_for_agent", initialize_for_agent), + ): + p = patch.object(target, attr, value) + p.start() + self.patches.append(p) + + # -- Hermes' surfaces ---------------------------------------------------------------------------- + + def served(self): + return [("default", self.home), ("members", self.members)] + + def discover(self) -> None: + """Plugin discovery in each served profile, as a multiplexed gateway runs it at start.""" + from gateway.run import _profile_runtime_scope + from hermes_cli.plugins import discover_plugins + + discover_plugins() + with _profile_runtime_scope(self.members): + discover_plugins() + + def runner(self): + """A runner with the real admission path (as ``tests/gateway/test_access_groups_ingress.py``).""" + from gateway.config import load_gateway_config + from gateway.run import GatewayRunner + + runner = object.__new__(GatewayRunner) + runner.config = load_gateway_config() + runner.adapters, runner._profile_adapters = {}, {} + runner.pairing_store = SimpleNamespace(is_approved=lambda *_a, **_kw: False) + runner._primary_profile_name = "default" + runner._startup_restore_in_progress = False + runner._scale_to_zero_note_real_inbound = lambda: None + runner._hm_pre_gateway_dispatch_hook = AsyncMock(side_effect=lambda event, source: event) + runner._hm_estop_gate = lambda event, source, is_internal: "admitted" + return runner + + def inbound(self, runner, user_id: str, roles=None): + from gateway.config import Platform + from gateway.platforms.base import BasePlatformAdapter + + class _Adapter(BasePlatformAdapter): + pass + + _Adapter.__abstractmethods__ = frozenset() + adapter = _Adapter.__new__(_Adapter) + adapter.platform, adapter.gateway_runner = Platform.DISCORD, runner + adapter.set_owner_profile(None) + runner.adapters[Platform.DISCORD] = adapter + return adapter.build_source( + chat_id=CHAT, + chat_type="group", + user_id=user_id, + guild_id=GUILD, + sender_role_ids=frozenset(roles) if roles is not None else None, + ) + + async def admitted(self, runner, source) -> bool: + from gateway.platforms.event import MessageEvent + from gateway.run import GatewayRunner + + return await GatewayRunner._handle_message(runner, MessageEvent(text="hi", source=source)) == "admitted" + + async def setup_prompt(self, runner, source, session_key: str) -> list[str]: + """``run_preagent_setup`` with resolve/prepare/pin stubbed (as Hermes' test of the pinned prompt): + the prompt the turn pins.""" + from gateway.platforms.event import MessageEvent, MessageType + from gateway.run_turn_setup_guard import run_preagent_setup + + pinned: list[str] = [] + runner.hooks = SimpleNamespace(emit=AsyncMock()) + runner._session_state = lambda _key: SimpleNamespace(turn=SimpleNamespace(setup_stop=None)) + runner._PreparedTurn = SimpleNamespace + + async def resolve(event, src): + return src, SimpleNamespace(session_id=session_key.rsplit(":", 1)[-1]), session_key + + async def prepare(*_a): + return SimpleNamespace(message_text="hello"), [] + + def pin(key, channel_prompt, src, *, internal): + pinned.append(channel_prompt) + return channel_prompt, src + + runner._hmwa_resolve_session, runner._hmwa_prepare_turn = resolve, prepare + runner._pinned_channel_inputs, runner._persist_prompt_pins = pin, AsyncMock() + event = MessageEvent( + text="hello", message_type=MessageType.TEXT, source=source, message_id="m1", channel_prompt="channel rules" + ) + await run_preagent_setup(runner, event, source, session_key, 1) + return pinned + + def build_agent(self, platform: str, **kw): + from run_agent import AIAgent + + with ( + patch("tools.schemas.get_tool_definitions", return_value=[]), + patch("tools.schemas.check_toolset_requirements", return_value={}), + patch("agent.process_bootstrap.OpenAI"), + ): + return AIAgent( + api_key="test-key-1234567890", + base_url="http://127.0.0.1:9/v1", + quiet_mode=True, + skip_context_files=True, + platform=platform, + **kw, + ) + + def requests(self) -> dict[str, Any]: + from fakes.ctx_server import digest + + seen = self.fake.requests() + names = {digest(MEMBER_KEY): "member", digest(DEFAULT_KEY): "default"} + return { + "keys": sorted({names.get(s.key_digest, s.key_digest) for s in seen}), + "routes": sorted({f"{s.method} {s.path}{':' + s.action if s.action else ''}" for s in seen}), + "narrowed": sorted({str(s.read_header) for s in seen}), + "n": len(seen), + } + + def status(self, home: Path) -> list[dict[str, Any]]: + path = home / "ctx_state" / "access" + out = [] + for file in sorted(path.glob("*.json")) if path.is_dir() else []: + data = json.loads(file.read_text(encoding="utf-8")) + out.append({"file": file.name, "state": data.get("state"), "base": data.get("base_blocks")}) + return out + + def close(self) -> None: + for p in reversed(self.patches): + p.stop() + self.fake.stop() + + +def _plain(value: Any) -> Any: + try: + return json.loads(json.dumps(value)) + except TypeError: + return repr(value) + + +def _decision(provider: Any) -> Any: + decision = getattr(provider, "_decision", None) + if decision is None: + return None + context = getattr(decision, "context", None) + return { + "kind": decision.kind, + "reason": decision.reason, + "strict": decision.strict, + "group": getattr(context, "group", None), + "scope_id": getattr(context, "scope_id", None), + "platform": getattr(context, "platform", None), + } + + +def _plugin_access_module(): + """The plugin's ``memory.access`` as Hermes loaded it (synthetic package name).""" + found = [m for name, m in sys.modules.items() if name.endswith(".memory.access") and hasattr(m, "current_access")] + return found[0] if found else None + + +def _ctx_of(access) -> Any: + if access is None: + return None + return { + "platform": access.platform, + "scope_id": access.scope_id, + "group": access.group, + "profile": access.profile, + "restricted": access.restricted, + "fields": sorted(access.fields), + } + + +@contextlib.contextmanager +def _served(world: World): + with patch("hermes_cli.profiles.profiles_to_serve", return_value=world.served()): + yield + + +# -- scenarios --------------------------------------------------------------------------------------- + + +def scenario_load(world: World) -> dict[str, Any]: + """1: discovery registers the fields (V3) and the hook (V4) from each profile; V8 is true.""" + from hermes_cli import access_fields, plugins + + world.discover() + hooks = {} + from gateway.run import _profile_runtime_scope + + for name, home in world.served(): + with _profile_runtime_scope(home): + hooks[name] = [ + getattr(cb, "__name__", "?") + "@" + getattr(cb, "__module__", "?").rsplit(".", 2)[-2] + for cb in plugins.get_plugin_manager().iter_hook_callbacks("access_group_fields") + ] + access = _plugin_access_module() + return { + "schema": sorted(access_fields._schemas.get("ctx_checkpoint", {})), + "holders": sorted(Path(str(h)).name for h in access_fields._holders.get("ctx_checkpoint", {})), + "hooks": hooks, + "access_supported": access.access_supported() if access else None, + } + + +async def _governed_turn(world: World, user: str, roles, session_key: str) -> dict[str, Any]: + from gateway import access_groups + from gateway.run import _async_profile_runtime_scope + + runner = world.runner() + source = world.inbound(runner, user, roles=roles) + out: dict[str, Any] = {} + with patch("gateway.run._gateway_runner_ref", lambda: runner): + out["admitted"] = await world.admitted(runner, source) + out["source_profile"] = source.profile + home = world.members if source.profile == "members" else world.home + async with _async_profile_runtime_scope(home): + with _turn_env(runner, source, session_key): + out["core_access"] = _ctx_of(access_groups.current_access()) + out["pinned"] = await world.setup_prompt(runner, source, session_key) + agent = world.build_agent( + "discord", session_id=session_key.rsplit(":", 1)[-1], gateway_session_key=session_key, user_id=user + ) + out["provider_loaded"] = agent._memory_manager is not None + with contextlib.suppress(Exception): + agent.close() + return out + + +@contextlib.contextmanager +def _turn_env(runner, source, session_key: str): + """The turn's session variables as the gateway binds them (``GatewayRunner._set_session_env``, + which also binds the access source ``current_access()`` reads).""" + context = SimpleNamespace( + source=source, + actor_user_id=source.user_id, + actor_user_name="", + turn_event=None, + session_key=session_key, + session_id=session_key.rsplit(":", 1)[-1], + ) + tokens = runner._set_session_env(context) + try: + yield + finally: + runner._clear_session_env(tokens) + + +def scenario_gateway(world: World) -> dict[str, Any]: + """2, 3, 5: a governed member turn and an operator turn through admission, setup and agent build; + then a CLI build in the default profile.""" + from gateway.run import _profile_runtime_scope + + with _served(world): + world.discover() + member = asyncio.run(_governed_turn(world, MEMBER, {GUILD}, "agent:members:discord:group:s-member")) + member["hook_calls"] = list(world.hook_calls) + member["inits"] = list(world.inits) + member["status"] = world.status(world.members) + member["requests"] = world.requests() + world.hook_calls.clear() + world.inits.clear() + operator = asyncio.run(_governed_turn(world, OWNER, None, "agent:main:discord:group:s-owner")) + operator["hook_calls"] = list(world.hook_calls) + operator["inits"] = list(world.inits) + world.inits.clear() + with _profile_runtime_scope(world.home): + agent = world.build_agent("cli", session_id="s-cli") + with contextlib.suppress(Exception): + agent.close() + cli = {"inits": list(world.inits)} + return {"member": member, "operator": operator, "cli": cli} + + +def scenario_timeout(world: World) -> dict[str, Any]: + """3: a ctx server that hangs; the plugin's budget ends before the core's hook timeout, the core + keeps the group's prompt, and the next session asks the plugin again (no timeout suppression).""" + from gateway.run import _async_profile_runtime_scope + + out: dict[str, Any] = {} + with _served(world): + world.discover() + runner = world.runner() + source = world.inbound(runner, MEMBER, roles={GUILD}) + + async def turns(): + with patch("gateway.run._gateway_runner_ref", lambda: runner): + out["admitted"] = await world.admitted(runner, source) + async with _async_profile_runtime_scope(world.members): + for n in (1, 2): + key = f"agent:members:discord:group:s-{n}" + with _turn_env(runner, source, key): + started = time.monotonic() + pinned = await world.setup_prompt(runner, source, key) + out[f"turn{n}"] = {"pinned": pinned, "seconds": round(time.monotonic() - started, 3)} + + asyncio.run(turns()) + out["hook_calls"] = list(world.hook_calls) + out["status"] = world.status(world.members) + return out + + +def scenario_background(world: World) -> dict[str, Any]: + """4 (H-2/VB-3): ``/background`` from a member's chat builds its agent with the group's access + context; the provider's background worker (queue_prefetch, sync_turn) carries the turn context.""" + from gateway.hooks import HookRegistry + from gateway.run import _async_profile_runtime_scope + + seen: dict[str, Any] = {"run_thread": [], "worker": []} + + def run_conversation(agent, *args, **kwargs): + access = _plugin_access_module() + seen["run_thread"].append( + { + "thread": threading.current_thread().name, + "plugin_current_access": _ctx_of(access.current_access() if access else None), + } + ) + manager = agent._memory_manager + if manager is not None: + for provider in manager.providers: + real = provider.queue_prefetch + + def queue_prefetch(query, *a, _real=real, **kw): + seen["worker"].append( + { + "thread": threading.current_thread().name, + "plugin_current_access": _ctx_of(access.current_access()), + } + ) + return _real(query, *a, **kw) + + provider.queue_prefetch = queue_prefetch + manager.queue_prefetch_all("what are the house rules?") + manager._drain_sync_executor() if hasattr(manager, "_drain_sync_executor") else None + return {"final_response": "done", "messages": []} + + with _served(world): + world.discover() + runner = world.runner() + source = world.inbound(runner, MEMBER, roles={GUILD}) + runner._running_agents, runner._background_tasks = {}, set() + runner._session_db = runner._reasoning_config = runner._fallback_model = None + runner._provider_routing, runner.hooks = {}, HookRegistry() + runner.session_store = MagicMock(**{"get_model_override.return_value": None}) + adapter = MagicMock(extract_media=lambda text: ([], text), extract_images=lambda text: ([], text)) + adapter.send = AsyncMock() + from gateway.config import Platform + + runner.adapters[Platform.DISCORD] = adapter + # Delivery is not under test: the admitted source names profile ``members``, which has no adapter of + # its own in this runner; the reply goes to the stub. + runner._delivery_adapter_for = lambda _source: adapter + + async def go(): + with patch("gateway.run._gateway_runner_ref", lambda: runner): + seen["admitted"] = await world.admitted(runner, source) + async with _async_profile_runtime_scope(world.members): + with ( + patch( + "gateway.run._resolve_runtime_agent_kwargs", + return_value={"api_key": "test-key-1234567890", "base_url": "http://127.0.0.1:9/v1"}, + ), + patch("gateway.run._load_gateway_config", return_value={}), + patch("tools.schemas.get_tool_definitions", return_value=[]), + patch("tools.schemas.check_toolset_requirements", return_value={}), + patch("agent.process_bootstrap.OpenAI"), + patch("run_agent.AIAgent.run_conversation", run_conversation), + ): + await runner._run_background_task("say hello", source, "bg_s3") + + asyncio.run(go()) + seen["inits"] = list(world.inits) + seen["sent"] = [ + str(c.args[1])[:200] if len(c.args) > 1 else str(c.kwargs)[:200] for c in adapter.send.await_args_list + ] + return seen + + +def scenario_delegate(world: World) -> dict[str, Any]: + """4 (H-2/VB-3): ``delegate_task``'s child built inside a member's turn (``checkpoint_required``, so + the child loads the provider as a fork) sees the group; and a fork of a CLI session: what the plugin + reads as the parent's platform (``HERMES_SESSION_PLATFORM``).""" + from agent.subagents.spawn import _build_child_agent + from gateway.run import _async_profile_runtime_scope, _profile_runtime_scope + + out: dict[str, Any] = {} + + def child_of(parent, label): + world.inits.clear() + with ( + patch("tools.schemas.get_tool_definitions", return_value=[]), + patch("tools.schemas.check_toolset_requirements", return_value={}), + patch("agent.process_bootstrap.OpenAI"), + ): + child = _build_child_agent(0, "summarize", None, None, None, 3, 1, parent) + access = _plugin_access_module() + out[label] = { + "inits": list(world.inits), + "plugin_current_access": _ctx_of(access.current_access() if access else None), + "parent_platform": access.session_parent_platform() if access else UNSET, + "env_has_session_platform": "HERMES_SESSION_PLATFORM" in os.environ, + } + with contextlib.suppress(Exception): + child.close() + + with _served(world): + world.discover() + runner = world.runner() + source = world.inbound(runner, MEMBER, roles={GUILD}) + + async def turn(): + key = "agent:members:discord:group:s-d" + with patch("gateway.run._gateway_runner_ref", lambda: runner): + out["admitted"] = await world.admitted(runner, source) + async with _async_profile_runtime_scope(world.members): + with _turn_env(runner, source, key): + parent = world.build_agent("discord", session_id="s-d", user_id=MEMBER, gateway_session_key=key) + out["parent_inits"] = list(world.inits) + child_of(parent, "gateway_fork") + + asyncio.run(turn()) + import hermes_yaml as yaml + + for mode in ("off", "local", "auto"): + cfg = world.home / "config.yaml" + data = yaml.safe_load(cfg.read_text(encoding="utf-8")) + data["memory"]["ctx_checkpoint"]["ungoverned"] = mode + cfg.write_text(_yaml(data), encoding="utf-8") + with _profile_runtime_scope(world.home): + world.inits.clear() + parent = world.build_agent("cli", session_id=f"s-cli-{mode}") + out[f"cli_parent_inits_{mode}"] = list(world.inits) + child_of(parent, f"cli_fork_{mode}") + with contextlib.suppress(Exception): + parent.close() + return out + + +def scenario_r7(world: World) -> dict[str, Any]: + """6: the core's baseline check of the restricted profile ``members`` (R7 among R2–R8), for the + group with fields, without, with ``enabled: false``, and with an invalid field value.""" + from gateway import access_check + from gateway.access_groups import parse_server + + with _served(world): + world.discover() + out = {} + variants = { + "fields": world.groups[1].get("fields"), + "none": None, + "enabled_false": {"ctx_checkpoint": {"enabled": False}}, + "wrong_type": {"ctx_checkpoint": {"enabled": "no"}}, + } + for label, fields in variants.items(): + group = dict(world.groups[1]) + if fields is None: + group.pop("fields", None) + else: + group["fields"] = fields + parsed = parse_server("discord", GUILD, {"groups": [world.groups[0], group]}) + if parsed.error: + out[label] = {"parse_error": parsed.error} + continue + resolved = [g for g in parsed.groups if g.name == "members"] + result = access_check.check_restricted_profile( + world.members, platform="discord", groups=resolved, receiving_bot_profile=False + ) + out[label] = {"ok": result.ok, "findings": list(result.findings)} + return out + + +def scenario_available(world: World) -> dict[str, Any]: + """7 (H-1): a profile without a default key (no CTX_KEY/CTX_API_KEY in its .env, no MCP entry) and + ``ungoverned: off`` or ``local``: Hermes' agent build keeps the provider.""" + from gateway.run import _profile_runtime_scope + + out = {} + with _served(world): + world.discover() + for mode in ("off", "local", "profile"): + cfg = world.members / "config.yaml" + import hermes_yaml as yaml + + data = yaml.safe_load(cfg.read_text(encoding="utf-8")) + data["memory"]["ctx_checkpoint"]["ungoverned"] = mode + cfg.write_text(_yaml(data), encoding="utf-8") + world.inits.clear() + with _profile_runtime_scope(world.members): + agent = world.build_agent("cli", session_id=f"s-{mode}") + out[mode] = {"provider_kept": agent._memory_manager is not None, "inits": list(world.inits)} + with contextlib.suppress(Exception): + agent.close() + return out + + +SCENARIOS = { + "load": (scenario_load, {}), + "gateway": (scenario_gateway, {}), + "timeout": (scenario_timeout, {"hook_timeout": 3.0, "latency": {"/api/whoami": 20.0}}), + "background": (scenario_background, {}), + "delegate": (scenario_delegate, {"checkpoint_required": True}), + "r7": (scenario_r7, {}), + "available": (scenario_available, {}), +} + + +def main() -> int: + name, root = sys.argv[1], Path(sys.argv[2]) + fn, options = SCENARIOS[name] + world = World(root, **options) + try: + result = fn(world) + finally: + world.close() + print(json.dumps({"scenario": name, "result": result}, sort_keys=True, default=repr), flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py new file mode 100644 index 000000000..57df270d4 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py @@ -0,0 +1,247 @@ +"""S3 (b), design 02 §7.1: ctx_checkpoint against Hermes with access groups (the core PR), through +Hermes' own entry points, each scenario in a process of its own (``tests/s3_core_child.py``): Hermes +binds its plugin registry, field registry and hook table at import. + +Runs only when ``CTX_S3_HERMES_SRC`` names a Hermes tree with ``gateway/access_groups.py`` (the core +PR's branch ``feat/access-groups``); the interpreter of this run must carry that tree's dependencies. +The umbrella suite of the workflow runs a pinned Hermes without access groups and skips this module. + + CTX_S3_HERMES_SRC=/path/to/hermes-agent python -m pytest tests/test_s3_core_contract.py + +What each test pins, against the draft's contract and hypotheses: the fields and hook register from +each served profile (V3, V4, V8); a member turn is admitted by the core's baseline check, its hook is +asked with ``restricted`` in the serving profile's secret scope and its text joins the group's prompt +(V4, H-3); ``initialize`` gets all five access values, ``false`` and ``{}`` included (V5, VB-2); the +hook's budget ends before the core's timeout and a failure is asked again (D2, D3); ``/background``, +the memory manager's worker and a ``delegate_task`` child see the group (V6a, H-2, VB-3); a CLI +session binds no ``HERMES_SESSION_PLATFORM``; R7 admits the restricted profile exactly when the group +carries the fields; the provider is available without a default key under ``ungoverned: off|local`` +(H-1). +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest + +SRC = os.environ.get("CTX_S3_HERMES_SRC", "") +if not SRC or not (Path(SRC) / "gateway" / "access_groups.py").is_file(): + pytest.skip("CTX_S3_HERMES_SRC names no Hermes tree with access groups", allow_module_level=True) + +CHILD = Path(__file__).resolve().parent / "s3_core_child.py" +GUILD = "100000000000000001" +K, M_SCOPE = "t:d1-k", "t:d1-members" +KEY_VAR = f"CTX_KEY_{GUILD}_MEMBERS" +HEADING = "## Knowledge for this conversation (ctx)" +FIELDS = { + "base_blocks", + "base_max_chars", + "base_rev", + "base_url", + "capture", + "enabled", + "key", + "read", + "recall", + "store", + "tenant", + "write", +} +ACCESS_KEYS = ("scope_id", "access_group", "access_group_restricted", "access_fields", "restricted_profile") +_RESULTS: dict[str, tuple[dict[str, Any], str]] = {} + + +def _run(scenario: str, tmp_path_factory: pytest.TempPathFactory) -> tuple[dict[str, Any], str]: + """The child's JSON summary and its whole output, one process per scenario (cached per run).""" + if scenario not in _RESULTS: + root = tmp_path_factory.mktemp(f"s3-{scenario}") + (root / ".hermes").mkdir() + (root / "tmp").mkdir() + env = { + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + "HOME": str(root), + "HERMES_HOME": str(root / ".hermes"), + "TMPDIR": str(root / "tmp"), + "PYTHONPATH": SRC, + "PYTHONDONTWRITEBYTECODE": "1", + "LANG": "C.UTF-8", + } + done = subprocess.run( # noqa: S603 - our own interpreter and our own child script + [sys.executable, "-B", str(CHILD), scenario, str(root)], + env=env, + capture_output=True, + text=True, + timeout=300, + check=False, + ) + output = done.stdout + done.stderr + assert done.returncode == 0, f"child {scenario} failed (rc {done.returncode}):\n{output[-4000:]}" + summary = json.loads(done.stdout.strip().splitlines()[-1]) + assert summary["scenario"] == scenario + _RESULTS[scenario] = (summary["result"], output) + return _RESULTS[scenario] + + +def _access(init: dict[str, Any]) -> dict[str, Any]: + return {key: init[key] for key in ACCESS_KEYS} + + +def test_discovery_registers_fields_and_hook_in_every_served_profile(tmp_path_factory): + result, _ = _run("load", tmp_path_factory) + assert result["access_supported"] is True # V8 on the public class + assert set(result["schema"]) == FIELDS # V3, the twelve fields + assert result["holders"] == [".hermes", "members"] # registered from each profile's home + assert result["hooks"] == { + "default": ["on_access_group_fields@memory"], + "members": ["on_access_group_fields@memory"], + } + + +def test_a_member_turn_gets_the_base_blocks_from_the_serving_profiles_key(tmp_path_factory): + result, _ = _run("gateway", tmp_path_factory) + member = result["member"] + assert member["admitted"] is True and member["source_profile"] == "members" # R1–R8 passed, R7 included + assert member["core_access"]["group"] == "members" and member["core_access"]["restricted"] is True + [call] = member["hook_calls"] + assert (call["restricted"], call["profile"], call["group"], call["fields"]) == ( + True, + "members", + "members", + ["ctx_checkpoint"], + ) + assert call["answered"] is True + prompt = call["prompt"] + assert prompt.startswith(HEADING) and "Be kind to each other." in prompt + assert "bravo-foreign-text" not in prompt and "said by a member" not in prompt # other server, own write scope + assert member["pinned"] == [f"channel rules\n\nBe brief.\n\n{prompt}"] + # H-3: the default profile's .env holds another key under the same name; only the member key reached ctx. + assert member["requests"]["keys"] == ["member"] + [status] = member["status"] + assert status["state"] == "bound" and status["base"]["members"]["state"] == "delivered" + assert status["base"]["members"]["loaded"] == 1 and len(status["base"]["members"]["skipped"]) == 2 + + +def test_initialize_gets_the_five_access_values_of_the_member_turn(tmp_path_factory): + result, _ = _run("gateway", tmp_path_factory) + [init] = result["member"]["inits"] + access = _access(init) + assert access["scope_id"] == GUILD and access["access_group"] == "members" + assert access["access_group_restricted"] is True and access["restricted_profile"] is True + assert access["access_fields"]["key"] == KEY_VAR and access["access_fields"]["read"] == [K] + assert access["access_fields"]["write"] == M_SCOPE + [decision] = init["decisions"] + assert (decision["kind"], decision["strict"], decision["group"]) == ("group", True, "members") + + +def test_false_and_empty_access_values_reach_initialize(tmp_path_factory): + """VB-2: an unrestricted group without ctx fields and a CLI build pass ``False``/``{}``/``None``.""" + result, _ = _run("gateway", tmp_path_factory) + operator = result["operator"] + [init] = operator["inits"] + assert _access(init) == { + "scope_id": GUILD, + "access_group": "operators", + "access_group_restricted": False, + "access_fields": {}, + "restricted_profile": False, + } + assert init["decisions"][0]["kind"] == "off" # row 3: governed_unbound off + [call] = operator["hook_calls"] + assert call["restricted"] is False and call["prompt"] is None + assert operator["pinned"] == ["channel rules"] + [cli] = result["cli"]["inits"] + assert _access(cli) == { + "scope_id": None, + "access_group": None, + "access_group_restricted": False, + "access_fields": {}, + "restricted_profile": False, + } + + +def test_the_hooks_budget_ends_before_the_core_timeout_and_a_failure_is_asked_again(tmp_path_factory): + """D2/D3: ctx hangs (whoami 20 s), plugins.hook_callback_timeout 3 s: the plugin gives up at half of it, + the core keeps the group's prompt, logs no timeout and asks the next session again.""" + result, output = _run("timeout", tmp_path_factory) + first, second = result["hook_calls"] + assert first["answered"] is False and 1.3 <= first["seconds"] < 2.9 + assert result["turn1"]["pinned"] == ["channel rules\n\nBe brief."] and result["turn1"]["seconds"] < 3.0 + assert second["answered"] is False # asked again: a raise is not cached and not backed off + assert result["turn2"]["pinned"] == ["channel rules\n\nBe brief."] + assert "timed out after" not in output and "skipped after a recent timeout" not in output + assert result["status"][0]["base"]["members"]["state"].startswith("unavailable") + + +def test_background_and_the_memory_worker_see_the_group(tmp_path_factory): + """H-2/VB-3 for ``/background``: its agent is built with the group's values, and current_access() holds + in its run thread and in the memory manager's background worker (queue_prefetch).""" + result, _ = _run("background", tmp_path_factory) + assert result["admitted"] is True + [init] = result["inits"] + assert init["access_group"] == "members" and init["restricted_profile"] is True + assert init["decisions"][0]["kind"] == "group" + [run] = result["run_thread"] + [worker] = result["worker"] + assert run["plugin_current_access"]["group"] == "members" + assert worker["thread"].startswith("mem-sync") and worker["plugin_current_access"]["group"] == "members" + assert any("done" in sent for sent in result["sent"]) + + +def test_a_delegate_child_of_a_member_turn_binds_the_group(tmp_path_factory): + result, _ = _run("delegate", tmp_path_factory) + fork = result["gateway_fork"] + [init] = fork["inits"] + assert (init["platform"], init["agent_context"]) == ("subagent", "subagent") + assert init["access_group"] == "members" and init["restricted_profile"] is True + assert (init["decisions"][0]["kind"], init["decisions"][0]["platform"]) == ("group", "discord") + assert fork["parent_platform"] == "discord" and fork["plugin_current_access"]["group"] == "members" + + +def test_a_cli_session_binds_no_session_platform(tmp_path_factory): + """The measured state (P-B's open hypothesis): Hermes binds no HERMES_SESSION_PLATFORM in a CLI session, + so the plugin cannot tell a CLI fork's parent from its session variables; the CLI parent itself binds + the profile under ``ungoverned: local``.""" + result, _ = _run("delegate", tmp_path_factory) + fork = result["cli_fork_local"] + assert fork["parent_platform"] is None and fork["env_has_session_platform"] is False + assert fork["plugin_current_access"] is None + assert result["cli_parent_inits_local"][0]["decisions"][0]["kind"] == "profile" + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="S3 finding S3-B1: a delegate child of a CLI session is off under ungoverned: local (no parent platform)", +) +def test_a_delegate_child_of_a_cli_session_keeps_the_profile_under_local(tmp_path_factory): + """The promise of ``ungoverned: local`` (design 02 §3.2: forks only when their parent session was local): + the child of a local CLI session is local too. Strict xfail while S3-B1 stands; a fix turns it green and + the marker comes off with it.""" + result, _ = _run("delegate", tmp_path_factory) + [init] = result["cli_fork_local"]["inits"] + assert init["platform"] == "subagent" + assert init["decisions"][0]["kind"] == "profile", init["decisions"][0] + + +def test_r7_admits_the_restricted_profile_exactly_when_the_group_carries_the_fields(tmp_path_factory): + result, _ = _run("r7", tmp_path_factory) + assert result["fields"] == {"ok": True, "findings": []} + assert result["enabled_false"] == {"ok": True, "findings": []} + assert result["none"] == {"ok": False, "findings": ["R7 members fields.ctx_checkpoint: not set"]} + assert "fields.ctx_checkpoint.enabled" in result["wrong_type"]["parse_error"] + + +def test_the_provider_is_available_without_a_default_key_under_off_and_local(tmp_path_factory): + """H-1: no CTX_KEY/CTX_API_KEY and no MCP entry in the restricted profile.""" + result, _ = _run("available", tmp_path_factory) + for mode in ("off", "local"): + assert result[mode]["provider_kept"] is True + [init] = result[mode]["inits"] + assert init["restricted_profile"] is True and init["decisions"][0]["kind"] == "off" # row 5 + assert result["profile"]["provider_kept"] is False diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py new file mode 100644 index 000000000..76b1906b3 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py @@ -0,0 +1,1086 @@ +"""S3 run (a) of design 02 §7.1: ctx_checkpoint's access-group binding against a real ``ctxd`` with +per-request scope narrowing (C-1), required narrowing (C-2, migration 198), ``keyset-provision`` (C-3) +and ``get`` with ``ids`` (C-4). Everything the S2 clusters proved against ``fakes/ctx_server.py`` is +asked of the server itself here; Hermes' side is still the fake host surface (``fakes/access_host``), +the core PR's own surface is S3 run (b). + +Skipped unless ``CTX_S3_URL`` and ``CTX_S3_ADMIN_KEY`` name a THROWAWAY ``ctxd`` on an empty database +(its bootstrap server-admin key): the module creates a tenant, scopes, keys, a backend row and blocks +there, and sets the tenant's write budget. Start one as ``go/web/e2e/live/docker-compose.e2e.yml`` +does (a fresh ``timescale/timescaledb-ha:pg18`` with ``initdb.sql``, ``ctxd`` with +``CTX_BOOTSTRAP_ADMIN_KEY``); never point it at a real deployment. Embeddings and chat come from a +stub in this process (one ``_global`` Ollama backend row on 127.0.0.1); nothing leaves the host. + +``CTX_S3_REPORT``: a file the module writes what it saw of the server to (raw answers without key +values, the differences from the fake), for the S3 report. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import hashlib +import http.client +import io +import json +import math +import os +import re +import threading +import urllib.error +import urllib.parse +import urllib.request +from collections.abc import Iterator, Mapping +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any + +import pytest +from fakes import access_host as ah + +URL = os.environ.get("CTX_S3_URL", "").rstrip("/") +ADMIN = os.environ.get("CTX_S3_ADMIN_KEY", "") +REPORT = os.environ.get("CTX_S3_REPORT", "") +# ``before-c1``: the server is a release without per-request narrowing (v5.94.0); only the tests at +# the end of the module run, and they expect every group binding to fail closed (design 02 §3.7). +BEFORE_C1 = os.environ.get("CTX_S3_SERVER", "") == "before-c1" + +pytestmark = pytest.mark.skipif( + not (URL and ADMIN), reason="CTX_S3_URL/CTX_S3_ADMIN_KEY name no throwaway ctxd (S3 run a)" +) + +_PKG = ah.load_plugin("ctx_checkpoint_s3_real") +acc = ah.plugin_module(_PKG, "memory.access") +nar = ah.plugin_module(_PKG, "memory.narrowing") +cli = ah.plugin_module(_PKG, "memory.access_cli") +bb = ah.plugin_module(_PKG, "memory.base_blocks") +cp = ah.plugin_module(_PKG, "memory.checkpoint") +st = ah.plugin_module(_PKG, "memory.status") +client_mod = ah.plugin_module(_PKG, "memory.client") +Provider = _PKG.CtxCheckpointMemoryProvider +CtxClient = client_mod.CtxClient +CtxApiError = client_mod.CtxApiError + +SLUG = "s3t" +SERVER_A, SERVER_B = "111", "222" +TOOLSETS = "platform_toolsets:\n discord: [web]\n" +WRITE_BUDGET = 40 # the tenant overlay of query.rate_limit_write this module sets +PROBE = "sthreeprobe" +SEEN: dict[str, Any] = {"deviations": []} + + +def _note(key: str, value: Any) -> None: + SEEN[key] = value + + +def _deviation(what: str, real: Any, fake: str) -> None: + SEEN["deviations"].append({"what": what, "real": real, "fake": fake}) + + +# -- plain HTTP to ctxd -------------------------------------------------------------------------- + +_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + +def call( + method: str, path: str, key: str, body: Any = None, headers: Mapping[str, str] | None = None, base: str = "" +) -> tuple[int, dict[str, Any], Any]: + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request((base or URL) + path, data=data, method=method) # noqa: S310 — CTX_S3_URL, http + request.add_header("X-Context-Key", key) + if data is not None: + request.add_header("Content-Type", "application/json") + for name, value in (headers or {}).items(): + request.add_header(name, value) + try: + with _OPENER.open(request, timeout=60) as answer: + raw, status, head = answer.read(), answer.status, answer.headers + except urllib.error.HTTPError as exc: + raw, status, head = exc.read(), exc.code, exc.headers + try: + parsed = json.loads(raw or b"{}") + except ValueError: + parsed = {"_raw": raw.decode("utf-8", "replace")[:300]} + return status, parsed if isinstance(parsed, dict) else {"_value": parsed}, head + + +def manage(key: str, body: Mapping[str, Any], headers: Mapping[str, str] | None = None) -> tuple[int, dict, Any]: + return call("POST", "/api/manage", key, dict(body), headers) + + +def must(answer: tuple[int, dict, Any], what: str) -> dict[str, Any]: + status, body, _head = answer + assert status == 200 and body.get("success", True) is not False, f"{what}: HTTP {status} {body}" + return body + + +def narrow(read: str, write: str = "") -> dict[str, str]: + out = {nar.HEADER_READ_SCOPES: read} + if write: + out[nar.HEADER_WRITE_SCOPE] = write + return out + + +# -- the embed/chat stub and a forwarding proxy --------------------------------------------------- + + +def _vector(text: str) -> list[float]: + """A bag-of-words vector (1024 dims): texts that share words lie close, so the vector arm ranks.""" + vec = [0.0] * 1024 + for word in re.findall(r"[a-z0-9]+", text.lower()): + vec[int(hashlib.md5(word.encode()).hexdigest(), 16) % 1024] += 1.0 # noqa: S324 — a bucket, not a secret + norm = math.sqrt(sum(v * v for v in vec)) or 1.0 + if not any(vec): + vec[0] = 1.0 + return [v / norm for v in vec] + + +class _Serve: + """A ThreadingHTTPServer on 127.0.0.1 in a daemon thread.""" + + handler: type[BaseHTTPRequestHandler] + + def __init__(self) -> None: + self.server = ThreadingHTTPServer(("127.0.0.1", 0), self.handler) + self.server.owner = self # type: ignore[attr-defined] + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self.server.server_address[1]}" + + def start(self): + self.thread.start() + return self + + def stop(self) -> None: + self.server.shutdown() + self.server.server_close() + + +class _StubHandler(BaseHTTPRequestHandler): + def log_message(self, *args: Any) -> None: + return None + + def _send(self, status: int, payload: Any) -> None: + raw = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + def do_GET(self) -> None: + if self.path.startswith("/api/tags"): + self._send(200, {"models": [{"name": "s3-embed", "model": "s3-embed"}]}) + elif self.path.startswith("/api/version"): + self._send(200, {"version": "0.0.0-s3"}) + else: + self._send(404, {"error": "not here"}) + + def do_POST(self) -> None: + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}") + self.server.owner.calls.append(self.path) # type: ignore[attr-defined] + if self.path.startswith("/api/embed"): + items = body.get("input") + texts = items if isinstance(items, list) else [items] + self._send(200, {"model": body.get("model"), "embeddings": [_vector(str(t)) for t in texts]}) + elif self.path.startswith("/api/chat"): + self._send( + 200, + { + "model": body.get("model"), + "message": {"role": "assistant", "content": f"{PROBE} answer"}, + "done": True, + "eval_count": 1, + "prompt_eval_count": 1, + }, + ) + else: + self._send(404, {"error": "not here"}) + + +class EmbedStub(_Serve): + handler = _StubHandler + + def __init__(self) -> None: + super().__init__() + self.calls: list[str] = [] + + +class _ProxyHandler(BaseHTTPRequestHandler): + def log_message(self, *args: Any) -> None: + return None + + def _forward(self) -> None: + owner: Proxy = self.server.owner # type: ignore[attr-defined] + length = int(self.headers.get("Content-Length") or 0) + data = self.rfile.read(length) if length else None + headers = {k: v for k, v in self.headers.items() if k.lower() not in ("host", "connection", "content-length")} + if owner.strip_request_narrowing: + headers = { + k: v + for k, v in headers.items() + if not k.lower().startswith("x-context-") or k.lower() == "x-context-key" + } + action = "" + if data: + with contextlib.suppress(ValueError, AttributeError): + parsed = json.loads(data) + action = str(parsed.get("action") or "") + ("+ids" if "ids" in parsed else "") + owner.seen.append((self.command, self.path, action, self.headers.get(nar.HEADER_READ_SCOPES, ""))) + target = urllib.parse.urlsplit(owner.target) + conn = http.client.HTTPConnection(target.hostname, target.port, timeout=60) + conn.request(self.command, self.path, body=data, headers=headers) + answer = conn.getresponse() + raw = answer.read() + self.send_response(answer.status) + for name, value in answer.getheaders(): + if name.lower() in ("connection", "transfer-encoding", "content-length"): + continue + if owner.strip_response_echo and name.lower() == nar.HEADER_NARROWED.lower(): + continue + self.send_header(name, value) + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + conn.close() + + do_GET = do_POST = do_PUT = do_DELETE = _forward + + +class Proxy(_Serve): + """Forwards to ctxd; records (method, path, action, read header); can lose the narrowing on the + way (the request headers, or the answer's echo) the way a misconfigured proxy would.""" + + handler = _ProxyHandler + + def __init__(self, *, strip_response_echo: bool = False, strip_request_narrowing: bool = False) -> None: + super().__init__() + self.target = URL + self.strip_response_echo = strip_response_echo + self.strip_request_narrowing = strip_request_narrowing + self.seen: list[tuple[str, str, str, str]] = [] + + +@contextlib.contextmanager +def proxy(**kwargs: Any) -> Iterator[Proxy]: + server = Proxy(**kwargs).start() + try: + yield server + finally: + server.stop() + + +# -- the world: one tenant, three provisioned groups, blocks in every scope ----------------------- + + +def _full(name: str) -> str: + return f"{SLUG}:{name}" + + +def _provision(home: Path, server: str, profile: str, group: str, *extra: str) -> tuple[int, str]: + out = io.StringIO() + argv = ["provision", "--server", f"discord:{server}", "--profile", profile, "--group", group] + with contextlib.redirect_stdout(out): + rc = cli.run_access([*argv, "--admin-key-env", "CTX_S3_TENANT_ADMIN", *extra], hermes_home=str(home)) + return rc, out.getvalue() + + +def _env_value(home: Path, name: str) -> str: + """The value of *name* in the home's ``.env``; empty when the line (or the file) is not there, so a + provision that wrote nothing fails in the test that checks it, not in the fixture.""" + env = home / ".env" + match = re.search(rf"^{re.escape(name)}=(.*)$", env.read_text(encoding="utf-8"), re.M) if env.exists() else None + return match.group(1).strip() if match else "" + + +@pytest.fixture(scope="module") +def world(tmp_path_factory): + if BEFORE_C1: + pytest.skip("the server has no per-request narrowing (CTX_S3_SERVER=before-c1)") + stub = EmbedStub().start() + try: + must( + manage( + ADMIN, + { + "action": "backend-create", + "data": { + "name": "s3-stub", + "base_url": stub.url, + "protocol": "ollama", + "roles": ["embed", "translate", "synthesis", "chat"], + "model_map": {"default": "s3-embed"}, + "trust": "full-trust", + "confirm_trust_elevation": True, + }, + }, + ), + "backend-create", + ) + made = must(manage(ADMIN, {"action": "tenant-create", "data": {"slug": SLUG, "display_name": "S3"}}), "tenant") + owner = str(made["owner_key"]) + tenant_id = str(must(call("GET", "/api/whoami", owner), "owner whoami")["tenant_id"]) + must(call("PUT", "/api/settings/query.rate_limit_write", owner, {"value": WRITE_BUDGET}), "write budget") + + base = tmp_path_factory.mktemp("s3-real") + homes = {name: base / "profiles" / name for name in ("members", "mods", "members-b", "late")} + for home in homes.values(): + home.mkdir(parents=True) + (home / "config.yaml").write_text(TOOLSETS, encoding="utf-8") + layout_a = cli.scope_layout(SERVER_A, ["members", "mods"]) + layout_b = cli.scope_layout(SERVER_B, ["members"]) + scopes = { + "kA": _full(layout_a[cli.KNOWLEDGE]), + "membersA": _full(layout_a["members"]), + "modsA": _full(layout_a["mods"]), + "kB": _full(layout_b[cli.KNOWLEDGE]), + "membersB": _full(layout_b["members"]), + "main": _full("main"), + } + runs: dict[str, tuple[int, str]] = {} + with pytest.MonkeyPatch.context() as mp: + ah.install(mp, v8=True, secrets={"CTX_BASE_URL": URL}) + mp.setenv("CTX_S3_TENANT_ADMIN", owner) + mp.setenv("CTX_BASE_URL", URL) + runs["members-1"] = _provision(homes["members"], SERVER_A, "members", "members", "--emit-yaml") + first_key = _env_value(homes["members"], "CTX_KEY_111_MEMBERS") + runs["members-2"] = _provision(homes["members"], SERVER_A, "members", "members") + runs["mods"] = _provision( + homes["mods"], SERVER_A, "mods", "mods", "--read", layout_a["members"].split(":")[-1] + ) + runs["members-b"] = _provision(homes["members-b"], SERVER_B, "members-b", "members") + keys = { + "owner": owner, + "members-first": first_key, + "members": _env_value(homes["members"], "CTX_KEY_111_MEMBERS"), + "mods": _env_value(homes["mods"], "CTX_KEY_111_MODS"), + "members-b": _env_value(homes["members-b"], "CTX_KEY_222_MEMBERS_B"), + } + # Plain writer keys (member, optional) homed in each scope: the blocks the groups must or + # must not see are written through /api/store, the production write path. + for name in ("kA", "membersA", "modsA", "kB"): + body = must( + manage( + owner, + {"action": "api-key-create", "data": {"label": f"s3-writer-{name}", "home_scope": scopes[name]}}, + ), + f"writer key {name}", + ) + keys[f"w-{name}"] = str(body["api_key"]) + # The write budget the owner set (its home scope s3t:main) as a group key sees it, then the + # same setting written by a tenant-admin key homed in the group's scope. + budget_seen = { + "owner": call("GET", "/api/whoami", owner)[1].get("rate_limit_write"), + "members after the owner's write": call("GET", "/api/whoami", keys["members"])[1].get("rate_limit_write"), + } + made = must( + manage( + owner, + {"action": "api-key-create", "data": {"label": "s3-admin-membersA", "home_scope": scopes["membersA"]}}, + ), + "admin key in the group scope", + ) + must( + manage(owner, {"action": "api-key-update", "data": {"id": made["id"], "tenant_role": "admin"}}), + "promote to admin", + ) + keys["admin-membersA"] = str(made["api_key"]) + must( + call("PUT", "/api/settings/query.rate_limit_write", keys["admin-membersA"], {"value": WRITE_BUDGET}), + "write budget of the group scope", + ) + budget_seen["members after the group scope's write"] = call("GET", "/api/whoami", keys["members"])[1].get( + "rate_limit_write" + ) + _note("write_budget_seen", budget_seen) + blocks: dict[str, str] = {} + + def store(name: str, key: str, title: str, content: str) -> None: + body = must( + call( + "POST", + "/api/store", + key, + {"category": "learnings", "title": title, "content": f"{content} {PROBE}"}, + ), + f"store {name}", + ) + blocks[name] = str(body["block"]["id"]) + + store("kA1", keys["w-kA"], "House rules of server A", "Be kind to each other in server A.") + store("kA2", keys["w-kA"], "FAQ of server A", "Ask in the help channel of server A.") + store("modsA", keys["w-modsA"], "Moderator notes", "Only moderators read this note.") + store("membersA", keys["w-membersA"], "Member chatter", "Something another member said.") + store("kB", keys["w-kB"], "Server B plans", "Bravo plans of server B.") + store("main", owner, "Owner notes", "The owner's own notes.") + yield { + "owner": owner, + "tenant_id": tenant_id, + "homes": homes, + "scopes": scopes, + "keys": keys, + "blocks": blocks, + "runs": runs, + "stub": stub, + } + finally: + stub.stop() + + +@pytest.fixture(scope="module", autouse=True) +def _report(): + """What the module saw of the server, into ``CTX_S3_REPORT`` once its last test ran.""" + yield + if REPORT: + Path(REPORT).write_text(json.dumps(SEEN, indent=2, sort_keys=True, default=str), encoding="utf-8") + + +@pytest.fixture +def host(world, monkeypatch): + """The fake Hermes surface with the profile's secrets (as the .env holds them).""" + nar.reset_proofs() + bb.reset_state() + monkeypatch.setenv("no_proxy", "127.0.0.1,localhost") + monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost") + keys = world["keys"] + installed = ah.install( + monkeypatch, + v8=True, + secrets={ + "CTX_BASE_URL": URL, + "CTX_KEY_111_MEMBERS": keys["members"], + "CTX_KEY_111_MODS": keys["mods"], + "CTX_KEY_222_MEMBERS_B": keys["members-b"], + }, + ) + yield installed + nar.reset_proofs() + bb.reset_state() + + +def _texts(home: Path) -> str: + return "\n".join(p.read_text(encoding="utf-8", errors="replace") for p in home.rglob("*") if p.is_file()) + + +# -- P-E against C-3 ------------------------------------------------------------------------------ + + +def test_provision_creates_the_scopes_and_one_required_key_per_label(world): + runs, keys, scopes, homes = world["runs"], world["keys"], world["scopes"], world["homes"] + for name, (rc, out) in runs.items(): + assert rc == 0, f"provision {name}: rc {rc}\n{out}" + assert world["owner"] not in out, "the tenant-admin key is never printed" + assert "created" in runs["members-1"][1] and "there already" in runs["members-2"][1] + assert "ctx_checkpoint" in runs["members-1"][1] and "members" in runs["members-1"][1] + for home in homes.values(): + assert world["owner"] not in _texts(home), "the tenant-admin key is never written" + assert "ungoverned: local" in (homes["members"] / "config.yaml").read_text(encoding="utf-8") + + status, who, _ = call("GET", "/api/whoami", keys["members"]) + assert status == 200, who + _note("whoami_members_unnarrowed", {k: v for k, v in who.items() if k not in ("api_key_id", "principal_id")}) + assert who["scope_narrowing"] == "required" and who["role"] == "member" and who["admin"] is False + assert who["label"] == "hermes:discord:111:members" and who["tenant_slug"] == SLUG + assert who["home_scope"] == scopes["membersA"] + assert who["read_scopes"] == [scopes["membersA"], scopes["kA"]] + assert who["write_scopes"] == [scopes["membersA"]] and who["confirm_writes"] is False + assert who["narrowed"] is None and who["rate_limit_write"] == WRITE_BUDGET + + status, body, _ = call("POST", "/api/search", keys["members"], {"query": PROBE}) + assert (status, body.get("code")) == (403, "scope_narrowing_required"), (status, body) + + status, body, _ = call("GET", "/api/whoami", keys["members-first"]) + assert status == 401, f"the key the second provision replaced still answers: {status} {body}" + + status, mods, _ = call("GET", "/api/whoami", keys["mods"]) + assert mods["read_scopes"] == [scopes["modsA"], scopes["kA"], scopes["membersA"]], mods + assert call("GET", "/api/whoami", keys["members-b"])[1]["read_scopes"] == [scopes["membersB"], scopes["kB"]] + + +def test_the_write_budget_a_group_key_reports_is_its_home_scopes(world): + """``query.rate_limit_write`` is overridden per home scope (``mutationScope`` and + ``RequestTenantScope`` are the key's home scope), not per tenant: the owner's setting (home + ``<slug>:main``) does not reach a group key homed in its own scope; a setting written in the group's + scope does. ``whoami`` reports what the write path enforces for the key (the same snapshot).""" + seen = SEEN["write_budget_seen"] + assert seen["owner"] == WRITE_BUDGET, seen + assert seen["members after the group scope's write"] == WRITE_BUDGET, seen + if seen["members after the owner's write"] != WRITE_BUDGET: + _deviation( + "query.rate_limit_write set by the tenant's owner does not reach keys homed in other scopes of the " + "tenant (a group key from keyset-provision reports the _global value)", + seen, + "design 02 §1.4 (CC-7) and §3.5 C-1: 'je Tenant überschreibbar', 'nach Tenant-Overlay'; " + "tests/fakes/ctx_server.py reports one value per key", + ) + + +def test_provision_at_the_key_limit_writes_no_env_line(world, host, monkeypatch): + tenant = world["tenant_id"] + must( + manage(ADMIN, {"action": "tenant-limit-set", "id": tenant, "data": {"max_scopes": 1000, "max_keys": 0}}), + "limit", + ) + try: + raw = manage( + world["owner"], + { + "action": "keyset-provision", + "data": { + "scopes": ["dlate-k"], + "keys": [{"label": "s3-late", "home_scope": "dlate-k", "allowed_scopes": []}], + }, + }, + ) + _note("keyset_provision_at_limit", {"status": raw[0], "body": raw[1]}) + if raw[0] == 429 and "code" not in raw[1]: + _deviation( + "keyset-provision past max_keys answers 429 without a code (limit, count, requested)", + raw[1], + "tests/fakes/ctx_server.py: 429 with code rate_limit, error max_keys", + ) + monkeypatch.setenv("CTX_S3_TENANT_ADMIN", world["owner"]) + monkeypatch.setenv("CTX_BASE_URL", URL) + rc, out = _provision(world["homes"]["late"], SERVER_A, "late", "late") + assert rc != 0, out + assert "nothing was created" in out, out + env = world["homes"]["late"] / ".env" + assert not env.exists() or "CTX_KEY_111_LATE" not in env.read_text(encoding="utf-8") + assert world["owner"] not in out + _texts(world["homes"]["late"]) + finally: + must( + manage(ADMIN, {"action": "tenant-limit-set", "id": tenant, "data": {"max_scopes": 1000, "max_keys": 1000}}), + "limit back", + ) + + +# -- P-A: the strict proof against the real whoami ------------------------------------------------- + + +def _expect(world, **overrides: Any): + scopes = world["scopes"] + values = { + "narrowing": nar.Narrowing(read=(scopes["kA"],)), + "strict": True, + "tenant": SLUG, + "label": nar.expected_label("discord", SERVER_A, "members"), + "env_names": ("CTX_KEY_111_MEMBERS",), + "platform_toolsets": ("web",), + "scope_id": SERVER_A, + "write": scopes["membersA"], + } + values.update(overrides) + return nar.Expect(**values) + + +def _raws(key: str, read: tuple[str, ...], base: str = URL) -> tuple[Mapping[str, Any], Mapping[str, Any]]: + nar.reset_proofs() + reader = CtxClient(base, key, timeout=10, narrowing=nar.Narrowing(read=read)) + return nar.whoami_raw(reader, narrowed=True, budget_s=10), nar.whoami_raw(reader, narrowed=False, budget_s=10) + + +def test_strict_proof_holds_for_the_provisioned_key(world, host): + scopes = world["scopes"] + narrowed, plain = _raws(world["keys"]["members"], (scopes["kA"],)) + _note("whoami_members_narrowed", {k: v for k, v in narrowed.items() if k not in ("api_key_id", "principal_id")}) + assert narrowed["narrowed"] == {"read": [scopes["kA"]], "write": ""} + assert narrowed["read_scopes"] == [scopes["kA"]] and narrowed["write_scopes"] == [] + verdict = nar.evaluate(narrowed, plain, _expect(world)) + assert verdict.ok and verdict.failed == (), verdict + + +@pytest.mark.parametrize( + ("rule", "override"), + [ + ("E2", {"tenant": "s3x"}), + ("E4", {"label": "hermes:discord:111:mods"}), + ("E3", {"write": "write-scope-of-another-group"}), + ("E5", {"narrowing": None}), + ("E7", {"env_names": ("CTX_KEY_111_MEMBERS", "CTX_KEY_222_MEMBERS_B"), "platform_toolsets": ("web", "file")}), + ], +) +def test_each_broken_expectation_fails_its_rule(world, host, rule, override): + scopes = world["scopes"] + if override.get("narrowing", 1) is None: + override = {"narrowing": nar.Narrowing(read=(scopes["kA"], scopes["membersA"]))} + if override.get("write") == "write-scope-of-another-group": + override = {"write": scopes["kA"]} + narrowed, plain = _raws(world["keys"]["members"], (scopes["kA"],)) + verdict = nar.evaluate(narrowed, plain, _expect(world, **override)) + assert not verdict.ok and rule in verdict.failed, verdict + + +def _member_key(world, label: str, **data: Any) -> str: + scopes = world["scopes"] + body = {"label": label, "home_scope": scopes["membersA"], "allowed_scopes": [scopes["kA"]], **data} + return str(must(manage(world["owner"], {"action": "api-key-create", "data": body}), label)["api_key"]) + + +def test_a_key_without_required_narrowing_fails_e2(world, host): + key = _member_key(world, "hermes:discord:111:opt") + narrowed, plain = _raws(key, (world["scopes"]["kA"],)) + assert plain["scope_narrowing"] == "optional" + verdict = nar.evaluate(narrowed, plain, _expect(world, label="hermes:discord:111:opt")) + assert verdict.failed == ("E2",), verdict + + +def test_a_key_reading_more_than_the_group_fails_e3(world, host): + scopes = world["scopes"] + key = _member_key( + world, "hermes:discord:111:wide", allowed_scopes=[scopes["kA"], scopes["kB"]], scope_narrowing="required" + ) + narrowed, plain = _raws(key, (scopes["kA"],)) + verdict = nar.evaluate(narrowed, plain, _expect(world, label="hermes:discord:111:wide")) + assert verdict.failed == ("E3",), verdict + + +def test_an_owner_or_server_admin_key_fails_e2(world, host): + narrowed, plain = _raws(world["owner"], (_full("main"),)) + assert narrowed["admin"] is False and narrowed["role"] == "member", "a narrowed request is never an admin request" + verdict = nar.evaluate(narrowed, plain, _expect(world, narrowing=nar.Narrowing(read=(_full("main"),)))) + assert "E2" in verdict.failed, verdict + narrowed, plain = _raws(ADMIN, ("private",)) + verdict = nar.evaluate(narrowed, plain, _expect(world, narrowing=nar.Narrowing(read=("private",)))) + assert "E2" in verdict.failed and plain["admin"] is True, verdict + + +def test_a_narrowing_outside_the_key_is_refused_by_the_server(world, host): + scopes = world["scopes"] + with pytest.raises(CtxApiError) as caught: + _raws(world["keys"]["members"], (scopes["kA"], scopes["modsA"])) + assert caught.value.status == 403 and caught.value.code == "scope_denied", caught.value + + +@pytest.mark.parametrize("way", ["answer loses the echo", "request loses the narrowing"]) +def test_a_proxy_that_loses_the_narrowing_ends_the_client(world, host, way): + scopes = world["scopes"] + kwargs = {"strip_response_echo": True} if way.startswith("answer") else {"strip_request_narrowing": True} + with proxy(**kwargs) as fwd: + nar.reset_proofs() + reader = CtxClient(fwd.url, world["keys"]["members"], timeout=10, narrowing=nar.Narrowing(read=(scopes["kA"],))) + with pytest.raises(CtxApiError) as caught: + nar.whoami_raw(reader, narrowed=True, budget_s=10) + assert caught.value.code == "narrowing_lost", caught.value + assert reader.narrowing_lost + with pytest.raises(CtxApiError): + reader.search(PROBE) + assert len(fwd.seen) == 1, f"after a lost narrowing the client asks nothing: {fwd.seen}" + + +def test_access_check_against_the_real_server(world, host): + scopes = world["scopes"] + fields = ["key=CTX_KEY_111_MEMBERS", f"tenant={SLUG}", f"read={scopes['kA']}", f"write={scopes['membersA']}"] + home = str(world["homes"]["members"]) + out = io.StringIO() + with contextlib.redirect_stdout(out): + rc = cli.run_access( + ["check", "--server", "discord:111", "--group", "members", *(f"--field={f}" for f in fields)], + hermes_home=home, + ) + assert rc == 0, out.getvalue() + # The key of this profile checked as if another profile served the group: the label differs (E4). + bad = io.StringIO() + with contextlib.redirect_stdout(bad): + rc = cli.run_access( + [ + "check", + "--server", + "discord:111", + "--group", + "members", + "--profile", + "mods", + *(f"--field={f}" for f in fields), + ], + hermes_home=home, + ) + assert rc == 1 and "E4" in bad.getvalue() and "hermes:discord:111:mods" in bad.getvalue(), bad.getvalue() + # A tenant the read scopes do not belong to is refused before any request (E1, the field forms). + other = io.StringIO() + with contextlib.redirect_stdout(other): + rc = cli.run_access( + [ + "check", + "--server", + "discord:111", + "--group", + "members", + *(f"--field={f}" for f in fields), + "--field=tenant=s3x", + ], + hermes_home=home, + ) + assert rc == 1 and "E1" in other.getvalue(), other.getvalue() + + +# -- the echo on the allowed routes, the refusal on the others (C-1 seen by the plugin's client) ---- + + +def test_every_route_the_plugin_uses_carries_the_echo(world, host): + scopes, blocks, key = world["scopes"], world["blocks"], world["keys"]["members"] + reader = CtxClient(URL, key, timeout=30, narrowing=nar.Narrowing(read=(scopes["kA"],))) + found = reader.search(PROBE, limit=20) + ids = {str(row.get("id")) for row in found.get("results", [])} + assert blocks["kA1"] in ids and not ids & {blocks[n] for n in ("modsA", "membersA", "kB", "main")}, found + assert str(reader.get_block(blocks["kA1"]).get("block", {}).get("id")) == blocks["kA1"] + missing = reader.get_block(blocks["modsA"]) + assert missing.get("success") is False, f"a block outside the narrowing is not found: {missing}" + entries = reader.get_blocks( + [blocks["kA1"], blocks["modsA"], blocks["membersA"], blocks["kB"], blocks["main"], "zz"] + ) + _note("get_blocks_entries", entries[1:]) + assert entries[0].get("id") == blocks["kA1"] and entries[0].get("scope") == scopes["kA"] + assert [e.get("code") for e in entries[1:5]] == ["not_found"] * 4, entries + if entries[5].get("code") != "not_found": + _deviation( + "get with ids: an id that is no UUID or prefix answers its own entry code", + entries[5], + "tests/fakes/ctx_server.py: every miss is not_found", + ) + answered = reader.query(f"house rules {PROBE}") + assert not reader.narrowing_lost, answered + writer = CtxClient( + URL, key, timeout=30, narrowing=nar.Narrowing(read=(scopes["membersA"],), write=scopes["membersA"]) + ) + stored = writer.store(category="learnings", title="written narrowed", content=f"a narrowed write {PROBE}") + assert stored.get("block", {}).get("scope") == scopes["membersA"], stored + status, body, head = manage(key, {"action": "type-list"}, narrow(scopes["kA"])) + assert status == 200 and head.get(nar.HEADER_NARROWED) == f"{scopes['kA']};", (status, body) + + +def test_routes_and_actions_outside_the_list_are_refused_narrowed(world, host): + scopes, key = world["scopes"], world["keys"]["members"] + seen = {} + for method, path, body in ( + ("POST", "/api/recent", {}), + ("POST", "/api/store/batch", {"items": []}), + ("POST", "/mcp", {"jsonrpc": "2.0", "id": 1, "method": "tools/list"}), + ): + status, answer, head = call(method, path, key, body, narrow(scopes["kA"])) + seen[path] = (status, answer.get("code"), head.get(nar.HEADER_NARROWED)) + assert (status, answer.get("code")) == (403, "scope_narrowing_route"), (path, status, answer) + for action in ("purge", "update", "api-key-list"): + status, answer, head = manage(key, {"action": action, "id": world["blocks"]["kA1"]}, narrow(scopes["kA"])) + seen[action] = (status, answer.get("code"), head.get(nar.HEADER_NARROWED)) + assert status == 403, (action, status, answer) + status, answer, head = call( + "POST", + "/api/store", + key, + {"category": "learnings", "title": "x", "content": "y", "scope": scopes["kA"]}, + narrow(scopes["kA"], scopes["kA"]), + ) + seen["store into a read-only scope"] = (status, answer.get("code"), head.get(nar.HEADER_NARROWED)) + assert status == 403, (status, answer) + _note("refusals_narrowed", seen) + echoed = {what: echo for what, (_s, _c, echo) in seen.items() if echo} + if echoed: + _deviation( + "refusals after an accepted narrowing carry the echo X-Context-Narrowed (non-2xx)", + echoed, + "S1 contract §5 ('answers outside 2xx carry no echo'); tests/fakes/ctx_server.py echoes a handler's " + "refusal as the server does and leaves the route refusal without, as the server does", + ) + + +# -- P-C: the group binding reads only its read set and writes only its write scope --------------- + + +def _member_fields(world, **extra: Any) -> dict[str, Any]: + scopes = world["scopes"] + return {"key": "CTX_KEY_111_MEMBERS", "tenant": SLUG, "read": [scopes["kA"]], "write": scopes["membersA"], **extra} + + +def _settings(home: Path, text: str) -> None: + (home / "config.yaml").write_text( + TOOLSETS + "memory:\n ctx_checkpoint:\n ungoverned: local\n prefetch_mode: search\n" + text, + encoding="utf-8", + ) + + +def _member_provider(world, fields: Mapping[str, Any]): + home = world["homes"]["members"] + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize( + "s3-session", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs( + scope_id=SERVER_A, group="members", group_restricted=True, fields=fields, restricted_profile=True + ), + ) + return provider + + +def _messages(n: int = 8, tag: str = "m") -> list[dict[str, str]]: + return [ + {"role": "user" if i % 2 == 0 else "assistant", "content": f"{tag} turn {i:03d} " + f"{tag}word " * 200} + for i in range(n) + ] + + +def test_group_binding_reads_only_its_read_set(world, host): + blocks, scopes = world["blocks"], world["scopes"] + _settings(world["homes"]["members"], " restricted_allow: [recall]\n") + provider = _member_provider(world, _member_fields(world, recall=True)) + assert provider._active, provider._access_off + text = provider.prefetch(f"house rules {PROBE}") + assert "House rules of server A" in text, text # recall in search mode lists titles + for foreign in ("Moderator notes", "Member chatter", "Server B plans", "Owner notes"): + assert foreign not in text, (foreign, text) + got = provider.handle_tool_call("ctx_get", {"block_id": blocks["modsA"]}) + assert "Only moderators" not in got and ('"error"' in got or "not found" in got.lower()), got + assert "Be kind to each other" in provider.handle_tool_call("ctx_get", {"block_id": blocks["kA1"]}) + searched = provider.handle_tool_call("ctx_search", {"query": PROBE}) + assert "House rules" in searched + for foreign in ("Moderator notes", "Member chatter", "Server B plans", "Owner notes"): + assert foreign not in searched, (foreign, searched) + names = [s.get("name") for s in provider.get_tool_schemas()] + assert "ctx_store" not in names + entries = provider._group.read_client.get_blocks([blocks["kA1"], blocks["modsA"], blocks["membersA"], blocks["kB"]]) + assert [e.get("code") for e in entries] == [None, "not_found", "not_found", "not_found"], entries + assert entries[0].get("scope") == scopes["kA"] + rows = st.read_access(str(world["homes"]["members"])) + bound = [r for r in rows if str(r.get("scope_id")) == SERVER_A or "111" in json.dumps(r)] + assert bound and bound[-1].get("state") == "bound", rows + assert world["keys"]["members"] not in _texts(world["homes"]["members"] / "ctx_state") + + +def test_group_capture_writes_only_its_write_scope_and_follows_the_write_budget(world, host, monkeypatch): + scopes = world["scopes"] + _settings(world["homes"]["members"], " restricted_allow: [recall, capture]\n") + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _member_provider(world, _member_fields(world, capture=True)) + assert provider._active, provider._access_off + writer = provider._group.write_client + answers: list[Mapping[str, Any]] = [] + inner = writer.store + + def recording_store(*args: Any, **kwargs: Any) -> Any: + answer = inner(*args, **kwargs) + answers.append(answer) + return answer + + monkeypatch.setattr(writer, "store", recording_store) + receipt = provider.on_pre_compress(_messages(), require_checkpoint=True) + assert receipt, "the chain was written" + assert provider._rate_limit_write == WRITE_BUDGET, provider._rate_limit_write + assert cp.window_writes(80, provider._rate_limit_write) == WRITE_BUDGET - 3 + assert provider._chain_writer is not None and provider._chain_writer.rate_limit_write == WRITE_BUDGET + ids = [str((a.get("block") or {}).get("id") or a.get("existing_id") or "") for a in answers] + assert answers and all(ids), answers + reader = world["keys"]["w-membersA"] + for block_id in ids: + status, body, _ = manage(reader, {"action": "get", "id": block_id}) + block = body.get("block") or {} + assert status == 200 and block.get("scope") == scopes["membersA"], (block_id, body) + assert {"server:discord:111", "group:members"} <= set(block.get("tags") or []), block.get("tags") + _note("chain", {"writes": len(answers), "receipt": str(receipt)[:200]}) + + +def test_group_without_fields_in_a_restricted_profile_sends_nothing(world, host): + with proxy() as fwd: + host.secrets.set_base({"CTX_BASE_URL": fwd.url, "CTX_KEY_111_MEMBERS": world["keys"]["members"]}) + home = world["homes"]["members"] + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize( + "s3-off", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id=SERVER_A, group="members", group_restricted=True, restricted_profile=True), + ) + assert provider.prefetch(PROBE) == "" and provider.get_tool_schemas() == [] + assert fwd.seen == [] + + +# -- P-D: the base-block hook over the real multi-id get -------------------------------------------- + + +def test_base_blocks_come_in_one_get_and_skip_what_the_group_may_not_read(world, host, monkeypatch): + blocks = world["blocks"] + home = world["homes"]["members"] + _settings(home, "") + monkeypatch.setenv("HERMES_HOME", str(home)) + order = [blocks[n] for n in ("kA1", "modsA", "membersA", "kB", "kA2", "main")] + with proxy() as fwd: + host.secrets.set_base({"CTX_BASE_URL": fwd.url, "CTX_KEY_111_MEMBERS": world["keys"]["members"]}) + fields = {"ctx_checkpoint": _member_fields(world, base_blocks=order)} + kwargs = ah.hook_kwargs(scope_id=SERVER_A, group="members", profile="members", fields=fields) + outcome = asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) + assert outcome.answered, outcome.error + text = (outcome.result or {}).get("prompt", "") + assert text.startswith(bb.HEADING), outcome.result + assert text.index("### House rules of server A") < text.index("### FAQ of server A") + for foreign in ("Moderator notes", "Member chatter", "Server B plans", "Owner notes"): + assert foreign not in text, (foreign, text) + gets = [row for row in fwd.seen if row[2].startswith("get")] + assert [row[2] for row in gets] == ["get+ids"], fwd.seen + _note("hook_requests", list(fwd.seen)) + + fwd.seen.clear() + none = asyncio.run( + ah.ainvoke_hook_callback( + bb.on_access_group_fields, + **ah.hook_kwargs(scope_id=SERVER_A, group="members", profile="members", fields={}), + ) + ) + assert none.answered and none.result is None and fwd.seen == [] + + +def test_a_base_block_of_the_write_scope_is_left_out_though_the_server_returns_it(world, host, monkeypatch): + """E6 as the second line: an unrestricted group whose read set holds its own write scope gets that + scope's block from the server (the narrowing allows it) and the hook still leaves it out.""" + blocks, scopes = world["blocks"], world["scopes"] + home = world["homes"]["members"] + _settings(home, "") + monkeypatch.setenv("HERMES_HOME", str(home)) + reader = CtxClient( + URL, world["keys"]["members"], timeout=30, narrowing=nar.Narrowing(read=(scopes["kA"], scopes["membersA"])) + ) + served = reader.get_blocks([blocks["membersA"]]) + assert served[0].get("scope") == scopes["membersA"], "the server hands the write scope's block out" + fields = { + "ctx_checkpoint": _member_fields( + world, read=[scopes["kA"], scopes["membersA"]], base_blocks=[blocks["kA1"], blocks["membersA"]] + ) + } + kwargs = ah.hook_kwargs(scope_id=SERVER_A, group="ops", restricted=False, profile="members", fields=fields) + outcome = asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) + assert outcome.answered, outcome.error + text = (outcome.result or {}).get("prompt", "") + assert "House rules of server A" in text and "Member chatter" not in text, text + + +# -- the coupling of a tenant grant (design 02 §3.4): every restricted binding of the tenant off ---- + + +def test_an_incoming_tenant_grant_turns_every_restricted_binding_off(world, host): + other = must(manage(ADMIN, {"action": "tenant-create", "data": {"slug": "s3g", "display_name": "S3 grant"}}), "s3g") + grant = must( + manage( + ADMIN, + { + "action": "tenant-grant-create", + "data": {"grantee_tenant": world["tenant_id"], "granted_scope": other["scope"]}, + }, + ), + "grant", + ) + grant_id = str(grant.get("id") or (grant.get("grant") or {}).get("id") or "") + try: + scopes = world["scopes"] + narrowed, plain = _raws(world["keys"]["members"], (scopes["kA"],)) + assert other["scope"] in plain["read_scopes"], plain + verdict = nar.evaluate(narrowed, plain, _expect(world)) + assert verdict.failed == ("E3",), verdict + _settings(world["homes"]["members"], " restricted_allow: [recall]\n") + nar.reset_proofs() + provider = _member_provider(world, _member_fields(world, recall=True)) + assert not provider._active and "E3" in str(provider._access_off), provider._access_off + finally: + if grant_id: + must(manage(ADMIN, {"action": "tenant-grant-delete", "id": grant_id}), "grant delete") + _note("tenant_grant_answer", grant) + + +# -- a server without C-1 (CTX_S3_SERVER=before-c1, v5.94.0): every group binding fails closed ------ +# Design 02 §3.7 row "ctx-Server ohne C-1" and §7.1 "Landung": the plugin lands before the server; a +# group then never binds (no echo, E5), the hook gives no prompt, provision creates nothing. + +old_server = pytest.mark.skipif(not BEFORE_C1, reason="CTX_S3_SERVER=before-c1 names a server without C-1") + + +@pytest.fixture(scope="module") +def old_world(tmp_path_factory): + made = must(manage(ADMIN, {"action": "tenant-create", "data": {"slug": SLUG, "display_name": "S3 old"}}), "tenant") + owner = str(made["owner_key"]) + must(manage(owner, {"action": "scope-create", "data": {"name": "d33-k"}}), "scope") + key = must( + manage( + owner, + { + "action": "api-key-create", + "data": { + "label": "hermes:discord:111:members", + "home_scope": _full("main"), + "allowed_scopes": [_full("d33-k")], + }, + }, + ), + "member key", + )["api_key"] + home = tmp_path_factory.mktemp("s3-old") / "profiles" / "members" + home.mkdir(parents=True) + (home / "config.yaml").write_text( + TOOLSETS + "memory:\n ctx_checkpoint:\n ungoverned: local\n restricted_allow: [recall]\n", + encoding="utf-8", + ) + return {"owner": owner, "key": str(key), "home": home} + + +@pytest.fixture +def old_host(old_world, monkeypatch): + nar.reset_proofs() + bb.reset_state() + monkeypatch.setenv("no_proxy", "127.0.0.1,localhost") + monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost") + yield ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": URL, "CTX_KEY_111_MEMBERS": old_world["key"]}) + nar.reset_proofs() + bb.reset_state() + + +def _old_fields(**extra: Any) -> dict[str, Any]: + return {"key": "CTX_KEY_111_MEMBERS", "tenant": SLUG, "read": [_full("d33-k")], "write": _full("main"), **extra} + + +@old_server +def test_before_c1_a_group_never_binds_and_reads_nothing(old_world, old_host): + with proxy() as fwd: + old_host.secrets.set_base({"CTX_BASE_URL": fwd.url, "CTX_KEY_111_MEMBERS": old_world["key"]}) + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize( + "s3-old", + hermes_home=str(old_world["home"]), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id=SERVER_A, group="members", group_restricted=True, fields=_old_fields(recall=True)), + ) + assert not provider._active, "no binding without the server's echo" + _note("before_c1_off_reason", str(provider._access_off)) + proofs = list(fwd.seen) + assert proofs and all(path == "/api/whoami" for _m, path, _a, _r in proofs), proofs + fwd.seen.clear() + assert provider.prefetch(PROBE) == "" and provider.get_tool_schemas() == [] + assert '"error"' in provider.handle_tool_call("ctx_search", {"query": PROBE}) + assert fwd.seen == [], fwd.seen + + +@old_server +def test_before_c1_the_hook_gives_no_prompt(old_world, old_host, monkeypatch): + monkeypatch.setenv("HERMES_HOME", str(old_world["home"])) + fields = {"ctx_checkpoint": _old_fields(base_blocks=["01a249c1-fb49-7e58-aade-b73d08a5f322"])} + with proxy() as fwd: + old_host.secrets.set_base({"CTX_BASE_URL": fwd.url, "CTX_KEY_111_MEMBERS": old_world["key"]}) + kwargs = ah.hook_kwargs(scope_id=SERVER_A, group="members", profile="members", fields=fields) + outcome = asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) + assert not (outcome.answered and outcome.result), outcome + assert not [row for row in fwd.seen if row[1] != "/api/whoami"], fwd.seen + _note( + "before_c1_hook", {"answered": outcome.answered, "error": repr(outcome.error), "requests": list(fwd.seen)} + ) + + +@old_server +def test_before_c1_provision_creates_nothing(old_world, old_host, monkeypatch, tmp_path): + home = tmp_path / "profiles" / "late" + home.mkdir(parents=True) + monkeypatch.setenv("CTX_S3_TENANT_ADMIN", old_world["owner"]) + monkeypatch.setenv("CTX_BASE_URL", URL) + rc, out = _provision(home, SERVER_A, "late", "late") + assert rc != 0 and "nothing was created" in out, out + assert not (home / ".env").exists() or "CTX_KEY_111_LATE" not in (home / ".env").read_text(encoding="utf-8") + _note("before_c1_provision", out) From 0f89e7f6b0103695dab9b33187ab1276c71d8b2d Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:23:48 +0100 Subject: [PATCH 19/65] fix(ctx_checkpoint): the fake ctx server answers as the ctx server of axis 02, and the base-block hook skips an ambiguous id prefix instead of retrying it on every turn tests/fakes/ctx_server.py followed the S1 contract where the Go server of axis 02 (C-1 to C-4) was built otherwise. It now follows the Go code, the place named next to each rule: 401 without success and code; the narrowing's refusals with a code and no echo, a handler's refusal of an accepted narrowing (403, 429) with the echo; read 429 without a code, write 429 with rate_limit; whoami with every field of the server (narrowed: null sent) and write_scopes as writableBlockScopes; store with success and the scope of the body judged; the action ctx decodes (the last spelling of action); unknown actions 400; get with ids as ctx answers it (not_found, invalid_id, ambiguous_id with matches, prefixes, uppercase ids, id beside ids, ids null, include_archived, created_at/updated_at, action in the envelope) and a server without C-4 that ignores ids; keyset-provision with the tenant-admin tier (403 admin key required), strict decoding, the name rules, scopes of the tenant only (403), quotas of keys and scopes (429 with limit, count after the replacements, requested), replace_label sparing keys that are no member keys (409), write_scopes within allowed or home (400), required narrowing by default and 64-hex keys, all without a code. tests/test_fake_ctx_wire.py pins these forms (29 red on the old fake). Against the aligned fake the plugin was wrong in one place: ambiguous_id, an answer about the block like not_found and invalid_id, was unknown to the hook, which then gave no text and raised BaseBlocksUnavailable on every turn for a base_blocks prefix of two blocks. It is skipped and named now. Two tests moved with the fake (a renamed method of the fake; a --read scope the tenant must have). The client's docstring no longer says ctx echoes no refusal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ctx_checkpoint/memory/base_blocks.py | 6 +- .../plugin/ctx_checkpoint/memory/client.py | 3 +- .../ctx_checkpoint/tests/fakes/ctx_server.py | 553 +++++++++++++----- .../tests/test_access_pa_client.py | 2 +- .../tests/test_access_pe_rules.py | 1 + .../tests/test_access_seam_server_forms.py | 83 +++ .../tests/test_fake_ctx_wire.py | 265 +++++++++ 7 files changed, 750 insertions(+), 163 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_server_forms.py create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index 665edff16..d8ba9824d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -77,9 +77,11 @@ # (``checkpoint.MAX_VALUE_CHARS``): a value that starts inside the text that is kept is judged whole. REDACT_SLACK = _cp.MAX_VALUE_CHARS # Entry codes of a multi-id get that are no answer about the block (try again later). Every other -# code of ctx's closed vocabulary, and ``not_found``/``invalid_id``, says the block cannot be had. +# code of ctx's closed vocabulary, and the miss codes of the multi-id get (``not_found``, ``invalid_id`` +# for a prefix under 8 characters, ``ambiguous_id`` for a prefix of several blocks; ctx +# go/internal/handler/get_ids.go), says the block cannot be had. _TRANSIENT_ENTRY_CODES = frozenset({"rate_limit", "write_conflict", "internal", "timeout"}) -_GONE_ENTRY_CODES = (frozenset(REJECT_CODES) | {"not_found", "invalid_id"}) - _TRANSIENT_ENTRY_CODES +_GONE_ENTRY_CODES = (frozenset(REJECT_CODES) | {"not_found", "invalid_id", "ambiguous_id"}) - _TRANSIENT_ENTRY_CODES # How many distinct refusals are named in a WARNING per process (a misconfigured group is named once, # not on every session). _WARNED_MAX = 256 diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py index ec552e16e..ade0f3da3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py @@ -514,7 +514,8 @@ def _request( ) -> dict[str, Any]: """One call. A narrowed client sends its narrowing headers (``unnarrowed``: not, for the unnarrowed ``whoami`` of a proof) and takes a successful answer only with the matching - ``X-Context-Narrowed`` echo; answers outside 2xx carry none and keep their own error.""" + ``X-Context-Narrowed`` echo; an answer outside 2xx keeps its own error (ctx echoes a handler's + refusal of an accepted narrowing too, the refusals of the narrowing itself not; neither is read).""" if self._url_refused: raise CtxApiError(BASE_URL_REFUSED) if self._narrowing_lost: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py index dd09d1a10..9de5017db 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -1,5 +1,11 @@ -"""A local ctx server with the target semantics of per-request narrowing (design 02 §3.5 C-1 to -C-4), stdlib only: one thread, ``127.0.0.1``, port 0. +"""A local ctx server with the semantics of per-request narrowing (design 02 §3.5 C-1 to C-4) as the +ctx server builds them, stdlib only: one thread, ``127.0.0.1``, port 0. + +Aligned with the Go server of axis 02 (branch ``feat/access-binding-server``, ``788319cd``); the place in +``go/internal/handler/`` each rule follows is named next to it (``go:<file>:<line>``). What the fake does +not model: OAuth bearer keys and the key's reduction to hex characters (keys here are any string), the +quota and busy answers of ``/api/query``, ``fields`` and the content window of ``get``, the actions the +plugin does not send (answered ``400 Unknown action``), unknown and escaped paths. Keys carry tenant (slug), home, ``allowed_scopes``, tenant grants, ``write_scopes``, ``scope_narrowing``, label, role, admin and ``confirm_writes``. Narrowing headers follow C-1 @@ -7,20 +13,22 @@ C-2 (``required`` keys refuse every unnarrowed request but ``whoami``), C-3 (``keyset-provision``) and C-4 (``get`` with ``ids``). Every request is counted per route and header set. Faults are switches on the server object: echo missing or wrong, latency per route, 429 per route, a server -without C-1 (headers ignored, ``whoami`` without the new fields) and without C-4 (``ids`` refused). - -Answer forms follow what ``memory/client.py`` and ``memory/provider.py`` read today: -``/api/query`` ``{"success", "answer", "sources"}``, ``/api/search`` ``{"success", "results"}``, -``/api/store`` ``{"block": {...}}``, ``/api/manage`` ``get`` as ctx answers it today -(``{"action": "get", "success": true, "block": {...}}``; a miss is 200 with ``{"success": false, -"error": "Block not found"}``). The multi-id form (C-4) is the S1 contract, the same the Go test of -C-4 pins: ``{"success": true, "blocks": [block | {"id", "error", "code": "not_found"}]}``. +without C-1 (headers ignored, ``whoami`` without the new fields) and without C-4 (``ids`` ignored). + +Answer forms: ``/api/query`` ``{"success", "answer", "sources"}``, ``/api/search`` ``{"success", +"results"}``, ``/api/store`` ``{"success", "block"}``, ``/api/manage`` ``get`` ``{"action": "get", +"success": true, "block": {...}, "graph_visible": ...}`` (a miss: 200 ``{"success": false, "error": +"Block not found"}``) and with ``ids`` ``{"action": "get", "success": true, "blocks": [block | {"id", +"code", "error"[, "matches"]}]}``. Refusals of ctx's write surfaces and of the narrowing carry a ``code``; +the actions of ``/api/manage`` keep their envelope without one (go:errcode.go:17-27). """ from __future__ import annotations import hashlib import json +import re +import secrets import threading import time import uuid @@ -32,7 +40,7 @@ HEADER_READ = "X-Context-Read-Scopes" HEADER_WRITE = "X-Context-Write-Scope" HEADER_NARROWED = "X-Context-Narrowed" -# C-1: the closed list of routes a narrowed request may take. +# C-1: the closed list of routes a narrowed request may take (go:narrowing.go:158-163). NARROWED_ROUTES = frozenset( { ("POST", "/api/query"), @@ -43,9 +51,25 @@ } ) NARROWED_ACTIONS = frozenset({"get", "type-list"}) +# The actions of /api/manage the fake answers; ctx knows more, the plugin sends no other. +MANAGE_ACTIONS = frozenset({"get", "type-list", "keyset-provision"}) MAX_READ_SCOPES = 8 MAX_IDS = 16 +MIN_ID_PREFIX = 8 # store.MinIDPrefixLen +MAX_MATCHES = 11 +KEYSET_MAX = 64 TYPE_NAMES = ("knowledge", "checkpoint", "session-digest", "fact") +SCOPE_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,22}[a-z0-9])?$") # go:tenant_manage.go:62 +FULL_ID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$") +KEYSET_FIELDS = frozenset({"scopes", "keys", "tenant_id"}) +KEYSET_KEY_FIELDS = frozenset( + {"label", "home_scope", "allowed_scopes", "write_scopes", "scope_narrowing", "replace_label"} +) +NOW = "2026-12-06T00:00:00Z" + + +def _uuid_of(*parts: str) -> str: + return str(uuid.uuid5(uuid.NAMESPACE_URL, "ctx-fake:" + ":".join(parts))) @dataclass @@ -65,17 +89,31 @@ class FakeKey: confirm_writes: bool = False active: bool = True + @property + def id(self) -> str: + return _uuid_of("key", self.secret) + @property def read_scopes(self) -> list[str]: + """Home, ``allowed_scopes``, then the tenant grants sorted, without doubles (go:auth/auth.go:134-144).""" out: list[str] = [] - for scope in (self.home, *self.allowed, *self.grants): + for scope in (self.home, *self.allowed, *sorted(self.grants)): if scope not in out: out.append(scope) return out @property def writable(self) -> list[str]: - return [self.home, *[s for s in self.write_scopes if s != self.home]] + """``writableBlockScopes`` (go:context_store.go:442-462): home, ``shared`` when it is an allowed + scope, then the write scopes that are allowed or home.""" + out = [self.home] + if "shared" in self.allowed: + out.append("shared") + readable = {self.home, *self.allowed} + for scope in self.write_scopes: + if scope in readable and scope not in out: + out.append(scope) + return out @dataclass @@ -102,7 +140,7 @@ class FakeCtx: def __init__(self) -> None: self.keys: dict[str, FakeKey] = {} self.blocks: dict[str, dict[str, Any]] = {} - self.scopes: set[str] = set() # scopes keyset-provision created or found (C-3) + self.scopes: set[str] = set() # scopes created by keyset-provision or add_scope (C-3) self.seen: list[Seen] = [] self.lock = threading.Lock() # Fault switches. @@ -114,7 +152,8 @@ def __init__(self) -> None: self.latency: dict[str, float] = {} # route key ("/api/whoami", "manage:get", ...) -> seconds self.throttle: dict[str, int] = {} # route key -> number of 429 answers still to give self.rate_limit_write = 100 # ctx's default (query.rate_limit_write) - self.max_keys = 50 + self.max_keys: int | None = 50 # a tenant's active keys (None: no limit) + self.max_scopes: int | None = 1000 # a tenant's scopes (None: no limit) self._server: ThreadingHTTPServer | None = None self._thread: threading.Thread | None = None @@ -125,6 +164,11 @@ def add_key(self, **kwargs: Any) -> FakeKey: self.keys[key.secret] = key return key + def add_scope(self, scope: str) -> str: + """A scope the tenant has (``<slug>:<name>``) without a key or a block in it.""" + self.scopes.add(scope) + return scope + def add_block(self, scope: str, title: str, content: str, *, block_id: str = "", **extra: Any) -> str: block_id = block_id or str(uuid.uuid4()) self.blocks[block_id] = { @@ -137,9 +181,19 @@ def add_block(self, scope: str, title: str, content: str, *, block_id: str = "", "tags": list(extra.pop("tags", [])), "metadata": dict(extra.pop("metadata", {})), "archived": bool(extra.pop("archived", False)), + "created_at": NOW, + "updated_at": NOW, } return block_id + def tenant_scopes(self, tenant: str) -> set[str]: + """The scopes a tenant has: created ones, those its keys and blocks name.""" + known = set(self.scopes) + for key in self.keys.values(): + known.update((key.home, *key.allowed, *key.write_scopes)) + known.update(block["scope"] for block in self.blocks.values()) + return {scope for scope in known if scope.startswith(f"{tenant}:")} + # -- counters ---------------------------------------------------------------------------- def count(self, path: str | None = None, action: str | None = None, *, narrowed: bool | None = None) -> int: @@ -205,7 +259,7 @@ def _handle(self, h: BaseHTTPRequestHandler, method: str) -> None: body = {} if not isinstance(body, dict): body = {} - action = str(body.get("action") or "") if path == "/api/manage" else "" + action = _action(body) if path == "/api/manage" else "" secret = h.headers.get("X-Context-Key") or "" read_values = h.headers.get_all(HEADER_READ) or [] write_values = h.headers.get_all(HEADER_WRITE) or [] @@ -232,6 +286,8 @@ def _handle(self, h: BaseHTTPRequestHandler, method: str) -> None: h.send_response(status) h.send_header("Content-Type", "application/json") h.send_header("Content-Length", str(len(data))) + if status == 401: # go:middleware.go:504-512 + h.send_header("WWW-Authenticate", 'Bearer scope="mcp"') if echo is not None and not self.echo_missing: h.send_header(HEADER_NARROWED, "x;y" if self.echo_wrong else echo) h.end_headers() @@ -251,37 +307,22 @@ def _answer( ) -> tuple[int, dict[str, Any], str | None]: key = self.keys.get(secret) if key is None or not key.active: - return 401, {"success": False, "error": "unauthorized", "code": "unauthorized"}, None + # go:middleware.go:683-697, :504-512: no success, no code, before the narrowing (no echo) + return 401, {"error": "unauthorized"}, None + narrowed: tuple[list[str], str] | None = None + if not self.without_c1: + refused, narrowed = self._narrow(method, path, key, read_values, write_values) + if refused is not None: + return refused[0], refused[1], None # refusals of narrowAuth carry no echo + # Auth sets the echo of an accepted narrowing before any handler runs: every answer of a + # narrowed request carries it, a handler's refusal too (go:middleware.go:702-707). + echo = f"{','.join(narrowed[0])};{narrowed[1]}" if narrowed else None route = f"manage:{action}" if action else path with self.lock: left = self.throttle.get(route, self.throttle.get(path, 0)) if left > 0: self.throttle[route if route in self.throttle else path] = left - 1 - return 429, {"success": False, "error": "rate limited", "code": "rate_limit"}, None - narrowed: tuple[list[str], str] | None = None - if not self.without_c1 and (read_values or write_values): - if not read_values: - return 400, _err("write scope without read scopes", "scope_narrowing_invalid"), None - if len(read_values) > 1 or len(write_values) > 1: - return 400, _err("narrowing header repeated", "scope_narrowing_invalid"), None - read = [s.strip() for s in read_values[0].split(",")] - if not read_values[0].strip() or any(not s for s in read) or len(read) != len(set(read)): - return 400, _err("empty or doubled narrowing", "scope_narrowing_invalid"), None - if len(read) > MAX_READ_SCOPES: - return 400, _err("too many read scopes", "scope_narrowing_invalid"), None - write = write_values[0].strip() if write_values else "" - if write_values and not write: - return 400, _err("empty write scope", "scope_narrowing_invalid"), None - if any(s not in key.read_scopes for s in read): - return 403, _err("scope outside the key", "scope_denied"), None - if write and (write not in key.writable or write not in read): - return 403, _err("write scope outside the key", "scope_denied"), None - if (method, path) not in NARROWED_ROUTES: - return 403, _err("route not open to narrowing", "scope_narrowing_route"), None - narrowed = (read, write) - elif not self.without_c1 and key.scope_narrowing == "required" and (method, path) != ("GET", "/api/whoami"): - return 403, _err("this key requires narrowing", "scope_narrowing_required"), None - echo = f"{','.join(narrowed[0])};{narrowed[1]}" if narrowed else None + return 429, _rate_limited(path, self.rate_limit_write), echo read_set = narrowed[0] if narrowed else key.read_scopes if (method, path) == ("GET", "/api/whoami"): return 200, self._whoami(key, narrowed), echo @@ -292,46 +333,79 @@ def _answer( hits = self._visible(read_set, body.get("types_exclude")) return 200, {"success": True, "results": hits}, echo if (method, path) == ("POST", "/api/store"): - if narrowed is not None: - if not narrowed[1]: - return 403, _err("no write scope on a narrowed request", "scope_denied"), echo - scope = narrowed[1] - else: - scope = key.home - block_id = self.add_block( - scope, - str(body.get("title") or ""), - str(body.get("content") or ""), - category=str(body.get("category") or "reference"), - type=str(body.get("type") or "knowledge"), - tags=list(body.get("tags") or []), - metadata=dict(body.get("metadata") or {}), - ) - now = "2026-12-06T00:00:00Z" - block = dict(self.blocks[block_id], created_at=now, updated_at=now) - return 200, {"block": block}, echo + return self._store(key, body, narrowed, echo) if (method, path) == ("POST", "/api/manage"): - if narrowed is not None and (action not in NARROWED_ACTIONS or _shadowed_action(body)): - return 403, _err("action not open to narrowing", "scope_narrowing_route"), echo + if narrowed is not None and action not in NARROWED_ACTIONS: # go:manage_table.go:433-450 + return 403, _err("this route is not available to a narrowed request", "scope_narrowing_route"), echo + if action not in MANAGE_ACTIONS: # go:manage_table.go:452-459 + return 400, {"success": False, "error": "Unknown action"}, echo return self._manage(key, action, body, read_set, echo) - if narrowed is not None: # unreachable: other routes were refused above - return 403, _err("route not open to narrowing", "scope_narrowing_route"), echo return 200, {"success": True}, echo + def _narrow( + self, method: str, path: str, key: FakeKey, read_values: list[str], write_values: list[str] + ) -> tuple[tuple[int, dict[str, Any]] | None, tuple[list[str], str] | None]: + """``narrowAuth`` (go:narrowing.go:75-163) in its order: header forms, the key's read set, the + write scope, the route; without a read header the required narrowing. Refusals with a code.""" + if not read_values: + if write_values: + return (400, _err("X-Context-Write-Scope needs X-Context-Read-Scopes", "scope_narrowing_invalid")), None + if key.scope_narrowing == "required" and (method, path) != ("GET", "/api/whoami"): + text = "this key answers narrowed requests only: name the scopes in X-Context-Read-Scopes" + return (403, _err(text, "scope_narrowing_required")), None + return None, None + if len(read_values) != 1 or len(write_values) > 1: + return (400, _err("each narrowing header may occur once", "scope_narrowing_invalid")), None + parts = read_values[0].split(",") + if len(parts) > MAX_READ_SCOPES: # counted before trimming (go:narrowing.go:122-125) + return (400, _err(f"{HEADER_READ} names more than 8 scopes", "scope_narrowing_invalid")), None + read = [part.strip() for part in parts] + if any(not scope for scope in read): + return (400, _err(f"{HEADER_READ} has an empty element", "scope_narrowing_invalid")), None + doubled = next((scope for i, scope in enumerate(read) if scope in read[:i]), None) + if doubled is not None: + return (400, _err(f"{HEADER_READ} names a scope twice: {doubled}", "scope_narrowing_invalid")), None + write = write_values[0].strip() if write_values else "" + if write_values and not write: + return (400, _err(f"{HEADER_WRITE} is empty", "scope_narrowing_invalid")), None + for scope in read: + if scope not in key.read_scopes: + return (403, _err(f"Cannot read the requested scope: {scope}", "scope_denied")), None + if write and (write not in read or write not in key.writable): + return (403, _err(f"Cannot write to requested scope: {write}", "scope_denied")), None + if (method, path) not in NARROWED_ROUTES: + return (403, _err("this route is not available to a narrowed request", "scope_narrowing_route")), None + return None, (read, write) + def whoami_answer(self, secret: str, read: Iterable[str] | None = None, write: str = "") -> dict[str, Any]: """The ``whoami`` body this server gives *secret* (narrowed to *read*/*write* when given), without a request: raw answers for the pure rule checks.""" return self._whoami(self.keys[secret], (list(read), write) if read is not None else None) def _whoami(self, key: FakeKey, narrowed: tuple[list[str], str] | None) -> dict[str, Any]: + """The fields of go:whoami.go:21-95 (``csrf_token`` only for a cookie session).""" out: dict[str, Any] = { "success": True, + "label": key.label, "home_scope": key.home, "read_scopes": list(key.read_scopes), - "tenant_slug": key.tenant, - "label": key.label, - "role": key.role, "admin": key.admin, + "tenant_id": _uuid_of("tenant", key.tenant), + "role": key.role, + "api_key_id": key.id, + "principal_id": _uuid_of("principal", key.secret), + "tenant_slug": key.tenant, + "tenant_display_name": key.tenant, + "capabilities": { + "workflow": True, + "model_api": { + "enabled": False, + "self_service": False, + "key_max_lifetime_s": 0, + "rotation_grace_s": 0, + "expiry_warn_s": 0, + }, + }, } if self.without_c1: return out @@ -339,12 +413,13 @@ def _whoami(self, key: FakeKey, narrowed: tuple[list[str], str] | None) -> dict[ { "write_scopes": [narrowed[1]] if narrowed and narrowed[1] else ([] if narrowed else key.writable), "confirm_writes": key.confirm_writes, + # A pointer without omitempty: "narrowed": null is sent (go:whoami.go:85). "narrowed": {"read": list(narrowed[0]), "write": narrowed[1]} if narrowed else None, - "scope_narrowing": key.scope_narrowing, "rate_limit_write": self.rate_limit_write, + "scope_narrowing": key.scope_narrowing, } ) - if narrowed: + if narrowed: # narrowAuth: read set as named, member, no server admin (go:narrowing.go:106-111) out["read_scopes"] = list(narrowed[0]) out["admin"] = False out["role"] = "member" @@ -354,117 +429,277 @@ def _visible(self, read_set: Iterable[str], types_exclude: Any) -> list[dict[str excluded = {str(t) for t in types_exclude} if isinstance(types_exclude, list) else set() scopes = set(read_set) return [ - {k: v for k, v in block.items() if k != "archived"} + _shown(block) for block in self.blocks.values() if block["scope"] in scopes and not block["archived"] and block["type"] not in excluded ] + def _store( + self, key: FakeKey, body: Mapping[str, Any], narrowed: tuple[list[str], str] | None, echo: str | None + ) -> tuple[int, dict[str, Any], str | None]: + """go:context_store.go:487-501: narrowed, the write scope (``scope`` in the body, if any, must be + it); unnarrowed, ``scope`` or home, among the key's writable scopes.""" + asked = str(body.get("scope") or "") + if narrowed is not None: + if not narrowed[1]: + text = "This narrowed request names no write scope (X-Context-Write-Scope)" + return 403, _err(text, "scope_denied"), echo + if asked and asked != narrowed[1]: + return 403, _err(f"Cannot write to requested scope: {asked}", "scope_denied"), echo + scope = narrowed[1] + else: + scope = asked or key.home + if scope not in key.writable: + return 403, _err(f"Cannot write to requested scope: {scope}", "scope_denied"), echo + block_id = self.add_block( + scope, + str(body.get("title") or ""), + str(body.get("content") or ""), + category=str(body.get("category") or "reference"), + type=str(body.get("type") or "knowledge"), + tags=list(body.get("tags") or []), + metadata=dict(body.get("metadata") or {}), + ) + return 200, {"success": True, "block": _shown(self.blocks[block_id])}, echo + def _manage( self, key: FakeKey, action: str, body: Mapping[str, Any], read_set: list[str], echo: str | None ) -> tuple[int, dict[str, Any], str | None]: if action == "type-list": return 200, {"success": True, "types": [{"name": name} for name in TYPE_NAMES]}, echo if action == "get": - if "ids" in body: - ids = body.get("ids") - if self.without_c4: - return 400, _err("Missing required field: id", "missing_fields"), echo - if not isinstance(ids, list) or not 1 <= len(ids) <= MAX_IDS: - return 400, _err("ids: 1 to 16", "invalid_body"), echo - return 200, {"success": True, "blocks": [self._get_one(str(i), read_set) for i in ids]}, echo - block_id = str(body.get("id") or "") - if not block_id: - return 400, _err("Missing required field: id", "missing_fields"), echo - # The single get answers as ctx does today (go/internal/handler/context_manage.go handleGet): - # 200 with {"action": "get", "success": true, "block": ...}; a miss is 200 with - # {"success": false, "error": "Block not found"}. - one = self._get_one(block_id, read_set) - if "error" in one: - return 200, {"success": False, "error": "Block not found"}, echo - return 200, {"action": "get", "success": True, "block": one}, echo - if action == "keyset-provision": - return self._keyset_provision(key, body, echo) - return 200, {"success": True}, echo - - def _get_one(self, block_id: str, read_set: list[str]) -> dict[str, Any]: - block = self.blocks.get(block_id) - if block is None or block["archived"] or (block["scope"] not in read_set and not self.leak_on_get): - return {"id": block_id, "error": "block not found", "code": "not_found"} - return {k: v for k, v in block.items() if k != "archived"} - - def _keyset_provision( - self, admin: FakeKey, body: Mapping[str, Any], echo: str | None - ) -> tuple[int, dict[str, Any], str | None]: - # Wire form of the S1 contract, the same the Go test of C-3 pins - # (go/cmd/ctxd/keyset_provision_c3_integration_test.go): tenant owner or admin (or a ctx server - # admin); data.scopes = bare scope names, created when missing; the answer lists the scopes as - # {"scope", "created"} and the keys as {"id", "label", "home_scope", "allowed_scopes", - # "write_scopes", "scope_narrowing", "api_key"}, both in request order. - if admin.role not in ("owner", "admin") and not admin.admin: - return 403, _err("tenant admin required", "scope_denied"), echo - data = body.get("data") if isinstance(body.get("data"), dict) else {} - keys = data.get("keys") if isinstance(data.get("keys"), list) else [] - names = data.get("scopes") if isinstance(data.get("scopes"), list) else [] - if len(names) > 64: - return 400, _err("at most 64 scopes", "invalid_body"), echo - if len(keys) > 64: - return 400, _err("at most 64 keys", "invalid_body"), echo - active = [k for k in self.keys.values() if k.tenant == admin.tenant and k.active] - replaced = {str(spec.get("label")) for spec in keys if isinstance(spec, dict) and spec.get("replace_label")} - after = len([k for k in active if k.label not in replaced]) + len(keys) - if after > self.max_keys: - return ( - 429, - { - "success": False, - "error": "max_keys", - "code": "rate_limit", - "limit": self.max_keys, - "count": len(active), - }, - echo, + return self._get(body, read_set, echo) + # keyset-provision: the tenant-admin tier, checked before the handler, without a code and with + # the text of the server-admin tier (go:manage_table.go:254, :394-397; auth/role.go:52-81). + if key.role not in ("owner", "admin") and not key.admin: + return 403, {"success": False, "error": "admin key required"}, echo + status, payload = self._keyset_provision(key, body) + return status, payload, echo + + # -- get (C-4: go:get_ids.go; the single get: go:context_manage.go:436-560) ------------------- + + def _get(self, body: Mapping[str, Any], read_set: list[str], echo: str | None) -> tuple[int, dict[str, Any], str]: + ids = body.get("ids") + one = body.get("id") + if ids is not None and not self.without_c4: # ids: null counts as not sent + if not isinstance(ids, list) or not all(isinstance(i, str) for i in ids): + return 400, _err("ids must be a list of block ids", "invalid_body"), echo + if one: + text = "id and ids exclude each other: send one block id in id, or a list in ids" + return 400, _err(text, "invalid_body"), echo + if not 1 <= len(ids) <= MAX_IDS: + return 400, _err(f"ids takes 1 to {MAX_IDS} block ids", "invalid_body"), echo + if body.get("include_archived"): + text = "include_archived reads one block by its full id: send it in id, not in ids" + return 400, _err(text, "invalid_body"), echo + return 200, {"action": "get", "success": True, "blocks": [self._entry(i, read_set) for i in ids]}, echo + block_id = str(one or "") + if not block_id: + return 400, {"success": False, "error": "Missing required field: id"}, echo + entry = self._entry(block_id, read_set) + code = entry.get("code") + if code == "invalid_id": + return 400, {"success": False, "error": entry["error"]}, echo + if code == "ambiguous_id": + answer = {"action": "get", "success": False, "error": "Ambiguous id prefix", "matches": entry["matches"]} + return 200, answer, echo + if code: + return 200, {"success": False, "error": "Block not found"}, echo + return 200, {"action": "get", "success": True, "block": entry, "graph_visible": True}, echo + + def _entry(self, asked: str, read_set: list[str]) -> dict[str, Any]: + """One id as ``store.ResolveBlockID`` resolves it: a full id exactly (lowercase), a prefix of at + least 8 characters among the blocks the caller sees; a miss is an entry with a code.""" + + def seen(block: Mapping[str, Any]) -> bool: + return not block["archived"] and (block["scope"] in read_set or self.leak_on_get) + + if FULL_ID.match(asked): + block = self.blocks.get(asked.lower()) + if block is not None and seen(block): + return _shown(block) + return {"id": asked, "code": "not_found", "error": "Block not found"} + if asked in self.blocks and seen(self.blocks[asked]): + return _shown(self.blocks[asked]) # a test id that is no UUID, asked whole + if len(asked) < MIN_ID_PREFIX: + error = f"store: id prefix must be at least {MIN_ID_PREFIX} characters (got {len(asked)})" + return {"id": asked, "code": "invalid_id", "error": error} + hits = [block for block_id, block in self.blocks.items() if block_id.lower().startswith(asked.lower())] + hits = [block for block in hits if seen(block)] + if len(hits) == 1: + return _shown(hits[0]) + if hits: + matches = [{k: b[k] for k in ("id", "title", "category", "tags", "scope")} for b in hits[:MAX_MATCHES]] + return {"id": asked, "code": "ambiguous_id", "error": "Ambiguous id prefix", "matches": matches} + return {"id": asked, "code": "not_found", "error": "Block not found"} + + # -- keyset-provision (C-3: go:keyset_provision.go, store/keyset.go) --------------------------- + + def _keyset_provision(self, admin: FakeKey, body: Mapping[str, Any]) -> tuple[int, dict[str, Any]]: + """Checks in ctx's order, then one transaction (nothing is written unless all pass): the names + and forms (400), the tenant's scopes (403) and their quota (429), the keys a ``replace_label`` + deactivates (409), the key quota (429), ``write_scopes`` within allowed or home (400). Every + refusal without a code (go:errcode.go:17-27).""" + if "id" in body: + return _plain(400, "keyset-provision takes no id; a server-admin names the tenant in data.tenant_id") + data = body.get("data") + if data is None: + return _plain(400, "Missing required field: data") + if not isinstance(data, dict): + return _plain(400, "Invalid data format: json: cannot unmarshal into keysetProvisionData") + unknown = sorted(set(data) - KEYSET_FIELDS) or sorted( + {name for spec in data.get("keys") or [] if isinstance(spec, dict) for name in spec} - KEYSET_KEY_FIELDS + ) + if unknown: + return _plain(400, f'Invalid data format: json: unknown field "{unknown[0]}"') + if data.get("tenant_id") and not admin.admin: + return _plain(403, "tenant_id is server-admin only") + names = data.get("scopes") or [] + specs = data.get("keys") or [] + if not isinstance(names, list) or not isinstance(specs, list) or not all(isinstance(s, dict) for s in specs): + return _plain(400, "Invalid data format: json: cannot unmarshal into keysetProvisionData") + if not names and not specs: + return _plain(400, "data needs scopes or keys") + if len(names) > KEYSET_MAX: + return _plain(400, f"at most {KEYSET_MAX} scopes per call") + if len(specs) > KEYSET_MAX: + return _plain(400, f"at most {KEYSET_MAX} keys per call") + tenant = admin.tenant + labels: list[str] = [] + for i, spec in enumerate(specs): + label = str(spec.get("label") or "") + if not label: + return _plain(400, f"keys[{i}]: label is required") + if label in labels: + return _plain(400, f'keys[{i}]: label "{label}" named twice') + labels.append(label) + wanted: list[str] = [] + for i, name in enumerate(names): + if not isinstance(name, str) or not SCOPE_NAME.match(name): + text = f"scopes[{i}]: name must be 1-24 chars of a-z, 0-9, '-' (no leading/trailing '-', no ':')" + return _plain(400, text) + if f"{tenant}:{name}" in wanted: + return _plain(400, f'scopes[{i}]: scope "{name}" named twice') + wanted.append(f"{tenant}:{name}") + made: list[dict[str, Any]] = [] + for i, spec in enumerate(specs): + resolved: dict[str, Any] = {"label": labels[i], "replace": spec.get("replace_label") is True} + for field_name in ("home_scope", "allowed_scopes", "write_scopes"): + raw = spec.get(field_name) + items = [raw] if field_name == "home_scope" else list(raw or []) + full = [] + for item in items: + scope = _key_scope(tenant, item) + if scope is None: + text = ( + f"keys[{i}]: scope \"{item}\" is neither a scope name (1-24 chars of a-z, 0-9, '-') " + "nor a full '<tenant>:<name>' scope" + ) + return _plain(400, text) + full.append(scope) + resolved[field_name] = full[0] if field_name == "home_scope" else full + narrowing = spec.get("scope_narrowing") or "required" + if narrowing not in ("optional", "required"): + return _plain(400, "scope_narrowing must be optional or required") + resolved["scope_narrowing"] = narrowing + made.append(resolved) + # -- the transaction, under the tenant's lock + have = self.tenant_scopes(tenant) + named = list(wanted) + [ + scope for spec in made for scope in (spec["home_scope"], *spec["allowed_scopes"], *spec["write_scopes"]) + ] + for scope in named: + if not scope.startswith(f"{tenant}:") or (scope not in have and scope not in wanted): + return _plain(403, f"not a scope of this tenant: {scope}") + new = [scope for scope in wanted if scope not in have] + if new and self.max_scopes is not None and len(have) + len(new) > self.max_scopes: + return _quota("tenant scope quota exceeded", self.max_scopes, len(have), len(new)) + active = [k for k in self.keys.values() if k.tenant == tenant and k.active] + replaced = [k for spec in made if spec["replace"] for k in active if k.label == spec["label"]] + guarded = sorted(k.label for k in replaced if k.role != "member" or k.admin) + if guarded: + text = ( + f'replace_label: an active key labelled "{guarded[0]}" is not a member key; ' + "revoke it with api-key-delete" ) - scopes_out = [] - for name in names: - full = f"{admin.tenant}:{name}" - created = full not in self.scopes - self.scopes.add(full) - scopes_out.append({"scope": full, "created": created}) + return _plain(409, text) + count = len([k for k in active if k not in replaced]) + if self.max_keys is not None and count + len(made) > self.max_keys: + return _quota("tenant key quota exceeded", self.max_keys, count, len(made)) + for i, spec in enumerate(made): + allowed = {spec["home_scope"], *spec["allowed_scopes"]} + outside = next((scope for scope in spec["write_scopes"] if scope not in allowed), None) + if outside is not None: + return _plain(400, f"keys[{i}]: store: write_scope not in allowed_scopes ∪ home_scope: {outside}") + # -- all checks passed: write + scopes_out = [{"scope": scope, "created": scope not in have} for scope in wanted] + self.scopes.update(wanted) + for key in replaced: + key.active = False out = [] - for spec in keys: - label = str(spec.get("label") or "") - if spec.get("replace_label"): - for other in active: - if other.label == label: - other.active = False - secret = "ctx_" + uuid.uuid4().hex - scope = lambda name: name if ":" in name else f"{admin.tenant}:{name}" # noqa: E731 - made = self.add_key( + for spec in made: + secret = secrets.token_hex(32) # 32 random bytes as hex, no prefix (go:store/api_keys.go:159-165) + key = self.add_key( secret=secret, - tenant=admin.tenant, - home=scope(str(spec.get("home_scope") or "")), - allowed=tuple(scope(str(s)) for s in spec.get("allowed_scopes") or ()), - write_scopes=tuple(scope(str(s)) for s in spec.get("write_scopes") or ()), - scope_narrowing=str(spec.get("scope_narrowing") or "optional"), - label=label, + tenant=tenant, + home=spec["home_scope"], + allowed=tuple(spec["allowed_scopes"]), + write_scopes=tuple(spec["write_scopes"]), + scope_narrowing=spec["scope_narrowing"], + label=spec["label"], ) out.append( { - "id": str(uuid.uuid4()), - "label": label, - "home_scope": made.home, - "allowed_scopes": list(made.allowed), - "write_scopes": list(made.write_scopes), - "scope_narrowing": made.scope_narrowing, + "id": key.id, + "label": key.label, + "home_scope": key.home, + "allowed_scopes": list(key.allowed), + "write_scopes": list(key.write_scopes), + "scope_narrowing": key.scope_narrowing, "api_key": secret, } ) - return 200, {"success": True, "scopes": scopes_out, "keys": out}, echo + return 200, {"success": True, "scopes": scopes_out, "keys": out} + + +def _action(body: Mapping[str, Any]) -> str: + """The one action ctx decodes: JSON keys match ``action`` in any case, the last one wins + (``{"action": "get", "ACTION": "purge"}`` is ``purge``; go:manage_table.go:433-450).""" + found = "" + for name, value in body.items(): + if name.lower() == "action": + found = str(value or "") + return found + + +def _key_scope(tenant: str, item: Any) -> str | None: + """A key's scope as ctx reads it: with ``:`` a full name (the store judges its tenant), else a scope + name of the caller's tenant (go:keyset_provision.go:185-198).""" + if not isinstance(item, str): + return None + if ":" in item: + return item + return f"{tenant}:{item}" if SCOPE_NAME.match(item) else None + + +def _shown(block: Mapping[str, Any]) -> dict[str, Any]: + return {k: v for k, v in block.items() if k != "archived"} + + +def _rate_limited(path: str, write_limit: int) -> dict[str, Any]: + """A 429 as ctx's handlers give it: the write rate with ``code: rate_limit`` (go:stage_gates.go: + 92-139), the read rate without a code (go:ratelimit.go:42-47).""" + if path == "/api/store": + return _err(f"Rate limit exceeded: max {write_limit} writes per 60 seconds", "rate_limit") + return {"success": False, "error": "Rate limit exceeded: max 600 reads per 60 seconds"} + + +def _quota(text: str, limit: int, count: int, requested: int) -> tuple[int, dict[str, Any]]: + return 429, {"success": False, "error": text, "limit": limit, "count": count, "requested": requested} -def _shadowed_action(body: Mapping[str, Any]) -> bool: - """A second spelling of ``action`` (``{"action":"get","ACTION":"purge"}``) counts as another action.""" - return any(k.lower() == "action" and k != "action" for k in body) +def _plain(status: int, text: str) -> tuple[int, dict[str, Any]]: + return status, {"success": False, "error": text} def _err(text: str, code: str) -> dict[str, Any]: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py index ac19558dd..82fe79fec 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py @@ -568,7 +568,7 @@ def test_get_blocks_redacts_the_key_in_the_entries_of_blocks_it_cannot_have(fake _keys(fake_ctx) monkeypatch.setattr( fake_ctx, - "_get_one", + "_entry", lambda block_id, read_set: {"id": block_id, "code": "not_found", "error": f"no block for {MEMBER_KEY}"}, ) client = CtxClient(fake_ctx.url, MEMBER_KEY, timeout=5, narrowing=Narrowing(read=(K,))) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py index d3376be01..06c5635f1 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -482,6 +482,7 @@ def broken(path, data): def test_provision_sends_only_what_ctx_decodes(admin): fake, home = admin + fake.add_scope("t:d111-extra") # ctx refuses a scope its tenant does not have (403) assert _provision(home, "--read", "t:d111-extra") == 0 (call,) = [r.body for r in fake.requests("/api/manage") if r.action == "keyset-provision"] assert set(call) == {"action", "data"} and set(call["data"]) == {"scopes", "keys"} diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_server_forms.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_server_forms.py new file mode 100644 index 000000000..9ba0b501f --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_server_forms.py @@ -0,0 +1,83 @@ +"""Seam fake/P-D: what the plugin does with the answers ctx gives since the fake answers as the Go server of +axis 02 (``tests/fakes/ctx_server.py``, ``tests/test_fake_ctx_wire.py``). + +``base_blocks`` takes block ids and id prefixes (``access._BLOCK_ID``); ctx's multi-id get answers a prefix +of more than one block the caller sees with an entry ``code: ambiguous_id`` (``go/internal/handler/ +get_ids.go:35``, ``:119-120``). That is an answer about the block, as ``not_found`` and ``invalid_id`` +are: the hook skips it and names it. Before, the code was unknown to the hook, which then gave no text at +all and raised ``BaseBlocksUnavailable`` on every turn ("the core asks again"), for a field the operator +has to fix.""" + +from __future__ import annotations + +import asyncio +import time + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_server_forms") +bb = ah.plugin_module(_PKG, "memory.base_blocks") +st = ah.plugin_module(_PKG, "memory.status") +_nar = ah.plugin_module(_PKG, "memory.narrowing") + +K, M = "t:d111-k", "t:d111-members" +MEMBER_KEY = "ctx_member_111_server_forms" +LABEL = "hermes:discord:111:members" +RULES = "aaaaaaaa-0000-4000-8000-000000000001" +TWINS = ("bbbbbbbb-0000-4000-8000-000000000001", "bbbbbbbb-0000-4000-8000-000000000002") +PREFIX = "bbbbbbbb-0000" + + +@pytest.fixture +def world(fake_ctx, monkeypatch, _isolated_hermes_home): + bb.reset_state() + _nar.reset_proofs() + home = _isolated_hermes_home + (home / "config.yaml").write_text("platform_toolsets:\n discord: [web]\n", encoding="utf-8") + fake_ctx.add_key(secret=MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=LABEL) + fake_ctx.add_block(K, "House rules", "be kind", block_id=RULES) + for block_id in TWINS: + fake_ctx.add_block(K, "Twin", "one of two", block_id=block_id) + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + yield fake_ctx, home + bb.reset_state() + _nar.reset_proofs() + + +def _call(base_blocks): + own = {"key": "CTX_KEY_111_MEMBERS", "tenant": "t", "read": [K], "write": M, "base_blocks": list(base_blocks)} + kwargs = ah.hook_kwargs(fields={"ctx_checkpoint": own}) + return asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, timeout=30.0, **kwargs)) + + +def _base_entry(home): + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + for row in st.read_access(str(home)): + entry = (row.get("base_blocks") or {}).get("members") + if entry: + return entry + time.sleep(0.02) + return {} + + +@pytest.mark.parametrize("without_c4", [False, True], ids=["multi-id get", "one get per id"]) +def test_an_ambiguous_prefix_is_skipped_and_named_not_retried(world, without_c4): + fake, home = world + fake.without_c4 = without_c4 + outcome = _call([RULES, PREFIX]) + assert outcome.answered and outcome.error is None, "a whole answer, not 'try again'" + assert "be kind" in outcome.result["prompt"] and "one of two" not in outcome.result["prompt"] + entry = _base_entry(home) + assert entry.get("state") == "delivered" and PREFIX in (entry.get("skipped") or {}) + + +def test_a_text_of_ambiguous_prefixes_only_is_not_delivered_and_not_retried(world): + fake, home = world + outcome = _call([PREFIX]) + assert outcome.answered and outcome.error is None and outcome.result is None + before = fake.count("/api/manage", "get") + assert _call([PREFIX]).result is None + assert fake.count("/api/manage", "get") == before, "the answer is kept: no fetch on the next turn" + assert _base_entry(home).get("state", "").startswith("not delivered") diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py new file mode 100644 index 000000000..b0863853c --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py @@ -0,0 +1,265 @@ +"""The fake ctx server answers as the Go server of axis 02 answers (``feat/access-binding-server``, +``788319cd``): status, body keys, ``code`` and the narrowing echo, for every form the plugin reads or a +test leans on. The place in ``go/internal/handler/`` is named per test (``go:<file>:<line>``). Plugin +tests run against this fake only; a fake that answers otherwise than ctx proves the plugin against a +server that does not exist.""" + +from __future__ import annotations + +import json +import re +import urllib.error +import urllib.request + +import pytest + +K, M = "t:d111-k", "t:d111-members" +MEMBER = "ctx_member_wire_secret" +ADMIN = "ctx_admin_wire_secret" + + +def _call(fake, method, path, body=None, *, key=MEMBER, read=None, write=None): + headers = {"X-Context-Key": key, "Content-Type": "application/json"} + if read is not None: + headers["X-Context-Read-Scopes"] = read + if write is not None: + headers["X-Context-Write-Scope"] = write + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request(fake.url + path, data=data, headers=headers, method=method) # noqa: S310 + try: + with urllib.request.urlopen(request, timeout=5) as answer: # noqa: S310 - 127.0.0.1 + return answer.status, json.loads(answer.read()), answer.headers + except urllib.error.HTTPError as exc: + return exc.code, json.loads(exc.read()), exc.headers + + +@pytest.fixture +def fake(fake_ctx): + fake_ctx.add_key(secret=MEMBER, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label="m") + fake_ctx.add_key(secret=ADMIN, tenant="t", home="t:main", role="admin") + return fake_ctx + + +# -- C-1/C-2 ----------------------------------------------------------------------------------------- + + +def test_an_unknown_key_is_401_without_code(fake): + """go:middleware.go:504-512, :683-697.""" + status, body, headers = _call(fake, "GET", "/api/whoami", key="nobody") + assert (status, body) == (401, {"error": "unauthorized"}) and headers.get("WWW-Authenticate") + + +def test_whoami_sends_narrowed_null_and_the_fields_of_the_server(fake): + """go:whoami.go:21-95, :85 (``narrowed`` has no omitempty).""" + _status, body, _headers = _call(fake, "GET", "/api/whoami") + assert "narrowed" in body and body["narrowed"] is None + for name in ("tenant_id", "api_key_id", "principal_id", "tenant_display_name", "capabilities"): + assert name in body + _status, narrowed, headers = _call(fake, "GET", "/api/whoami", read=K) + assert narrowed["narrowed"] == {"read": [K], "write": ""} and headers["X-Context-Narrowed"] == f"{K};" + assert narrowed["api_key_id"] == body["api_key_id"], "the same key in both answers" + + +def test_write_scopes_follow_writable_block_scopes(fake): + """go:context_store.go:442-462: home, shared when allowed, the write scopes that are allowed or home.""" + fake.add_key(secret="ctx_w", tenant="t", home="t:a", allowed=("shared", "t:b"), write_scopes=("t:b", "t:c")) + _status, body, _headers = _call(fake, "GET", "/api/whoami", key="ctx_w") + assert body["write_scopes"] == ["t:a", "shared", "t:b"] + + +@pytest.mark.parametrize( + ("headers", "status", "code"), + [ + ({"write": K}, 400, "scope_narrowing_invalid"), + ({"read": ",".join(f"t:s{i}" for i in range(9))}, 400, "scope_narrowing_invalid"), + ({"read": f"{K},{K}"}, 400, "scope_narrowing_invalid"), + ({"read": "t:other"}, 403, "scope_denied"), + ({"read": K, "write": K}, 403, "scope_denied"), + ], +) +def test_refusals_of_the_narrowing_carry_a_code_and_no_echo(fake, headers, status, code): + """go:narrowing.go:75-163: every refusal of narrowAuth goes through writeJSONReject, before the echo.""" + got, body, answer_headers = _call(fake, "POST", "/api/search", {"query": "x"}, **headers) + assert (got, body["code"]) == (status, code) and "X-Context-Narrowed" not in answer_headers + + +def test_a_required_key_refuses_unnarrowed_but_whoami(fake): + """go:narrowing.go:77-85.""" + status, body, _headers = _call(fake, "POST", "/api/search", {"query": "x"}) + assert (status, body["code"]) == (403, "scope_narrowing_required") + assert _call(fake, "GET", "/api/whoami")[0] == 200 + + +def test_a_handler_refusal_of_a_narrowed_request_carries_the_echo(fake): + """go:middleware.go:702-707: the echo is set before the handler runs.""" + status, body, headers = _call(fake, "POST", "/api/store", {"title": "t", "content": "c"}, read=K) + assert (status, body["code"], headers["X-Context-Narrowed"]) == (403, "scope_denied", f"{K};") + status, body, headers = _call(fake, "POST", "/api/manage", {"action": "update"}, read=K) + assert (status, body["code"], headers["X-Context-Narrowed"]) == (403, "scope_narrowing_route", f"{K};") + + +@pytest.mark.parametrize(("path", "code"), [("/api/search", None), ("/api/store", "rate_limit")]) +def test_a_429_carries_the_echo_and_a_code_only_on_writes(fake, path, code): + """go:ratelimit.go:42-47 (reads, no code), go:stage_gates.go:92-139 (writes, rate_limit).""" + fake.throttle[path] = 1 + status, body, headers = _call(fake, "POST", path, {"title": "t", "content": "c"}, read=M, write=M) + assert (status, body.get("code"), headers["X-Context-Narrowed"]) == (429, code, f"{M};{M}") + + +def test_the_decoded_action_is_the_last_spelling(fake): + """go:manage_table.go:433-450: JSON keys match ``action`` in any case, the last one wins.""" + status, body, _headers = _call(fake, "POST", "/api/manage", {"action": "get", "ACTION": "purge"}, read=K) + assert (status, body["code"]) == (403, "scope_narrowing_route") + + +def test_an_unknown_action_is_400_without_code(fake): + """go:manage_table.go:452-459.""" + assert _call(fake, "POST", "/api/manage", {"action": "nope"}, key=ADMIN)[:2] == ( + 400, + {"success": False, "error": "Unknown action"}, + ) + + +def test_store_answers_success_and_judges_the_scope_of_the_body(fake): + """go:context_store.go:487-501.""" + status, body, _headers = _call(fake, "POST", "/api/store", {"title": "t", "content": "c"}, read=M, write=M) + assert status == 200 and body["success"] is True and body["block"]["scope"] == M + status, body, _headers = _call( + fake, "POST", "/api/store", {"title": "t", "content": "c", "scope": K}, read=f"{M},{K}", write=M + ) + assert (status, body["code"]) == (403, "scope_denied") + + +# -- C-4 --------------------------------------------------------------------------------------------- + + +def test_get_with_ids_answers_entries_with_the_codes_of_the_server(fake): + """go:get_ids.go:34-59, :112-135: not_found, invalid_id (prefix < 8), ambiguous_id (+ matches).""" + one = fake.add_block(K, "A", "a", block_id="aaaaaaaa-0000-4000-8000-000000000001") + fake.add_block(K, "B", "b", block_id="aaaaaaaa-0000-4000-8000-000000000002") + asked = [one.upper(), "aaaaaaaa-0000", "aaaa", "bbbbbbbb-0000-4000-8000-000000000009"] + status, body, _headers = _call(fake, "POST", "/api/manage", {"action": "get", "ids": asked}, read=K) + assert status == 200 and body["action"] == "get" and body["success"] is True + found, ambiguous, short, missing = body["blocks"] + assert found["id"] == one and {"created_at", "updated_at", "scope"} <= set(found) + assert (ambiguous["code"], len(ambiguous["matches"])) == ("ambiguous_id", 2) + assert short["code"] == "invalid_id" and short["id"] == "aaaa" + assert missing == {"id": asked[3], "code": "not_found", "error": "Block not found"} + + +@pytest.mark.parametrize( + "body", + [ + {"action": "get", "ids": ["x" * 36], "id": "y" * 36}, + {"action": "get", "ids": []}, + {"action": "get", "ids": ["a"] * 17}, + {"action": "get", "ids": [None]}, + {"action": "get", "ids": ["x" * 36], "include_archived": True}, + ], +) +def test_get_with_ids_refuses_what_the_server_refuses(fake, body): + """go:get_ids.go:40-46, :90-102.""" + status, answer, _headers = _call(fake, "POST", "/api/manage", body, read=K) + assert (status, answer["code"]) == (400, "invalid_body") + + +def test_ids_null_reads_the_single_id(fake): + """go:get_ids.go:61-76: ``ids: null`` counts as not sent.""" + block = fake.add_block(K, "A", "a") + status, body, _headers = _call(fake, "POST", "/api/manage", {"action": "get", "id": block, "ids": None}, read=K) + assert status == 200 and body["block"]["id"] == block and "graph_visible" in body + + +def test_a_server_without_c4_ignores_ids(fake): + """``bcf686a5``: ``manageRequest`` has no ``ids``; ``ids`` alone is a missing ``id``, without a code.""" + fake.without_c4 = True + block = fake.add_block(K, "A", "a") + assert _call(fake, "POST", "/api/manage", {"action": "get", "ids": [block]}, read=K)[:2] == ( + 400, + {"success": False, "error": "Missing required field: id"}, + ) + status, body, _headers = _call(fake, "POST", "/api/manage", {"action": "get", "id": block, "ids": [block]}, read=K) + assert status == 200 and body["block"]["id"] == block + + +# -- C-3 --------------------------------------------------------------------------------------------- + + +def _keyset(fake, data, key=ADMIN, **extra): + return _call(fake, "POST", "/api/manage", {"action": "keyset-provision", "data": data, **extra}, key=key)[:2] + + +def _spec(**overrides): + spec = {"label": "hermes:discord:111:members", "home_scope": "d111-members", "allowed_scopes": ["d111-k"]} + spec.update(overrides) + return spec + + +def test_keyset_mints_required_hex_keys_by_default(fake): + """go:keyset_provision.go:50-54, :199-202; go:store/api_keys.go:159-165.""" + status, body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec(write_scopes=[])]}) + assert status == 200 + (key,) = body["keys"] + assert key["scope_narrowing"] == "required" and re.fullmatch(r"[0-9a-f]{64}", key["api_key"]) + assert key["home_scope"] == "t:d111-members" and key["allowed_scopes"] == ["t:d111-k"] + + +@pytest.mark.parametrize( + ("data", "extra", "status"), + [ + ({"keys": [_spec()], "extra": 1}, {}, 400), + ({"keys": [{**_spec(), "Replace": True}]}, {}, 400), + ({"keys": [_spec()]}, {"id": "x"}, 400), + ({}, {}, 400), + ({"scopes": ["t:full"]}, {}, 400), + ({"scopes": ["a", "a"]}, {}, 400), + ({"keys": [_spec(), _spec()]}, {}, 400), + ({"keys": [_spec(scope_narrowing="maybe")]}, {}, 400), + ({"scopes": ["d111-k", "d111-members"], "keys": [_spec(write_scopes=["d111-x"])]}, {}, 403), + ({"scopes": ["d111-k", "d111-members"], "keys": [_spec(allowed_scopes=["other:k"])]}, {}, 403), + ({"tenant_id": "x", "scopes": ["a"]}, {}, 403), + ], +) +def test_keyset_refusals_carry_no_code_and_write_nothing(fake, data, extra, status): + """go:keyset_provision.go:32-202, go:store/keyset.go:64-75; go:errcode.go:17-27 (no code).""" + before = len(fake.keys) + got, body = _keyset(fake, data, **extra) + assert got == status and "code" not in body and body["success"] is False + assert len(fake.keys) == before + + +def test_keyset_write_scopes_outside_allowed_or_home_is_400(fake): + """go:store/api_keys.go:147-154 (checked at the insert, after the tenant's scopes).""" + fake.add_scope("t:d111-x") + status, body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec(write_scopes=["d111-x"])]}) + assert status == 400 and "write_scope not in allowed_scopes" in body["error"] and "code" not in body + + +def test_keyset_for_a_member_key_is_403_admin_key_required(fake): + """go:manage_table.go:254, :394-397.""" + fake.add_key(secret="ctx_plain_member", tenant="t", home="t:x") + assert _keyset(fake, {"scopes": ["a"]}, key="ctx_plain_member") == ( + 403, + {"success": False, "error": "admin key required"}, + ) + + +def test_keyset_quota_is_429_with_limit_count_and_requested(fake): + """go:keyset_provision.go:250-262, go:store/keyset.go:344-360: count after the replacements.""" + fake.add_key(secret="ctx_old", tenant="t", home="t:d111-members", label="hermes:discord:111:members") + fake.max_keys = 3 # member, admin, old + status, body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec()]}) + assert (status, body["limit"], body["count"], body["requested"]) == (429, 3, 3, 1) and "code" not in body + status, body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec(replace_label=True)]}) + assert status == 200, "the replaced key does not count" + assert not fake.keys["ctx_old"].active + fake.max_scopes = len(fake.tenant_scopes("t")) + status, body = _keyset(fake, {"scopes": ["d111-new"]}) + assert (status, body["error"], body["requested"]) == (429, "tenant scope quota exceeded", 1) + + +def test_keyset_replace_label_spares_a_key_that_is_no_member_key(fake): + """go:store/keyset.go:70-75, :311-342.""" + fake.add_key(secret="ctx_owner", tenant="t", home="t:main", role="owner", label="hermes:discord:111:members") + status, _body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec(replace_label=True)]}) + assert status == 409 and fake.keys["ctx_owner"].active From 6463dca528d30dbf128578c785d0db4716831bd9 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:33:47 +0100 Subject: [PATCH 20/65] fix(ctx_checkpoint): a delegate_task child of a CLI session is local under ungoverned: local, proven by the agent whose turn builds it ungoverned: local (the recipe for operator profiles) admits local sessions and their forks. A fork learned its parent's platform only from HERMES_SESSION_PLATFORM, which Hermes binds in gateway sessions alone: a delegate_task child of a CLI session was off, and under compression.checkpoint_required its compaction failed (S3-B1; the same under auto once the profile saw a governed session). access.fork_parent_platform(init) is the parent_platform of the decision now: the gateway session variable first; else, for a fork, the agent whose turn builds it (Hermes binds it per turn, agent.subagent_lifecycle.get_active_subagent_parent, a published module; the tool executor copies the context into the tool's thread), and only when its session_id is the fork's parent_session_id. A gateway parent names its messaging platform, a cron parent cron, a fork of a fork subagent; no parent, another session's parent or no parent_session_id stays unknown and strict. Nothing is read from os.environ. Same on Hermes without the access groups (row 1). The S3 contract run builds the child inside the parent's turn as delegate_task does; the strict xfail of S3-B1 comes off (green against Hermes with the access groups), and the same child built outside the parent's turn stays off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/access.py | 31 +++- .../plugin/ctx_checkpoint/memory/provider.py | 2 +- .../ctx_checkpoint/tests/s3_core_child.py | 11 +- .../tests/test_access_seam_cli_fork.py | 151 ++++++++++++++++++ .../tests/test_s3_core_contract.py | 12 +- 5 files changed, 195 insertions(+), 12 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_cli_fork.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py index 03a4774a2..841145c0b 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -334,6 +334,32 @@ def session_parent_platform() -> str | None: return value or None +def fork_parent_platform(init_kwargs: Mapping[str, Any]) -> str | None: + """The platform of the session a fork was built in, the ``parent_platform`` of ``decide``: the + session variable (``session_parent_platform``, bound in gateway sessions); else, for a fork, the + agent whose turn builds it (Hermes binds it per turn, ``agent.subagent_lifecycle``, a published + module; the tool executor copies the context into the tool's thread), and only when that agent's + ``session_id`` is the fork's ``parent_session_id``: a CLI or TUI session binds no session variable. + ``None`` when unknown; nothing here is read from ``os.environ``.""" + known = session_parent_platform() + if known is not None or not isinstance(init_kwargs, Mapping) or not _fork(init_kwargs): + return known + wanted = init_kwargs.get("parent_session_id") + if not isinstance(wanted, str) or not wanted: + return None + try: + from agent.subagent_lifecycle import get_active_subagent_parent + + parent = get_active_subagent_parent() + except Exception: + return None + if parent is None or getattr(parent, "session_id", None) != wanted: + return None + platform = getattr(parent, "platform", None) + platform = platform.strip().lower() if isinstance(platform, str) else "" + return platform or None + + def context_from_init(init_kwargs: Mapping[str, Any]) -> AccessContext | None: """The access group ``initialize`` was told about (``platform``, ``scope_id``, ``access_group``, ``access_group_restricted``, ``access_fields``, ``agent_identity``); ``None`` without @@ -997,8 +1023,8 @@ def decide( v8: bool, ) -> Decision: """The decision table of design 02 §4.2 (first matching row): pure, no network, no files, no - secret. ``current``: ``current_access()`` at the build; ``parent_platform``: the copied session - variable ``HERMES_SESSION_PLATFORM`` of a fork (``session_parent_platform()``); ``settings``: + secret. ``current``: ``current_access()`` at the build; ``parent_platform``: the platform of a + fork's parent session (``fork_parent_platform(init_kwargs)``); ``settings``: ``load_settings`` (an unknown mode decides as ``off``); ``markers``: ``read_markers``; ``v8``: ``access_supported()``. ``governed_unbound: profile`` opens the profile's connection only in a profile known to serve no restricted group (``restricted_profile`` false, no ``restricted_seen``). @@ -1090,6 +1116,7 @@ def decide( "current_access", "decide", "e7_inputs", + "fork_parent_platform", "is_strict", "load_settings", "parse_fields", diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 03ef483d1..7f0d839d3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -752,7 +752,7 @@ def _decide_access(self, kwargs: Mapping[str, Any]) -> None: decision = _access.decide( init, _access.current_access(), - _access.session_parent_platform(), + _access.fork_parent_platform(init), settings, markers, _access.access_supported(), diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py b/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py index 9f5cd0d2e..8dee46bd0 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py @@ -583,15 +583,20 @@ async def go(): def scenario_delegate(world: World) -> dict[str, Any]: """4 (H-2/VB-3): ``delegate_task``'s child built inside a member's turn (``checkpoint_required``, so the child loads the provider as a fork) sees the group; and a fork of a CLI session: what the plugin - reads as the parent's platform (``HERMES_SESSION_PLATFORM``).""" + reads as the parent's platform (``HERMES_SESSION_PLATFORM``, the agent whose turn builds the fork).""" from agent.subagents.spawn import _build_child_agent from gateway.run import _async_profile_runtime_scope, _profile_runtime_scope out: dict[str, Any] = {} - def child_of(parent, label): + def child_of(parent, label, *, in_parent_turn=True): + # delegate_task builds the child inside the parent's turn, which binds the parent + # (agent/turn_facade.py: bind_subagent_parent; the tool executor copies the context). + from agent.subagent_lifecycle import bind_subagent_parent + world.inits.clear() with ( + bind_subagent_parent(parent) if in_parent_turn else contextlib.nullcontext(), patch("tools.schemas.get_tool_definitions", return_value=[]), patch("tools.schemas.check_toolset_requirements", return_value={}), patch("agent.process_bootstrap.OpenAI"), @@ -635,6 +640,8 @@ async def turn(): parent = world.build_agent("cli", session_id=f"s-cli-{mode}") out[f"cli_parent_inits_{mode}"] = list(world.inits) child_of(parent, f"cli_fork_{mode}") + if mode == "local": # the same child built outside the parent's turn: no proven parent + child_of(parent, "cli_fork_local_outside_turn", in_parent_turn=False) with contextlib.suppress(Exception): parent.close() return out diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_cli_fork.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_cli_fork.py new file mode 100644 index 000000000..ba0aa7054 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_cli_fork.py @@ -0,0 +1,151 @@ +"""Seam S3-B1: the fork of a local session is local. A ``delegate_task`` child of a CLI session was ``off`` +under ``ungoverned: local`` (the operator recipe), because Hermes binds ``HERMES_SESSION_PLATFORM`` only in +gateway sessions (``gateway/run.py``) and the plugin knew no other sign of the parent's platform. + +The sign used now: the agent whose turn builds the fork. Hermes binds it per turn +(``agent.subagent_lifecycle.bind_subagent_parent`` in ``agent/turn_facade.py``, a ContextVar the tool +executor copies into the tool's thread) and publishes the reader (``get_active_subagent_parent``, +``plugin_api.json``). It counts only when its ``session_id`` is the fork's ``parent_session_id`` (what +``delegate_task`` passes, ``agent/agent_init_memory_provider.py``): a parent of another fork, no parent, +or a fork without ``parent_session_id`` stays unknown, and unknown stays strict. A gateway session's +variable comes first; nothing is read from ``os.environ``. A fork of a fork names ``subagent``: not local. +""" + +from __future__ import annotations + +import contextvars + +import pytest +from agent.subagent_lifecycle import bind_subagent_parent +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_cli_fork") +acc = ah.plugin_module(_PKG, "memory.access") +_nar = ah.plugin_module(_PKG, "memory.narrowing") +Provider = _PKG.CtxCheckpointMemoryProvider + +PROFILE_KEY = "ctx_profile_key_cli_fork" + + +class _Agent: + """Stands for the AIAgent whose turn runs ``delegate_task`` (what the plugin reads of it).""" + + def __init__(self, platform, session_id="s-parent"): + self.platform = platform + self.session_id = session_id + + +def _fork_init(parent_session_id="s-parent", **extra): + init = {"platform": "subagent", "agent_context": "subagent", **extra} + if parent_session_id is not None: + init["parent_session_id"] = parent_session_id + return init + + +def _isolated(fn): + """Run *fn* in a copy of the context: nothing it binds outlives the test.""" + return contextvars.copy_context().run(fn) + + +def _under(parent, fn): + def run(): + with bind_subagent_parent(parent): + return fn() + + return _isolated(run) + + +@pytest.mark.parametrize("platform", ["cli", "tui", "discord", "cron", "subagent"]) +def test_the_parent_whose_turn_builds_the_fork_names_its_platform(platform): + assert _under(_Agent(platform), lambda: acc.fork_parent_platform(_fork_init())) == platform + + +@pytest.mark.parametrize( + ("parent", "init"), + [ + (None, _fork_init()), + (_Agent("cli", "s-other"), _fork_init()), + (_Agent("cli"), _fork_init(parent_session_id=None)), + (_Agent("cli"), {"platform": "discord", "agent_context": "primary", "parent_session_id": "s-parent"}), + (_Agent(None), _fork_init()), + (_Agent(" "), _fork_init()), + ], + ids=["no parent bound", "another session's parent", "no parent_session_id", "no fork", "no platform", "blank"], +) +def test_a_parent_that_is_not_proven_stays_unknown(parent, init): + if parent is None: + assert _isolated(lambda: acc.fork_parent_platform(init)) is None + else: + assert _under(parent, lambda: acc.fork_parent_platform(init)) is None + + +def test_the_gateway_session_variable_comes_first(): + from gateway.session_context import clear_session_vars, set_session_vars + + def run(): + tokens = set_session_vars(platform="discord") + try: + return acc.fork_parent_platform(_fork_init()) + finally: + clear_session_vars(tokens) + + assert _under(_Agent("cli"), run) == "discord" + + +def test_the_process_environment_makes_no_parent(monkeypatch): + """``HERMES_SESSION_PLATFORM`` in ``os.environ`` is process state any session could have set.""" + monkeypatch.setenv("HERMES_SESSION_PLATFORM", "cli") + assert _isolated(lambda: acc.fork_parent_platform(_fork_init())) is None + + +# -- the real entrance: initialize of a fork ---------------------------------------------------------- + + +@pytest.fixture +def profile(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:ops") + _nar.reset_proofs() + + def make(mode, *, v8=True, governed_seen=False): + ah.install(monkeypatch, v8=v8, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY": PROFILE_KEY}) + home = tmp_path / mode / str(v8) / str(governed_seen) / "profiles" / "ops" + home.mkdir(parents=True) + (home / "config.yaml").write_text(f"memory:\n ctx_checkpoint:\n ungoverned: {mode}\n", encoding="utf-8") + if governed_seen: + acc.raise_markers(str(home), governed_seen=True) + return home + + yield make + _nar.reset_proofs() + + +def _fork_session(home, parent, *, v5=True): + def build(): + provider = Provider(config={"transport": "rest", "memory": True}) + kwargs = dict(_fork_init(), **(ah.v5_kwargs() if v5 else {})) + provider.initialize("s-child", hermes_home=str(home), **kwargs) + return provider + + provider = _under(parent, build) if parent is not None else _isolated(build) + return provider._decision.kind, provider._client is not None + + +@pytest.mark.parametrize( + ("mode", "v8", "governed_seen"), + [("local", True, False), ("local", False, False), ("auto", True, True)], + ids=["local, core PR", "local, no core PR", "auto after a governed session"], +) +def test_a_fork_of_a_cli_session_keeps_the_profile(profile, mode, v8, governed_seen): + home = profile(mode, v8=v8, governed_seen=governed_seen) + assert _fork_session(home, _Agent("cli"), v5=v8) == ("profile", True) + + +@pytest.mark.parametrize( + "parent", + [None, _Agent("discord"), _Agent("cli", "s-other"), _Agent("cron"), _Agent("subagent")], + ids=["no parent", "gateway parent", "another session", "cron parent", "fork of a fork"], +) +@pytest.mark.parametrize(("mode", "governed_seen"), [("local", False), ("auto", True)]) +def test_a_fork_of_any_other_session_stays_off(profile, parent, mode, governed_seen): + home = profile(mode, governed_seen=governed_seen) + assert _fork_session(home, parent) == ("off", False) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py index 57df270d4..66c0c3184 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py @@ -214,19 +214,17 @@ def test_a_cli_session_binds_no_session_platform(tmp_path_factory): assert result["cli_parent_inits_local"][0]["decisions"][0]["kind"] == "profile" -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="S3 finding S3-B1: a delegate child of a CLI session is off under ungoverned: local (no parent platform)", -) def test_a_delegate_child_of_a_cli_session_keeps_the_profile_under_local(tmp_path_factory): """The promise of ``ungoverned: local`` (design 02 §3.2: forks only when their parent session was local): - the child of a local CLI session is local too. Strict xfail while S3-B1 stands; a fix turns it green and - the marker comes off with it.""" + the child of a local CLI session is local too (S3-B1). The sign is the agent whose turn builds the child + (``agent.subagent_lifecycle``), proven by the child's ``parent_session_id``; the same child built outside + the parent's turn has no proven parent and stays off.""" result, _ = _run("delegate", tmp_path_factory) [init] = result["cli_fork_local"]["inits"] assert init["platform"] == "subagent" assert init["decisions"][0]["kind"] == "profile", init["decisions"][0] + [outside] = result["cli_fork_local_outside_turn"]["inits"] + assert outside["decisions"][0]["kind"] == "off", outside["decisions"][0] def test_r7_admits_the_restricted_profile_exactly_when_the_group_carries_the_fields(tmp_path_factory): From 771146087709bb68bf12068f798748a442c8b604 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 06:44:44 +0100 Subject: [PATCH 21/65] =?UTF-8?q?feat(ctx=5Fcheckpoint):=200.20.0=20?= =?UTF-8?q?=E2=80=94=20the=20access=20groups=20documented,=20the=20hook=20?= =?UTF-8?q?declared,=20and=20the=20release=20notes=20name=20what=20changes?= =?UTF-8?q?=20without=20them?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit README: a section "Access groups" with the twelve fields (who sets them, what they do, what applies when they are not set), the proof of a binding (rules E1 to E7), sessions without an access group and the markers, the eight settings, "Base blocks", "Recipe for restricted profiles", "Operator profiles on Discord", the operator tools and their warnings, hermes memory status with access groups, the write limit, and "What this does not promise"; "What it does on your machine" and "Layout" name what the access groups read, write and call. The text follows the built code: auto without a direct-message exception, governed_unbound: profile only in profiles without restricted groups, E7 failing without a saved toolset list, base_workers 32, server:/group: tags dropped everywhere, ctx_store refusing ctx_plugin metadata, CLI subagents local under ungoverned: local. CHANGELOG 0.20.0 with "Behaviour changes without access groups" and the minimum ctx server for group bindings (per-request scope narrowing, 5.95.0 or later). plugin.yaml: 0.20.0, the description, and provides_hooks: [access_group_fields], so hermes plugins validate passes against Hermes with access groups (it failed on an undeclared hook) and against the pinned Hermes (a warning: declared, not registered). VERSION, PLUGIN_VERSION and the skill's version follow. The README test of P-F is switched on; the S1 shield list is empty and marks nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- README.md | 2 +- integrations/hermes/README.md | 10 + .../hermes/plugin/ctx_checkpoint/README.md | 342 +++++++++++++++++- .../hermes/plugin/ctx_checkpoint/VERSION | 2 +- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 77 ++++ .../plugin/ctx_checkpoint/memory/README.md | 6 +- .../ctx_checkpoint/memory/checkpoint.py | 2 +- .../hermes/plugin/ctx_checkpoint/plugin.yaml | 8 +- .../ctx_checkpoint/skills/ctx-memory/SKILL.md | 2 +- .../ctx_checkpoint/tests/fakes/s1_pending.py | 9 +- 10 files changed, 434 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 53c93776f..01dc7be82 100644 --- a/README.md +++ b/README.md @@ -320,7 +320,7 @@ Three plugins for [Hermes](https://github.com/NousResearch/hermes-agent) live in | Plugin | What it does | Install | |---|---|---| -| [`ctx_checkpoint`](integrations/hermes/README.md) | The ctx memory provider. Before Hermes shortens (compacts) a long conversation, it archives the direct transcript in ctx; on request, no compaction runs without that copy. Afterwards the agent's system prompt names that copy and how to read it. With `memory: true` also recall before each turn, `ctx_*` agent tools, a mirror of Hermes' memory files, fact extraction, session digests and the skill `ctx-memory`. Talks to ctx through Hermes' own MCP connection. Its memory engine was contributed by derLonius (W4-NERF) as [hermes-ctx-plugin](https://github.com/W4-NERF/hermes-ctx-plugin). | `hermes plugins install ctx_checkpoint`, then `hermes memory setup ctx_checkpoint` or the forms in Hermes Desktop (Settings → Memory and Settings → Plugins); `hermes memory status` shows whether checkpoints work | +| [`ctx_checkpoint`](integrations/hermes/README.md) | The ctx memory provider. Before Hermes shortens (compacts) a long conversation, it archives the direct transcript in ctx; on request, no compaction runs without that copy. Afterwards the agent's system prompt names that copy and how to read it. With `memory: true` also recall before each turn, `ctx_*` agent tools, a mirror of Hermes' memory files, fact extraction, session digests and the skill `ctx-memory`. Talks to ctx through Hermes' own MCP connection. On a Hermes with access groups, each group of a governed server can get its own ctx key, scopes and base blocks, narrowed per request (needs a ctx server with per-request scope narrowing, 5.95.0 or later). Its memory engine was contributed by derLonius (W4-NERF) as [hermes-ctx-plugin](https://github.com/W4-NERF/hermes-ctx-plugin). | `hermes plugins install ctx_checkpoint`, then `hermes memory setup ctx_checkpoint` or the forms in Hermes Desktop (Settings → Memory and Settings → Plugins); `hermes memory status` shows whether checkpoints work | | [`ctx_handover`](integrations/hermes/plugin/ctx_handover/README.md) | Moves a running Hermes session, with its conversation and project folder, from one of your machines to another and back. Works without ctx. | `hermes plugins install ctx_handover` and `hermes plugins enable ctx_handover`, on both machines | | [`ctx_discord_policy`](integrations/hermes/plugin/ctx_discord_policy/README.md) | Lets the members of your Discord servers talk to a Hermes bot in a restricted Hermes profile while your own messages run in yours; it writes Hermes' own routing configuration for that, and each server is set up inside Discord with `/policy`. Works without ctx. | `hermes plugins install GottZ/ctx/integrations/hermes/plugin/ctx_discord_policy --enable` in the default profile, the member profile and every profile your own turns run in, then restart the gateway | diff --git a/integrations/hermes/README.md b/integrations/hermes/README.md index 526a92e34..b0267a4ff 100644 --- a/integrations/hermes/README.md +++ b/integrations/hermes/README.md @@ -54,6 +54,16 @@ digests, the `hermes ctx_checkpoint` CLI and the bundled `ctx-memory` skill. | Agent contexts | chain written in every context, labelled via `metadata.agent_context` | mirror, facts, digests skipped in `cron`/`flush`/`subagent` forks | | Setup | Desktop/Dashboard memory form or `hermes memory setup ctx_checkpoint` | the same form; one `memory: on/off` choice | +**Access groups (0.20.0).** On a Hermes with access groups +([NousResearch/hermes-agent#164604](https://github.com/NousResearch/hermes-agent/pull/164604)), +every group of a governed server can bind to its own ctx key and scopes, narrowed per request and +proven before use, and get base blocks for its prompt; group bindings need a ctx server with +per-request scope narrowing (5.95.0 or later). On a Hermes without them nothing of it is +registered. See [Access groups](plugin/ctx_checkpoint/README.md#access-groups) and, for what +changes without them, the 0.20.0 entry of the +[engine CHANGELOG](plugin/ctx_checkpoint/memory/CHANGELOG.md). The catalog pin stays at 0.19.1 +until the core pull request is decided. + The memory layer's engine (`plugin/ctx_checkpoint/memory/`) was contributed by derLonius (W4-NERF) as [hermes-ctx-plugin](https://github.com/W4-NERF/hermes-ctx-plugin) and is maintained here since ctx v5.29.0 (plugin 0.6.0); v5.28.0 shipped it for a day diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 7bccde4a7..5a8845af0 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -21,7 +21,9 @@ Compaction checkpoint head <root-session> ← stable title, upserted per ses Everything talks to ctx through Hermes' own MCP dispatch to the `mcp_servers.ctx` entry — the plugin holds no credentials. `transport: rest` switches to a REST client -with its own key (see below for what that buys). +with its own key (see below for what that buys). On a Hermes with access groups, each +group of a governed server can be bound to its own ctx key and scopes, always over REST +with the key its fields name ([Access groups](#access-groups)). ## Install @@ -201,9 +203,9 @@ The connection test names the tools when the entry name is rewritten. | Memory mirror | Hermes' curated `MEMORY.md`/`USER.md` writes become `agent-briefing` / `reference` blocks | `auto_memory_mirror` | | Fact extraction | up to 5 salient closing statements of the compacted turns become `learnings` blocks of type `session-digest`, deduplicated across compactions | `auto_compress_extract`, `facts_from_user`, `facts_reject_cjk_codeswitch` | | Session digests | one intent → outcome digest per segment (after a compaction, rolling, after idle, at session end), type `session-digest` | `auto_session_digest`, `digest_*`, `idle_digest_minutes` | -| Provenance | every write is tagged `source:hermes`, `profile:<name>`, `hook:<origin>` | — | +| Provenance | every write is tagged `source:hermes`, `profile:<name>`, `hook:<origin>`; a session of an access group adds `server:<platform>:<server id>` and `group:<group>` | — | | Skill | `ctx_checkpoint:ctx-memory` tells the model how to use the store well (query as a question, verify before acting, one durable fact per block) | registered with the provider | -| CLI | `hermes ctx_checkpoint status\|sync\|query\|store\|search\|get` | needs `transport: rest` for everything but `status` | +| CLI | `hermes ctx_checkpoint status\|sync\|query\|store\|search\|get` and `access …` ([Access groups](#access-groups)) | needs `transport: rest` for everything but `status` and `access` | All of these keys go under `memory.ctx_checkpoint` by their engine names; the four switches `auto_recall`, `auto_memory_mirror`, `auto_compress_extract` and @@ -373,6 +375,297 @@ returns an empty receipt and the compaction proceeds. The plugin negotiates the contract version with the loading host at runtime; details, host probes and the operator warnings are in the [full integration guide](../../README.md). +## Access groups + +Hermes with access groups (the core pull request NousResearch/hermes-agent#164604) lets a bot owner +put a governed server's members and roles into an ordered list of groups, each served by a Hermes +profile; a *restricted* group runs only in a profile that passes the core's profile check. On such a +Hermes, `ctx_checkpoint` registers twelve fields under the namespace `ctx_checkpoint` +(`/policy field <group> ctx_checkpoint.<name>=<value>`) and the hook `access_group_fields`, and binds +every session of a group to the ctx key and scopes its fields name. Hermes itself knows nothing of +ctx: the fields are the plugin's, and so are the rules below. + +It needs a **ctx server with per-request scope narrowing (5.95.0 or later)**: every group binding is +proven against it (`whoami`) and every request of a group carries the narrowing headers +(`X-Context-Read-Scopes`, `X-Context-Write-Scope`), whose echo (`X-Context-Narrowed`) the client +checks on every answer. Against an older server a group binding is off (the echo is missing); the +profile's own connection works as before. + +On a Hermes without access groups the plugin registers no fields and no hook (it asks for +`register_access_fields` on Hermes' public `PluginContext`), and nothing in this section applies +except the settings `ungoverned` and the markers (see the CHANGELOG, *Behaviour changes without +access groups*). + +### Fields of a group + +Hermes checks the type of a field; the plugin checks its form before it reads a secret or sends a +request, and a group with a broken field gets no ctx (`access status` names the field and the rule). +A value of the wrong type makes Hermes refuse the whole server entry. Only a bot owner may set an +`env_name` field (`key`, `base_url`); server admins may set the others. + +| Field | Type | What it does | Not set | +|---|---|---|---| +| `key` | env name | the variable in the serving profile's `.env` that holds the group's ctx key: `CTX_KEY`, `CTX_API_KEY` or `CTX_KEY_<…>`; a restricted group only `CTX_KEY_<server id>_<…>` of its own server (the server id of letters and digits) | restricted: no ctx; unrestricted: `governed_unbound` | +| `base_url` | env name | the variable that holds the group's ctx server URL: `CTX_BASE_URL` or `CTX_BASE_URL_<…>`; its value must be `https://` with a host, without user info, query or fragment | the profile's URL (`CTX_BASE_URL`, `memory.ctx_checkpoint.rest_base_url`, `ctx_base_url` of `ctx.json`, the origin of the ctx `mcp_servers` entry), without the `https` rule | +| `tenant` | str | the tenant slug the key must belong to | not checked; a restricted group needs it | +| `read` | list | 1 to 8 ctx scopes (`<slug>:<name>`, none twice) that recall, the read tools and the base blocks read | the key's read set without its home scope (at most 8, else off); a restricted group needs it | +| `write` | str | the scope the chain, facts, digests and the `MEMORY.md`/`USER.md` mirror write to; must be the key's home scope | the key's home scope; a restricted group needs it | +| `store` | str | the scope `ctx_store` writes to, within the key's write scopes (unrestricted groups only; restricted groups never get `ctx_store`) | `write` | +| `recall` | bool | recall before each turn | unrestricted on, restricted off; a restricted group's `true` counts only with `restricted_allow: [recall]` | +| `capture` | bool | chain, facts, digests and mirror are written | unrestricted on, restricted off; a restricted group's `true` counts only with `restricted_allow: [capture]` | +| `base_blocks` | list | up to 16 block ids (none twice) whose content joins the group's prompt ([Base blocks](#base-blocks)) | no base blocks | +| `base_max_chars` | int | most characters the base blocks add, 256 to 8 000 | 4 000 | +| `base_rev` | int | raise it to reload the base blocks in every session of the group | 0 | +| `enabled` | bool | `false`: the group gets no ctx; counts as set for the core's profile check | `true` | + +A restricted group needs `key`, `tenant`, `read` and `write`, with `write` not in `read` and every +scope in the tenant. Every block the chain, the facts, the digests, the mirror or `ctx_store` writes +for a group carries the tags `server:<platform>:<server id>` and `group:<group>`; the chain's head and +manifest carry `ctx_plugin.access` (platform, server, group, profile). Tags with these prefixes from +the model (`ctx_store`) or the CLI (`--tag`) are dropped, and `ctx_store` refuses metadata under the +key `ctx_plugin`. + +### The proof of a binding (rules E1 to E7) + +A group binds only after `whoami` of its key, narrowed to the group's `read`, and for a restricted +group also unnarrowed, passes the rules below; then every request of the group carries the narrowing. +What fails is named with the value it expected (`access status`, `access check`). + +| Rule | Holds when | For | +|---|---|---| +| E1 | the fields above are set and well formed; `write` not in `read`; `key` is `CTX_KEY_<server id>_…` | restricted | +| E2 | the key's tenant is `tenant`; it is no ctx server admin, its role is `member`, and it requires narrowing (`scope_narrowing: required`) | restricted (tenant: every group that sets it) | +| E3 | `write` is the key's home scope; the key writes exactly `write`, reads exactly `read` plus `write` (an incoming tenant grant fails this) and does not stage its writes (`confirm_writes`) | restricted; home scope and `read` within the key for all | +| E4 | the key's label is `hermes:<platform>:<server id>:<profile>` (a profile name that makes it longer than 100 characters is replaced by `#` and 16 hex digits of its SHA-256) | restricted | +| E5 | the narrowed `whoami` reports exactly the narrowing sent, and every answer echoes it | every group | +| E6 | every base block lies in `read` and not in `write` | every group (base blocks) | +| E7 | when the profile's `.env` holds a ctx key variable of another server or profile (`CTX_KEY`, `CTX_API_KEY`, any `CTX_KEY_*`/`CTX_API_KEY_*` but exactly one of this server), the saved toolset list `platform_toolsets.<platform>` of the profile names none of `terminal`, `file`, `code_execution`, `debugging`, `delegation` and no `hermes-*` bundle; without a saved list E7 fails | restricted | + +A proof that fails at the network (no answer, 5xx, 429) is asked again at most every 60 seconds; one +that fails at a rule keeps the session off until its agent is built anew. Raw `whoami` answers are +kept per process 60 seconds (15 after a failure) and judged again for every binding. The write client +of a group proves its own narrowing before its first write, off the turn. A group change within a +turn, or an answer without the echo, turns the agent off for the rest of its life. + +### Sessions without an access group + +What a session that serves no access group gets (a direct message, a server that is not governed, +`/background`, cron, the API server, a local CLI session) is the setting `ungoverned`; once a profile +has served a governed session, messaging sessions without their group get no ctx whatever the setting +says (the core passes no group also when it cannot read the turn's one). A profile that has served a +restricted group gets no ctx for any session without its group, on any Hermes. Both are markers in +`ctx_state/access-mode.json` (`governed_seen`, `restricted_seen`): they only rise, survive the state +pruning, and only `hermes ctx_checkpoint access reset-marker` lowers them. + +A fork (`delegate_task`, a checkpoint fork) counts as local when its parent session was: Hermes binds +the platform of a gateway session to the session, and for a CLI or TUI session the plugin takes the +agent whose turn builds the fork, when that agent's session is the fork's parent. A fork of a fork, +and a child built outside its parent's turn (a delegation backend in another process), has no proven +parent and counts as not local. + +### Settings (`memory.ctx_checkpoint.*` in `config.yaml`) + +Set by whoever writes the profile's `config.yaml`, never through `/policy` and never from `ctx.json`. +A number outside its range is moved to the nearest bound; an unknown mode is `off` (one WARNING); a +`config.yaml` that cannot be read, or a `memory` / `memory.ctx_checkpoint` that is no mapping, gives +`ungoverned: off` and `governed_unbound: off`. YAML reads an unquoted `off` as false, which counts as +`off` too. + +| Setting | Values | Default | What it does | +|---|---|---|---| +| `ungoverned` | `auto`, `profile`, `local`, `off` | `auto` | sessions without an access group: `profile` the profile's own connection (as 0.19.1); `local` the profile's connection for local sessions only (`cli`, `tui`, `desktop`, `local`, `codex`, `acp`, `gui`, and their forks), `off` for everything else; `off` no ctx; `auto` is `profile` until the profile serves a governed session, then `local` | +| `governed_unbound` | `profile`, `off` | `off` | an unrestricted group without `ctx_checkpoint` fields or without `key`: `profile` gives it the profile's own connection, but only in a profile that serves no restricted group | +| `restricted_allow` | a list of `recall`, `capture` | `[]` | what restricted groups of this profile may switch on with their fields | +| `base_cache_s` | 60 to 86 400 | 900 | life of a rendered base-block text in the process-wide cache | +| `base_cache_entries` | 64 to 65 536 | 2 048 | entries of that cache (one per group with base blocks; the largest value of the profiles a gateway serves counts) | +| `base_timeout_s` | 1 to 10 | 4 | budget of one hook call, at most half of Hermes' `plugins.hook_callback_timeout` | +| `base_workers` | 1 to 32 | 32 | threads of the hook's own pool (it starts with 4 and grows to the largest value of the profiles served). Measured with 2 000 groups, 200 ms per request and every session restarted at once: 32 threads gave every group its base blocks after 18 turns, 16 after 28 | +| `verify_timeout_s` | 1 to 10 | 3 | budget of a proof (`whoami`) on the turn's path | + +With access groups the provider is available in a profile without a default key when `ungoverned` +is `local` or `off`. + +### Base blocks + +`base_blocks` is how a group gets curated knowledge without recall. Before a governed turn Hermes calls +the hook `access_group_fields`; `ctx_checkpoint` answers with the content of the group's base blocks, +which Hermes adds to the group's prompt: + +```text +## Knowledge for this conversation (ctx) +### <title of block 1> +<content of block 1> +### <title of block 2> +… +``` + +- The text depends only on the blocks (same blocks, same text) and is cut at `base_max_chars`: the + block that overflows ends in `…[truncated]`, the rest is left out. Every bound key is replaced in it. +- The hook reads with the group's key, narrowed to `read`, after the same proof as the binding (E1 to + E5, E7), with one `get` for all ids (a server without the multi-id `get` is asked once per id). A + block outside `read`, in `write` (E6), not found, archived, an id prefix shorter than 8 characters or + one that names several blocks is left out and named in `access status`. +- Only whole answers: when ctx does not answer in time, answers 429 or 5xx, or the budget runs out, + the hook gives no text and Hermes asks again on a later turn. The budget is `base_timeout_s`, at + most half of `plugins.hook_callback_timeout` (a core timeout under 2 seconds leaves the hook too + little). The work runs in the hook's own thread pool, never on the gateway's event loop. +- Hermes keeps an answer per session, group and fields: a changed block reaches new sessions after + `base_cache_s`; `/policy field <group> ctx_checkpoint.base_rev=<n+1>` reloads it in every session of + the group at once (and rebuilds their agents). +- Hermes drops a contribution that would take the group's prompt past 8 000 characters, whole. +- The hook needs `key`; a group without it gets no base blocks, also under `governed_unbound: profile`. + An unrestricted group without `read` reads the key's read set without its home scope. + +### Recipe for restricted profiles + +- No standard key in the profile: no `CTX_KEY` and no `CTX_API_KEY` in its `.env`, no ctx entry in + `mcp_servers`. A session without its group (a direct message, a route into the profile) or an older + `ctx_checkpoint` would reach ctx with it, and a ctx MCP entry gives the model ctx tools past the + plugin. +- `memory.ctx_checkpoint.ungoverned: local` (`access provision` sets it) or `off`. +- `compression.checkpoint_required: false`: a group without `capture` writes no chain, and a required + checkpoint would stop its compactions ("no ctx binding for this session"). +- One key per server and profile: home scope = the group's scope, `allowed_scopes` = its `read`, + no `write_scopes`, `scope_narrowing: required`, label `hermes:<platform>:<server id>:<profile>`, + variable `CTX_KEY_<server id>_<PROFILE>` (`access provision` creates exactly this). +- ctx profiles are other profiles than the catch-all route's profile and the member profiles of + `ctx_discord_policy` (`access check` warns when a profile of restricted groups also served sessions + without an access group). +- One profile per server as soon as the profile needs tools that read files or run commands (E7): + then its `.env` holds only its own server's key. +- One tenant per operator, without incoming tenant grants (a grant reaches every key of the tenant and + turns every restricted binding of it off at once); a community that needs a hard separation gets a + tenant of its own. +- Groups and their fields in one write: `access provision --emit-yaml` prints the group entry with its + fields for `gateway.access_groups`. + +### Operator profiles on Discord + +An operator profile that serves Discord keeps ctx for its local work and no other: +`memory.ctx_checkpoint.ungoverned: local`. CLI and TUI sessions and their subagents keep the profile's +connection; Discord sessions, `/background` tasks and cron jobs without an access group get none +(without it, a `/background` task or a cron job of a governed server runs on the profile's private +connection and answers in the channel it came from). On a Hermes without access groups this is the setting that keeps +member text of a server out of the operator's ctx; `auto` closes the same path only after the profile +served a governed session. An operator group that should use ctx in its server gets its own fields +(`key`, `read`, `write`, optionally `store` for knowledge it files with `ctx_store`); without them +`governed_unbound: off` keeps it off. + +### Operator tools: `hermes ctx_checkpoint access …` + +Every command works on the profile it runs in: `hermes -p <profile> ctx_checkpoint access …` (Hermes +takes `-p`/`--profile` before the plugin sees it). The plugin never reads the core's +`gateway.access_groups`; `check` takes a group's fields on the command line, as `/policy field` does. + +- `access status [--server <platform>:<id>]` — no network. Lists every access-group binding of the + profile from its status files (`ctx_state/access/<platform>-<server>-<profile>.json`): `bound`, + `off: <reason>` or a group that gets no ctx by its own fields; for an `off` binding every broken + rule with the value it expected; tenant, read and write scopes, the key's digest (never the key), + the time of the last change; per group whether the base-block hook delivered its text and, if not, + why; the markers `restricted_seen` and `governed_seen`; messaging sessions without an access group + that ran on the profile's own connection; and the way to cut a group off at once (deactivate its key + with `ctx manage api-key-update` and `active=false`; ctx checks the key on every request, without a + cache). A status file of a group you removed stays until you delete it. +- `access check --server <platform>:<id> --group <name> [--profile <p>] [--restricted | --unrestricted] + --field <name>=<value> …` — proves a group's fields the way the provider binds them: their forms + (E1) before any secret is read, then the URL, the key, the narrowed and the unnarrowed `whoami` (E2 + to E5, E7) and, for a group that writes, the write client's own narrowing. Every broken rule is named + with the value it expected (for example `✗ E4: expected label hermes:discord:123…:members`). Exit + code 1 when a rule is broken, 0 otherwise; warnings do not change it. It does not prove the base + blocks (E6) or the store client of `store`, and says so; `access status` shows what the hook did + with the base blocks. Lists take comma-separated values (`--field read=t:d…-k,t:d…-faq`); + `ctx_checkpoint.` before a field name is optional. +- `access provision --server <platform>:<id> --group <name> --admin-key-env <VAR> [--profile <p>] + [--read <scope> …] [--per-community] [--base-url-env CTX_BASE_URL_<…>] [--roles <ids>] [--users <ids>] + [--emit-yaml]` — sets up ctx for a restricted group: names the group's scopes and the key's label + (`hermes:<platform>:<server>:<profile>`), creates the scopes and a member key that requires narrowing + in one `keyset-provision` call with the tenant-admin key from `<VAR>` (read, sent once, never stored + or printed; a key that requires narrowing cannot be that admin key), writes the new key as one line + `CTX_KEY_<server>_<PROFILE>=…` into the profile's `.env` (mode 0600, every other line kept, an older + line for the same variable replaced), sets `memory.ctx_checkpoint.ungoverned: local` (an `off` + stays), and prints the `/policy field` line for an existing group and the `/policy group` line for a + new one; `--emit-yaml` adds the whole group entry with its fields for `gateway.access_groups` (one + write, so the group never exists without its fields). A `--read` scope must already be a scope of the + tenant. Nothing is written when ctx refuses (a 4xx answer; a reached `max_keys` or `max_scopes` + answers 429). Without a clear answer (no answer in time, a 5xx or a proxy error) the set may have + been created and the earlier key of the label may already be inactive: run the same command again — + `replace_label` deactivates the key of the earlier run, so one key per label stays active and lands + in the `.env`. The `.env` is read again just before the write, so a line another writer added + meanwhile stays. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising + `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id + or group name no scope or variable name can hold, a `--profile` other than the profile the command + runs in (run it with `hermes -p <profile>`), a URL that is no http(s) URL, a profile URL of plain + `http://` to a host outside this computer and the local network (the admin key would travel + unencrypted). Keep the tenant-admin key in the shell's environment for this one command; the command + warns when it finds it in the profile's `.env`. +- `access reset-marker --restricted | --governed [--profile <p>]` — lowers the named marker(s) of the + profile (they only rise by themselves); refuses a `--profile` other than the one it runs in. Do this + only for a profile that no longer serves restricted groups (`--restricted`) or governed servers + (`--governed`). + +Scope names (one tenant per operator, the default): `d<server id in base 36>-k` for the server's +knowledge and `d<server id in base 36>-<group>` for the group, at most 24 characters; `_` in a group +name becomes `-` (so `a_b` and `a-b` collide and are refused); a group part longer than 9 characters +is cut and ends in a 4-character hash. With `--per-community` (a tenant of this server alone): `k` and +`<group>`. + +Warnings of `access check`: + +- `the profile's .env holds the standard key CTX_KEY …` — a profile that serves restricted groups + carries no standard key: a session without its access group or an older ctx_checkpoint would reach + ctx with it. +- `mcp_servers.<name> reaches ctx past the plugin …` — a ctx MCP entry in a profile that serves + restricted groups gives the model ctx tools with that entry's key, which no access group narrows. +- `the key reads scopes of another tenant …` — a tenant grant reaches every key of the tenant, so + every restricted binding of that tenant fails E3 at once. +- `this profile also served messaging sessions without an access group …` — a profile of restricted + ctx groups is no catch-all route or member profile of a server that is not governed. +- `memory.ctx_checkpoint.ungoverned: profile in a profile that serves governed servers …` — + `/background`, cron and sessions without their access group take the profile's own connection; set + it to `local`. + +**`hermes memory status`** with access groups adds `access_groups` (`N bound, M off, K without ctx +by their fields`) and names up to five bindings that are off (`access_off`, `access_off_2`, …). While +one binding is off for another reason than its group's own fields (`enabled: false`, no fields, no key +with `governed_unbound: off`), the report is not ok and its summary starts with +`✗ M of N access-group bindings off`. A profile without a connection of its own (`ungoverned: local` +or `off`, no `CTX_KEY`) is ok when all its groups are bound. Groups whose base blocks were not +delivered are named in `access_base_blocks`; a status file that cannot be read makes the report not +ok as well (`access_unreadable`). Without access groups the report is as before. + +**The write limit.** The checkpoint chain plans its writes per minute below the write limit its +key's `whoami` reports (`rate_limit_write`, ctx 5.95.0 or later), keeping 3 writes of the window for +other writes of the key; `0` is no limit, and a server without the field leaves the window as in +0.19.1. ctx keys that limit by the key's home scope: a group key gets a lower limit through a +settings write with a tenant-admin key of the group's home scope, or ctx's global setting. + +### What this does not promise + +- **A ctx MCP entry in a restricted profile** gives the model ctx tools with that entry's key, past + the plugin and every group; `access check` warns, the core's profile check does not look at MCP + entries. +- **Toolsets of loaded plugins** are not judged by E7; one that reads files lets a member read the + `.env` and the keys in it. +- **The markers and status files** live in the profile's home; a model with file tools in the same + profile can change or read them (they name servers, tenants and scopes, never a key). One OS user, + one trust boundary (Hermes' `SECURITY.md`). +- **Text a member quotes** reaches operator turns; with an operator binding it lands in that + server's operator scope, not in another server's. +- **Scopes of one tenant are not independent**: ctx's duplicate guard compares blocks across the + tenant's scopes. A community that needs a hard separation gets its own tenant. +- **Keys without required narrowing**: the narrowing is the plugin's; only a key with + `scope_narrowing: required` refuses a client that leaves it out (E2 demands it of restricted + groups, not of unrestricted ones). +- **Rights changed after a binding** are proven again at the next agent build; until then the reads + stay within the narrowing. A deactivated key fails from its next request on; a base-block text + already given to a session stays in its prompt until a new session or `base_rev`. +- **Writes after a group change**: a worker of the old agent finishes in the old group's scope. +- **Without access groups in Hermes** the plugin cannot tell a member from an operator: `ungoverned: + local` keeps Discord sessions out of an operator profile, and the member profiles of + `ctx_discord_policy` carry no memory provider. +- **Forks without a proven parent** (a fork of a fork, a delegation backend in another process) count + as not local and get no ctx under `local`. + ## Status and the last checkpoint `hermes memory status` and `hermes ctx_checkpoint status` print the same report: @@ -539,7 +832,12 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). for the blocks), and the connection test (connect and list the tools of that server entry) when you save the settings or ask for the status. With `transport: rest`, HTTPS calls of the plugin's own stdlib client to - `CTX_BASE_URL` instead. No third-party services, no telemetry. + `CTX_BASE_URL` instead. With [access groups](#access-groups), REST calls of the same client + to the ctx server a group's fields name (else the profile's), with the group's key and the + narrowing headers: `whoami` to prove a binding, the group's recall, tools and writes, and from + the hook one `get` for the group's base blocks; `hermes ctx_checkpoint access check` and + `access provision` call `whoami` and `keyset-provision` when you run them. No third-party + services, no telemetry. - **Data sent:** direct user/assistant text of the turns about to be compacted; with memory features on also the mirrored `MEMORY.md`/`USER.md` entries, the extracted facts, the digests and what the model stores explicitly. Tool @@ -587,8 +885,12 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). `CTX_KEY` on `transport: rest` — only to redact them (when the provider connects, and in `hermes memory status`, `hermes ctx_checkpoint …`, the connection test and setup; 0.14.0), and with memory features on the - profile's `state.db` (read-only, to find a resumed session's root). Nothing - outside that. + profile's `state.db` (read-only, to find a resumed session's root). With access groups also: + the key and URL variables a group's fields name, from the serving profile's secret scope; the + variable names of the profile's `.env` (values dropped at once) and its `platform_toolsets` (rule + E7); the access group of the turn (the access arguments of `initialize`, and Hermes' + `current_access()`); the agent whose turn builds a fork (its platform and session id); the + markers `ctx_state/access-mode.json`. Nothing outside that. - **Writes, when you save the settings:** `memory.ctx_checkpoint`, the named `mcp_servers` entry and — in terminal setup — `memory.provider` in `config.yaml`, merged into the file so other sections stay as they are; the @@ -600,9 +902,16 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). empty lock file `checkpoint-status.lock` next to it, which serializes the writers. With memory features on, also small state files under `$HERMES_HOME/ctx_state/` (fact dedupe keys and digest segments per root session, mode 0600, pruned after - `state_retention_days`). -- **No** shell commands, background network beyond the above, stored credentials - or self-updating code. + `state_retention_days`). **With access groups:** `ctx_state/access-mode.json` (the markers, + written only when one rises; kept by the pruning) with the lock `access-mode.lock`, + `ctx_state/access/<platform>-<server>-<profile>.json` (a binding's state and the outcome of its + base blocks, mode 0600, written only on a change) with the lock `access.lock`, and + `ctx_state/access-sessions.state` (once per platform and connection: messaging sessions that ran + without an access group, also on a Hermes without access groups). `access provision` writes one + line into the profile's `.env` (under `ctx_state/env-provision.lock`) and + `memory.ctx_checkpoint.ungoverned` into `config.yaml`; `access reset-marker` writes the markers. +- **No** shell commands, background network beyond the above, stored credentials (but the key + `access provision` writes into the profile's `.env` when you run it) or self-updating code. - **Core modules used:** `agent.memory_provider`, `agent.redact` (redaction), `agent.secret_scope` (profile-scoped `.env` reads, REST transport), `tools.registry` (MCP dispatch and the tool error envelope), @@ -610,7 +919,12 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). Desktop memory form; the module Hermes asks `config_schema.py` to use) and `hermes_cli.mcp_config._probe_single_server` (the connection test behind `hermes mcp test`) — imported because the memory-provider surface has no public - seam for these yet; `hermes plugins validate` lists them as private imports. + seam for these yet; `hermes plugins validate` lists them as private imports. For access groups + only published surfaces: `hermes_cli.plugins.PluginContext` (does this Hermes have access + groups), `gateway.access_groups.current_access` (read from the module Hermes loaded, never + imported), `gateway.session_context.get_session_env`, `agent.subagent_lifecycle` + (`get_active_subagent_parent`), `agent.secret_scope.load_env_file`, `hermes_cli.config` + (`load_config_readonly`, `read_user_config_raw`, `save_config`) and `hermes_constants`. ## Tests @@ -658,8 +972,12 @@ plugin.yaml, VERSION manifest and version (one for the whole plugin); plugin.yam skills/ctx-memory/ the bundled skill (registered as ctx_checkpoint:ctx-memory) memory/ the engine: provider, tools, client (REST), mcp_client, config, checkpoint (chain writer), digest, status (connection test, outcome - file, status report), cli — README + CHANGELOG inside -tests/ umbrella suite + file, status report, access status files), cli — README + CHANGELOG + inside; for access groups: access (fields, settings, decision, + markers), narrowing (the proof, rules E2 to E7), base_blocks (the + hook), access_cli (hermes ctx_checkpoint access …) +tests/ umbrella suite (tests/fakes/: the fake ctx server and Hermes' access-group + surface; test_s3_*: opt-in runs against a real ctxd and Hermes) memory/tests/ engine suite (loads the engine as package ctx_plugin) ``` diff --git a/integrations/hermes/plugin/ctx_checkpoint/VERSION b/integrations/hermes/plugin/ctx_checkpoint/VERSION index 41915c799..5a03fb737 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/VERSION +++ b/integrations/hermes/plugin/ctx_checkpoint/VERSION @@ -1 +1 @@ -0.19.1 +0.20.0 diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 0fecb6cc1..48c6de5f5 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -6,6 +6,83 @@ from ctx_checkpoint 0.6.0 on the engine is versioned with the plugin (`../VERSIO `../plugin.yaml`) and this file records engine-level changes only. Internal phase names (P1–P6) refer to the ctx-plugin-v2 work packages. +## [ctx_checkpoint 0.20.0] — 2026-12-06 + +Access groups: on a Hermes with access groups (NousResearch/hermes-agent#164604), every group of a +governed server binds to its own ctx key and scopes ([README, Access groups](../README.md#access-groups)). +Group bindings need a **ctx server with per-request scope narrowing (5.95.0 or later)**; against an +older server a group binding is off and the profile's own connection works as before. + +- **Fields and hook** (`access.py`, `base_blocks.py`). `register()` asks Hermes' public + `PluginContext` for `register_access_fields`; with it, the plugin registers twelve fields under the + namespace `ctx_checkpoint` (`key`, `base_url`, `tenant`, `read`, `write`, `store`, `recall`, + `capture`, `base_blocks`, `base_max_chars`, `base_rev`, `enabled`; no defaults, forms checked by the + plugin before any secret is read) and the hook `access_group_fields`. Without it, nothing is + registered. +- **The decision** (`access.decide`, pure): a session of a governed group binds to its fields; a + restricted group without fields, without `key` or with a broken field gets no ctx; an unrestricted + one without them gets `governed_unbound` (default `off`; `profile` only in a profile that serves no + restricted group). Sessions without an access group get `ungoverned` (`auto` default: the profile's + connection until the profile serves a governed session, then `local`; `local`: local sessions and + their forks only; `off`; `profile`). Once a profile served a governed session, messaging sessions + without their group get no ctx; once it served a restricted group, no session without its group + gets ctx, on any Hermes. The markers (`ctx_state/access-mode.json`) only rise; `access + reset-marker` lowers them. `restricted_allow` decides whether restricted groups may switch on + `recall` and `capture` (both off by default). +- **The binding** (`provider.py`): `initialize` drops the previous binding first, then decides, then + binds the group over REST with up to three clients (read, write, store), each narrowed per request; + the read client's binding is proven before use (`narrowing.py`, rules E1 to E7: tenant, member role, + required narrowing, exact read and write sets, label `hermes:<platform>:<server>:<profile>`, the + narrowing echoed, no foreign key with file tools in the profile). A lost echo, a group change within + a turn or a failed proof turns the agent off. Blocks a group writes carry `server:`/`group:` tags + and the chain `ctx_plugin.access`. +- **Base blocks** (`base_blocks.py`): the hook answers with the group's base blocks as its prompt text, + after the same proof, in one `get` with `ids` (one per id on a server without it), never a partial + text; its own thread pool (`base_workers`, default 32, measured) and budget (`base_timeout_s`, at + most half of the core's hook timeout); a render cache per group (`base_cache_s`, + `base_cache_entries`); `base_rev` reloads. +- **The chain follows the write limit** of its key (`whoami.rate_limit_write`, minus 3 writes for the + key's other writes; `0` is no limit) for every chain of the key in the process. +- **Operator tools and status** (`access_cli.py`, `status.py`): `hermes ctx_checkpoint access status | + check | provision | reset-marker`; a status file per binding (`ctx_state/access/`) with the outcome of + its base blocks; `hermes memory status` is not ok while a binding is off for another reason than + its group's own fields. +- Fixed before release: the state pruning (`state_retention_days`) deleted the markers after 30 days + and a session whose root id was `access-mode` wrote its fact ledger over them (both kept now); a + status write that failed could abort `initialize` (guarded); an id prefix of several blocks in + `base_blocks` (ctx's `ambiguous_id`) made the hook retry on every turn (skipped and named now); a + `delegate_task` child of a CLI session was off under `ungoverned: local` (local now when the agent + whose turn builds it is its parent and local; a fork of a fork stays off). + +### Behaviour changes without access groups + +For an installation that never turns access groups on (a Hermes without them, or one with them and +no `gateway.access_groups` for this profile), sessions keep the profile's own connection as in 0.19.1 +(`ungoverned: auto` stays `profile` while the profile never served a governed session). Changed: + +- **An unreadable `config.yaml`**, or a `memory` / `memory.ctx_checkpoint` that is no mapping, gives + `ungoverned: off`: no ctx for any session, where 0.19.1 connected with its defaults. A value of + `ungoverned` or `governed_unbound` that is not one of theirs is `off`, with a WARNING. +- **Tags** `server:…` and `group:…` that the model passes to `ctx_store` or the CLI to `--tag` are + dropped; `ctx_store` refuses metadata under the key `ctx_plugin` (`reserved_metadata`). +- **`initialize` drops the previous binding first.** A recall warm-up queued during it finds no client; + an `initialize` that raises leaves no tool schemas (0.19.1 kept them, their calls failed); a mirror or + digest write that runs during an `initialize` is dropped; an idle timer of an earlier binding writes + nothing. +- **The chain plans fewer writes per minute** when the key's `whoami` reports a write limit below 100 + (ctx 5.95.0 or later: limit − 3 per window, shared by every chain of the key in the process); `0` + lifts a lower limit; a server without the field plans as 0.19.1. +- **`ctx_state/access-sessions.state`** is written once per messaging platform and connection when a + messaging session runs on the profile's own connection (shown by `access status`). +- **`hermes ctx_checkpoint`** has the subcommand `access`. `hermes memory status` adds keys only when + status files of access-group bindings exist. +- **The state pruning** keeps `ctx_state/access-mode.json`; a session whose root id is `access-mode` + (in any case) keeps its fact ledger under a name with a hash suffix. +- **`plugin.yaml` declares `provides_hooks: [access_group_fields]`**; `hermes plugins validate` on a + Hermes without access groups warns that the hook is declared but not registered (exit code 0). +- On a Hermes with access groups the plugin registers its fields and its hook even when no group uses + them; the hook answers groups without `ctx_checkpoint` fields with nothing, without network. + ## [ctx_checkpoint 0.19.1] — 2026-11-26 Every REST call ends within its bound — status line, headers and body (#566). diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/README.md b/integrations/hermes/plugin/ctx_checkpoint/memory/README.md index 653ded35a..16622bc40 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/README.md @@ -249,8 +249,10 @@ that names no type, `--all-types` included. - Every write carries `source:hermes`, `profile:<name>` (`…/profiles/<name>` → `<name>`, otherwise `default`) and `hook:<origin>`: `memory_write`, `pre_compress`, `checkpoint`, - `session_end`, `digest_rolling`, `digest_idle`, `tool`, `cli`. Agent tags using the - reserved `source:`/`profile:`/`hook:` prefixes are dropped. + `session_end`, `digest_rolling`, `digest_idle`, `tool`, `cli`. A session of an access group + (0.20.0, [Access groups](../README.md#access-groups)) adds `server:<platform>:<server id>` and + `group:<group>`. Agent and CLI tags using the reserved `source:`/`profile:`/`hook:`/`server:`/ + `group:` prefixes are dropped, and `ctx_store` refuses metadata under the key `ctx_plugin`. - A CTX upsert without `tags` resets a block's tags to `[]`, so tags are sent on every store. A `noop` (identical content) leaves existing tags unchanged. - Memory mirror: `add`/`replace` upsert one block — `agent-briefing` with title diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py index d95695f2c..90222fce9 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py @@ -50,7 +50,7 @@ logger = logging.getLogger(__name__) -PLUGIN_VERSION = "0.19.1" # ctx_checkpoint plugin version — keep in sync with ../plugin.yaml and ../VERSION +PLUGIN_VERSION = "0.20.0" # ctx_checkpoint plugin version — keep in sync with ../plugin.yaml and ../VERSION UPSTREAM_REF = "GottZ/ctx integrations/hermes/plugin/ctx_checkpoint 0.4.3 @ 38fdb74 (MPL-2.0)" CATEGORY_CHECKPOINT = "compaction-checkpoints" diff --git a/integrations/hermes/plugin/ctx_checkpoint/plugin.yaml b/integrations/hermes/plugin/ctx_checkpoint/plugin.yaml index c33027aa9..019bcc157 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/plugin.yaml +++ b/integrations/hermes/plugin/ctx_checkpoint/plugin.yaml @@ -1,6 +1,10 @@ name: ctx_checkpoint -version: 0.19.1 -description: "ctx memory provider: durable pre-compaction transcript checkpoints (fail-closed on request), and with memory: true recall, ctx_* agent tools, MEMORY.md/USER.md mirror, fact extraction and session digests — over Hermes' own MCP dispatch, no credentials of its own." +version: 0.20.0 +description: "ctx memory provider: durable pre-compaction transcript checkpoints (fail-closed on request), and with memory: true recall, ctx_* agent tools, MEMORY.md/USER.md mirror, fact extraction and session digests — over Hermes' own MCP dispatch, no credentials of its own. On a Hermes with access groups, each group of a governed server binds to its own ctx key and scopes (narrowed per request, proven before use) and gets base blocks for its prompt." +# The hook only a Hermes with access groups knows (register() registers it there and nowhere else); +# on a Hermes without them validate warns that it is declared but not registered. +provides_hooks: + - access_group_fields # The first Hermes whose delegate_task children inherit the provider under # compression.checkpoint_required (before, every sub-agent compaction failed closed). requires_hermes: ">=0.23.1" diff --git a/integrations/hermes/plugin/ctx_checkpoint/skills/ctx-memory/SKILL.md b/integrations/hermes/plugin/ctx_checkpoint/skills/ctx-memory/SKILL.md index 64466e7ed..1cb179510 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/skills/ctx-memory/SKILL.md +++ b/integrations/hermes/plugin/ctx_checkpoint/skills/ctx-memory/SKILL.md @@ -1,7 +1,7 @@ --- name: ctx-memory description: "Use the ctx knowledge store as long-term memory and evidence layer: query as a question, search to browse, get by id, verify before acting, persist one durable fact per block." -version: 0.19.1 +version: 0.20.0 author: ctx (GottZ/ctx) license: MPL-2.0 metadata: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py index 40343593f..ae543bc15 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -1,9 +1,6 @@ """Clusters whose red S1 tests are still shielded (``tests/conftest.py`` gives each test marked ``access_cluster(<c>)`` with ``c`` listed here a strict xfail). Switching a cluster on = deleting -its line. ``CTX_S1_UNSHIELD=1`` lifts the shield for every cluster (the red proof).""" +its line. ``CTX_S1_UNSHIELD=1`` lifts the shield for every cluster (the red proof). Every cluster of +axis 02 is built: the set is empty, and the shield marks nothing.""" -S1_PENDING = frozenset( - { - "P-F", - } -) +S1_PENDING: frozenset[str] = frozenset() From 5fc7db57543be9882f1c821cf262284623754002 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:07:38 +0100 Subject: [PATCH 22/65] fix(ctx_checkpoint): a session's platform is the one the gateway bound for its turn, and the docs say what the review found they overstated A fresh review of the plugin diff found the gateway's hygiene agent (the compaction before a turn) built without a platform: Hermes passes platform "cli" to initialize and stamps its own platform only afterwards. Under ungoverned: local, or auto after a governed session, a direct message's or an ungoverned server's transcript then went into the operator profile's private ctx under compression.checkpoint_required. The gateway binds the session's platform before it builds that agent; access._session_platform now takes that bound value before the one initialize names (forks unchanged). A CLI session, which binds none, keeps its own; nothing is read from os.environ. The fake resolves id prefixes as ctx does (lowercase hex and '-' only, else not_found). README and CHANGELOG no longer say more than the code holds: a_b and a-b are refused only within one provision call, and one key per server and profile means a second group of the same profile replaces the first one's key; --profile is refused where the home's profile name is known; an unrestricted group's write is checked against the home scope by its write client (access check is stricter); the write limit applies on REST and group bindings and below max_parts + 5; status files are per server and profile; the hook replaces the group's key; the governed_seen rule needs Hermes with access groups. "Behaviour changes without access groups" adds hermes plugins doctor's error on the declared hook, an initialize that raises while connecting, access-sessions.state for sessions that get none, and restricted_seen rising when Hermes reports a restricted profile. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 49 ++++++---- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 26 ++++-- .../plugin/ctx_checkpoint/memory/access.py | 13 ++- .../ctx_checkpoint/tests/fakes/ctx_server.py | 4 +- .../test_access_seam_session_platform.py | 91 +++++++++++++++++++ .../tests/test_fake_ctx_wire.py | 5 +- 6 files changed, 154 insertions(+), 34 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_session_platform.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 5a8845af0..53c21dd76 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -409,11 +409,11 @@ A value of the wrong type makes Hermes refuse the whole server entry. Only a bot | `base_url` | env name | the variable that holds the group's ctx server URL: `CTX_BASE_URL` or `CTX_BASE_URL_<…>`; its value must be `https://` with a host, without user info, query or fragment | the profile's URL (`CTX_BASE_URL`, `memory.ctx_checkpoint.rest_base_url`, `ctx_base_url` of `ctx.json`, the origin of the ctx `mcp_servers` entry), without the `https` rule | | `tenant` | str | the tenant slug the key must belong to | not checked; a restricted group needs it | | `read` | list | 1 to 8 ctx scopes (`<slug>:<name>`, none twice) that recall, the read tools and the base blocks read | the key's read set without its home scope (at most 8, else off); a restricted group needs it | -| `write` | str | the scope the chain, facts, digests and the `MEMORY.md`/`USER.md` mirror write to; must be the key's home scope | the key's home scope; a restricted group needs it | +| `write` | str | the scope the chain, facts, digests and the `MEMORY.md`/`USER.md` mirror write to; must be the key's home scope (a restricted group's proof checks it; for an unrestricted group the write client checks it before its first write, so only a group with `capture`) | the key's home scope; a restricted group needs it | | `store` | str | the scope `ctx_store` writes to, within the key's write scopes (unrestricted groups only; restricted groups never get `ctx_store`) | `write` | | `recall` | bool | recall before each turn | unrestricted on, restricted off; a restricted group's `true` counts only with `restricted_allow: [recall]` | | `capture` | bool | chain, facts, digests and mirror are written | unrestricted on, restricted off; a restricted group's `true` counts only with `restricted_allow: [capture]` | -| `base_blocks` | list | up to 16 block ids (none twice) whose content joins the group's prompt ([Base blocks](#base-blocks)) | no base blocks | +| `base_blocks` | list | up to 16 block ids (none twice; ctx resolves an id prefix of 8 or more lowercase hex characters) whose content joins the group's prompt ([Base blocks](#base-blocks)) | no base blocks | | `base_max_chars` | int | most characters the base blocks add, 256 to 8 000 | 4 000 | | `base_rev` | int | raise it to reload the base blocks in every session of the group | 0 | | `enabled` | bool | `false`: the group gets no ctx; counts as set for the core's profile check | `true` | @@ -435,7 +435,7 @@ What fails is named with the value it expected (`access status`, `access check`) |---|---|---| | E1 | the fields above are set and well formed; `write` not in `read`; `key` is `CTX_KEY_<server id>_…` | restricted | | E2 | the key's tenant is `tenant`; it is no ctx server admin, its role is `member`, and it requires narrowing (`scope_narrowing: required`) | restricted (tenant: every group that sets it) | -| E3 | `write` is the key's home scope; the key writes exactly `write`, reads exactly `read` plus `write` (an incoming tenant grant fails this) and does not stage its writes (`confirm_writes`) | restricted; home scope and `read` within the key for all | +| E3 | `write` is the key's home scope; the key writes exactly `write`, reads exactly `read` plus `write` (an incoming tenant grant fails this) and does not stage its writes (`confirm_writes`) | restricted; for an unrestricted group the write client checks the home scope before its first write, and ctx refuses a `read` outside the key | | E4 | the key's label is `hermes:<platform>:<server id>:<profile>` (a profile name that makes it longer than 100 characters is replaced by `#` and 16 hex digits of its SHA-256) | restricted | | E5 | the narrowed `whoami` reports exactly the narrowing sent, and every answer echoes it | every group | | E6 | every base block lies in `read` and not in `write` | every group (base blocks) | @@ -452,7 +452,10 @@ turn, or an answer without the echo, turns the agent off for the rest of its lif What a session that serves no access group gets (a direct message, a server that is not governed, `/background`, cron, the API server, a local CLI session) is the setting `ungoverned`; once a profile has served a governed session, messaging sessions without their group get no ctx whatever the setting -says (the core passes no group also when it cannot read the turn's one). A profile that has served a +says, on a Hermes with access groups (the core passes no group also when it cannot read the turn's one). +The platform of a session is the one the gateway bound for its turn, else the one Hermes passes to +`initialize` (Hermes passes `cli` for agents it builds without a platform, such as the gateway's hygiene +agent before a turn). A profile that has served a restricted group gets no ctx for any session without its group, on any Hermes. Both are markers in `ctx_state/access-mode.json` (`governed_seen`, `restricted_seen`): they only rise, survive the state pruning, and only `hermes ctx_checkpoint access reset-marker` lowers them. @@ -500,11 +503,13 @@ which Hermes adds to the group's prompt: ``` - The text depends only on the blocks (same blocks, same text) and is cut at `base_max_chars`: the - block that overflows ends in `…[truncated]`, the rest is left out. Every bound key is replaced in it. + block that overflows ends in `…[truncated]`, the rest is left out. The group's key is replaced wherever it + stands, then the chain's redaction rules run over the text. - The hook reads with the group's key, narrowed to `read`, after the same proof as the binding (E1 to E5, E7), with one `get` for all ids (a server without the multi-id `get` is asked once per id). A - block outside `read`, in `write` (E6), not found, archived, an id prefix shorter than 8 characters or - one that names several blocks is left out and named in `access status`. + block outside `read`, in `write` (E6), not found, archived, an id prefix shorter than 8 characters, one + with other characters than lowercase hex and `-`, or one that names several blocks is left out and + named in `access status`. - Only whole answers: when ctx does not answer in time, answers 429 or 5xx, or the budget runs out, the hook gives no text and Hermes asks again on a later turn. The budget is `base_timeout_s`, at most half of `plugins.hook_callback_timeout` (a core timeout under 2 seconds leaves the hook too @@ -558,7 +563,8 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co `gateway.access_groups`; `check` takes a group's fields on the command line, as `/policy field` does. - `access status [--server <platform>:<id>]` — no network. Lists every access-group binding of the - profile from its status files (`ctx_state/access/<platform>-<server>-<profile>.json`): `bound`, + profile from its status files (`ctx_state/access/<platform>-<server>-<profile>.json`, one per server and + profile: two groups of one server served by one profile share it, the latest binding shows): `bound`, `off: <reason>` or a group that gets no ctx by its own fields; for an `off` binding every broken rule with the value it expected; tenant, read and write scopes, the key's digest (never the key), the time of the last change; per group whether the base-block hook delivered its text and, if not, @@ -567,7 +573,9 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co with `ctx manage api-key-update` and `active=false`; ctx checks the key on every request, without a cache). A status file of a group you removed stays until you delete it. - `access check --server <platform>:<id> --group <name> [--profile <p>] [--restricted | --unrestricted] - --field <name>=<value> …` — proves a group's fields the way the provider binds them: their forms + --field <name>=<value> …` — proves a group's fields the way the provider binds them (for an + unrestricted group a little stricter: it checks `write` against the home scope also without `capture`; + it reads the key variable from the shell's environment too, the binding only from the profile): their forms (E1) before any secret is read, then the URL, the key, the narrowed and the unnarrowed `whoami` (E2 to E5, E7) and, for a group that writes, the write client's own narrowing. Every broken rule is named with the value it expected (for example `✗ E4: expected label hermes:discord:123…:members`). Exit @@ -594,20 +602,24 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co meanwhile stays. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id or group name no scope or variable name can hold, a `--profile` other than the profile the command - runs in (run it with `hermes -p <profile>`), a URL that is no http(s) URL, a profile URL of plain + runs in where the home's profile name is known (`…/profiles/<name>` or the account's default home; run + it with `hermes -p <profile>`), a URL that is no http(s) URL, a profile URL of plain `http://` to a host outside this computer and the local network (the admin key would travel unencrypted). Keep the tenant-admin key in the shell's environment for this one command; the command warns when it finds it in the profile's `.env`. - `access reset-marker --restricted | --governed [--profile <p>]` — lowers the named marker(s) of the - profile (they only rise by themselves); refuses a `--profile` other than the one it runs in. Do this + profile (they only rise by themselves); refuses a `--profile` other than the one it runs in (where the + home's profile name is known). Do this only for a profile that no longer serves restricted groups (`--restricted`) or governed servers (`--governed`). Scope names (one tenant per operator, the default): `d<server id in base 36>-k` for the server's knowledge and `d<server id in base 36>-<group>` for the group, at most 24 characters; `_` in a group -name becomes `-` (so `a_b` and `a-b` collide and are refused); a group part longer than 9 characters -is cut and ends in a 4-character hash. With `--per-community` (a tenant of this server alone): `k` and -`<group>`. +name becomes `-`, so `a_b` and `a-b` get the same scope name (refused only when one command names both: +give one of them another name); a group part longer than 9 characters is cut and ends in a 4-character +hash. With `--per-community` (a tenant of this server alone): `k` and `<group>`. The key's label and +variable name the server and the profile, not the group: one key per server and profile, so `provision` +for a second group served by the same profile replaces the key of the first. Warnings of `access check`: @@ -633,10 +645,11 @@ or `off`, no `CTX_KEY`) is ok when all its groups are bound. Groups whose base b delivered are named in `access_base_blocks`; a status file that cannot be read makes the report not ok as well (`access_unreadable`). Without access groups the report is as before. -**The write limit.** The checkpoint chain plans its writes per minute below the write limit its -key's `whoami` reports (`rate_limit_write`, ctx 5.95.0 or later), keeping 3 writes of the window for -other writes of the key; `0` is no limit, and a server without the field leaves the window as in -0.19.1. ctx keys that limit by the key's home scope: a group key gets a lower limit through a +**The write limit.** On REST connections and group bindings (the MCP transport reads no `whoami`), the +checkpoint chain plans its writes per minute below the write limit its key's `whoami` reports +(`rate_limit_write`, ctx 5.95.0 or later), keeping 3 writes of the window for other writes of the key: +the window shrinks when the limit minus 3 is below what the chain plans (`max_parts` + 2, so below 85 +with the default 80); `0` is no limit, and a server without the field leaves the window as in 0.19.1. ctx keys that limit by the key's home scope: a group key gets a lower limit through a settings write with a tenant-admin key of the group's home scope, or ctx's global setting. ### What this does not promise diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 48c6de5f5..0ab02d787 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -42,7 +42,8 @@ older server a group binding is off and the profile's own connection works as be most half of the core's hook timeout); a render cache per group (`base_cache_s`, `base_cache_entries`); `base_rev` reloads. - **The chain follows the write limit** of its key (`whoami.rate_limit_write`, minus 3 writes for the - key's other writes; `0` is no limit) for every chain of the key in the process. + key's other writes; `0` is no limit) for every chain of the key in the process, on REST connections + and group bindings (the MCP transport reads no `whoami`). - **Operator tools and status** (`access_cli.py`, `status.py`): `hermes ctx_checkpoint access status | check | provision | reset-marker`; a status file per binding (`ctx_state/access/`) with the outcome of its base blocks; `hermes memory status` is not ok while a binding is off for another reason than @@ -66,22 +67,31 @@ no `gateway.access_groups` for this profile), sessions keep the profile's own co - **Tags** `server:…` and `group:…` that the model passes to `ctx_store` or the CLI to `--tag` are dropped; `ctx_store` refuses metadata under the key `ctx_plugin` (`reserved_metadata`). - **`initialize` drops the previous binding first.** A recall warm-up queued during it finds no client; - an `initialize` that raises leaves no tool schemas (0.19.1 kept them, their calls failed); a mirror or + an `initialize` that raises before its access decision leaves no tool schemas (0.19.1 kept them, their + calls failed; one that raises later, while connecting, keeps them as before); a mirror or digest write that runs during an `initialize` is dropped; an idle timer of an earlier binding writes nothing. -- **The chain plans fewer writes per minute** when the key's `whoami` reports a write limit below 100 - (ctx 5.95.0 or later: limit − 3 per window, shared by every chain of the key in the process); `0` - lifts a lower limit; a server without the field plans as 0.19.1. +- **The chain plans fewer writes per minute** on a REST connection when the key's `whoami` reports a + write limit whose value minus 3 is below what the chain plans (`max_parts` + 2: below 85 with the + default 80; ctx 5.95.0 or later; shared by every chain of the key in the process); `0` lifts a lower + limit; a server without the field, and the MCP transport, plan as 0.19.1. - **`ctx_state/access-sessions.state`** is written once per messaging platform and connection when a - messaging session runs on the profile's own connection (shown by `access status`). + messaging session runs on the profile's own connection or gets none (shown by `access status`). - **`hermes ctx_checkpoint`** has the subcommand `access`. `hermes memory status` adds keys only when status files of access-group bindings exist. - **The state pruning** keeps `ctx_state/access-mode.json`; a session whose root id is `access-mode` (in any case) keeps its fact ledger under a name with a hash suffix. - **`plugin.yaml` declares `provides_hooks: [access_group_fields]`**; `hermes plugins validate` on a - Hermes without access groups warns that the hook is declared but not registered (exit code 0). + Hermes without access groups warns that the hook is declared but not registered (exit code 0), and + `hermes plugins doctor` there reports `unknown hook 'access_group_fields' in provides_hooks` as an + error (exit code 1 with `--ci`). - On a Hermes with access groups the plugin registers its fields and its hook even when no group uses - them; the hook answers groups without `ctx_checkpoint` fields with nothing, without network. + them; the hook answers groups without `ctx_checkpoint` fields with nothing, without network. When + Hermes reports the profile as restricted (it does so too when it cannot tell), the session gets no + ctx and the marker `restricted_seen` rises, also without configured groups. +- **A session's platform** is the one the gateway bound for the turn, before the one `initialize` + names: an agent Hermes builds inside a messaging turn without a platform (passed as `cli`, the + gateway's hygiene agent) no longer counts as local under `ungoverned: local`. ## [ctx_checkpoint 0.19.1] — 2026-11-26 diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py index 841145c0b..41b245bc9 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -915,9 +915,11 @@ def _fork(init: Mapping[str, Any]) -> bool: def _session_platform(init: Mapping[str, Any], parent_platform: str | None) -> str | None: - """The platform the session is used on: a fork's parent session's (unknown: ``None``), else the - one ``initialize`` names.""" - platform = parent_platform if _fork(init) else init.get("platform") + """The platform the session is used on: a fork's parent session's (unknown: ``None``); else the one + the gateway bound for the turn (``parent_platform`` carries it for every session), before the one + ``initialize`` names: Hermes builds some agents of a messaging turn without a platform and passes + ``cli`` for them (the gateway's hygiene agent).""" + platform = parent_platform if _fork(init) else (parent_platform or init.get("platform")) return platform.strip().lower() if isinstance(platform, str) and platform.strip() else None @@ -1023,8 +1025,9 @@ def decide( v8: bool, ) -> Decision: """The decision table of design 02 §4.2 (first matching row): pure, no network, no files, no - secret. ``current``: ``current_access()`` at the build; ``parent_platform``: the platform of a - fork's parent session (``fork_parent_platform(init_kwargs)``); ``settings``: + secret. ``current``: ``current_access()`` at the build; ``parent_platform``: the session platform + bound in the build's context (``fork_parent_platform(init_kwargs)``: for a fork its parent's, for any + other session its own, which comes before the ``platform`` of ``initialize``); ``settings``: ``load_settings`` (an unknown mode decides as ``off``); ``markers``: ``read_markers``; ``v8``: ``access_supported()``. ``governed_unbound: profile`` opens the profile's connection only in a profile known to serve no restricted group (``restricted_profile`` false, no ``restricted_seen``). diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py index 9de5017db..45160b6c8 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -524,7 +524,9 @@ def seen(block: Mapping[str, Any]) -> bool: if len(asked) < MIN_ID_PREFIX: error = f"store: id prefix must be at least {MIN_ID_PREFIX} characters (got {len(asked)})" return {"id": asked, "code": "invalid_id", "error": error} - hits = [block for block_id, block in self.blocks.items() if block_id.lower().startswith(asked.lower())] + if any(ch not in "0123456789abcdef-" for ch in asked): # go:store/block_id_text.go:66-73 + return {"id": asked, "code": "not_found", "error": "Block not found"} + hits = [block for block_id, block in self.blocks.items() if block_id.startswith(asked)] hits = [block for block in hits if seen(block)] if len(hits) == 1: return _shown(hits[0]) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_session_platform.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_session_platform.py new file mode 100644 index 000000000..63e98e1b6 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_session_platform.py @@ -0,0 +1,91 @@ +"""Review finding: an agent the gateway builds for a messaging session without naming its platform is a +messaging session, not a local one. The gateway's hygiene agent (the compaction before a turn, +``gateway/run_turn_hygiene.py``) is built without ``platform``, so Hermes passes ``platform="cli"`` to +``initialize`` (``agent/agent_init_memory_provider.py``) and stamps its own platform only afterwards. Under +``ungoverned: local`` (or ``auto`` after a governed session) it took the profile's connection, and with +``compression.checkpoint_required`` the transcript of a direct message or of a server that is not governed +went into the operator's private ctx. The gateway binds the session's platform for the turn before it builds +that agent (``gateway/run_turn_prepare.py``): that bound value now comes before the one ``initialize`` +names. A session the turn's context names no platform for (a CLI session) keeps its own; nothing is read +from ``os.environ``.""" + +from __future__ import annotations + +import contextvars + +import pytest +from fakes import access_host as ah +from gateway.session_context import clear_session_vars, set_session_vars + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_session_platform") +acc = ah.plugin_module(_PKG, "memory.access") +_nar = ah.plugin_module(_PKG, "memory.narrowing") +Provider = _PKG.CtxCheckpointMemoryProvider + +PROFILE_KEY = "ctx_profile_key_session_platform" + + +def _in_turn(platform, fn): + """Run *fn* in a copy of the context with the gateway's session variables bound (``platform``).""" + + def run(): + tokens = set_session_vars(platform=platform) if platform else None + try: + return fn() + finally: + if tokens is not None: + clear_session_vars(tokens) + + return contextvars.copy_context().run(run) + + +@pytest.mark.parametrize(("mode", "governed_seen"), [("local", False), ("auto", True)]) +def test_the_bound_session_platform_comes_before_the_one_initialize_names(tmp_path, mode, governed_seen): + init = {"platform": "cli", "agent_context": "primary", "hermes_home": str(tmp_path), **ah.v5_kwargs()} + settings = {**acc.SETTINGS_DEFAULTS, "ungoverned": mode} + markers = acc.Markers(governed_seen=governed_seen) + decision = _in_turn( + "discord", lambda: acc.decide(init, None, acc.fork_parent_platform(init), settings, markers, True) + ) + assert decision.kind == "off", decision + alone = acc.decide(init, None, _in_turn(None, lambda: acc.fork_parent_platform(init)), settings, markers, True) + assert alone.kind == "profile", "a CLI session without a bound platform stays local" + + +@pytest.fixture +def profile(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:ops") + _nar.reset_proofs() + + def make(mode, *, v8=True, governed_seen=False): + ah.install(monkeypatch, v8=v8, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY": PROFILE_KEY}) + home = tmp_path / mode / str(v8) / str(governed_seen) / "profiles" / "ops" + home.mkdir(parents=True) + (home / "config.yaml").write_text(f"memory:\n ctx_checkpoint:\n ungoverned: {mode}\n", encoding="utf-8") + if governed_seen: + acc.raise_markers(str(home), governed_seen=True) + return home + + yield make + _nar.reset_proofs() + + +def _session(home, bound_platform, *, v5=True): + def build(): + provider = Provider(config={"transport": "rest", "memory": True}) + kwargs = {"platform": "cli", "agent_context": "primary", **(ah.v5_kwargs() if v5 else {})} + provider.initialize("s-hygiene", hermes_home=str(home), **kwargs) + return provider._decision.kind, provider._client is not None + + return _in_turn(bound_platform, build) + + +@pytest.mark.parametrize( + ("mode", "v8", "governed_seen"), + [("local", True, False), ("local", False, False), ("auto", True, True)], + ids=["local, core PR", "local, no core PR", "auto after a governed session"], +) +def test_the_hygiene_agent_of_a_discord_session_gets_no_profile_connection(profile, mode, v8, governed_seen): + home = profile(mode, v8=v8, governed_seen=governed_seen) + assert _session(home, "discord", v5=v8) == ("off", False) + assert _session(home, None, v5=v8) == ("profile", True), "the CLI session itself keeps the profile" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py index b0863853c..35acd1364 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py @@ -137,10 +137,11 @@ def test_get_with_ids_answers_entries_with_the_codes_of_the_server(fake): """go:get_ids.go:34-59, :112-135: not_found, invalid_id (prefix < 8), ambiguous_id (+ matches).""" one = fake.add_block(K, "A", "a", block_id="aaaaaaaa-0000-4000-8000-000000000001") fake.add_block(K, "B", "b", block_id="aaaaaaaa-0000-4000-8000-000000000002") - asked = [one.upper(), "aaaaaaaa-0000", "aaaa", "bbbbbbbb-0000-4000-8000-000000000009"] + asked = [one.upper(), "aaaaaaaa-0000", "aaaa", "bbbbbbbb-0000-4000-8000-000000000009", "AAAAAAAA-0000-4000"] status, body, _headers = _call(fake, "POST", "/api/manage", {"action": "get", "ids": asked}, read=K) assert status == 200 and body["action"] == "get" and body["success"] is True - found, ambiguous, short, missing = body["blocks"] + found, ambiguous, short, missing, upper_prefix = body["blocks"] + assert upper_prefix["code"] == "not_found", "a prefix outside [0-9a-f-] matches nothing (block_id_text.go:66-73)" assert found["id"] == one and {"created_at", "updated_at", "scope"} <= set(found) assert (ambiguous["code"], len(ambiguous["matches"])) == ("ambiguous_id", 2) assert short["code"] == "invalid_id" and short["id"] == "aaaa" From 96a49ac8edb67c70442f6dfbfe4314c700bdb073 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:22:45 +0100 Subject: [PATCH 23/65] =?UTF-8?q?fix(ctx=5Fcheckpoint):=20access=20provisi?= =?UTF-8?q?on=20replaces=20no=20key=20silently=20=E2=80=94=20a=20second=20?= =?UTF-8?q?group=20of=20a=20server=20and=20profile=20and=20a=20scope=20ano?= =?UTF-8?q?ther=20key=20homes=20are=20refused,=20rotating=20a=20group's=20?= =?UTF-8?q?key=20asks=20for=20--replace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before the set is made, provision asks ctx for the tenant's active keys (api-key-list with the tenant-admin key) and refuses, naming what is there: the label's key homed in another group's scope (one key serves one group per server and profile; a second group of the same profile used to replace the first one's key, which then failed E3), and the group's scope homing a key of another label (two runs for a_b and a-b used to share one scope). The same group again is refused while its key is in the profile's .env; --replace rotates it. A run that stopped before its .env line still repeats without it. The fake ctx server answers api-key-list as ctx does; the tests that rotated a key by a plain repeat ask for --replace now (S1 test_provision_twice_leaves_one_active_key_per_label, two P-E tests, the S3 harness). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 54 ++++--- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 4 +- .../ctx_checkpoint/memory/access_cli.py | 87 +++++++++++ .../ctx_checkpoint/tests/fakes/ctx_server.py | 29 +++- .../tests/test_access_pe_rules.py | 9 +- .../tests/test_access_pe_tools.py | 2 +- .../test_access_seam_provision_conflicts.py | 145 ++++++++++++++++++ .../ctx_checkpoint/tests/test_s3_real_ctxd.py | 2 +- 8 files changed, 300 insertions(+), 32 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 53c21dd76..8e9c4c035 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -583,30 +583,35 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co blocks (E6) or the store client of `store`, and says so; `access status` shows what the hook did with the base blocks. Lists take comma-separated values (`--field read=t:d…-k,t:d…-faq`); `ctx_checkpoint.` before a field name is optional. -- `access provision --server <platform>:<id> --group <name> --admin-key-env <VAR> [--profile <p>] +- - `access provision --server <platform>:<id> --group <name> --admin-key-env <VAR> [--profile <p>] [--read <scope> …] [--per-community] [--base-url-env CTX_BASE_URL_<…>] [--roles <ids>] [--users <ids>] - [--emit-yaml]` — sets up ctx for a restricted group: names the group's scopes and the key's label - (`hermes:<platform>:<server>:<profile>`), creates the scopes and a member key that requires narrowing - in one `keyset-provision` call with the tenant-admin key from `<VAR>` (read, sent once, never stored - or printed; a key that requires narrowing cannot be that admin key), writes the new key as one line - `CTX_KEY_<server>_<PROFILE>=…` into the profile's `.env` (mode 0600, every other line kept, an older - line for the same variable replaced), sets `memory.ctx_checkpoint.ungoverned: local` (an `off` - stays), and prints the `/policy field` line for an existing group and the `/policy group` line for a - new one; `--emit-yaml` adds the whole group entry with its fields for `gateway.access_groups` (one - write, so the group never exists without its fields). A `--read` scope must already be a scope of the - tenant. Nothing is written when ctx refuses (a 4xx answer; a reached `max_keys` or `max_scopes` - answers 429). Without a clear answer (no answer in time, a 5xx or a proxy error) the set may have - been created and the earlier key of the label may already be inactive: run the same command again — - `replace_label` deactivates the key of the earlier run, so one key per label stays active and lands - in the `.env`. The `.env` is read again just before the write, so a line another writer added + [--emit-yaml] [--replace]` — sets up ctx for a restricted group: names the group's scopes and the + key's label (`hermes:<platform>:<server>:<profile>`), creates the scopes and a member key that + requires narrowing in one `keyset-provision` call with the tenant-admin key from `<VAR>` (read, sent + once, never stored or printed; a key that requires narrowing cannot be that admin key), writes the new + key as one line `CTX_KEY_<server>_<PROFILE>=…` into the profile's `.env` (mode 0600, every other line + kept), sets `memory.ctx_checkpoint.ungoverned: local` (an `off` stays), and prints the `/policy field` + line for an existing group and the `/policy group` line for a new one; `--emit-yaml` adds the whole + group entry with its fields for `gateway.access_groups` (one write, so the group never exists without + its fields). A `--read` scope must already be a scope of the tenant. It replaces nothing silently: + before the set is made it asks ctx for the tenant's active keys (`api-key-list`) and refuses, naming + what is there, a second group for a server and profile whose key another group's scope homes (one key + per server and profile: give the second group a profile of its own) and a group whose scope is the + home of another key (another group of the server whose name maps to the same scope); the same group + again is refused while its key is in the profile's `.env`, and `--replace` rotates it (a new key, the + earlier one deactivated). Nothing is written when ctx refuses (a 4xx answer; a reached `max_keys` or + `max_scopes` answers 429). Without a clear answer (no answer in time, a 5xx or a proxy error) the set + may have been created and the earlier key of the label may already be inactive: run the same command + again — `replace_label` deactivates the key of the earlier run, so one key per label stays active and + lands in the `.env`. The `.env` is read again just before the write, so a line another writer added meanwhile stays. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id or group name no scope or variable name can hold, a `--profile` other than the profile the command runs in where the home's profile name is known (`…/profiles/<name>` or the account's default home; run - it with `hermes -p <profile>`), a URL that is no http(s) URL, a profile URL of plain - `http://` to a host outside this computer and the local network (the admin key would travel - unencrypted). Keep the tenant-admin key in the shell's environment for this one command; the command - warns when it finds it in the profile's `.env`. + it with `hermes -p <profile>`), a URL that is no http(s) URL, a profile URL of plain `http://` to a + host outside this computer and the local network (the admin key would travel unencrypted). Keep the + tenant-admin key in the shell's environment for this one command; the command warns when it finds it + in the profile's `.env`. - `access reset-marker --restricted | --governed [--profile <p>]` — lowers the named marker(s) of the profile (they only rise by themselves); refuses a `--profile` other than the one it runs in (where the home's profile name is known). Do this @@ -615,11 +620,12 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co Scope names (one tenant per operator, the default): `d<server id in base 36>-k` for the server's knowledge and `d<server id in base 36>-<group>` for the group, at most 24 characters; `_` in a group -name becomes `-`, so `a_b` and `a-b` get the same scope name (refused only when one command names both: -give one of them another name); a group part longer than 9 characters is cut and ends in a 4-character -hash. With `--per-community` (a tenant of this server alone): `k` and `<group>`. The key's label and -variable name the server and the profile, not the group: one key per server and profile, so `provision` -for a second group served by the same profile replaces the key of the first. +name becomes `-`, so `a_b` and `a-b` get the same scope name (refused within one command, and across +runs because `provision` asks ctx which key homes that scope: give one of them another name); a group +part longer than 9 characters is cut and ends in a 4-character hash. With `--per-community` (a tenant of +this server alone): `k` and `<group>`. The key's label and variable name the server and the profile, not +the group: one key per server and profile, so `provision` refuses a second group served by the same +profile on that server and names the key of the first. Warnings of `access check`: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 0ab02d787..33bd20cb1 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -47,7 +47,9 @@ older server a group binding is off and the profile's own connection works as be - **Operator tools and status** (`access_cli.py`, `status.py`): `hermes ctx_checkpoint access status | check | provision | reset-marker`; a status file per binding (`ctx_state/access/`) with the outcome of its base blocks; `hermes memory status` is not ok while a binding is off for another reason than - its group's own fields. + its group's own fields. `provision` replaces no key silently: it asks ctx for the tenant's keys first + and refuses a second group of a server and profile and a scope another key homes; the same group + again needs `--replace` while its key is in the `.env`. - Fixed before release: the state pruning (`state_retention_days`) deleted the markers after 30 days and a session whose root id was `access-mode` wrote its fact ledger over them (both kept now); a status write that failed could abort `initialize` (guarded); an id prefix of several blocks in diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index fc884c55e..8ab6de4ca 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -195,6 +195,11 @@ def add_arguments(parser: argparse.ArgumentParser) -> None: provision.add_argument("--roles", default="", help="Role ids of the group, for --emit-yaml and /policy group") provision.add_argument("--users", default="", help="User ids of the group, for --emit-yaml and /policy group") provision.add_argument("--emit-yaml", action="store_true", help="Also print the group entry with its fields") + provision.add_argument( + "--replace", + action="store_true", + help="Rotate the key of this same group: a new key in the .env, the earlier one deactivated (no other group)", + ) reset = subs.add_parser("reset-marker", help="Lower this profile's markers (it served restricted/governed groups)") reset.add_argument("--profile", help="The profile (shown; the markers are this profile's)") reset.add_argument("--restricted", action="store_true", help="Lower restricted_seen") @@ -754,6 +759,26 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: missing = "the ctx server URL (CTX_BASE_URL or rest_base_url)" if not url else args.admin_key_env print(f" ✗ {missing} is not set; nothing was sent") return 1 + try: + conflict = _key_conflict( + url, + admin_key, + label=label, + own=own, + variable=variable, + env_value=_env_values(home).get(variable, ""), + replace=args.replace, + ) + except ValueError: # a URL CtxClient does not take (no http(s), no host) + print(f" ✗ {_status.display_url(url) or url!r} is no http(s) URL of a ctx server; nothing was sent") + return 1 + except _client.CtxApiError as exc: + cause = _status.redact_error(exc, (admin_key,)) + print(f" ✗ ctx did not list the tenant's keys ({cause}); nothing was created") + return 1 + if conflict: + print(f" ✗ {conflict}. Nothing was created") + return 1 request = { "action": "keyset-provision", "data": { @@ -823,6 +848,68 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: return rc +def _env_values(home: str) -> dict[str, str]: + """The variables of the home's ``.env`` with their values (Hermes' tokenizer; never printed).""" + path = Path(home) / ".env" + if not path.is_file(): + return {} + try: + from agent.secret_scope import load_env_file + + return {str(name): str(value) for name, value in load_env_file(path).items()} + except Exception: + return {} + + +def _key_conflict( + url: str, admin_key: str, *, label: str, own: str, variable: str, env_value: str, replace: bool +) -> str: + """Why this set would replace something it must not, from ctx's own list of the tenant's active keys + (``api-key-list`` with the tenant-admin key; ``""``: nothing). A key serves one group per server and + profile: its label names them, its home is the group's scope. Refused: (1) the label's key homed in + another group's scope; (2) the group's scope homing a key of another label (another server, profile + or group whose name maps to the same scope); (3) without *replace*, a key of this group in the + ``.env`` already (rotation is asked for, not done by a repeat). A run that stopped before its + ``.env`` line finds its key at ctx and none in the ``.env``: it repeats.""" + who = _client.CtxClient(url, admin_key, timeout=REQUEST_TIMEOUT_S).whoami() + slug = who.get("tenant_slug") if isinstance(who, Mapping) and who.get("success") is not False else None + if not isinstance(slug, str) or not access.SLUG_PATTERN.match(slug): + raise _client.CtxApiError("whoami of the tenant-admin key names no tenant") + listed = _manage_once(url, admin_key, {"action": "api-key-list", "data": {"active_only": True}}) + keys = listed.get("keys") + if listed.get("success") is not True or not isinstance(keys, list): + raise _client.CtxApiError(f"api-key-list answered no list ({str(listed.get('error') or '')[:120]})") + mine = [ + key + for key in keys + if isinstance(key, Mapping) + and key.get("active") is not False + and str(key.get("home_scope") or "").startswith(f"{slug}:") + ] + target = f"{slug}:{own}" + for key in mine: + if key.get("label") == label and key.get("home_scope") != target: + return ( + f"the key {label} of this server and profile is homed in {key.get('home_scope')}, the scope of " + f"another group: a key serves one group per server and profile, so give this group another " + f"profile (or deactivate that key first if its group is gone)" + ) + for key in mine: + if key.get("home_scope") == target and key.get("label") != label: + return ( + f"{target} is the home of the key {key.get('label') or '(no label)'}: another group of this server " + f"uses that scope (group names that differ only in _ and - share it); give this group another name" + ) + if env_value and not replace: + held = any(key.get("label") == label for key in mine) + where = f"its key {label} is active at ctx" if held else f"ctx has no active key {label}" + return ( + f"{variable} in the profile's .env holds a key for this server and profile already ({where}); " + f"--replace makes a new key for this same group and deactivates the earlier one" + ) + return "" + + def _full_name(scope: str) -> str: """A scope of the request as the answer names it, the slug left open (``*:<name>`` for a bare name).""" return scope if ":" in scope else f"*:{scope}" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py index 45160b6c8..43080d6b6 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -52,7 +52,7 @@ ) NARROWED_ACTIONS = frozenset({"get", "type-list"}) # The actions of /api/manage the fake answers; ctx knows more, the plugin sends no other. -MANAGE_ACTIONS = frozenset({"get", "type-list", "keyset-provision"}) +MANAGE_ACTIONS = frozenset({"get", "type-list", "keyset-provision", "api-key-list"}) MAX_READ_SCOPES = 8 MAX_IDS = 16 MIN_ID_PREFIX = 8 # store.MinIDPrefixLen @@ -473,9 +473,36 @@ def _manage( # the text of the server-admin tier (go:manage_table.go:254, :394-397; auth/role.go:52-81). if key.role not in ("owner", "admin") and not key.admin: return 403, {"success": False, "error": "admin key required"}, echo + if action == "api-key-list": + return 200, self._api_key_list(key, body), echo status, payload = self._keyset_provision(key, body) return status, payload, echo + def _api_key_list(self, caller: FakeKey, body: Mapping[str, Any]) -> dict[str, Any]: + """``api-key-list`` (go:context_manage.go handleApiKeyList, store.ListApiKeys): the caller's + tenant (a ctx server admin: every tenant), active keys unless ``data.active_only`` is false, + newest first; no plaintext, no tenant field.""" + data = body.get("data") if isinstance(body.get("data"), dict) else {} + active_only = data.get("active_only") is not False + with self.lock: + keys = list(self.keys.values()) + listed = [ + { + "id": key.id, + "label": key.label, + "home_scope": key.home, + "allowed_scopes": list(key.allowed), + "tenant_role": key.role, + "write_scopes": list(key.write_scopes), + "scope_narrowing": key.scope_narrowing, + "active": key.active, + "created_at": NOW, + } + for key in reversed(keys) + if (caller.admin or key.tenant == caller.tenant) and (key.active or not active_only) + ] + return {"success": True, "keys": listed} + # -- get (C-4: go:get_ids.go; the single get: go:context_manage.go:436-560) ------------------- def _get(self, body: Mapping[str, Any], read_set: list[str], echo: str | None) -> tuple[int, dict[str, Any], str]: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py index 06c5635f1..2cc2bb650 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -453,7 +453,7 @@ def test_provision_writes_one_env_line_0600_and_keeps_every_other_line(admin, ca before = "FOO=bar\n# a comment\nCTX_KEY_111_MEMBERS=old-value\nexport OTHER='x y'\nCTX_KEY_111_MEMBERS=older\n" (home / ".env").write_text(before, encoding="utf-8") os.chmod(home / ".env", 0o644) - assert _provision(home) == 0 + assert _provision(home, "--replace") == 0 (key,) = [k for k in _new_keys(fake) if k.active] after = (home / ".env").read_text(encoding="utf-8") assert after == f"FOO=bar\n# a comment\nCTX_KEY_111_MEMBERS={key.secret}\nexport OTHER='x y'\n" @@ -499,7 +499,7 @@ def test_provision_sets_ungoverned_local_in_its_own_profile_and_keeps_off(admin) assert _provision(home) == 0 assert acc.load_settings(str(home))["ungoverned"] == "local" (home / "config.yaml").write_text("memory:\n ctx_checkpoint:\n ungoverned: 'off'\n", encoding="utf-8") - assert _provision(home) == 0 + assert _provision(home, "--replace") == 0 assert acc.load_settings(str(home))["ungoverned"] == "off" @@ -596,8 +596,9 @@ def test_provision_keeps_a_line_another_writer_added_while_ctx_answered(admin, m def answer_while_another_writes(url, key, payload): answer = real(url, key, payload) - with open(home / ".env", "a", encoding="utf-8") as handle: - handle.write("WRITTEN_MEANWHILE=1\n") + if payload.get("action") == "keyset-provision": + with open(home / ".env", "a", encoding="utf-8") as handle: + handle.write("WRITTEN_MEANWHILE=1\n") return answer monkeypatch.setattr(cli, "_manage_once", answer_while_another_writes) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py index f374805d6..0aee04ad7 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py @@ -100,7 +100,7 @@ def test_provision_at_the_key_limit_writes_no_env_line(fake_ctx, monkeypatch, tm def test_provision_twice_leaves_one_active_key_per_label(fake_ctx, monkeypatch, tmp_path, capsys): _provision_world(fake_ctx, monkeypatch, tmp_path) assert _provision(tmp_path, "--emit-yaml") == 0 - assert _provision(tmp_path) == 0 + assert _provision(tmp_path, "--replace") == 0 # rotating the group's key is asked for (fresh review, finding 2) calls = [r.body for r in fake_ctx.requests("/api/manage") if r.action == "keyset-provision"] assert len(calls) == 2 and all(k.get("replace_label") for c in calls for k in c["data"]["keys"]) labels = [k.label for k in fake_ctx.keys.values() if k.active and k.label.startswith("hermes:")] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py new file mode 100644 index 000000000..961bab764 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py @@ -0,0 +1,145 @@ +"""``access provision`` replaces nothing silently (fresh review of the plugin layer, finding 2). A key +serves one group per server and profile (its label and variable name the server and the profile, not the +group), and two group names that differ only in ``_`` and ``-`` map to one scope. Asked of ctx before the +set is made (``api-key-list`` with the tenant-admin key), across runs and hosts: + +- a second group for a server and profile whose key another group's scope homes is refused, naming it; +- a group whose scope is the home of a key of another server/profile (another group) is refused; +- the same group again is refused while its key is in the profile's ``.env``; ``--replace`` rotates it. + +A run that stopped before it wrote the ``.env`` line repeats without ``--replace``: ctx holds the key of +the same label in the same scope, the ``.env`` holds none, and ``replace_label`` deactivates it. The +one-call collision of ``a_b``/``a-b`` (S1, L-PE-3) is unchanged and tested where it was.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_provision_conflicts") +cli = ah.plugin_module(_PKG, "memory.access_cli") + +ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_conflicts" + + +@pytest.fixture +def ctx(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "process-home")) + return fake_ctx + + +def _home(tmp_path, profile): + home = tmp_path / "profiles" / profile + home.mkdir(parents=True, exist_ok=True) + return home + + +def _provision(home, profile, group, *extra, server="111"): + argv = ["provision", "--server", f"discord:{server}", "--profile", profile, "--group", group] + return cli.run_access([*argv, "--admin-key-env", "CTX_ADMIN", *extra], hermes_home=str(home)) + + +def _sets(fake): + return fake.count("/api/manage", "keyset-provision") + + +def _active(fake): + return sorted((key.label, key.home) for key in fake.keys.values() if key.active and key.label.startswith("hermes:")) + + +def test_the_fake_lists_the_tenant_s_active_keys_as_ctx_does(ctx): + ctx.add_key(secret="ctx_other_tenant_key_0001", tenant="u", home="u:main", label="foreign") + ctx.add_key(secret="ctx_inactive_key_000001", tenant="t", home="t:old", label="old", active=False) + status, body, _echo = ctx._answer( + "POST", "/api/manage", "api-key-list", {"action": "api-key-list"}, ADMIN_KEY, [], [] + ) + assert status == 200 and body["success"] is True + assert {key["label"] for key in body["keys"]} == {""} # the admin key itself; no foreign, no inactive one + assert set(body["keys"][0]) == { + "id", + "label", + "home_scope", + "allowed_scopes", + "tenant_role", + "write_scopes", + "scope_narrowing", + "active", + "created_at", + } + + +def test_a_second_group_of_the_same_server_and_profile_is_refused_naming_the_first(ctx, tmp_path, capsys): + home = _home(tmp_path, "members") + assert _provision(home, "members", "members") == 0 + before = (home / ".env").read_text(encoding="utf-8") + capsys.readouterr() + assert _provision(home, "members", "mods") == 1 + out = capsys.readouterr().out + assert "hermes:discord:111:members" in out and "-members" in out and "another profile" in out, out + assert _sets(ctx) == 1 and len(_active(ctx)) == 1 + assert (home / ".env").read_text(encoding="utf-8") == before + + +def test_the_second_group_is_refused_with_replace_as_well(ctx, tmp_path): + home = _home(tmp_path, "members") + assert _provision(home, "members", "members") == 0 + assert _provision(home, "members", "mods", "--replace") == 1 + assert _sets(ctx) == 1 + + +def test_a_group_whose_scope_another_group_homes_is_refused_across_runs(ctx, tmp_path, capsys): + """``a_b`` and ``a-b`` in two runs (two profiles): the second would share the first one's scope.""" + first, second = _home(tmp_path, "first"), _home(tmp_path, "second") + assert _provision(first, "first", "a_b") == 0 + capsys.readouterr() + assert _provision(second, "second", "a-b") == 1 + out = capsys.readouterr().out + assert "hermes:discord:111:first" in out and "-a-b" in out, out + assert _sets(ctx) == 1 and not (second / ".env").exists() + + +def test_the_same_group_again_needs_replace_while_its_key_is_in_the_env(ctx, tmp_path, capsys): + home = _home(tmp_path, "members") + assert _provision(home, "members", "members") == 0 + first = (home / ".env").read_text(encoding="utf-8") + capsys.readouterr() + assert _provision(home, "members", "members") == 1 + out = capsys.readouterr().out + assert "CTX_KEY_111_MEMBERS" in out and "--replace" in out, out + assert _sets(ctx) == 1 and (home / ".env").read_text(encoding="utf-8") == first + assert _provision(home, "members", "members", "--replace") == 0 + assert _sets(ctx) == 2 and len(_active(ctx)) == 1 + (key,) = [k for k in ctx.keys.values() if k.active and k.label == "hermes:discord:111:members"] + assert (home / ".env").read_text(encoding="utf-8") == f"CTX_KEY_111_MEMBERS={key.secret}\n" + + +def test_a_key_in_the_env_without_its_key_at_ctx_needs_replace(ctx, tmp_path, capsys): + home = _home(tmp_path, "members") + (home / ".env").write_text("CTX_KEY_111_MEMBERS=ctx_key_nobody_holds_any_more\n", encoding="utf-8") + assert _provision(home, "members", "members") == 1 + assert "--replace" in capsys.readouterr().out and _sets(ctx) == 0 + assert _provision(home, "members", "members", "--replace") == 0 + + +def test_a_run_that_stopped_before_its_env_line_repeats_without_replace(ctx, tmp_path, monkeypatch): + home = _home(tmp_path, "members") + real = cli._atomic_write + + def broken(path, data): + raise OSError("disk full") + + monkeypatch.setattr(cli, "_atomic_write", broken) + assert _provision(home, "members", "members") == 1 + monkeypatch.setattr(cli, "_atomic_write", real) + assert _provision(home, "members", "members") == 0 + assert _sets(ctx) == 2 and len(_active(ctx)) == 1 + + +def test_another_server_of_the_same_profile_is_its_own_key(ctx, tmp_path): + home = _home(tmp_path, "members") + assert _provision(home, "members", "members") == 0 + assert _provision(home, "members", "members", server="222") == 0 + assert len(_active(ctx)) == 2 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py index 76b1906b3..6c99fc67f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py @@ -346,7 +346,7 @@ def world(tmp_path_factory): mp.setenv("CTX_BASE_URL", URL) runs["members-1"] = _provision(homes["members"], SERVER_A, "members", "members", "--emit-yaml") first_key = _env_value(homes["members"], "CTX_KEY_111_MEMBERS") - runs["members-2"] = _provision(homes["members"], SERVER_A, "members", "members") + runs["members-2"] = _provision(homes["members"], SERVER_A, "members", "members", "--replace") runs["mods"] = _provision( homes["mods"], SERVER_A, "mods", "mods", "--read", layout_a["members"].split(":")[-1] ) From a76856f3f59820bb709cc72798ca41b5c8de1fe4 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:27:15 +0100 Subject: [PATCH 24/65] fix(ctx_checkpoint): a binding whose write or store client ctx refused shows as bound with that client off, not as bound The group still reads, but what the refused client writes (chain, facts, digests, or ctx_store) is not written, and under checkpoint_required every compaction fails. The status file now says "bound; write client off: <why>" (or the store client) with the rules it broke and their expected values; access status shows it and hermes memory status counts it as off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 24 +++--- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 5 +- .../plugin/ctx_checkpoint/memory/provider.py | 14 +++ .../tests/test_access_seam_client_status.py | 86 +++++++++++++++++++ 4 files changed, 116 insertions(+), 13 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_client_status.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 8e9c4c035..31a0d97f3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -562,16 +562,18 @@ Every command works on the profile it runs in: `hermes -p <profile> ctx_checkpoi takes `-p`/`--profile` before the plugin sees it). The plugin never reads the core's `gateway.access_groups`; `check` takes a group's fields on the command line, as `/policy field` does. -- `access status [--server <platform>:<id>]` — no network. Lists every access-group binding of the - profile from its status files (`ctx_state/access/<platform>-<server>-<profile>.json`, one per server and - profile: two groups of one server served by one profile share it, the latest binding shows): `bound`, - `off: <reason>` or a group that gets no ctx by its own fields; for an `off` binding every broken - rule with the value it expected; tenant, read and write scopes, the key's digest (never the key), - the time of the last change; per group whether the base-block hook delivered its text and, if not, - why; the markers `restricted_seen` and `governed_seen`; messaging sessions without an access group - that ran on the profile's own connection; and the way to cut a group off at once (deactivate its key - with `ctx manage api-key-update` and `active=false`; ctx checks the key on every request, without a - cache). A status file of a group you removed stays until you delete it. +- - `access status [--server <platform>:<id>]` — no network. Lists every access-group binding of the + profile from its status files (`ctx_state/access/<platform>-<server>-<profile>.json`, one per server + and profile: two groups of one server served by one profile share it, the latest binding shows): + `bound`, `bound; write client off: <reason>` (or `store client`: the group reads, but ctx refused the + client its chain, facts and digests or `ctx_store` write through — counted as off), `off: <reason>` or + a group that gets no ctx by its own fields; for an `off` binding every broken rule with the value it + expected; tenant, read and write scopes, the key's digest (never the key), the time of the last + change; per group whether the base-block hook delivered its text and, if not, why; the markers + `restricted_seen` and `governed_seen`; messaging sessions without an access group that ran on the + profile's own connection; and the way to cut a group off at once (deactivate its key with `ctx manage + api-key-update` and `active=false`; ctx checks the key on every request, without a cache). A status + file of a group you removed stays until you delete it. - `access check --server <platform>:<id> --group <name> [--profile <p>] [--restricted | --unrestricted] --field <name>=<value> …` — proves a group's fields the way the provider binds them (for an unrestricted group a little stricter: it checks `write` against the home scope also without `capture`; @@ -645,7 +647,7 @@ Warnings of `access check`: **`hermes memory status`** with access groups adds `access_groups` (`N bound, M off, K without ctx by their fields`) and names up to five bindings that are off (`access_off`, `access_off_2`, …). While one binding is off for another reason than its group's own fields (`enabled: false`, no fields, no key -with `governed_unbound: off`), the report is not ok and its summary starts with +with `governed_unbound: off`), or ctx refused its write or store client, the report is not ok and its summary starts with `✗ M of N access-group bindings off`. A profile without a connection of its own (`ungoverned: local` or `off`, no `CTX_KEY`) is ok when all its groups are bound. Groups whose base blocks were not delivered are named in `access_base_blocks`; a status file that cannot be read makes the report not diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 33bd20cb1..f0ffb686e 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -46,8 +46,9 @@ older server a group binding is off and the profile's own connection works as be and group bindings (the MCP transport reads no `whoami`). - **Operator tools and status** (`access_cli.py`, `status.py`): `hermes ctx_checkpoint access status | check | provision | reset-marker`; a status file per binding (`ctx_state/access/`) with the outcome of - its base blocks; `hermes memory status` is not ok while a binding is off for another reason than - its group's own fields. `provision` replaces no key silently: it asks ctx for the tenant's keys first + its base blocks and the write or store client ctx refused (`bound; write client off: …`); + `hermes memory status` is not ok while a binding, or one of its clients, is off for another reason + than its group's own fields. `provision` replaces no key silently: it asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope another key homes; the same group again needs `--replace` while its key is in the `.env`. - Fixed before release: the state pruning (`state_retention_days`) deleted the markers after 30 days diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 7f0d839d3..a59a9d08a 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -177,6 +177,7 @@ class _GroupBinding: tenant_seen: str = "" proven: set[str] = field(default_factory=set) refused: dict[str, str] = field(default_factory=dict) + refused_rules: dict[str, str] = field(default_factory=dict) # "<kind> client <rule>" -> expected value retry_at: dict[str, float] = field(default_factory=dict) def clients(self) -> tuple[CtxClient, ...]: @@ -1041,10 +1042,12 @@ def _client_proven(self, kind: str, client: Any) -> bool: return False group.refused[kind] = f"the ctx server refused the proof ({_proof_cause(exc)})" logger.warning("CTX %s client off (profile=%s): %s", kind, self._profile, group.refused[kind]) + self._record_clients_refused(group) return False except Exception as exc: group.refused[kind] = f"the proof failed ({type(exc).__name__})" logger.warning("CTX %s client off (profile=%s): %s", kind, self._profile, group.refused[kind]) + self._record_clients_refused(group) return False result = _narrowing.evaluate( raw, @@ -1062,18 +1065,29 @@ def _client_proven(self, kind: str, client: Any) -> bool: ) if not result.ok: group.refused[kind] = ", ".join(result.failed) + group.refused_rules.update({f"{kind} client {rule}": text for rule, text in result.detail.items()}) logger.warning( "CTX %s client off (profile=%s): %s", kind, self._profile, "; ".join(f"{rule}: expected {text}" for rule, text in result.detail.items()), ) + self._record_clients_refused(group) return False group.proven.add(kind) if kind == "write" and self._group is group: self._rate_limit_write = _write_limit(raw) return True + def _record_clients_refused(self, group: _GroupBinding) -> None: + """A write or store client ctx refused is part of the binding's state: the group reads, but + what that client writes is not written, so the status says ``bound; write client off: <why>`` + (``access status``, ``hermes memory status`` counts it as off) instead of ``bound``.""" + if self._group is not group or self._access_off or "group" not in group.proven: + return + reasons = "; ".join(f"{kind} client off: {why}" for kind, why in sorted(group.refused.items())) + self._record_access_state(group.context, f"bound; {reasons}", rules=group.refused_rules) + def _access_gate(self) -> bool: """Whether this instance may reach ctx now (design 02 §4.3, §4.6): it is not off, the turn (when one runs) serves the access group and fields the agent was built for, and no narrowed diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_client_status.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_client_status.py new file mode 100644 index 000000000..0c279dd97 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_client_status.py @@ -0,0 +1,86 @@ +"""A refused write or store client is part of the binding's status (fresh review of the plugin layer, +finding 6): the group reads, but the chain, the facts or ``ctx_store`` write nothing — the status file +says ``bound; write client off: <why>`` (the rules it broke with their expected values) instead of +``bound``, ``access status`` shows it and ``hermes memory status`` is not ok. Real provider over REST +against the fake ctx server, as the P-C tests run it.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_client_status") +st = ah.plugin_module(_PKG, "memory.status") +cli = ah.plugin_module(_PKG, "memory.access_cli") +_nar = ah.plugin_module(_PKG, "memory.narrowing") +Provider = _PKG.CtxCheckpointMemoryProvider + +A_K, A_OPS, A_MEMBERS = "t:d111-k", "t:d111-ops", "t:d111-members" +OPS_KEY = "ctx_ops_111_client_status" + + +@pytest.fixture +def world(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=OPS_KEY, tenant="t", home=A_OPS, allowed=(A_K,), write_scopes=(A_K,), label="ops") + fake_ctx.add_block(A_K, "Server A rules", "alpha knowledge") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_OPS": OPS_KEY}) + home = tmp_path / "profiles" / "ops" + home.mkdir(parents=True) + (home / "config.yaml").write_text("platform_toolsets:\n discord: [web]\n", encoding="utf-8") + monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) + _nar.reset_proofs() + yield fake_ctx, home + _nar.reset_proofs() + + +def _provider(home, fields): + provider = Provider(config={"transport": "rest", "memory": True}) + provider.initialize( + "s-1", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields), + ) + return provider + + +def _row(home): + (row,) = [r for r in st.read_access(str(home)) if (r["platform"], r["scope_id"]) == ("discord", "111")] + return row + + +def _messages(): + return [{"role": "user" if i % 2 == 0 else "assistant", "content": f"line {i} " + "x" * 200} for i in range(6)] + + +def test_a_refused_write_client_shows_in_the_status(world, capsys): + _fake, home = world + provider = _provider(home, {"key": "CTX_KEY_111_OPS", "read": [A_K], "write": A_K}) # write is not the home + assert _row(home)["state"] == "bound" + assert provider.on_pre_compress(_messages()) == "" # the write client proves itself and is refused + row = _row(home) + assert row["state"].startswith("bound; write client off"), row + assert "E3" in row["state"] and "home scope" in row["rules"]["write client E3"], row + assert st.access_class(row) == "off" + status = provider.get_status_config({}) + assert status["ok"] is False and "write client off" in status["access_off"] + assert cli.run_access(["status"], hermes_home=str(home)) == 0 + assert "write client off" in capsys.readouterr().out + + +def test_a_refused_store_client_shows_in_the_status(world): + _fake, home = world + provider = _provider(home, {"key": "CTX_KEY_111_OPS", "read": [A_K], "write": A_OPS, "store": A_MEMBERS}) + result = provider.handle_tool_call("ctx_store", {"category": "reference", "title": "t", "content": "c"}) + assert '"error"' in result + row = _row(home) + assert row["state"].startswith("bound; store client off: the ctx server refused the proof"), row + assert st.access_class(row) == "off" + + +def test_a_proven_write_client_leaves_the_status_bound(world): + _fake, home = world + provider = _provider(home, {"key": "CTX_KEY_111_OPS", "read": [A_K], "write": A_OPS}) + assert provider.on_pre_compress(_messages(), require_checkpoint=True) + assert _row(home)["state"] == "bound" From b87a10fee6aa012fa648a8e3cc49acd4e6e5c427 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:31:00 +0100 Subject: [PATCH 25/65] fix(ctx_checkpoint): access check reads a group's key and base_url variable from the profile only The check read them from the secret scope and then from the environment of the shell it ran in, which can carry another profile's values; it could pass where the binding then found the variable empty. It now reads the profile's own secrets (its .env and secret sources, the mapping Hermes binds for the profile's turns) and reports a key or URL variable that is not there, naming a shell variable of that name without its value. The tests of check keep the group's key in the profile's .env. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 25 +++---- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 3 +- .../ctx_checkpoint/memory/access_cli.py | 39 +++++++++-- .../tests/test_access_pe_rules.py | 7 +- .../test_access_seam_check_profile_keys.py | 66 +++++++++++++++++++ 5 files changed, 121 insertions(+), 19 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_check_profile_keys.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 31a0d97f3..349f3bab5 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -574,18 +574,19 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co profile's own connection; and the way to cut a group off at once (deactivate its key with `ctx manage api-key-update` and `active=false`; ctx checks the key on every request, without a cache). A status file of a group you removed stays until you delete it. -- `access check --server <platform>:<id> --group <name> [--profile <p>] [--restricted | --unrestricted] - --field <name>=<value> …` — proves a group's fields the way the provider binds them (for an - unrestricted group a little stricter: it checks `write` against the home scope also without `capture`; - it reads the key variable from the shell's environment too, the binding only from the profile): their forms - (E1) before any secret is read, then the URL, the key, the narrowed and the unnarrowed `whoami` (E2 - to E5, E7) and, for a group that writes, the write client's own narrowing. Every broken rule is named - with the value it expected (for example `✗ E4: expected label hermes:discord:123…:members`). Exit - code 1 when a rule is broken, 0 otherwise; warnings do not change it. It does not prove the base - blocks (E6) or the store client of `store`, and says so; `access status` shows what the hook did - with the base blocks. Lists take comma-separated values (`--field read=t:d…-k,t:d…-faq`); - `ctx_checkpoint.` before a field name is optional. -- - `access provision --server <platform>:<id> --group <name> --admin-key-env <VAR> [--profile <p>] +- - `access check --server <platform>:<id> --group <name> [--profile <p>] [--restricted | + --unrestricted] --field <name>=<value> …` — proves a group's fields the way the provider binds them + (for an unrestricted group a little stricter: it checks `write` against the home scope also without + `capture`; it reads the key and the `base_url` variable from the profile's own `.env` and secret + sources only, as the binding does; a key that only the shell's environment holds is reported as + missing): their forms (E1) before any secret is read, then the URL, the key, the narrowed and the + unnarrowed `whoami` (E2 to E5, E7) and, for a group that writes, the write client's own narrowing. + Every broken rule is named with the value it expected (for example `✗ E4: expected label + hermes:discord:123…:members`). Exit code 1 when a rule is broken, 0 otherwise; warnings do not change + it. It does not prove the base blocks (E6) or the store client of `store`, and says so; `access + status` shows what the hook did with the base blocks. Lists take comma-separated values (`--field + read=t:d…-k,t:d…-faq`); `ctx_checkpoint.` before a field name is optional. - +- `access provision --server <platform>:<id> --group <name> --admin-key-env <VAR> [--profile <p>] [--read <scope> …] [--per-community] [--base-url-env CTX_BASE_URL_<…>] [--roles <ids>] [--users <ids>] [--emit-yaml] [--replace]` — sets up ctx for a restricted group: names the group's scopes and the key's label (`hermes:<platform>:<server>:<profile>`), creates the scopes and a member key that diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index f0ffb686e..526e9a063 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -50,7 +50,8 @@ older server a group binding is off and the profile's own connection works as be `hermes memory status` is not ok while a binding, or one of its clients, is off for another reason than its group's own fields. `provision` replaces no key silently: it asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope another key homes; the same group - again needs `--replace` while its key is in the `.env`. + again needs `--replace` while its key is in the `.env`. `access check` reads the group's key from the + profile's `.env` and secret sources only, never from the shell's environment. - Fixed before release: the state pruning (`state_retention_days`) deleted the markers after 30 days and a session whose root id was `access-mode` wrote its fact ledger over them (both kept now); a status write that failed could abort `initialize` (guarded); an id prefix of several blocks in diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 8ab6de4ca..b7f87f380 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -286,7 +286,9 @@ def _ids(text: str, option: str) -> list[str]: def _secret(name: str) -> str: - """A variable of the profile (its secret scope, then the process environment); never printed.""" + """A variable for ``provision`` (the tenant-admin key, which belongs in the shell's environment, and + ``--base-url-env``): the secret scope, then the process environment; never printed. ``check`` reads + the group's variables from the profile only (:func:`_profile_secrets`).""" try: value = env_secret(name) except Exception: @@ -294,6 +296,25 @@ def _secret(name: str) -> str: return value or os.environ.get(name, "").strip() +def _profile_secrets(home: str) -> dict[str, str] | None: + """The profile's own secrets — its ``.env`` and secret sources, the mapping Hermes binds for the + profile's turns (``agent.secret_scope.build_profile_secret_scope``) — never the environment of the + shell this runs in, which may carry another profile's values; ``None`` when they cannot be read.""" + try: + from agent.secret_scope import build_profile_secret_scope + + return {str(name): str(value) for name, value in build_profile_secret_scope(Path(home)).items()} + except Exception: + return None + + +def _shell_has(name: str) -> str: + """A note when the shell's environment has *name* (never its value).""" + if not os.environ.get(name): + return "" + return " (this shell's environment has it, but that may be another profile's; the gateway reads the profile's)" + + def _user_config(home: str) -> dict[str, Any]: """The home's config.yaml as written (``{}`` when missing or unreadable).""" try: @@ -446,8 +467,18 @@ def _prove( """The proof of the binding as the provider makes it (design 02 §4.2 step 5): URL, key, E7 inputs, the narrowed and the unnarrowed ``whoami`` judged by ``narrowing.evaluate``, and the write client's own proof when the group writes. Prints a line per rule; the broken count and the raw answers.""" + secrets = _profile_secrets(home) + if secrets is None: + print(" ✗ the profile's secrets (its .env and secret sources) cannot be read") + return 1, {} if fields.base_url: - url = _secret(fields.base_url) + url = secrets.get(fields.base_url, "").strip() + if not url: + print( + f" ✗ base_url: {fields.base_url} is not in the profile's .env or its secret sources" + f"{_shell_has(fields.base_url)}" + ) + return 1, {} if not access.valid_base_url(url): print(f" ✗ base_url: expected an https URL of a ctx server in {fields.base_url}") return 1, {} @@ -457,9 +488,9 @@ def _prove( print(" ✗ base_url: expected a ctx server URL of the profile (CTX_BASE_URL or rest_base_url)") return 1, {} print(f" ctx server: {_status.display_url(url)}") - key = _secret(fields.key) + key = secrets.get(fields.key, "").strip() if not key: - print(f" ✗ key: expected the ctx key in {fields.key} of the profile's .env") + print(f" ✗ key: {fields.key} is not in the profile's .env or its secret sources{_shell_has(fields.key)}") return 1, {} inputs = access.e7_inputs(home, platform) if strict else ((), ()) settings = access.load_settings(home) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py index 2cc2bb650..15c16a51f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -312,6 +312,8 @@ def build(**key): host = ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) home = _home(tmp_path) + # check reads the group's key from the profile's own .env (fresh review, finding 16) + (home / ".env").write_text(f"CTX_KEY_111_MEMBERS={MEMBER_KEY}\n", encoding="utf-8") monkeypatch.setenv("HERMES_HOME", str(home)) nar.reset_proofs() yield build, host, home @@ -373,7 +375,8 @@ def test_check_refuses_a_broken_field_before_any_secret_or_request(member, capsy def test_check_warns_of_a_standard_key_in_a_restricted_profile(member, capsys): build, _host, home = member build() - (home / ".env").write_text("CTX_KEY=x\n", encoding="utf-8") + with open(home / ".env", "a", encoding="utf-8") as handle: + handle.write("CTX_KEY=x\n") assert _run(home, "check", *MEMBER, *FIELDS) == 0 assert re.search(r"⚠ .*standard key CTX_KEY", capsys.readouterr().out) @@ -419,7 +422,7 @@ def test_check_of_an_unrestricted_group_in_an_open_profile_warns_of_no_standard_ fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:d111-ops", allowed=(A_K,)) ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_OPS": PROFILE_KEY}) home = _home(tmp_path, "ops") - (home / ".env").write_text("CTX_KEY=x\n", encoding="utf-8") + (home / ".env").write_text(f"CTX_KEY=x\nCTX_KEY_111_OPS={PROFILE_KEY}\n", encoding="utf-8") nar.reset_proofs() argv = ["--server", "discord:111", "--profile", "ops", "--group", "ops", "--unrestricted"] assert _run(home, "check", *argv, "--field", "key=CTX_KEY_111_OPS", "--field", f"read={A_K}") == 0 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_check_profile_keys.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_check_profile_keys.py new file mode 100644 index 000000000..ff0cbddd9 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_check_profile_keys.py @@ -0,0 +1,66 @@ +"""``access check`` reads the group's key (and its ``base_url`` variable) from the profile only — its +``.env`` and secret sources, the mapping Hermes binds for the profile's turns — never from the +environment of the shell it runs in, which may carry another profile's values (fresh review of the +plugin layer, finding 16). A key that is not in the profile is a broken check that says so, before any +request.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_check_profile_keys") +cli = ah.plugin_module(_PKG, "memory.access_cli") +_nar = ah.plugin_module(_PKG, "memory.narrowing") + +A_K, A_MEMBERS = "t:d111-k", "t:d111-members" +MEMBER_KEY = "ctx_member_111_check_secrets" +ARGS = ["check", "--server", "discord:111", "--profile", "members", "--group", "members", "--restricted"] +FIELDS = ["--field", "key=CTX_KEY_111_MEMBERS", "--field", "tenant=t", "--field", f"read={A_K}"] + + +@pytest.fixture +def world(fake_ctx, monkeypatch, tmp_path): + label = "hermes:discord:111:members" + fake_ctx.add_key( + secret=MEMBER_KEY, tenant="t", home=A_MEMBERS, allowed=(A_K,), scope_narrowing="required", label=label + ) + home = tmp_path / "profiles" / "members" + home.mkdir(parents=True) + (home / "config.yaml").write_text("platform_toolsets:\n discord: [web]\n", encoding="utf-8") + monkeypatch.setenv("HERMES_HOME", str(home)) + _nar.reset_proofs() + yield fake_ctx, home + _nar.reset_proofs() + + +def _check(home, *extra): + return cli.run_access([*ARGS, *FIELDS, "--field", f"write={A_MEMBERS}", *extra], hermes_home=str(home)) + + +def test_a_key_only_in_the_shell_s_environment_is_not_the_profile_s(world, monkeypatch, capsys): + fake, home = world + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}) + monkeypatch.setenv("CTX_KEY_111_MEMBERS", MEMBER_KEY) + assert _check(home) == 1 + out = capsys.readouterr().out + assert "CTX_KEY_111_MEMBERS" in out and "not in the profile" in out, out + assert fake.count() == 0 and MEMBER_KEY not in out + + +def test_the_key_in_the_profile_s_env_is_checked(world, monkeypatch, capsys): + fake, home = world + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake.url}) + (home / ".env").write_text(f"CTX_KEY_111_MEMBERS={MEMBER_KEY}\n", encoding="utf-8") + assert _check(home) == 0, capsys.readouterr().out + + +def test_a_base_url_variable_only_in_the_shell_s_environment_is_not_the_profile_s(world, monkeypatch, capsys): + fake, home = world + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL_111": "https://ctx.example"}) + monkeypatch.setenv("CTX_BASE_URL_111", "https://ctx.example") + (home / ".env").write_text(f"CTX_KEY_111_MEMBERS={MEMBER_KEY}\n", encoding="utf-8") + assert _check(home, "--field", "base_url=CTX_BASE_URL_111") == 1 + out = capsys.readouterr().out + assert "CTX_BASE_URL_111" in out and "not in the profile" in out, out + assert fake.count() == 0 From c561a29e3cf37a887879438978b271413fd24806 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:35:26 +0100 Subject: [PATCH 26/65] test(ctx_checkpoint): provision weighs only its own tenant's keys when a ctx server admin key lists every tenant The mutant that dropped the tenant filter of provision's key check survived: no test listed keys of another tenant. A ctx server admin key's api-key-list names every tenant's keys, and a key of the same label in another tenant is not this tenant's group. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../test_access_seam_provision_conflicts.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py index 961bab764..fcc61fe6d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py @@ -143,3 +143,23 @@ def test_another_server_of_the_same_profile_is_its_own_key(ctx, tmp_path): assert _provision(home, "members", "members") == 0 assert _provision(home, "members", "members", server="222") == 0 assert len(_active(ctx)) == 2 + + +def test_a_ctx_server_admin_key_weighs_only_the_keys_of_its_own_tenant(fake_ctx, monkeypatch, tmp_path): + """A ctx server admin's ``api-key-list`` names every tenant's keys; a key of the same label in another + tenant (another operator's bot in the same Discord server) is not this tenant's group.""" + server_admin = "ctx_server_admin_MARKED_FAKE_KEY" + fake_ctx.add_key(secret=server_admin, tenant="t", home="t:main", role="owner", admin=True) + fake_ctx.add_key( + secret="ctx_other_operator_key_00001", + tenant="u", + home="u:d2ix-mods", + label="hermes:discord:111:members", + scope_narrowing="required", + ) + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": server_admin}) + monkeypatch.setenv("CTX_ADMIN", server_admin) + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "process-home")) + home = _home(tmp_path, "members") + assert _provision(home, "members", "members") == 0 + assert _sets(fake_ctx) == 1 From 157e426c87bb876eeec1711e18da2c589b58b80f Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 07:41:55 +0100 Subject: [PATCH 27/65] =?UTF-8?q?chore:=20the=20plugin=20branch=20carries?= =?UTF-8?q?=20no=20server=20file=20=E2=80=94=20the=20Go=20contract=20stubs?= =?UTF-8?q?=20land=20with=20the=20server?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../keyset_provision_c3_integration_test.go | 494 ----------- .../manage_get_ids_c4_integration_test.go | 261 ------ go/cmd/ctxd/narrowing_c1_integration_test.go | 806 ------------------ ..._narrowing_required_c2_integration_test.go | 385 --------- go/internal/auth/auth.go | 28 - go/internal/handler/manage_table.go | 9 - go/internal/handler/middleware.go | 15 +- go/internal/handler/narrowing.go | 65 -- go/internal/store/api_keys.go | 16 +- go/internal/store/api_keys_insert_test.go | 4 +- .../store/api_keys_write_scopes_test.go | 4 +- go/internal/store/provision.go | 3 +- 12 files changed, 9 insertions(+), 2081 deletions(-) delete mode 100644 go/cmd/ctxd/keyset_provision_c3_integration_test.go delete mode 100644 go/cmd/ctxd/manage_get_ids_c4_integration_test.go delete mode 100644 go/cmd/ctxd/narrowing_c1_integration_test.go delete mode 100644 go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go delete mode 100644 go/internal/handler/narrowing.go diff --git a/go/cmd/ctxd/keyset_provision_c3_integration_test.go b/go/cmd/ctxd/keyset_provision_c3_integration_test.go deleted file mode 100644 index f1074158f..000000000 --- a/go/cmd/ctxd/keyset_provision_c3_integration_test.go +++ /dev/null @@ -1,494 +0,0 @@ -//go:build integration && s1red_c3 - -// Achse 02, cluster C-3 (design2/02-ctx-checkpoint.md §3.5 C-3, §7.3, BP-26): -// the manage action keyset-provision creates, for a tenant-admin in its own -// tenant, the missing scopes and then the keys of one set in ONE transaction -// under the tenant row's lock, with the checks of scope-create and -// api-key-create (name rules, max_scopes, max_keys, write_scopes ⊆ -// allowed ∪ {home}), at most 64 scopes and 64 keys per call, each key its own -// principal; replace_label deactivates the active keys of the same label in -// the same transaction. Written in S1, where the action does not exist; the -// second build tag keeps the file out of every gate until C-3 lands. To -// enable, shorten the constraint line to `//go:build integration`. The -// required keys need C-2 (integration order C-1, C-2, C-4, C-3). -// -// Wire form fixed by these tests (S1 contract, design §3.5 plus the lead's -// reading where the design is silent): -// -// request: {"action":"keyset-provision","data":{"scopes":[<name>…], -// "keys":[{"label","home_scope","allowed_scopes","write_scopes", -// "scope_narrowing","replace_label"}…]}} -// names in "scopes" are bare scope names (scope-create's rule); -// a key's scopes are bare names (the tenant's "<slug>:" is put in -// front) or full scope names, which must be the tenant's own (403). -// answer: {"success":true,"scopes":[{"scope":"<slug>:<name>","created":bool}…], -// "keys":[{"id","label","home_scope","allowed_scopes","write_scopes", -// "scope_narrowing","api_key"}…]} — both in request order, the -// plaintext (api_key) only here. -// -// Every refusal test ends with a valid call of the same caller (its control): -// on a tree without the action the refusals would pass for the wrong reason -// (an unknown action is a 400 that creates nothing too). -// -// go test -tags=integration,s1red_c3 -p 1 -count=1 -run '^TestC3' ./cmd/ctxd/ -package main - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "slices" - "strings" - "testing" - - "github.com/jackc/pgx/v5/pgxpool" - - "github.com/GottZ/ctx/internal/backends" - "github.com/GottZ/ctx/internal/blocktype" - "github.com/GottZ/ctx/internal/config" - "github.com/GottZ/ctx/internal/dispatch" - "github.com/GottZ/ctx/internal/events" - "github.com/GottZ/ctx/internal/store" - "github.com/GottZ/ctx/internal/testdb" -) - -// c3AdminKey is the bootstrap server-admin key (default tenant, owner). -const c3AdminKey = "c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0c3a0" - -type c3Resp struct { - status int - body map[string]any - raw string -} - -// c3World: tenant c3t with its owner key; the server-admin key. -type c3World struct { - pool *pgxpool.Pool - router http.Handler - owner string // owner key of c3t - tenantID string // id of c3t -} - -func c3Setup(t *testing.T) *c3World { - t.Helper() - pool := testdb.SetupTestDB(t) - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - applyEnv(t, map[string]string{}) - cc, issues := loadFromEnv() - if config.HasErrors(issues) { - t.Fatalf("env fixture invalid: %v", issues) - } - cfgStore := config.NewStore(cc) - backendPool := backends.NewPool(pool, nil) - scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) - projectHub := events.NewProjectHub(ctx, pool, cfgStore) - d := dispatch.New(nil, dispatch.DefaultSettings()) - t.Cleanup(d.Close) - scheduler.SetDispatcher(d) - if created, _, err := store.BootstrapAdminKey(ctx, pool, c3AdminKey, "c3-admin"); err != nil || !created { - t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) - } - w := &c3World{pool: pool, router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d)} - r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3t", "display_name": "C3"}}).must(t, "tenant-create") - w.owner, _ = r.body["owner_key"].(string) - tn, _ := r.body["tenant"].(map[string]any) - w.tenantID, _ = tn["id"].(string) - if w.owner == "" || w.tenantID == "" { - t.Fatalf("fixture tenant-create: %s", r.raw) - } - return w -} - -func (w *c3World) do(t *testing.T, method, path, key string, body any) c3Resp { - t.Helper() - var rd io.Reader = http.NoBody - if body != nil { - b, err := json.Marshal(body) - if err != nil { - t.Fatal(err) - } - rd = bytes.NewReader(b) - } - req := httptest.NewRequest(method, path, rd) - req.Header.Set("X-Context-Key", key) - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - rec := httptest.NewRecorder() - w.router.ServeHTTP(rec, req) - var out map[string]any - _ = json.Unmarshal(rec.Body.Bytes(), &out) - return c3Resp{status: rec.Code, body: out, raw: rec.Body.String()} -} - -func (w *c3World) manage(t *testing.T, key string, body map[string]any) c3Resp { - t.Helper() - return w.do(t, http.MethodPost, "/api/manage", key, body) -} - -func (r c3Resp) must(t *testing.T, what string) c3Resp { - t.Helper() - if r.status != http.StatusOK || r.body["success"] != true { - t.Fatalf("%s: HTTP %d %s", what, r.status, r.raw) - } - return r -} - -// provision posts one keyset-provision as key. -func (w *c3World) provision(t *testing.T, key string, scopes []string, keys ...map[string]any) c3Resp { - t.Helper() - if scopes == nil { - scopes = []string{} - } - return w.manage(t, key, map[string]any{"action": "keyset-provision", "data": map[string]any{"scopes": scopes, "keys": keys}}) -} - -// c3Key is one key spec. -func c3Key(label, home string, allowed, write []string, narrowing string) map[string]any { - if allowed == nil { - allowed = []string{} - } - if write == nil { - write = []string{} - } - return map[string]any{"label": label, "home_scope": home, "allowed_scopes": allowed, "write_scopes": write, "scope_narrowing": narrowing} -} - -// state is the tenant's scopes and active key labels, sorted. -func (w *c3World) state(t *testing.T) (scopes, labels []string) { - t.Helper() - ctx := context.Background() - rows, err := w.pool.Query(ctx, `SELECT scope FROM context_tenant_scopes WHERE tenant_id = $1::uuid ORDER BY scope`, w.tenantID) - if err != nil { - t.Fatal(err) - } - for rows.Next() { - var s string - if err := rows.Scan(&s); err != nil { - t.Fatal(err) - } - scopes = append(scopes, s) - } - rows.Close() - rows, err = w.pool.Query(ctx, `SELECT label FROM context_api_keys WHERE tenant_id = $1::uuid AND active ORDER BY label`, w.tenantID) - if err != nil { - t.Fatal(err) - } - for rows.Next() { - var s string - if err := rows.Scan(&s); err != nil { - t.Fatal(err) - } - labels = append(labels, s) - } - rows.Close() - return scopes, labels -} - -// wantUnchanged fails unless the tenant's scopes and active keys are exactly -// the ones before. -func (w *c3World) wantUnchanged(t *testing.T, what string, scopes, labels []string) { - t.Helper() - s, l := w.state(t) - if !slices.Equal(s, scopes) || !slices.Equal(l, labels) { - t.Errorf("%s: scopes %v keys %v, want unchanged %v %v (nothing created)", what, s, l, scopes, labels) - } -} - -// keysOf reads the answer's keys: label → (id, plaintext). -func c3KeysOf(r c3Resp) (labels []string, ids, plains map[string]string) { - ids, plains = map[string]string{}, map[string]string{} - list, _ := r.body["keys"].([]any) - for _, e := range list { - m, _ := e.(map[string]any) - l, _ := m["label"].(string) - labels = append(labels, l) - ids[l], _ = m["id"].(string) - plains[l], _ = m["api_key"].(string) - } - return labels, ids, plains -} - -func (w *c3World) whoami(t *testing.T, key string) map[string]any { - t.Helper() - r := w.do(t, http.MethodGet, "/api/whoami", key, nil) - if r.status != http.StatusOK { - t.Fatalf("whoami: HTTP %d %s", r.status, r.raw) - } - return r.body -} - -// TestC3KeysetProvisionCreatesScopesAndKeys: missing scopes are created, an -// existing own scope is reused, the keys carry label, scopes and -// scope_narrowing as asked, and their plaintexts appear in this answer only. -func TestC3KeysetProvisionCreatesScopesAndKeys(t *testing.T) { - w := c3Setup(t) - w.manage(t, w.owner, map[string]any{"action": "scope-create", "data": map[string]any{"name": "k"}}).must(t, "scope-create k") - - r := w.provision(t, w.owner, []string{"k", "members", "mods"}, - c3Key("hermes:discord:111:members", "members", []string{"k"}, nil, "required"), - c3Key("hermes:discord:111:mods", "mods", []string{"k", "members"}, nil, "required")) - r.must(t, "keyset-provision") - - sc, _ := r.body["scopes"].([]any) - var got []string - for _, e := range sc { - m, _ := e.(map[string]any) - got = append(got, fmt.Sprintf("%v=%v", m["scope"], m["created"])) - } - if want := []string{"c3t:k=false", "c3t:members=true", "c3t:mods=true"}; !slices.Equal(got, want) { - t.Errorf("answer scopes %v, want %v (in request order, k reused)", got, want) - } - scopes, _ := w.state(t) - if want := []string{"c3t:k", "c3t:main", "c3t:members", "c3t:mods"}; !slices.Equal(scopes, want) { - t.Errorf("tenant scopes %v, want %v", scopes, want) - } - - labels, ids, plains := c3KeysOf(r) - if want := []string{"hermes:discord:111:members", "hermes:discord:111:mods"}; !slices.Equal(labels, want) { - t.Fatalf("answer keys %v, want %v in request order", labels, want) - } - for l, wantHome := range map[string]string{"hermes:discord:111:members": "c3t:members", "hermes:discord:111:mods": "c3t:mods"} { - if plains[l] == "" || ids[l] == "" { - t.Errorf("%s: no id or plaintext in the answer", l) - continue - } - b := w.whoami(t, plains[l]) - if b["label"] != l || b["home_scope"] != wantHome || b["scope_narrowing"] != "required" || b["role"] != "member" || b["admin"] != false || b["api_key_id"] != ids[l] { - t.Errorf("%s: whoami label %v home %v scope_narrowing %v role %v admin %v id %v, want %s %s required member false %s", - l, b["label"], b["home_scope"], b["scope_narrowing"], b["role"], b["admin"], b["api_key_id"], l, wantHome, ids[l]) - } - } - b := w.whoami(t, plains["hermes:discord:111:mods"]) - rs, _ := b["read_scopes"].([]any) - if fmt.Sprint(rs) != "[c3t:mods c3t:k c3t:members]" { - t.Errorf("mods key reads %v, want [c3t:mods c3t:k c3t:members]", rs) - } - - // The plaintexts are in no later answer. - list := w.manage(t, w.owner, map[string]any{"action": "api-key-list"}).must(t, "api-key-list") - for l, p := range plains { - if strings.Contains(list.raw, p) { - t.Errorf("api-key-list carries the plaintext of %s", l) - } - } -} - -// TestC3QuotaRefusesTheWholeSet: a set that would pass max_scopes after its -// second new scope, or max_keys, is a 429 and creates nothing — not the -// scopes before the limit, not a key. -func TestC3QuotaRefusesTheWholeSet(t *testing.T) { - w := c3Setup(t) - w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 3, "max_keys": 3}}).must(t, "tenant-limit-set") - scopes, labels := w.state(t) - - r := w.provision(t, w.owner, []string{"a", "b", "c"}, c3Key("c3-q", "a", nil, nil, "required")) - if r.status != http.StatusTooManyRequests { - t.Errorf("third new scope over max_scopes 3 (main counts): HTTP %d %s, want 429", r.status, r.raw) - } - if r.body["limit"] != float64(3) || r.body["count"] == nil { - t.Errorf("the 429 names limit %v and count %v, want the limit 3 and the tenant's count", r.body["limit"], r.body["count"]) - } - w.wantUnchanged(t, "after the scope refusal", scopes, labels) - - r = w.provision(t, w.owner, []string{"a"}, c3Key("c3-q1", "a", nil, nil, "required"), c3Key("c3-q2", "a", nil, nil, "required"), c3Key("c3-q3", "a", nil, nil, "required")) - if r.status != http.StatusTooManyRequests { - t.Errorf("three keys over max_keys 3 (the owner key counts): HTTP %d %s, want 429", r.status, r.raw) - } - w.wantUnchanged(t, "after the key refusal", scopes, labels) - - w.provision(t, w.owner, []string{"a", "b"}, c3Key("c3-q1", "a", nil, nil, "required"), c3Key("c3-q2", "b", nil, nil, "required")).must(t, "control: within both limits") -} - -// TestC3MemberIsRefused: keyset-provision is a tenant-admin action. -func TestC3MemberIsRefused(t *testing.T) { - w := c3Setup(t) - r := w.manage(t, w.owner, map[string]any{"action": "api-key-create", "data": map[string]any{"label": "c3-member", "home_scope": "c3t:main"}}).must(t, "member key") - member, _ := r.body["api_key"].(string) - scopes, labels := w.state(t) - if r := w.provision(t, member, []string{"members"}, c3Key("c3-by-member", "members", nil, nil, "required")); r.status != http.StatusForbidden { - t.Errorf("member: HTTP %d %s, want 403", r.status, r.raw) - } - w.wantUnchanged(t, "after the member's call", scopes, labels) - w.provision(t, w.owner, []string{"members"}, c3Key("c3-by-owner", "members", nil, nil, "required")).must(t, "control: the owner") -} - -// TestC3ForeignScopeIsRefused: a key that names another tenant's scope is a -// 403, and nothing of the set is created. -func TestC3ForeignScopeIsRefused(t *testing.T) { - w := c3Setup(t) - r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3u", "display_name": "C3 other"}}).must(t, "second tenant") - foreign, _ := r.body["scope"].(string) - scopes, labels := w.state(t) - for _, k := range []map[string]any{ - c3Key("c3-foreign-read", "members", []string{foreign}, nil, "required"), - c3Key("c3-foreign-home", foreign, nil, nil, "required"), - } { - if r := w.provision(t, w.owner, []string{"members"}, k); r.status != http.StatusForbidden { - t.Errorf("%s: HTTP %d %s, want 403", k["label"], r.status, r.raw) - } - w.wantUnchanged(t, fmt.Sprint(k["label"]), scopes, labels) - } - w.provision(t, w.owner, []string{"members"}, c3Key("c3-own", "members", []string{"c3t:main"}, nil, "required")).must(t, "control: own scopes, bare and full") -} - -// TestC3WriteScopesOutsideTheReadSetAreRefused: write_scopes ⊄ allowed ∪ -// {home} is a 400, and nothing is created. -func TestC3WriteScopesOutsideTheReadSetAreRefused(t *testing.T) { - w := c3Setup(t) - scopes, labels := w.state(t) - r := w.provision(t, w.owner, []string{"k", "members", "mods"}, - c3Key("c3-ok", "members", []string{"k"}, nil, "required"), - c3Key("c3-blind", "members", []string{"k"}, []string{"mods"}, "required")) - if e, _ := r.body["error"].(string); r.status != http.StatusBadRequest || !strings.Contains(e, "write_scope") { - t.Errorf("write scope outside the read set: HTTP %d %s, want 400 naming the write_scope", r.status, r.raw) - } - w.wantUnchanged(t, "after the refusal", scopes, labels) - w.provision(t, w.owner, []string{"k", "members"}, c3Key("c3-ok", "members", []string{"k"}, []string{"k"}, "required")).must(t, "control: write scope inside the read set") -} - -// TestC3SizeOfASetIsCapped: 65 keys or 65 scopes in one call are a 400 before -// anything is created, also when the tenant's limits would allow them; 64 -// keys pass. -func TestC3SizeOfASetIsCapped(t *testing.T) { - w := c3Setup(t) - w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 1000, "max_keys": 1000}}).must(t, "tenant-limit-set") - scopes, labels := w.state(t) - keys := func(n int) []map[string]any { - out := make([]map[string]any, n) - for i := range out { - out[i] = c3Key(fmt.Sprintf("c3-many-%02d", i), "many", nil, nil, "required") - } - return out - } - if r := w.provision(t, w.owner, []string{"many"}, keys(65)...); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "64") { - t.Errorf("65 keys: HTTP %d %s, want 400 naming the cap 64", r.status, r.raw) - } - w.wantUnchanged(t, "after 65 keys", scopes, labels) - names := make([]string, 65) - for i := range names { - names[i] = fmt.Sprintf("s%02d", i) - } - if r := w.provision(t, w.owner, names, c3Key("c3-many-scopes", "s00", nil, nil, "required")); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "64") { - t.Errorf("65 scopes: HTTP %d %s, want 400 naming the cap 64", r.status, r.raw) - } - w.wantUnchanged(t, "after 65 scopes", scopes, labels) - r := w.provision(t, w.owner, []string{"many"}, keys(64)...).must(t, "control: 64 keys") - if l, _, _ := c3KeysOf(r); len(l) != 64 { - t.Errorf("64 keys asked, %d answered", len(l)) - } -} - -// TestC3ReplaceLabelDeactivatesThePreviousKey: replace_label deactivates the -// active keys of the tenant with the same label, in the same call, so a -// repeated provision leaves one active key per label. -func TestC3ReplaceLabelDeactivatesThePreviousKey(t *testing.T) { - w := c3Setup(t) - const label = "hermes:discord:222:members" - - // The same label in another tenant: labels are predictable, so the - // replacement must stay inside the caller's tenant. - r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3v", "display_name": "C3 same label"}}).must(t, "second tenant") - otherOwner, _ := r.body["owner_key"].(string) - r = w.provision(t, otherOwner, []string{"members"}, c3Key(label, "members", nil, nil, "required")).must(t, "the other tenant's key") - _, _, other := c3KeysOf(r) - - r = w.provision(t, w.owner, []string{"members"}, c3Key(label, "members", nil, nil, "required")).must(t, "first provision") - _, _, first := c3KeysOf(r) - // At the key limit (owner key and the first key): the replacement does not - // count the key it deactivates. - w.manage(t, c3AdminKey, map[string]any{"action": "tenant-limit-set", "id": w.tenantID, "data": map[string]any{"max_scopes": 25, "max_keys": 2}}).must(t, "tenant-limit-set") - k := c3Key(label, "members", nil, nil, "required") - k["replace_label"] = true - r = w.provision(t, w.owner, []string{"members"}, k).must(t, "second provision with replace_label, at max_keys") - _, _, second := c3KeysOf(r) - if s := w.do(t, http.MethodGet, "/api/whoami", first[label], nil); s.status != http.StatusUnauthorized { - t.Errorf("the replaced key still authenticates: HTTP %d", s.status) - } - if s := w.do(t, http.MethodGet, "/api/whoami", second[label], nil); s.status != http.StatusOK { - t.Errorf("the new key does not authenticate: HTTP %d %s", s.status, s.raw) - } - if s := w.do(t, http.MethodGet, "/api/whoami", other[label], nil); s.status != http.StatusOK { - t.Errorf("the other tenant's key with the same label was deactivated: HTTP %d %s", s.status, s.raw) - } - var n int - if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_api_keys WHERE label = $1 AND active AND tenant_id = $2::uuid`, label, w.tenantID).Scan(&n); err != nil || n != 1 { - t.Errorf("%d active key(s) with the label in the tenant (err %v), want 1", n, err) - } -} - -// TestC3TenantIDIsServerAdminOnly: like api-key-create, only a server-admin -// may name tenant_id; a tenant-admin naming another tenant is a 403 and -// nothing is created in either tenant. -func TestC3TenantIDIsServerAdminOnly(t *testing.T) { - w := c3Setup(t) - r := w.manage(t, c3AdminKey, map[string]any{"action": "tenant-create", "data": map[string]any{"slug": "c3w", "display_name": "C3 target"}}).must(t, "target tenant") - tn, _ := r.body["tenant"].(map[string]any) - target, _ := tn["id"].(string) - scopes, labels := w.state(t) - data := map[string]any{"tenant_id": target, "scopes": []string{"members"}, "keys": []map[string]any{c3Key("c3-cross", "members", nil, nil, "required")}} - - r = w.manage(t, w.owner, map[string]any{"action": "keyset-provision", "data": data}) - if r.status != http.StatusForbidden { - t.Errorf("tenant-admin naming another tenant: HTTP %d %s, want 403", r.status, r.raw) - } - w.wantUnchanged(t, "the caller's tenant", scopes, labels) - var n int - if err := w.pool.QueryRow(context.Background(), `SELECT (SELECT count(*) FROM context_api_keys WHERE label = 'c3-cross') + (SELECT count(*) FROM context_tenant_scopes WHERE scope = 'c3w:members')`).Scan(&n); err != nil || n != 0 { - t.Errorf("the refused call created %d key(s) or scope(s) (err %v)", n, err) - } - - r = w.manage(t, c3AdminKey, map[string]any{"action": "keyset-provision", "data": data}).must(t, "server-admin naming the tenant") - _, _, plains := c3KeysOf(r) - if b := w.whoami(t, plains["c3-cross"]); b["tenant_slug"] != "c3w" || b["home_scope"] != "c3w:members" { - t.Errorf("server-admin provision: key in tenant %v home %v, want c3w c3w:members", b["tenant_slug"], b["home_scope"]) - } - w.wantUnchanged(t, "the caller's tenant after the server-admin call", scopes, labels) -} - -// TestC3EveryKeyIsItsOwnPrincipal (BP-26): the keys of one set never share a -// principal — signed in with one of them, /api/session/keys lists that one -// key and no other, so a leaked key cannot select its way to the others. -func TestC3EveryKeyIsItsOwnPrincipal(t *testing.T) { - w := c3Setup(t) - r := w.provision(t, w.owner, []string{"a", "b"}, - c3Key("c3-p-a", "a", nil, nil, "optional"), - c3Key("c3-p-b", "b", nil, nil, "optional"), - c3Key("c3-p-c", "b", []string{"a"}, nil, "required")).must(t, "keyset-provision") - _, ids, plains := c3KeysOf(r) - principals := map[string]string{} - for l, p := range plains { - b := w.whoami(t, p) - pid, _ := b["principal_id"].(string) - if pid == "" { - t.Errorf("%s: no principal_id", l) - } - if other, dup := principals[pid]; dup { - t.Errorf("%s and %s share the principal %s", l, other, pid) - } - principals[pid] = l - } - if ob := w.whoami(t, w.owner); principals[fmt.Sprint(ob["principal_id"])] != "" { - t.Errorf("a provisioned key shares the owner's principal") - } - for _, l := range []string{"c3-p-a", "c3-p-b"} { - s := w.do(t, http.MethodGet, "/api/session/keys", plains[l], nil) - if s.status != http.StatusOK { - t.Errorf("%s: session keys: HTTP %d %s", l, s.status, s.raw) - continue - } - list, _ := s.body["keys"].([]any) - if len(list) != 1 { - t.Errorf("%s: /api/session/keys lists %d key(s), want exactly its own (%s)", l, len(list), s.raw) - continue - } - if m, _ := list[0].(map[string]any); m["api_key_id"] != ids[l] { - t.Errorf("%s: /api/session/keys lists %v, want %s", l, m["api_key_id"], ids[l]) - } - } -} diff --git a/go/cmd/ctxd/manage_get_ids_c4_integration_test.go b/go/cmd/ctxd/manage_get_ids_c4_integration_test.go deleted file mode 100644 index 22384951f..000000000 --- a/go/cmd/ctxd/manage_get_ids_c4_integration_test.go +++ /dev/null @@ -1,261 +0,0 @@ -//go:build integration && s1red_c4 - -// Achse 02, cluster C-4 (design2/02-ctx-checkpoint.md §3.5 C-4, §7.3): -// POST /api/manage {"action":"get","ids":[…]} with 1 to 16 ids answers the -// blocks in request order, each id through the resolution of today's get -// (store.ResolveBlockID over the read scopes and the block grants); an id -// that resolves to no visible block is an entry with a code, never a failure -// of the whole request. "id" alone stays as it is. Written in S1, where "ids" -// is ignored; the second build tag keeps the file out of every gate until C-4 -// lands. To enable, shorten the constraint line to `//go:build integration`. -// The narrowed cases need C-1 as well (integration order C-1, C-2, C-4). -// -// Wire form fixed by these tests (S1 contract; the reading of the plugin fake -// tests/fakes/ctx_server.py where the design is silent): -// -// {"success":true,"blocks":[ -// {…the block a single get answers under "block"…}, -// {"id":"<as asked>","code":"not_found","error":"…"}, …]} -// -// one entry per asked id, in request order; an entry with "code" is a miss. -// An id the caller may not see answers exactly like an id that does not exist -// (no existence oracle). -// -// go test -tags=integration,s1red_c4 -p 1 -count=1 -run '^TestC4' ./cmd/ctxd/ -package main - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/GottZ/ctx/internal/backends" - "github.com/GottZ/ctx/internal/blocktype" - "github.com/GottZ/ctx/internal/config" - "github.com/GottZ/ctx/internal/dispatch" - "github.com/GottZ/ctx/internal/events" - "github.com/GottZ/ctx/internal/handler" - "github.com/GottZ/ctx/internal/store" - "github.com/GottZ/ctx/internal/testdb" -) - -// c4AdminKey is the bootstrap server-admin key (default tenant, owner). -const c4AdminKey = "c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0c4a0" - -// c4Missing is a well-formed id no block has. -const c4Missing = "00000000-0000-7000-8000-00000000c4c4" - -type c4Resp struct { - status int - body map[string]any - header http.Header - raw string -} - -// c4World: default tenant with scope default:k; key w (home work, allowed -// shared and default:k); blocks in private (granted to the default tenant as -// a single block), private (not granted), shared, work (two), default:k. -type c4World struct { - router http.Handler - w string - blocks map[string]string -} - -func (c *c4World) do(t *testing.T, key string, extra http.Header, body any) c4Resp { - t.Helper() - return c.req(t, http.MethodPost, "/api/manage", key, extra, body) -} - -func (c *c4World) req(t *testing.T, method, path, key string, extra http.Header, body any) c4Resp { - t.Helper() - var rd io.Reader = http.NoBody - if body != nil { - b, err := json.Marshal(body) - if err != nil { - t.Fatal(err) - } - rd = bytes.NewReader(b) - } - req := httptest.NewRequest(method, path, rd) - req.Header.Set("X-Context-Key", key) - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - for k, vs := range extra { - for _, v := range vs { - req.Header.Add(k, v) - } - } - rec := httptest.NewRecorder() - c.router.ServeHTTP(rec, req) - var out map[string]any - _ = json.Unmarshal(rec.Body.Bytes(), &out) - return c4Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} -} - -func (r c4Resp) must(t *testing.T, what string) c4Resp { - t.Helper() - if r.status != http.StatusOK || r.body["success"] != true { - t.Fatalf("%s: HTTP %d %s", what, r.status, r.raw) - } - return r -} - -func c4Setup(t *testing.T) *c4World { - t.Helper() - pool := testdb.SetupTestDB(t) - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - applyEnv(t, map[string]string{}) - cc, issues := loadFromEnv() - if config.HasErrors(issues) { - t.Fatalf("env fixture invalid: %v", issues) - } - cfgStore := config.NewStore(cc) - backendPool := backends.NewPool(pool, nil) - scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) - projectHub := events.NewProjectHub(ctx, pool, cfgStore) - d := dispatch.New(nil, dispatch.DefaultSettings()) - t.Cleanup(d.Close) - scheduler.SetDispatcher(d) - if created, _, err := store.BootstrapAdminKey(ctx, pool, c4AdminKey, "c4-admin"); err != nil || !created { - t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) - } - c := &c4World{router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d), blocks: map[string]string{}} - - c.do(t, c4AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": "k"}}).must(t, "scope-create k") - mint := func(data map[string]any) string { - r := c.do(t, c4AdminKey, nil, map[string]any{"action": "api-key-create", "data": data}).must(t, "api-key-create") - k, _ := r.body["api_key"].(string) - return k - } - c.w = mint(map[string]any{"label": "c4-w", "home_scope": "work", "allowed_scopes": []string{"shared", "default:k"}}) - kw := mint(map[string]any{"label": "c4-kw", "home_scope": "default:k"}) - put := func(name, key, scope string) { - body := map[string]any{"category": "learnings", "title": "c4 " + name, "content": "c4 " + name + " content"} - if scope != "" { - body["scope"] = scope - } - r := c.req(t, http.MethodPost, "/api/store", key, nil, body).must(t, "store "+name) - blk, _ := r.body["block"].(map[string]any) - c.blocks[name], _ = blk["id"].(string) - } - put("granted", c4AdminKey, "") - put("private", c4AdminKey, "") - put("shared", c4AdminKey, "shared") - put("work1", c.w, "") - put("work2", c.w, "") - put("k", kw, "") - c.do(t, c4AdminKey, nil, map[string]any{"action": "block-grant-create", - "data": map[string]any{"block_id": c.blocks["granted"], "grantee_tenant": store.DefaultTenantID}}).must(t, "block-grant-create") - return c -} - -// c4Entry is one entry of a multi-get answer: its "id" (the block's id when -// found, the asked id when missed) and its code ("" when found). -type c4Entry struct{ id, code, err string } - -func c4Entries(t *testing.T, r c4Resp) []c4Entry { - t.Helper() - list, ok := r.body["blocks"].([]any) - if !ok { - t.Errorf("answer has no blocks list: HTTP %d %s", r.status, r.raw) - return nil - } - out := make([]c4Entry, 0, len(list)) - for _, e := range list { - m, _ := e.(map[string]any) - var en c4Entry - en.id, _ = m["id"].(string) - en.code, _ = m["code"].(string) - en.err, _ = m["error"].(string) - out = append(out, en) - } - return out -} - -// wantEntries checks the answer entry by entry: name "" means "not found". -func (c *c4World) wantEntries(t *testing.T, what string, r c4Resp, asked []string, found []string) { - t.Helper() - if r.status != http.StatusOK || r.body["success"] != true { - t.Errorf("%s: HTTP %d %s, want 200 success", what, r.status, r.raw) - return - } - got := c4Entries(t, r) - if len(got) != len(asked) { - t.Errorf("%s: %d entries, want %d (one per id, in order)", what, len(got), len(asked)) - return - } - for i, e := range got { - switch want := found[i]; { - case want == "" && (e.id != asked[i] || e.code != "not_found"): - t.Errorf("%s: entry %d (%s): id %q code %q, want a not_found entry for the asked id", what, i, asked[i], e.id, e.code) - case want != "" && (e.id != c.blocks[want] || e.code != ""): - t.Errorf("%s: entry %d: id %q code %q, want block %s (%s), request order", what, i, e.id, e.code, want, c.blocks[want]) - } - } -} - -// TestC4GetIdsAnswersInOrder: found blocks and misses in the order asked; an -// id the key may not read answers like one that does not exist; a block read -// through a block grant is found unnarrowed. -func TestC4GetIdsAnswersInOrder(t *testing.T) { - c := c4Setup(t) - asked := []string{c.blocks["work2"], c.blocks["shared"], c4Missing, c.blocks["work1"], c.blocks["private"], c.blocks["k"], c.blocks["granted"]} - r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": asked}) - c.wantEntries(t, "seven ids", r, asked, []string{"work2", "shared", "", "work1", "", "k", "granted"}) - // No existence oracle: the miss of a block the key may not read and the - // miss of an id no block has differ in nothing but the id. - if e := c4Entries(t, r); len(e) == len(asked) && (e[2].code != e[4].code || e[2].err != e[4].err || e[2].err == "") { - t.Errorf("the invisible block's entry %+v differs from the missing id's %+v", e[4], e[2]) - } - // "id" alone is unchanged: one block under "block". - one := c.do(t, c.w, nil, map[string]any{"action": "get", "id": c.blocks["work1"]}).must(t, "single get") - if b, _ := one.body["block"].(map[string]any); b["id"] != c.blocks["work1"] { - t.Errorf("single get answers %v", one.raw) - } -} - -// TestC4GetIdsCountIsCapped: 17 ids are a 400; 16 are answered (control). -func TestC4GetIdsCountIsCapped(t *testing.T) { - c := c4Setup(t) - ids := func(n int) []string { - out := make([]string, n) - for i := range out { - out[i] = fmt.Sprintf("00000000-0000-7000-8000-%012d", i) - } - out[0] = c.blocks["work1"] - return out - } - if r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": ids(17)}); r.status != http.StatusBadRequest || !strings.Contains(r.raw, "16") { - t.Errorf("17 ids: HTTP %d %s, want 400 naming the cap 16", r.status, r.raw) - } - r := c.do(t, c.w, nil, map[string]any{"action": "get", "ids": ids(16)}) - want := make([]string, 16) - want[0] = "work1" - c.wantEntries(t, "16 ids", r, ids(16), want) -} - -// TestC4NarrowedGetIdsReadsOnlyTheNamedScopes: under a narrowing the multi-get -// finds blocks of the named scopes only; a block-grant block is not found. -func TestC4NarrowedGetIdsReadsOnlyTheNamedScopes(t *testing.T) { - c := c4Setup(t) - h := http.Header{} - h.Set(handler.HeaderReadScopes, "work") - asked := []string{c.blocks["work1"], c.blocks["shared"], c.blocks["k"], c.blocks["granted"]} - r := c.do(t, c.w, h, map[string]any{"action": "get", "ids": asked}) - c.wantEntries(t, "narrowed to work", r, asked, []string{"work1", "", "", ""}) - if got := r.header.Get(handler.HeaderNarrowed); got != "work;" { - t.Errorf("narrowed multi-get: echo %q, want \"work;\"", got) - } - - h.Set(handler.HeaderReadScopes, "work,shared,default:k") - r = c.do(t, c.w, h, map[string]any{"action": "get", "ids": asked}) - c.wantEntries(t, "narrowed to all own scopes", r, asked, []string{"work1", "shared", "k", ""}) -} diff --git a/go/cmd/ctxd/narrowing_c1_integration_test.go b/go/cmd/ctxd/narrowing_c1_integration_test.go deleted file mode 100644 index 2066593d8..000000000 --- a/go/cmd/ctxd/narrowing_c1_integration_test.go +++ /dev/null @@ -1,806 +0,0 @@ -//go:build integration && s1red_c1 - -// Achse 02, cluster C-1 (design2/02-ctx-checkpoint.md §3.5 C-1, §7.3): a -// request narrows its key's rights to the scopes it names — X-Context-Read- -// Scopes (1 to 8, in order) and X-Context-Write-Scope (one, inside the read -// set, writable for the key) — on a closed list of routes and /api/manage -// actions, echoed in X-Context-Narrowed. Written in S1 against the inert stubs -// of internal/handler/narrowing.go; the second build tag keeps the file out of -// every gate until C-1 lands. To enable, shorten the constraint line to -// `//go:build integration`. -// -// The tests drive the PRODUCTION router (NewRouter): the route rule sits in the -// Auth middleware and means something only against the mounts production -// serves. Every fixture goes through a write path — tenant-create, -// scope-create, api-key-create, /api/store, delete, tenant-grant-create, -// block-grant-create, PUT /api/settings — except confirm_writes, which has none -// and is set in SQL. TestC1Pin* are green on the stubs on purpose: they pin -// what a narrowing must leave alone (the mutant "HomeScope rewritten") and -// carry no red reason of their own. -// -// go test -tags=integration,s1red_c1 -p 1 -count=1 -run '^TestC1' ./cmd/ctxd/ -package main - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/http" - "net/http/httptest" - "slices" - "strings" - "testing" - - "github.com/jackc/pgx/v5/pgxpool" - - "github.com/GottZ/ctx/internal/backends" - "github.com/GottZ/ctx/internal/blocktype" - "github.com/GottZ/ctx/internal/config" - "github.com/GottZ/ctx/internal/dispatch" - "github.com/GottZ/ctx/internal/events" - "github.com/GottZ/ctx/internal/handler" - "github.com/GottZ/ctx/internal/settings" - "github.com/GottZ/ctx/internal/store" - "github.com/GottZ/ctx/internal/testdb" -) - -// c1AdminKey is the bootstrap server-admin key (default tenant, owner). -const c1AdminKey = "c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0c1a0" - -// c1Probe is the word every fixture block carries, so one search finds them all. -const c1Probe = "narrowprobe" - -// c1Resp is one answer of the router. -type c1Resp struct { - status int - body map[string]any - header http.Header - raw string -} - -// c1World is the fixture: the router, the keys and the blocks. -// -// Default tenant: scopes private, work, shared (baseline) plus default:k and -// default:m. Key w: home work, allowed shared and default:k (writable: work, -// shared; default:k read-only). Key x: home default:m, allowed and write -// default:k. Key kw: home default:k. Tenant c1two: owner key, home c1two:main, -// granted to the default tenant (a grant scope in every default key's read -// set). Block "private" is granted to the default tenant as a single block. -type c1World struct { - pool *pgxpool.Pool - router http.Handler - keys map[string]string - blocks map[string]string - two string // c1two:main, the grant scope -} - -// c1EmbedHost serves the embed and translate halves of an Ollama backend: one -// fixed vector per input. -func c1EmbedHost(t *testing.T) string { - t.Helper() - vec := make([]float64, 1024) - for i := range vec { - vec[i] = float64((i % 2) * 2) - } - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - switch r.URL.Path { - case "/api/embed": - var req struct { - Input any `json:"input"` - } - _ = json.NewDecoder(r.Body).Decode(&req) - n := 1 - if in, ok := req.Input.([]any); ok { - n = len(in) - } - out := make([][]float64, n) - for i := range out { - out[i] = vec - } - _ = json.NewEncoder(w).Encode(map[string]any{"embeddings": out}) - case "/api/chat": - _, _ = io.Copy(io.Discard, r.Body) - _ = json.NewEncoder(w).Encode(map[string]any{ - "message": map[string]any{"role": "assistant", "content": c1Probe}, - "eval_count": 1, "prompt_eval_count": 1, - }) - default: - _, _ = io.Copy(io.Discard, r.Body) - w.WriteHeader(http.StatusNotFound) - } - })) - t.Cleanup(srv.Close) - return srv.URL -} - -// c1Router builds the production router on a fresh database, with an embed -// backend, and the bootstrap admin key. -func c1Router(t *testing.T) (*pgxpool.Pool, http.Handler) { - t.Helper() - pool := testdb.SetupTestDB(t) - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - - applyEnv(t, map[string]string{}) - cc, issues := loadFromEnv() - if config.HasErrors(issues) { - t.Fatalf("env fixture invalid: %v", issues) - } - cfgStore := config.NewStore(cc) - // The tenant overlay, as the boot wires it (main.go): the settings a - // tenant-admin writes reach that tenant's requests. - cfgStore.SetOverlay(settings.TenantOverlay(pool)) - backendPool := backends.NewPool(pool, nil) - host := c1EmbedHost(t) - backendPool.SeedSnapshotForTest([]backends.Backend{ - {ID: "c1-embed", Name: "c1-embed", Scope: "_global", Host: host, Protocol: backends.ProtocolOllama, - Model: "test-embed", Trust: backends.TrustFull, Enabled: true, Priority: 1, Roles: []string{backends.RoleEmbed}}, - {ID: "c1-chat", Name: "c1-chat", Scope: "_global", Host: host, Protocol: backends.ProtocolOllama, - Model: "test-chat", Trust: backends.TrustFull, Enabled: true, Priority: 1, Roles: []string{backends.RoleTranslate}}, - }) - scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) - projectHub := events.NewProjectHub(ctx, pool, cfgStore) - d := dispatch.New(nil, dispatch.DefaultSettings()) - t.Cleanup(d.Close) - scheduler.SetDispatcher(d) - if created, _, err := store.BootstrapAdminKey(ctx, pool, c1AdminKey, "c1-admin"); err != nil || !created { - t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) - } - return pool, NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d) -} - -// c1Narrow is the header set of a narrowing: read scopes, optionally the -// write scope. -func c1Narrow(read string, write ...string) http.Header { - h := http.Header{} - h.Set(handler.HeaderReadScopes, read) - if len(write) > 0 { - h.Set(handler.HeaderWriteScope, write[0]) - } - return h -} - -// do sends one request with the raw key and the extra headers. -func (w *c1World) do(t *testing.T, method, path, key string, extra http.Header, body any) c1Resp { - t.Helper() - var rd io.Reader = http.NoBody - if body != nil { - b, ok := body.([]byte) - if !ok { - var err error - if b, err = json.Marshal(body); err != nil { - t.Fatal(err) - } - } - rd = bytes.NewReader(b) - } - req := httptest.NewRequest(method, path, rd) - req.Header.Set("X-Context-Key", key) - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - for k, vs := range extra { - for _, v := range vs { - req.Header.Add(k, v) - } - } - rec := httptest.NewRecorder() - w.router.ServeHTTP(rec, req) - var out map[string]any - _ = json.Unmarshal(rec.Body.Bytes(), &out) - return c1Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} -} - -// manage posts one /api/manage body. -func (w *c1World) manage(t *testing.T, key string, extra http.Header, body map[string]any) c1Resp { - t.Helper() - return w.do(t, http.MethodPost, "/api/manage", key, extra, body) -} - -// must fails the test unless the answer is a 200. -func (r c1Resp) must(t *testing.T, what string) c1Resp { - t.Helper() - if r.status != http.StatusOK { - t.Fatalf("fixture %s: HTTP %d %s", what, r.status, r.raw) - } - return r -} - -// storeBlock writes one block through /api/store and returns its id. -func (w *c1World) storeBlock(t *testing.T, key, scope, title string) string { - t.Helper() - body := map[string]any{"category": "learnings", "title": title, "content": title + " " + c1Probe + " content"} - if scope != "" { - body["scope"] = scope - } - r := w.do(t, http.MethodPost, "/api/store", key, nil, body).must(t, "store "+title) - blk, _ := r.body["block"].(map[string]any) - id, _ := blk["id"].(string) - if id == "" { - t.Fatalf("fixture store %s: no block id in %s", title, r.raw) - } - return id -} - -// mintKey creates one key through api-key-create as the admin. -func (w *c1World) mintKey(t *testing.T, data map[string]any) string { - t.Helper() - r := w.manage(t, c1AdminKey, nil, map[string]any{"action": "api-key-create", "data": data}).must(t, "api-key-create") - k, _ := r.body["api_key"].(string) - if k == "" { - t.Fatalf("fixture api-key-create: no key in %s", r.raw) - } - return k -} - -func c1Setup(t *testing.T) *c1World { - t.Helper() - pool, router := c1Router(t) - w := &c1World{pool: pool, router: router, keys: map[string]string{}, blocks: map[string]string{}} - for _, n := range []string{"k", "m"} { - w.manage(t, c1AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": n}}).must(t, "scope-create "+n) - } - w.keys["w"] = w.mintKey(t, map[string]any{"label": "c1-w", "home_scope": "work", "allowed_scopes": []string{"shared", "default:k"}}) - w.keys["x"] = w.mintKey(t, map[string]any{"label": "c1-x", "home_scope": "default:m", - "allowed_scopes": []string{"default:k"}, "write_scopes": []string{"default:k"}}) - w.keys["kw"] = w.mintKey(t, map[string]any{"label": "c1-kw", "home_scope": "default:k"}) - - w.blocks["private"] = w.storeBlock(t, c1AdminKey, "", "c1 private alpha") - w.blocks["shared"] = w.storeBlock(t, c1AdminKey, "shared", "c1 shared foxtrot") - w.blocks["work"] = w.storeBlock(t, w.keys["w"], "", "c1 work bravo") - w.blocks["k"] = w.storeBlock(t, w.keys["kw"], "", "c1 k charlie") - w.blocks["m"] = w.storeBlock(t, w.keys["x"], "", "c1 m golf") - - r := w.manage(t, c1AdminKey, nil, map[string]any{"action": "tenant-create", - "data": map[string]any{"slug": "c1two", "display_name": "C1 two"}}).must(t, "tenant-create") - w.keys["two"], _ = r.body["owner_key"].(string) - w.two, _ = r.body["scope"].(string) - if w.keys["two"] == "" || w.two == "" { - t.Fatalf("fixture tenant-create: %s", r.raw) - } - w.blocks["two"] = w.storeBlock(t, w.keys["two"], "", "c1 two delta") - w.blocks["twoArchived"] = w.storeBlock(t, w.keys["two"], "", "c1 two archived echo") - w.manage(t, w.keys["two"], nil, map[string]any{"action": "delete", "id": w.blocks["twoArchived"]}).must(t, "delete") - w.manage(t, c1AdminKey, nil, map[string]any{"action": "tenant-grant-create", - "data": map[string]any{"grantee_tenant": store.DefaultTenantID, "granted_scope": w.two}}).must(t, "tenant-grant-create") - w.manage(t, c1AdminKey, nil, map[string]any{"action": "block-grant-create", - "data": map[string]any{"block_id": w.blocks["private"], "grantee_tenant": store.DefaultTenantID}}).must(t, "block-grant-create") - return w -} - -// c1IDs reads the "id" of every element of the list under key. -func c1IDs(body map[string]any, key string) []string { - list, _ := body[key].([]any) - var ids []string - for _, e := range list { - m, _ := e.(map[string]any) - if id, _ := m["id"].(string); id != "" { - ids = append(ids, id) - } - } - return ids -} - -// names maps block ids back to their fixture names, for readable failures. -func (w *c1World) names(ids []string) []string { - out := make([]string, 0, len(ids)) - for _, id := range ids { - name := id - for n, b := range w.blocks { - if b == id { - name = n - } - } - out = append(out, name) - } - slices.Sort(out) - return out -} - -// code is the machine code of an answer. -func (r c1Resp) code() string { - c, _ := r.body["code"].(string) - return c -} - -// wantRefused fails unless the answer is status with code. -func c1WantRefused(t *testing.T, what string, r c1Resp, status int, code string) { - t.Helper() - if r.status != status || r.code() != code { - t.Errorf("%s: HTTP %d code %q, want %d %q (%s)", what, r.status, r.code(), status, code, strings.TrimSpace(r.raw)) - } -} - -// wantEcho fails unless the answer carries the narrowing echo want. -func c1WantEcho(t *testing.T, what string, r c1Resp, want string) { - t.Helper() - if got := r.header.Get(handler.HeaderNarrowed); got != want || len(r.header.Values(handler.HeaderNarrowed)) != 1 { - t.Errorf("%s: %s = %q (%d value(s)), want exactly %q", what, handler.HeaderNarrowed, got, len(r.header.Values(handler.HeaderNarrowed)), want) - } -} - -// TestC1NarrowedSearchReadsOnlyTheNamedScopes: a narrowed /api/search finds -// blocks of the named scopes and nothing else; the unnarrowed request of the -// same key finds the rest (fixture control). -func TestC1NarrowedSearchReadsOnlyTheNamedScopes(t *testing.T) { - w := c1Setup(t) - body := map[string]any{"query": c1Probe, "limit": 50} - all := w.do(t, http.MethodPost, "/api/search", w.keys["w"], nil, body).must(t, "unnarrowed search") - // private: through the block grant; two: through the tenant grant. - if got := w.names(c1IDs(all.body, "results")); !slices.Equal(got, []string{"k", "private", "shared", "two", "work"}) { - t.Fatalf("fixture: the unnarrowed search of key w finds %v, want [k private shared two work] (%s)", got, all.raw) - } - for _, c := range []struct { - read string - want []string - }{ - {"work", []string{"work"}}, - {"default:k", []string{"k"}}, - {w.two, []string{"two"}}, - {"shared,work", []string{"shared", "work"}}, - } { - r := w.do(t, http.MethodPost, "/api/search", w.keys["w"], c1Narrow(c.read), body) - if r.status != http.StatusOK { - t.Errorf("search narrowed to %s: HTTP %d %s", c.read, r.status, r.raw) - continue - } - if got := w.names(c1IDs(r.body, "results")); !slices.Equal(got, c.want) { - t.Errorf("search narrowed to %s finds %v, want %v", c.read, got, c.want) - } - c1WantEcho(t, "search narrowed to "+c.read, r, c.read+";") - } -} - -// TestC1NarrowedQueryReadsOnlyTheNamedScopes: the same for /api/query -// (synthesize off) — the red test the design names first. -func TestC1NarrowedQueryReadsOnlyTheNamedScopes(t *testing.T) { - w := c1Setup(t) - body := map[string]any{"query": c1Probe, "synthesize": false, "limit": 20} - all := w.do(t, http.MethodPost, "/api/query", w.keys["w"], nil, body).must(t, "unnarrowed query") - if got := w.names(c1IDs(all.body, "sources")); len(got) < 2 || !slices.Contains(got, "work") { - t.Fatalf("fixture: the unnarrowed query of key w finds %v, want work and at least one other scope's block (%s)", got, all.raw) - } - for _, c := range []struct { - read string - want []string - }{ - {"work", []string{"work"}}, - {"default:k", []string{"k"}}, - } { - r := w.do(t, http.MethodPost, "/api/query", w.keys["w"], c1Narrow(c.read), body) - if r.status != http.StatusOK { - t.Errorf("query narrowed to %s: HTTP %d %s", c.read, r.status, r.raw) - continue - } - if got := w.names(c1IDs(r.body, "sources")); !slices.Equal(got, c.want) { - t.Errorf("query narrowed to %s finds %v, want %v", c.read, got, c.want) - } - c1WantEcho(t, "query narrowed to "+c.read, r, c.read+";") - } -} - -// TestC1ScopeOutsideTheKeyIsDenied: a read scope the key cannot read is a -// 403 scope_denied, on every route — never a silently smaller read set. -func TestC1ScopeOutsideTheKeyIsDenied(t *testing.T) { - w := c1Setup(t) - h := c1Narrow("work,private") - c1WantRefused(t, "search", w.do(t, http.MethodPost, "/api/search", w.keys["w"], h, map[string]any{"query": c1Probe}), http.StatusForbidden, "scope_denied") - c1WantRefused(t, "query", w.do(t, http.MethodPost, "/api/query", w.keys["w"], h, map[string]any{"query": c1Probe, "synthesize": false}), http.StatusForbidden, "scope_denied") - c1WantRefused(t, "whoami", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], h, nil), http.StatusForbidden, "scope_denied") -} - -// c1Count counts the blocks with this title, archived included. -func (w *c1World) c1Count(t *testing.T, title string) int { - t.Helper() - var n int - if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_blocks WHERE title = $1`, title).Scan(&n); err != nil { - t.Fatal(err) - } - return n -} - -// TestC1NarrowedWriteNeedsItsWriteScope: a narrowed write without -// X-Context-Write-Scope writes nothing (403 scope_denied, the answer still -// carries the echo — the narrowing itself was valid). A write scope the key -// can only read, or one outside the read set, makes the narrowing itself -// invalid: 403 scope_denied on every route, whoami included. Nothing lands in -// any scope. -func TestC1NarrowedWriteNeedsItsWriteScope(t *testing.T) { - w := c1Setup(t) - for _, c := range []struct { - name string - h http.Header - scope string - badWrite bool // the write scope itself is refused (in the Auth middleware) - }{ - {"read header only", c1Narrow("work"), "", false}, - {"read header only, scope named in the body", c1Narrow("work"), "work", false}, - {"read-only scope as write scope", c1Narrow("work,default:k", "default:k"), "", true}, - {"write scope outside the read set", c1Narrow("work", "shared"), "", true}, - } { - title := "c1 refused write " + c.name - body := map[string]any{"category": "learnings", "title": title, "content": "x " + c1Probe} - if c.scope != "" { - body["scope"] = c.scope - } - r := w.do(t, http.MethodPost, "/api/store", w.keys["w"], c.h, body) - c1WantRefused(t, c.name, r, http.StatusForbidden, "scope_denied") - if n := w.c1Count(t, title); n != 0 { - t.Errorf("%s: %d block(s) written, want none", c.name, n) - } - if c.badWrite { - c1WantRefused(t, c.name+" (whoami)", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c.h, nil), http.StatusForbidden, "scope_denied") - } else { - c1WantEcho(t, c.name, r, "work;") - } - } -} - -// TestC1NarrowingHeaderFormIsChecked: X-Context-Write-Scope alone, an empty -// header, a header that occurs twice, an empty list element and more than -// eight read scopes are 400 scope_narrowing_invalid — before any handler runs. -func TestC1NarrowingHeaderFormIsChecked(t *testing.T) { - w := c1Setup(t) - writeOnly := http.Header{} - writeOnly.Set(handler.HeaderWriteScope, "work") - empty := http.Header{} - empty.Set(handler.HeaderReadScopes, "") - twiceRead := http.Header{} - twiceRead.Add(handler.HeaderReadScopes, "work") - twiceRead.Add(handler.HeaderReadScopes, "shared") - twiceWrite := c1Narrow("work") - twiceWrite.Add(handler.HeaderWriteScope, "work") - twiceWrite.Add(handler.HeaderWriteScope, "work") - emptyElement := c1Narrow("work,,shared") - for _, c := range []struct { - name string - h http.Header - }{ - {"write scope alone", writeOnly}, - {"empty read header", empty}, - {"read header twice", twiceRead}, - {"write header twice", twiceWrite}, - {"empty list element", emptyElement}, - } { - c1WantRefused(t, c.name+" (whoami)", w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c.h, nil), http.StatusBadRequest, "scope_narrowing_invalid") - title := "c1 invalid header " + c.name - c1WantRefused(t, c.name+" (store)", w.do(t, http.MethodPost, "/api/store", w.keys["w"], c.h, - map[string]any{"category": "learnings", "title": title, "content": "x"}), http.StatusBadRequest, "scope_narrowing_invalid") - if n := w.c1Count(t, title); n != 0 { - t.Errorf("%s: %d block(s) written, want none", c.name, n) - } - } -} - -// TestC1ReadScopesAreCappedAtEight: eight distinct readable scopes narrow a -// request; a ninth is 400 scope_narrowing_invalid, also when the key reads all -// nine. -func TestC1ReadScopesAreCappedAtEight(t *testing.T) { - w := c1Setup(t) - for _, n := range []string{"n1", "n2", "n3"} { - w.manage(t, c1AdminKey, nil, map[string]any{"action": "scope-create", "data": map[string]any{"name": n}}).must(t, "scope-create "+n) - } - key := w.mintKey(t, map[string]any{"label": "c1-nine", "home_scope": "work", - "allowed_scopes": []string{"private", "shared", "default:k", "default:m", "default:n1", "default:n2", "default:n3"}}) - eight := "work,private,shared,default:k,default:m,default:n1,default:n2,default:n3" - r := w.do(t, http.MethodGet, "/api/whoami", key, nil, nil).must(t, "whoami of the nine-scope key") - if rs := c1Strings(r.body["read_scopes"]); len(rs) != 9 || !slices.Contains(rs, w.two) { - t.Fatalf("fixture: the key reads %v, want nine scopes with the grant scope %s", rs, w.two) - } - r = w.do(t, http.MethodGet, "/api/whoami", key, c1Narrow(eight), nil) - if r.status != http.StatusOK { - t.Errorf("eight read scopes: HTTP %d %s, want 200", r.status, r.raw) - } - c1WantEcho(t, "eight read scopes", r, eight+";") - c1WantRefused(t, "nine read scopes", w.do(t, http.MethodGet, "/api/whoami", key, c1Narrow(eight+","+w.two), nil), http.StatusBadRequest, "scope_narrowing_invalid") -} - -// TestC1NarrowedWriteLandsInItsWriteScope: a narrowed write without a scope in -// the body lands in X-Context-Write-Scope — here a write_scope of the key, -// not its home — and passes the write recheck of issue #555 -// (store.WithRequestKey carries the key's own scopes, and default:k is one of -// its write_scopes). The answer carries the echo. -func TestC1NarrowedWriteLandsInItsWriteScope(t *testing.T) { - w := c1Setup(t) - r := w.do(t, http.MethodPost, "/api/store", w.keys["x"], c1Narrow("default:k", "default:k"), - map[string]any{"category": "learnings", "title": "c1 narrowed write hotel", "content": "x " + c1Probe}) - if r.status != http.StatusOK { - t.Fatalf("narrowed write: HTTP %d %s", r.status, r.raw) - } - blk, _ := r.body["block"].(map[string]any) - if got, _ := blk["scope"].(string); got != "default:k" { - t.Errorf("narrowed write answered scope %q, want default:k (the write scope, not the home default:m)", got) - } - var scope string - if err := w.pool.QueryRow(context.Background(), `SELECT scope FROM context_blocks WHERE title = 'c1 narrowed write hotel' AND NOT is_archived`).Scan(&scope); err != nil { - t.Fatalf("narrowed write: row: %v", err) - } - if scope != "default:k" { - t.Errorf("narrowed write stored in %q, want default:k", scope) - } - c1WantEcho(t, "narrowed write", r, "default:k;default:k") - - // The home scope narrowed explicitly, named in the body as well. - r = w.do(t, http.MethodPost, "/api/store", w.keys["x"], c1Narrow("default:m", "default:m"), - map[string]any{"category": "learnings", "title": "c1 narrowed home write india", "content": "x", "scope": "default:m"}) - if r.status != http.StatusOK { - t.Fatalf("narrowed home write: HTTP %d %s", r.status, r.raw) - } - c1WantEcho(t, "narrowed home write", r, "default:m;default:m") -} - -// TestC1BlockGrantIsInvisibleWhenNarrowed: a block the key reads only through -// a block grant is found unnarrowed (fixture control) and not found under any -// narrowing — a narrowed request reads its named scopes and nothing else. -func TestC1BlockGrantIsInvisibleWhenNarrowed(t *testing.T) { - w := c1Setup(t) - get := map[string]any{"action": "get", "id": w.blocks["private"]} - if r := w.manage(t, w.keys["w"], nil, get).must(t, "unnarrowed get of the granted block"); r.body["success"] != true { - t.Fatalf("fixture: key w does not read the granted block unnarrowed: %s", r.raw) - } - r := w.manage(t, w.keys["w"], c1Narrow("work,shared,default:k"), get) - if r.status != http.StatusOK || r.body["success"] != false { - t.Errorf("narrowed get of the granted block: HTTP %d %s, want 200 with success false (not found)", r.status, r.raw) - } - c1WantEcho(t, "narrowed get of the granted block", r, "work,shared,default:k;") - s := w.do(t, http.MethodPost, "/api/search", w.keys["w"], c1Narrow("work,shared,default:k"), map[string]any{"query": "alpha"}) - if slices.Contains(c1IDs(s.body, "results"), w.blocks["private"]) || s.status != http.StatusOK { - t.Errorf("narrowed search: HTTP %d, finds the granted block: %s", s.status, s.raw) - } -} - -// TestC1RoutesOutsideTheListAreRefused: a narrowed request on any route but -// the five of the list is 403 scope_narrowing_route — decided in the Auth -// middleware, by method and path, before the route's handler runs. -func TestC1RoutesOutsideTheListAreRefused(t *testing.T) { - w := c1Setup(t) - h := c1Narrow("work") - mcp := c1Narrow("work") - mcp.Set("Accept", "application/json, text/event-stream") - for _, c := range []struct { - method, path string - body any - }{ - {http.MethodPost, "/mcp", map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}}, - {http.MethodPost, "/api/store/batch", map[string]any{"items": []any{map[string]any{"category": "learnings", "title": "c1 batch kilo", "content": "x"}}}}, - {http.MethodPost, "/api/blob/store", map[string]any{"file": "aGk=", "filename": "f.txt", "category": "files", "title": "c1 blob lima", "mime_type": "text/plain"}}, - {http.MethodPost, "/api/recent", map[string]any{}}, - {http.MethodGet, "/api/session/keys", nil}, - } { - hc := h - if c.path == "/mcp" { - hc = mcp - } - c1WantRefused(t, c.method+" "+c.path, w.do(t, c.method, c.path, w.keys["w"], hc, c.body), http.StatusForbidden, "scope_narrowing_route") - } - if n := w.c1Count(t, "c1 batch kilo"); n != 0 { - t.Errorf("narrowed batch wrote %d block(s)", n) - } -} - -// TestC1ManageActionsOutsideTheListAreRefused: on /api/manage a narrowed -// request runs get and type-list only; update and purge are 403 -// scope_narrowing_route and change nothing. BP-25: Go's decoder matches JSON -// keys case-insensitively and the LAST one wins, so {"action":"get", -// "ACTION":"purge"} decodes to purge — the check must judge that one decoded -// action (a check reading the lowercase key would see get). The other key -// order is left open: refusing it as well is safe. -func TestC1ManageActionsOutsideTheListAreRefused(t *testing.T) { - w := c1Setup(t) - - // The premise, on the decoder the dispatcher uses. - var probe struct { - Action string `json:"action"` - } - if err := json.NewDecoder(strings.NewReader(`{"action":"get","ACTION":"purge"}`)).Decode(&probe); err != nil || probe.Action != "purge" { - t.Fatalf("premise: the decoder reads %q (err %v), want purge — rewrite the BP-25 cases", probe.Action, err) - } - - hw := c1Narrow("work") - r := w.manage(t, w.keys["w"], hw, map[string]any{"action": "update", "id": w.blocks["work"], "data": map[string]any{"content": "c1 overwritten"}}) - c1WantRefused(t, "narrowed update", r, http.StatusForbidden, "scope_narrowing_route") - c1WantEcho(t, "narrowed update", r, "work;") - var content string - if err := w.pool.QueryRow(context.Background(), `SELECT content FROM context_blocks WHERE id = $1`, w.blocks["work"]).Scan(&content); err != nil || content == "c1 overwritten" { - t.Errorf("narrowed update changed the block: %q (err %v)", content, err) - } - - ha := c1Narrow("private") - r = w.manage(t, c1AdminKey, ha, map[string]any{"action": "purge"}) - c1WantRefused(t, "narrowed purge (owner key)", r, http.StatusForbidden, "scope_narrowing_route") - c1WantEcho(t, "narrowed purge", r, "private;") - c1WantRefused(t, "narrowed delete", w.manage(t, w.keys["w"], hw, map[string]any{"action": "delete", "id": w.blocks["work"]}), http.StatusForbidden, "scope_narrowing_route") - - raw := []byte(`{"action":"get","id":"` + w.blocks["private"] + `","ACTION":"purge"}`) - c1WantRefused(t, "BP-25 get then ACTION purge", w.do(t, http.MethodPost, "/api/manage", c1AdminKey, ha, raw), http.StatusForbidden, "scope_narrowing_route") - r = w.manage(t, w.keys["w"], hw, map[string]any{"action": "type-list"}) - if r.status != http.StatusOK { - t.Errorf("narrowed type-list: HTTP %d %s", r.status, r.raw) - } - c1WantEcho(t, "narrowed type-list", r, "work;") -} - -// TestC1EchoOnEveryNarrowedAnswer: every answer to a narrowed request carries -// X-Context-Narrowed: <read scopes as sent>;<write scope> — the client's proof -// that no proxy dropped the narrowing (E5 of the plugin). -func TestC1EchoOnEveryNarrowedAnswer(t *testing.T) { - w := c1Setup(t) - h := c1Narrow("work,shared") - for _, c := range []struct { - method, path string - body any - }{ - {http.MethodGet, "/api/whoami", nil}, - {http.MethodPost, "/api/search", map[string]any{"query": c1Probe}}, - {http.MethodPost, "/api/query", map[string]any{"query": c1Probe, "synthesize": false}}, - {http.MethodPost, "/api/manage", map[string]any{"action": "get", "id": w.blocks["work"]}}, - {http.MethodPost, "/api/manage", map[string]any{"action": "type-list"}}, - } { - r := w.do(t, c.method, c.path, w.keys["w"], h, c.body) - if r.status != http.StatusOK { - t.Errorf("%s %s narrowed: HTTP %d %s", c.method, c.path, r.status, r.raw) - } - c1WantEcho(t, c.method+" "+c.path, r, "work,shared;") - } - r := w.do(t, http.MethodPost, "/api/store", w.keys["w"], c1Narrow("work,shared", "work"), - map[string]any{"category": "learnings", "title": "c1 echo write juliet", "content": "x"}) - if r.status != http.StatusOK { - t.Errorf("narrowed store: HTTP %d %s", r.status, r.raw) - } - c1WantEcho(t, "POST /api/store", r, "work,shared;work") - if r := w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], nil, nil); len(r.header.Values(handler.HeaderNarrowed)) != 0 { - t.Errorf("an unnarrowed answer carries %s: %v", handler.HeaderNarrowed, r.header.Values(handler.HeaderNarrowed)) - } -} - -// c1Strings reads a JSON string list. -func c1Strings(v any) []string { - list, _ := v.([]any) - out := make([]string, 0, len(list)) - for _, e := range list { - s, _ := e.(string) - out = append(out, s) - } - return out -} - -// TestC1WhoamiReportsTheWriteSideAndTheNarrowing: whoami grows write_scopes -// (the effective write set), confirm_writes, narrowed ({read, write} or -// null) and rate_limit_write (the write limit per 60 s that applies to the -// key: query.rate_limit_write after the tenant overlay). -func TestC1WhoamiReportsTheWriteSideAndTheNarrowing(t *testing.T) { - w := c1Setup(t) - whoami := func(key string, h http.Header) map[string]any { - t.Helper() - r := w.do(t, http.MethodGet, "/api/whoami", key, h, nil) - if r.status != http.StatusOK { - t.Fatalf("whoami: HTTP %d %s", r.status, r.raw) - } - return r.body - } - has := func(what string, body map[string]any, field string) bool { - t.Helper() - if _, ok := body[field]; !ok { - t.Errorf("%s: whoami has no %q", what, field) - return false - } - return true - } - - // Unnarrowed: the key's effective write set, home first. - b := whoami(w.keys["x"], nil) - if has("x unnarrowed", b, "write_scopes") && !slices.Equal(c1Strings(b["write_scopes"]), []string{"default:m", "default:k"}) { - t.Errorf("x unnarrowed: write_scopes %v, want [default:m default:k]", b["write_scopes"]) - } - if has("x unnarrowed", b, "confirm_writes") && b["confirm_writes"] != false { - t.Errorf("x unnarrowed: confirm_writes %v, want false", b["confirm_writes"]) - } - if has("x unnarrowed", b, "narrowed") && b["narrowed"] != nil { - t.Errorf("x unnarrowed: narrowed %v, want null", b["narrowed"]) - } - if has("x unnarrowed", b, "rate_limit_write") && b["rate_limit_write"] != float64(100) { - t.Errorf("x unnarrowed: rate_limit_write %v, want 100 (the default of query.rate_limit_write)", b["rate_limit_write"]) - } - - // Narrowed with a write scope: the write set is that scope alone. - b = whoami(w.keys["x"], c1Narrow("default:k", "default:k")) - if has("x narrowed", b, "write_scopes") && !slices.Equal(c1Strings(b["write_scopes"]), []string{"default:k"}) { - t.Errorf("x narrowed: write_scopes %v, want [default:k]", b["write_scopes"]) - } - if n, _ := b["narrowed"].(map[string]any); n == nil || !slices.Equal(c1Strings(n["read"]), []string{"default:k"}) || n["write"] != "default:k" { - t.Errorf("x narrowed: narrowed %v, want {read:[default:k], write:default:k}", b["narrowed"]) - } - - // Narrowed without a write scope: nothing writable, read in header order. - b = whoami(w.keys["w"], c1Narrow("shared,work")) - if has("w narrowed", b, "write_scopes") && len(c1Strings(b["write_scopes"])) != 0 { - t.Errorf("w narrowed read-only: write_scopes %v, want []", b["write_scopes"]) - } - if n, _ := b["narrowed"].(map[string]any); n == nil || !slices.Equal(c1Strings(n["read"]), []string{"shared", "work"}) || n["write"] != "" { - t.Errorf("w narrowed read-only: narrowed %v, want {read:[shared work], write:\"\"}", b["narrowed"]) - } - - // confirm_writes has no write path (it is set out of band). - if _, err := w.pool.Exec(context.Background(), `UPDATE context_api_keys SET confirm_writes = true WHERE label = 'c1-kw'`); err != nil { - t.Fatal(err) - } - if b = whoami(w.keys["kw"], nil); b["confirm_writes"] != true { - t.Errorf("kw with confirm_writes: confirm_writes %v, want true", b["confirm_writes"]) - } - - // The tenant overlay of query.rate_limit_write. - w.do(t, http.MethodPut, "/api/settings/query.rate_limit_write", w.keys["two"], nil, map[string]any{"value": 40}).must(t, "tenant overlay of query.rate_limit_write") - if r := w.do(t, http.MethodGet, "/api/settings/query.rate_limit_write", w.keys["two"], nil, nil).must(t, "read back the overlay"); !strings.Contains(r.raw, `"value":40`) { - t.Fatalf("fixture: tenant c1two reads back %s, want the overlay 40", r.raw) - } - if b = whoami(w.keys["two"], nil); b["rate_limit_write"] != float64(40) { - t.Errorf("tenant c1two with the overlay 40: rate_limit_write %v, want 40", b["rate_limit_write"]) - } - if b = whoami(w.keys["w"], nil); b["rate_limit_write"] != float64(100) { - t.Errorf("default tenant beside c1two's overlay: rate_limit_write %v, want 100", b["rate_limit_write"]) - } -} - -// TestC1NarrowedRequestIsNeverAnAdmin: under a narrowing the request is a -// member without the server-admin tier, whatever the key is — a narrowed -// request is never an administration request. -func TestC1NarrowedRequestIsNeverAnAdmin(t *testing.T) { - w := c1Setup(t) - r := w.do(t, http.MethodGet, "/api/whoami", c1AdminKey, nil, nil).must(t, "unnarrowed admin whoami") - if r.body["admin"] != true || r.body["role"] != "owner" { - t.Fatalf("fixture: the admin key reads admin %v role %v, want true owner", r.body["admin"], r.body["role"]) - } - r = w.do(t, http.MethodGet, "/api/whoami", c1AdminKey, c1Narrow("private"), nil) - if r.status != http.StatusOK || r.body["admin"] != false || r.body["role"] != "member" { - t.Errorf("narrowed admin whoami: HTTP %d admin %v role %v, want 200 false member", r.status, r.body["admin"], r.body["role"]) - } -} - -// TestC1ArchivedBlockOutsideTheNarrowingStaysHidden: the archive read of a -// narrowed request covers the named scopes that are the key's own, not every -// own scope — an archived block of an own scope the request does not name is -// not found. -func TestC1ArchivedBlockOutsideTheNarrowingStaysHidden(t *testing.T) { - w := c1Setup(t) - id := w.storeBlock(t, w.keys["w"], "shared", "c1 shared archived mike") - w.manage(t, w.keys["w"], nil, map[string]any{"action": "delete", "id": id}).must(t, "delete") - get := map[string]any{"action": "get", "id": id, "include_archived": true} - if r := w.manage(t, w.keys["w"], nil, get).must(t, "unnarrowed archive read"); r.body["success"] != true { - t.Fatalf("fixture: key w does not read its own archived block unnarrowed: %s", r.raw) - } - r := w.manage(t, w.keys["w"], c1Narrow("work"), get) - if r.status != http.StatusOK || r.body["success"] != false { - t.Errorf("archive read narrowed to work of a block in shared: HTTP %d %s, want not found", r.status, r.raw) - } - c1WantEcho(t, "narrowed archive read", r, "work;") -} - -// TestC1PinHomeScopeStaysTheKeys (green on the stubs): a narrowing with a -// grant scope first leaves the home scope the key's own — backend chain, -// quota, the archive read and the settings overlay hang on it. -func TestC1PinHomeScopeStaysTheKeys(t *testing.T) { - w := c1Setup(t) - r := w.do(t, http.MethodGet, "/api/whoami", w.keys["w"], c1Narrow(w.two+",work"), nil).must(t, "narrowed whoami") - if r.body["home_scope"] != "work" { - t.Errorf("narrowed whoami with the grant scope first: home_scope %v, want work", r.body["home_scope"]) - } -} - -// TestC1PinArchivedBlockOfAGrantScopeStaysHidden (green on the stubs): the -// archive read is limited to the key's own scopes; a narrowing that names a -// grant scope, first, does not make that scope the key's own. -func TestC1PinArchivedBlockOfAGrantScopeStaysHidden(t *testing.T) { - w := c1Setup(t) - get := map[string]any{"action": "get", "id": w.blocks["twoArchived"], "include_archived": true} - for _, h := range []http.Header{nil, c1Narrow(w.two), c1Narrow(w.two + ",work")} { - r := w.manage(t, w.keys["w"], h, get) - if r.status != http.StatusOK || r.body["success"] != false { - t.Errorf("get of an archived block of the grant scope (narrowing %v): HTTP %d %s, want not found", h, r.status, r.raw) - } - } - if r := w.manage(t, w.keys["two"], nil, get).must(t, "owner get"); r.body["success"] != true { - t.Fatalf("fixture: the owner does not read its own archived block: %s", r.raw) - } -} diff --git a/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go b/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go deleted file mode 100644 index d1e4e1a4a..000000000 --- a/go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go +++ /dev/null @@ -1,385 +0,0 @@ -//go:build integration && s1red_c2 - -// Achse 02, cluster C-2 (design2/02-ctx-checkpoint.md §3.5 C-2, §7.3): a key -// can require narrowing (context_api_keys.scope_narrowing, migration 198). A -// required key answers every unnarrowed request with 403 -// scope_narrowing_required — reads, writes, /api/session/*, /mcp — except -// GET /api/whoami, which reports the column. Set through api-key-create and -// api-key-update (tenant-admin, like write_scopes); every existing key stays -// optional. Written in S1 before the column exists; the second build tag keeps -// the file out of every gate until C-2 lands. To enable, shorten the -// constraint line to `//go:build integration`. The narrowed positive case -// needs C-1 as well (integration order C-1, C-2). -// -// The HTTP tests drive the PRODUCTION router; the migration test follows the -// migration tests of internal/store (chain up to 197, seed, 198, assert). Its -// seed is plain SQL in the 197 shape: after C-2 the production key insert -// names the new column and cannot write a 197 database. -// -// go test -tags=integration,s1red_c2 -p 1 -count=1 -run '^TestC2' ./cmd/ctxd/ -package main - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "io" - "io/fs" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/jackc/pgx/v5/pgconn" - "github.com/jackc/pgx/v5/pgxpool" - - "github.com/GottZ/ctx/internal/backends" - "github.com/GottZ/ctx/internal/blocktype" - "github.com/GottZ/ctx/internal/config" - "github.com/GottZ/ctx/internal/dispatch" - "github.com/GottZ/ctx/internal/events" - "github.com/GottZ/ctx/internal/handler" - "github.com/GottZ/ctx/internal/store" - "github.com/GottZ/ctx/internal/testdb" - "github.com/GottZ/ctx/migrations" -) - -// c2AdminKey is the bootstrap server-admin key (default tenant, owner). -const c2AdminKey = "c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0c2a0" - -type c2Resp struct { - status int - body map[string]any - header http.Header - raw string -} - -type c2World struct { - pool *pgxpool.Pool - router http.Handler -} - -func c2Setup(t *testing.T) *c2World { - t.Helper() - pool := testdb.SetupTestDB(t) - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - applyEnv(t, map[string]string{}) - cc, issues := loadFromEnv() - if config.HasErrors(issues) { - t.Fatalf("env fixture invalid: %v", issues) - } - cfgStore := config.NewStore(cc) - backendPool := backends.NewPool(pool, nil) - scheduler := events.NewScheduler(pool, cfgStore, backendPool, events.StartupConfig{}) - projectHub := events.NewProjectHub(ctx, pool, cfgStore) - d := dispatch.New(nil, dispatch.DefaultSettings()) - t.Cleanup(d.Close) - scheduler.SetDispatcher(d) - if created, _, err := store.BootstrapAdminKey(ctx, pool, c2AdminKey, "c2-admin"); err != nil || !created { - t.Fatalf("bootstrap admin key: created=%v err=%v", created, err) - } - return &c2World{pool: pool, router: NewRouter(ctx, pool, cfgStore, scheduler, backendPool, blocktype.NewRegistry(), projectHub, d)} -} - -func (w *c2World) do(t *testing.T, method, path, key string, extra http.Header, body any) c2Resp { - t.Helper() - var rd io.Reader = http.NoBody - if body != nil { - b, err := json.Marshal(body) - if err != nil { - t.Fatal(err) - } - rd = bytes.NewReader(b) - } - req := httptest.NewRequest(method, path, rd) - req.Header.Set("X-Context-Key", key) - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - for k, vs := range extra { - for _, v := range vs { - req.Header.Add(k, v) - } - } - rec := httptest.NewRecorder() - w.router.ServeHTTP(rec, req) - var out map[string]any - _ = json.Unmarshal(rec.Body.Bytes(), &out) - return c2Resp{status: rec.Code, body: out, header: rec.Header(), raw: rec.Body.String()} -} - -func (w *c2World) manage(t *testing.T, key string, body map[string]any) c2Resp { - t.Helper() - return w.do(t, http.MethodPost, "/api/manage", key, nil, body) -} - -func (r c2Resp) must(t *testing.T, what string) c2Resp { - t.Helper() - if r.status != http.StatusOK || r.body["success"] == false { - t.Fatalf("fixture %s: HTTP %d %s", what, r.status, r.raw) - } - return r -} - -func (r c2Resp) code() string { - c, _ := r.body["code"].(string) - return c -} - -// mint creates a key through api-key-create as the admin and returns its -// plaintext and id; the answer's status is the caller's to judge. -func (w *c2World) mint(t *testing.T, data map[string]any) (c2Resp, string, string) { - t.Helper() - r := w.manage(t, c2AdminKey, map[string]any{"action": "api-key-create", "data": data}) - k, _ := r.body["api_key"].(string) - id, _ := r.body["id"].(string) - return r, k, id -} - -// scopeNarrowing is the scope_narrowing whoami reports for key ("" when the -// field is missing). -func (w *c2World) scopeNarrowing(t *testing.T, key string) string { - t.Helper() - r := w.do(t, http.MethodGet, "/api/whoami", key, nil, nil) - if r.status != http.StatusOK { - t.Errorf("whoami: HTTP %d %s, want 200 (whoami stays open to a required key)", r.status, r.raw) - return "" - } - v, _ := r.body["scope_narrowing"].(string) - return v -} - -// c2Unnarrowed are the unnarrowed requests a required key is refused: reads, -// a write, a manage read, the session surface and /mcp. -func c2Unnarrowed(blockID string) []struct { - method, path string - body any - write string -} { - return []struct { - method, path string - body any - write string - }{ - {http.MethodPost, "/api/query", map[string]any{"query": "c2probe", "synthesize": false}, ""}, - {http.MethodPost, "/api/search", map[string]any{"query": "c2probe"}, ""}, - {http.MethodPost, "/api/store", map[string]any{"category": "learnings", "title": "c2 refused write", "content": "x"}, "c2 refused write"}, - {http.MethodPost, "/api/manage", map[string]any{"action": "get", "id": blockID}, ""}, - {http.MethodPost, "/api/recent", map[string]any{}, ""}, - {http.MethodGet, "/api/session/keys", nil, ""}, - {http.MethodPost, "/api/session/select-key", map[string]any{"api_key_id": "00000000-0000-0000-0000-000000000000"}, ""}, - {http.MethodPost, "/mcp", map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, ""}, - } -} - -// wantRequired checks every unnarrowed request of key is refused with -// scope_narrowing_required, and that the refused write wrote nothing (the -// mutant "required on reads only"). -func (w *c2World) wantRequired(t *testing.T, who, key, blockID string) { - t.Helper() - mcp := http.Header{} - mcp.Set("Accept", "application/json, text/event-stream") - for _, c := range c2Unnarrowed(blockID) { - var h http.Header - if c.path == "/mcp" { - h = mcp - } - r := w.do(t, c.method, c.path, key, h, c.body) - if r.status != http.StatusForbidden || r.code() != "scope_narrowing_required" { - t.Errorf("%s: unnarrowed %s %s: HTTP %d code %q, want 403 scope_narrowing_required (%s)", who, c.method, c.path, r.status, r.code(), strings.TrimSpace(r.raw)) - } - if c.write != "" { - var n int - if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_blocks WHERE title = $1`, c.write).Scan(&n); err != nil || n != 0 { - t.Errorf("%s: the refused unnarrowed write wrote %d block(s) (err %v)", who, n, err) - } - } - } -} - -// TestC2RequiredKeyRefusesEveryUnnarrowedRequest: a key minted with -// scope_narrowing "required" is refused every unnarrowed request but whoami, -// which reports "required"; narrowed, it reads (C-1 echo). -func TestC2RequiredKeyRefusesEveryUnnarrowedRequest(t *testing.T) { - w := c2Setup(t) - r := w.do(t, http.MethodPost, "/api/store", c2AdminKey, nil, map[string]any{"category": "learnings", "title": "c2 shared block", "content": "c2probe", "scope": "shared"}).must(t, "store") - blk, _ := r.body["block"].(map[string]any) - blockID, _ := blk["id"].(string) - - r, key, _ := w.mint(t, map[string]any{"label": "c2-required", "home_scope": "work", "allowed_scopes": []string{"shared"}, "scope_narrowing": "required"}) - r.must(t, "api-key-create with scope_narrowing required") - if got, _ := r.body["scope_narrowing"].(string); got != "required" { - t.Errorf("api-key-create echoes scope_narrowing %q, want required", got) - } - if got := w.scopeNarrowing(t, key); got != "required" { - t.Errorf("whoami of the required key: scope_narrowing %q, want required", got) - } - w.wantRequired(t, "required key", key, blockID) - - h := http.Header{} - h.Set(handler.HeaderReadScopes, "shared") - n := w.do(t, http.MethodPost, "/api/search", key, h, map[string]any{"query": "c2probe"}) - if n.status != http.StatusOK || n.header.Get(handler.HeaderNarrowed) != "shared;" { - t.Errorf("narrowed search of the required key: HTTP %d echo %q, want 200 with echo \"shared;\" (%s)", n.status, n.header.Get(handler.HeaderNarrowed), n.raw) - } -} - -// TestC2KeyUpdateSwitchesTheRequirement: api-key-update turns the requirement -// on and off for an existing key. -func TestC2KeyUpdateSwitchesTheRequirement(t *testing.T) { - w := c2Setup(t) - _, key, id := w.mint(t, map[string]any{"label": "c2-switch", "home_scope": "work"}) - if key == "" || id == "" { - t.Fatal("fixture: api-key-create returned no key") - } - w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}).must(t, "optional key searches unnarrowed") - - r := w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "required"}}) - if r.status != http.StatusOK || r.body["success"] != true { - t.Fatalf("api-key-update scope_narrowing required: HTTP %d %s", r.status, r.raw) - } - if k, _ := r.body["key"].(map[string]any); k["scope_narrowing"] != "required" { - t.Errorf("api-key-update answers key %v, want scope_narrowing required", r.body["key"]) - } - if got := w.scopeNarrowing(t, key); got != "required" { - t.Errorf("whoami after the switch: scope_narrowing %q, want required", got) - } - s := w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}) - if s.status != http.StatusForbidden || s.code() != "scope_narrowing_required" { - t.Errorf("unnarrowed search after the switch: HTTP %d code %q, want 403 scope_narrowing_required", s.status, s.code()) - } - - w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "optional"}}).must(t, "switch back") - w.do(t, http.MethodPost, "/api/search", key, nil, map[string]any{"query": "c2probe"}).must(t, "optional again") -} - -// TestC2ScopeNarrowingValueIsChecked: a value other than optional and required -// is a 400 on create and update, and nothing is created or changed. -func TestC2ScopeNarrowingValueIsChecked(t *testing.T) { - w := c2Setup(t) - r, _, _ := w.mint(t, map[string]any{"label": "c2-bogus", "home_scope": "work", "scope_narrowing": "sometimes"}) - if r.status != http.StatusBadRequest { - t.Errorf("api-key-create scope_narrowing sometimes: HTTP %d %s, want 400", r.status, r.raw) - } - var n int - if err := w.pool.QueryRow(context.Background(), `SELECT count(*) FROM context_api_keys WHERE label = 'c2-bogus'`).Scan(&n); err != nil || n != 0 { - t.Errorf("api-key-create with a bad value created %d key(s) (err %v)", n, err) - } - - _, key, id := w.mint(t, map[string]any{"label": "c2-keep", "home_scope": "work"}) - r = w.manage(t, c2AdminKey, map[string]any{"action": "api-key-update", "data": map[string]any{"id": id, "scope_narrowing": "sometimes"}}) - if r.status != http.StatusBadRequest { - t.Errorf("api-key-update scope_narrowing sometimes: HTTP %d %s, want 400", r.status, r.raw) - } - if got := w.scopeNarrowing(t, key); got != "optional" { - t.Errorf("whoami after the refused update: scope_narrowing %q, want optional", got) - } -} - -// TestC2KeysWithoutTheFieldStayOptional: a key minted without the field, and -// the bootstrap key, are optional and keep working unnarrowed. -func TestC2KeysWithoutTheFieldStayOptional(t *testing.T) { - w := c2Setup(t) - _, key, _ := w.mint(t, map[string]any{"label": "c2-plain", "home_scope": "work"}) - for who, k := range map[string]string{"plain key": key, "bootstrap admin": c2AdminKey} { - if got := w.scopeNarrowing(t, k); got != "optional" { - t.Errorf("%s: whoami scope_narrowing %q, want optional", who, got) - } - w.do(t, http.MethodPost, "/api/search", k, nil, map[string]any{"query": "c2probe"}).must(t, who+" searches unnarrowed") - } -} - -// c2Migration198 is the file name of migration 198, whatever C-2 calls it. -func c2Migration198(t *testing.T) string { - t.Helper() - files, err := fs.Glob(migrations.FS, "198_*.sql") - if err != nil { - t.Fatal(err) - } - if len(files) != 1 { - t.Fatalf("migration 198: %d file(s) %v in go/migrations, want exactly one", len(files), files) - } - return files[0] -} - -// c2Column describes context_api_keys.scope_narrowing: type, nullability and -// default ("" when the column does not exist). -func c2Column(t *testing.T, pool *pgxpool.Pool) string { - t.Helper() - var typ, nullable, def string - err := pool.QueryRow(context.Background(), `SELECT data_type, is_nullable, coalesce(column_default, '') - FROM information_schema.columns - WHERE table_schema = current_schema() AND table_name = 'context_api_keys' AND column_name = 'scope_narrowing'`).Scan(&typ, &nullable, &def) - if err != nil { - return "" - } - return typ + " nullable=" + nullable + " default=" + def -} - -// c2WantCheck pins the CHECK: a value outside the two is refused (23514). -func c2WantCheck(t *testing.T, pool *pgxpool.Pool, label string) { - t.Helper() - _, err := pool.Exec(context.Background(), `UPDATE context_api_keys SET scope_narrowing = 'sometimes' WHERE label = $1`, label) - var pgErr *pgconn.PgError - if !errors.As(err, &pgErr) || pgErr.Code != "23514" { - t.Errorf("scope_narrowing = 'sometimes' on %s: err %v, want a CHECK violation (23514)", label, err) - } -} - -// TestC2Migration198 (design2/02 §3.5 C-2): context_api_keys.scope_narrowing -// TEXT NOT NULL DEFAULT 'optional' CHECK (optional|required), forward on a -// fresh and on a populated database; existing keys read optional, also -// through ctx_auth and ctx_auth_by_id, whose last column it is. -func TestC2Migration198(t *testing.T) { - ctx := context.Background() - const want = "text nullable=NO default='optional'::text" - file := c2Migration198(t) - - t.Run("fresh", func(t *testing.T) { - pool := testdb.SetupTestDB(t) - if got := c2Column(t, pool); got != want { - t.Fatalf("%s on a fresh database: column %q, want %q", file, got, want) - } - if _, _, err := store.CreateApiKey(ctx, pool, "c2-fresh", "work", nil, store.DefaultTenantID); err != nil { - t.Fatal(err) - } - c2WantCheck(t, pool, "c2-fresh") - }) - - t.Run("populated", func(t *testing.T) { - pool := testdb.SetupTestDBUpTo(t, 197) - const plain = "c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0c2b0" - sum := sha256.Sum256([]byte(plain)) - var keyID string - if err := pool.QueryRow(ctx, `WITH p AS (INSERT INTO context_principals (display_name) VALUES ('c2-old') RETURNING id) - INSERT INTO context_api_keys (label, key_hash, home_scope, allowed_scopes, active, tenant_id, tenant_role, principal_id) - SELECT 'c2-old', $1, 'private', '{shared}', true, $2::uuid, 'member', p.id FROM p - RETURNING id::text`, hex.EncodeToString(sum[:]), store.DefaultTenantID).Scan(&keyID); err != nil { - t.Fatalf("seed a 197 key: %v", err) - } - if err := store.RunMigrationsUpTo(ctx, pool, 198); err != nil { - t.Fatalf("run migrations up to 198: %v", err) - } - if got := c2Column(t, pool); got != want { - t.Fatalf("%s on a populated database: column %q, want %q", file, got, want) - } - var v string - if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM context_api_keys WHERE id = $1::uuid`, keyID).Scan(&v); err != nil || v != "optional" { - t.Errorf("the existing key reads %q (err %v), want optional", v, err) - } - if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM ctx_auth($1)`, plain).Scan(&v); err != nil || v != "optional" { - t.Errorf("ctx_auth: scope_narrowing %q (err %v), want optional", v, err) - } - if err := pool.QueryRow(ctx, `SELECT scope_narrowing FROM ctx_auth_by_id($1::uuid)`, keyID).Scan(&v); err != nil || v != "optional" { - t.Errorf("ctx_auth_by_id: scope_narrowing %q (err %v), want optional", v, err) - } - c2WantCheck(t, pool, "c2-old") - if err := store.RunMigrations(ctx, pool); err != nil { - t.Fatalf("run migrations again: %v", err) - } - }) -} diff --git a/go/internal/auth/auth.go b/go/internal/auth/auth.go index 8e153ae90..64a5973d7 100644 --- a/go/internal/auth/auth.go +++ b/go/internal/auth/auth.go @@ -47,36 +47,8 @@ type AuthResult struct { // sole authorisation decision. Achse 03 (token) and 05 (session) resolve // their AuthResult through the SAME ctx_auth_by_id(uuid) SQL sibling. PrincipalID string - // Narrowed is the request's per-request narrowing (Achse 02 C-1): nil for an - // unnarrowed request. Only the Auth middleware sets it, and only on the - // AuthResult it hands to the handlers; the request key that store writes - // recheck (store.WithRequestKey) stays the unnarrowed key's. - Narrowed *Narrowing - // ScopeNarrowing is the key's scope_narrowing column (Achse 02 C-2): - // ScopeNarrowingOptional or ScopeNarrowingRequired. "" reads as optional. - ScopeNarrowing string } -// Narrowing is a request's narrowing (Achse 02 C-1). Read is the read set of -// this request, in header order; Write is its write scope ("" = the request -// writes nothing); Writable is the write set handed to the block write gate -// ([Write] when the request has a write scope, else empty). A write scope the -// UNNARROWED key cannot write, or one outside Read, never gets here: the -// narrowing is refused (403 scope_denied) before an AuthResult carries it. -type Narrowing struct { - Read []string - Write string - Writable []string -} - -// The values of a key's scope_narrowing (Achse 02 C-2): an optional key may -// narrow a request, a required key answers nothing but GET /api/whoami -// without a narrowing. -const ( - ScopeNarrowingOptional = "optional" - ScopeNarrowingRequired = "required" -) - // SanitizeKey strips all non-hex characters from an API key. func SanitizeKey(raw string) string { return hexOnly.ReplaceAllString(raw, "") diff --git a/go/internal/handler/manage_table.go b/go/internal/handler/manage_table.go index ea73930ab..781aa8982 100644 --- a/go/internal/handler/manage_table.go +++ b/go/internal/handler/manage_table.go @@ -437,15 +437,6 @@ func (h *ManageHandler) handleManage(w http.ResponseWriter, r *http.Request, act return } - // Per-request narrowing (Achse 02 C-1, BP-25): the route rule lives in the - // Auth middleware, which must not read the body; the action rule is - // checked here, on the ONE decoded req.Action the dispatch below uses — - // never on a second reading of the body. - if authResult.Narrowed != nil && !manageActionAllowedNarrowed(req.Action) { - writeNarrowingRouteRefused(w) - return - } - action, known := actions[req.Action] if !known { writeJSON(w, http.StatusBadRequest, map[string]any{ diff --git a/go/internal/handler/middleware.go b/go/internal/handler/middleware.go index 8137c8467..8705eb3d9 100644 --- a/go/internal/handler/middleware.go +++ b/go/internal/handler/middleware.go @@ -696,22 +696,11 @@ func Auth(pool *pgxpool.Pool) func(http.Handler) http.Handler { return } - // Per-request narrowing (Achse 02 C-1, narrowing.go): the handlers - // see the narrowed AuthResult; the request key below stays the - // key's own. - narrowed, rej := narrowAuth(r, result) - if rej != nil { - writeJSONReject(w, rej) - return - } - - ctx := context.WithValue(r.Context(), authResultKey, narrowed) + ctx := context.WithValue(r.Context(), authResultKey, result) // The request's key and the scopes it granted travel to every // write the request makes (issue #555, store.WithRequestKey): a // write whose key a tenant-delete removed, or took a scope from, - // while the request ran writes nothing. Fed from the UNNARROWED - // result: a narrowing shrinks what the request may do, never what - // the recheck holds the key to. + // while the request ran writes nothing. ctx = store.WithRequestKey(ctx, store.RequestKey{ ID: result.ApiKeyID, HomeScope: result.HomeScope, diff --git a/go/internal/handler/narrowing.go b/go/internal/handler/narrowing.go deleted file mode 100644 index 5a7736bbe..000000000 --- a/go/internal/handler/narrowing.go +++ /dev/null @@ -1,65 +0,0 @@ -// Per-request scope narrowing (Achse 02, cluster C-1; design2/02 §3.5): a -// request names the scopes it reads (X-Context-Read-Scopes) and, optionally, -// the one scope it writes (X-Context-Write-Scope), and for that request the -// key's rights shrink to exactly these. The key's own scopes stay what the -// write recheck of issue #555 (store.WithRequestKey) checks against. -// -// S1 contract: the signatures below are fixed, the bodies are inert — the -// headers are ignored and every request runs unnarrowed, byte-identical to the -// tree before this file. C-1 fills them in; C-2 adds the required-narrowing -// check to narrowAuth. -package handler - -import ( - "net/http" - - "github.com/GottZ/ctx/internal/auth" -) - -// The narrowing headers. HeaderReadScopes carries 1 to 8 scopes, -// comma-separated, in the order the request reads them; HeaderWriteScope the -// one scope the request writes. HeaderNarrowed is the echo on the answer to a -// narrowed request: "<read scopes, comma-separated>;<write scope>". -const ( - HeaderReadScopes = "X-Context-Read-Scopes" - HeaderWriteScope = "X-Context-Write-Scope" - HeaderNarrowed = "X-Context-Narrowed" -) - -// codeScopeNarrowingRoute is the code of the refusal of a narrowed request on -// a route or /api/manage action outside the narrowing's closed list. It is not -// a rejectClass of errcode.go yet: a class there is closed vocabulary that -// docs/api.md and docs/mcp.md list (TestRejectClassesAreDocumented), and the -// documentation is C-1's. C-1 moves it into errcode.go next to its -// documentation. -const codeScopeNarrowingRoute = "scope_narrowing_route" - -// narrowAuth derives the AuthResult a request runs with from the key's -// AuthResult ar and the narrowing headers of r. It returns the AuthResult to -// hand to the handlers (ar itself when the request carries no narrowing) or a -// refusal the Auth middleware answers with. It never modifies ar. -// -// S1 stub: the headers are ignored, every request is unnarrowed. -func narrowAuth(r *http.Request, ar *auth.AuthResult) (*auth.AuthResult, *writeReject) { - return ar, nil -} - -// manageActionAllowedNarrowed reports whether a narrowed /api/manage request -// may run action — the one action the dispatcher decoded (BP-25). C-1: only -// "get" and "type-list". -// -// S1 stub: no request is narrowed yet, so the dispatcher never asks; every -// action is allowed. -func manageActionAllowedNarrowed(action string) bool { - return true -} - -// writeNarrowingRouteRefused answers a narrowed request whose route or manage -// action lies outside the narrowing's closed list: 403 with the house -// {"success":false,"error":…} envelope and the code scope_narrowing_route. -func writeNarrowingRouteRefused(w http.ResponseWriter) { - writeJSONCode(w, http.StatusForbidden, codeScopeNarrowingRoute, map[string]any{ - "success": false, - "error": "this route is not available to a narrowed request", - }) -} diff --git a/go/internal/store/api_keys.go b/go/internal/store/api_keys.go index 7b50f770c..b2da1d95f 100644 --- a/go/internal/store/api_keys.go +++ b/go/internal/store/api_keys.go @@ -10,7 +10,6 @@ import ( "strings" "time" - "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/pgxdb" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" @@ -92,14 +91,7 @@ func validateWriteScopes(homeScope string, allowedScopes, writeScopes []string) // RETURNING now carry tenant_role — additive vs v4.0.1 (whose create path // omitted the column and returned TenantRole==""); the column has existed since // 059, so this is SQL-only, NO migration. -// -// scopeNarrowing is the key's scope_narrowing (auth.ScopeNarrowingOptional or -// auth.ScopeNarrowingRequired, Achse 02). The S1 contract fixes the parameter -// so the keyset mint (C-3) can be built against it; the column arrives with -// migration 198 (C-2), and until then the value is not stored — every caller -// passes auth.ScopeNarrowingOptional, which is what the column's default will -// be. -func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role, scopeNarrowing string) (ApiKey, string, error) { +func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, allowedScopes, writeScopes []string, tenantID, role string) (ApiKey, string, error) { if label == "" { return ApiKey{}, "", fmt.Errorf("api_keys: label is required") } @@ -198,7 +190,7 @@ func insertApiKeyTx(ctx context.Context, q pgxdb.Rower, label, homeScope string, // it mints are exactly as before. Owner / quota-gated mints are separate paths // that pass their own role through the shared primitive. func CreateApiKey(ctx context.Context, pool *pgxpool.Pool, label, homeScope string, allowedScopes []string, tenantID string) (*ApiKey, string, error) { - key, plaintext, err := insertApiKeyTx(ctx, pool, label, homeScope, allowedScopes, nil, tenantID, "member", auth.ScopeNarrowingOptional) + key, plaintext, err := insertApiKeyTx(ctx, pool, label, homeScope, allowedScopes, nil, tenantID, "member") if err != nil { return nil, "", err } @@ -275,7 +267,7 @@ func MintKeyWithQuota(ctx context.Context, pool *pgxpool.Pool, label, homeScope } var err error - key, plaintext, err = insertApiKeyTx(ctx, tx, label, homeScope, allowedScopes, writeScopes, tenantID, role, auth.ScopeNarrowingOptional) + key, plaintext, err = insertApiKeyTx(ctx, tx, label, homeScope, allowedScopes, writeScopes, tenantID, role) return err }); err != nil { return ApiKey{}, "", err @@ -309,7 +301,7 @@ func MintOwnerKey(ctx context.Context, q pgxdb.Rower, label, homeScope string, a // Owner keys mint with empty write_scopes (nil): an owner's home_scope IS the // tenant's first scope and covers the bootstrap corpus; explicit write_scopes // are a later, per-key concern via api-key-update. - return insertApiKeyTx(ctx, q, label, homeScope, allowedScopes, nil, tenantID, "owner", auth.ScopeNarrowingOptional) + return insertApiKeyTx(ctx, q, label, homeScope, allowedScopes, nil, tenantID, "owner") } // ListApiKeys returns API key rows ordered by created_at desc, scoped to one diff --git a/go/internal/store/api_keys_insert_test.go b/go/internal/store/api_keys_insert_test.go index dfcaeb8dd..0d8ebd20a 100644 --- a/go/internal/store/api_keys_insert_test.go +++ b/go/internal/store/api_keys_insert_test.go @@ -4,8 +4,6 @@ import ( "context" "strings" "testing" - - "github.com/GottZ/ctx/internal/auth" ) // insertApiKeyTx is the shared INSERT primitive behind CreateApiKey (and the @@ -38,7 +36,7 @@ func TestInsertApiKeyTx_ValidationOwnedByPrimitive(t *testing.T) { {"reserved allowed_scope", "lbl", "tenant-a", []string{"shared", "_x"}, "reserved"}, } for _, c := range cases { - _, _, err := insertApiKeyTx(ctx, nil, c.label, c.homeScope, c.allowed, nil, "", role, auth.ScopeNarrowingOptional) + _, _, err := insertApiKeyTx(ctx, nil, c.label, c.homeScope, c.allowed, nil, "", role) if err == nil { t.Errorf("role=%s %s: expected error, got nil", role, c.name) continue diff --git a/go/internal/store/api_keys_write_scopes_test.go b/go/internal/store/api_keys_write_scopes_test.go index 7eac6e831..8b20387b1 100644 --- a/go/internal/store/api_keys_write_scopes_test.go +++ b/go/internal/store/api_keys_write_scopes_test.go @@ -5,8 +5,6 @@ import ( "errors" "strings" "testing" - - "github.com/GottZ/ctx/internal/auth" ) // validateWriteScopes is the mint/update-time half of the 078 write_scopes invariant @@ -58,7 +56,7 @@ func TestValidateWriteScopes(t *testing.T) { // would fall through to q.QueryRow(nil) and panic. func TestInsertApiKeyTx_RejectsBlindWriterBeforeDB(t *testing.T) { ctx := context.Background() - _, _, err := insertApiKeyTx(ctx, nil, "lbl", "private", []string{"shared"}, []string{"work"}, "", "member", auth.ScopeNarrowingOptional) + _, _, err := insertApiKeyTx(ctx, nil, "lbl", "private", []string{"shared"}, []string{"work"}, "", "member") if !errors.Is(err, ErrWriteScopeNotAllowed) { t.Fatalf("insertApiKeyTx blind-writer err = %v, want ErrWriteScopeNotAllowed", err) } diff --git a/go/internal/store/provision.go b/go/internal/store/provision.go index e3373854c..2dac1ac3a 100644 --- a/go/internal/store/provision.go +++ b/go/internal/store/provision.go @@ -20,7 +20,6 @@ import ( "errors" "fmt" - "github.com/GottZ/ctx/internal/auth" "github.com/GottZ/ctx/internal/backends" "github.com/GottZ/ctx/internal/pgxdb" "github.com/jackc/pgx/v5" @@ -185,7 +184,7 @@ func ProvisionProject(ctx context.Context, pool *pgxpool.Pool, p ProvisionParams // (NON-NIL empty: no '{shared}' inheritance), write = [] (NON-NIL empty). The // role is 'member' (agents never own). This is the verbindlicher Vertrag §5.5. agentKey, agentPlain, err := insertApiKeyTx(ctx, tx, - p.Slug+agentKeyLabelSuffix, p.Scope, []string{}, []string{}, tn.ID, "member", auth.ScopeNarrowingOptional) + p.Slug+agentKeyLabelSuffix, p.Scope, []string{}, []string{}, tn.ID, "member") if err != nil { return err } From efefef30beadcd9c54ffb206e2471564d826e414 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:14:12 +0100 Subject: [PATCH 28/65] test(ctx_checkpoint): the group binding's races and failures the review of #596 named, red before their fixes Seven cases, each made with event barriers at the named point (a blocked call, a lock that signals when a second thread has to wait for it): a governed or restricted session served while its markers cannot be written; a proof timed out on a short caller budget answering a caller with time left; a turn-off overwritten by a proof's publication; a store proof that completes after a turn-off; a read tool answering from the binding a re-initialization put in place; an idle digest stored through the writer of the next binding. Four guards (markers another writer raised, a full disk without access groups, an HTTP refusal remembered for every caller) hold already. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../tests/test_access_binding_races.py | 316 ++++++++++++++++++ 1 file changed, 316 insertions(+) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py new file mode 100644 index 000000000..c1fbbd117 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py @@ -0,0 +1,316 @@ +"""The group binding under concurrency and failure (GottZ/ctx#596 review): every path that sends for +a group works on one snapshot of the binding the gate checked, and a stale snapshot sends nothing; +a governed session is served only once its markers are on disk; a proof that ran out of a short +caller budget is no answer for a caller with time left. + +The interleavings are made with event barriers at the named points (a blocked call, a lock that +signals when a second thread has to wait for it), never by guessing with sleeps.""" + +from __future__ import annotations + +import errno +import threading + +import pytest +import test_access_pc_binding as pc +from fakes import access_host as ah +from fakes.ctx_server import digest + +pytestmark = pytest.mark.access_cluster("P-C") + +world = pc.world # the P-C world: fake ctx, host with the core PR's surface, a profile home +_acc = ah.plugin_module(pc._PKG, "memory.access") +_nar = ah.plugin_module(pc._PKG, "memory.narrowing") +_client = ah.plugin_module(pc._PKG, "memory.client") + +A_MODS = "t:d111-mods" +MODS_KEY = "ctx_mods_a" +MODS_FIELDS = {"key": "CTX_KEY_111_MODS", "read": [pc.B_K], "write": A_MODS} +WAIT_S = 20.0 # a barrier that is not reached within this fails the test (no hang) + + +def _add_mods(fake, host): + """A second unrestricted group of server 111 with its own key, reading server B's knowledge.""" + fake.add_key(secret=MODS_KEY, tenant="t", home=A_MODS, allowed=(pc.B_K,)) + host.secrets.set_base({**host.secrets.var.get(), "CTX_KEY_111_MODS": MODS_KEY}) + + +def _ops(home): + return pc._provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=pc.OPS_FIELDS)) + + +def _reinit_mods(provider, home): + provider.initialize( + "s-1", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="mods", group_restricted=False, fields=MODS_FIELDS), + ) + + +def _run(target): + """``target`` on a thread of its own; returns (thread, box) with the result or the error in ``box``.""" + box: dict = {} + + def body(): + try: + box["result"] = target() + except BaseException as exc: # reported to the test + box["error"] = exc + + thread = threading.Thread(target=body, name="race-t1", daemon=True) + thread.start() + return thread, box + + +def _joined(thread, box): + thread.join(WAIT_S) + assert not thread.is_alive(), "the first thread did not finish" + if "error" in box: + raise box["error"] + return box.get("result") + + +class _SignallingLock: + """A lock that sets ``waiting`` when a caller has to wait for it (another thread holds it).""" + + def __init__(self, inner, waiting: threading.Event) -> None: + self._inner = inner + self._waiting = waiting + + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: + if self._inner.acquire(False): + return True + if not blocking: + return False + self._waiting.set() + return self._inner.acquire(True, timeout) + + def release(self) -> None: + self._inner.release() + + def __enter__(self): + self.acquire() + return self + + def __exit__(self, *exc) -> None: + self.release() + + +# -- markers: a governed session is served only once its markers are on disk (#4815624943, #4815624958) + + +def _disk(monkeypatch, *, another_writer_first: bool = False) -> dict: + """``ctx_state`` cannot be written (no space left) while ``state["full"]``; with + ``another_writer_first`` another process writes the same markers just before our write fails.""" + state = {"full": True} + real = _acc._write_markers + + def write(path, markers): + if not state["full"]: + return real(path, markers) + if another_writer_first: + real(path, markers) + raise OSError(errno.ENOSPC, "No space left on device") + + monkeypatch.setattr(_acc, "_write_markers", write) + return state + + +def test_a_governed_group_is_not_served_while_its_markers_cannot_be_written(world, monkeypatch): + fake, _host, home = world + disk = _disk(monkeypatch) + provider = _ops(home) + assert provider.prefetch("plans?") == "" and provider.get_tool_schemas() == [] + assert '"error"' in provider.handle_tool_call("ctx_query", {"text": "plans?"}) + assert fake.count() == 0 and _acc.read_markers(str(home)) == _acc.Markers(False, False) + disk["full"] = False # the next initialize tries again + again = _ops(home) + assert "alpha knowledge" in again.prefetch("plans?") + assert _acc.read_markers(str(home)).governed_seen is True + + +def test_a_restricted_group_is_not_served_while_its_markers_cannot_be_written(world, monkeypatch): + fake, _host, home = world + pc._config(home, settings=" restricted_allow: [recall]\n") + _disk(monkeypatch) + provider = pc._member(home, {**pc.MEMBER_FIELDS, "recall": True}) + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +def test_markers_another_writer_raised_meanwhile_count(world, monkeypatch): + """Guard: our write fails, but a re-read finds the markers another process wrote just before.""" + _fake, _host, home = world + _disk(monkeypatch, another_writer_first=True) + assert "alpha knowledge" in _ops(home).prefetch("plans?") + + +@pytest.mark.parametrize("v8", [False, True], ids=["hermes-without-access-groups", "no-group-session"]) +def test_a_full_disk_changes_nothing_without_access_groups(world, monkeypatch, v8): + """Guard: with no access group in play no marker is needed; the profile's connection is 0.19.1's.""" + fake, _host, home = world + ah.install(monkeypatch, v8=v8, secrets={"CTX_KEY": pc.PROFILE_KEY, "CTX_BASE_URL": fake.url}) + _disk(monkeypatch) + provider = pc.Provider(config={"transport": "rest", "memory": True}) + kwargs = ah.v5_kwargs() if v8 else {} + provider.initialize("s-1", hermes_home=str(home), platform="cli", agent_context="primary", **kwargs) + text = provider.prefetch("plans?") + assert "alpha knowledge" in text and "bravo knowledge" in text + assert {r.key_digest for r in fake.requests()} == {digest(pc.PROFILE_KEY)} + + +# -- a proof that ran out of a short caller budget (#4815624953) ------------------------------------ + + +def test_a_proof_that_ran_out_of_a_short_budget_is_no_answer_for_a_caller_with_time(fake_ctx): + _nar.reset_proofs() + fake_ctx.add_key(secret=pc.OPS_A_KEY, tenant="t", home=pc.A_OPS, allowed=(pc.A_K,)) + client = _client.CtxClient(fake_ctx.url, pc.OPS_A_KEY, narrowing=_nar.Narrowing(read=(pc.A_K,))) + fake_ctx.latency["/api/whoami"] = 0.5 + with pytest.raises(_client.CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=0.05) + answer = _nar.whoami_raw(client, narrowed=True, budget_s=5.0) + assert answer["narrowed"]["read"] == [pc.A_K] + + +def test_an_http_refusal_is_remembered_for_every_caller(fake_ctx): + """Guard: a refusal the server answered is a state of the key, whatever the caller's budget.""" + _nar.reset_proofs() + key = fake_ctx.add_key(secret=pc.OPS_A_KEY, tenant="t", home=pc.A_OPS, allowed=(pc.A_K,)) + client = _client.CtxClient(fake_ctx.url, pc.OPS_A_KEY, narrowing=_nar.Narrowing(read=(pc.A_K,))) + key.active = False + with pytest.raises(_client.CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=0.5) + key.active = True + fake_ctx.reset_counters() + with pytest.raises(_client.CtxApiError): + _nar.whoami_raw(client, narrowed=True, budget_s=5.0) + assert fake_ctx.count() == 0 + + +# -- one snapshot of the binding per call (#4815624950, #4815624963, #4815624964, #4815624967) ------ + + +def test_a_binding_published_while_it_is_turned_off_stays_off(world, monkeypatch): + """The proof publishes the binding; a turn-off between its check and its publication must win.""" + fake, _host, home = world + fake.throttle["/api/whoami"] = 4 # the first proof gets no answer: the binding stays pending + provider = _ops(home) + assert not provider._active and provider._group is not None + fake.throttle.clear() + _nar.reset_proofs() + group = provider._group + arrived = threading.Event() + # Set when the turn-off has run, or when it has to wait for a lock the publication holds. + turned_off_or_waiting = threading.Event() + + class _Proven(set): + def add(self, item): + if item == "group": + arrived.set() + assert turned_off_or_waiting.wait(WAIT_S) + super().add(item) + + group.proven = _Proven(group.proven) + for name in ("_off_lock", "_binding_lock"): + if hasattr(provider, name): + setattr(provider, name, _SignallingLock(getattr(provider, name), turned_off_or_waiting)) + t1, box = _run(lambda: provider._prove_group(group)) + assert arrived.wait(WAIT_S) + + def turn_off(): + provider._turn_off("trip wire: a turn of another group") + turned_off_or_waiting.set() + + t2 = threading.Thread(target=turn_off, daemon=True) + t2.start() + _joined(t1, box) + t2.join(WAIT_S) + assert not t2.is_alive() + assert provider._access_off and not provider._active and provider._client is None + fake.reset_counters() + assert provider.prefetch("plans?") == "" and fake.count() == 0 + + +def test_a_store_proof_that_ends_after_a_turn_off_sends_nothing(world, monkeypatch): + fake, _host, home = world + fields = {**pc.OPS_FIELDS, "store": pc.A_K} + provider = pc._provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + arrived, go = threading.Event(), threading.Event() + real = _nar.whoami_raw + + def whoami_raw(client, *, narrowed, budget_s): + narrowing = getattr(client, "narrowing", None) + if narrowed and narrowing is not None and narrowing.write == pc.A_K: # the store client's proof + arrived.set() + assert go.wait(WAIT_S) + return real(client, narrowed=narrowed, budget_s=budget_s) + + monkeypatch.setattr(_nar, "whoami_raw", whoami_raw) + fake.reset_counters() + t1, box = _run(lambda: provider.handle_tool_call("ctx_store", {"category": "c", "title": "t", "content": "x"})) + assert arrived.wait(WAIT_S) + provider._turn_off("narrowing_lost: an answer without the echo") + go.set() + result = _joined(t1, box) + assert '"error"' in result + assert fake.count("/api/store") == 0 + + +def test_a_read_tool_never_answers_from_the_binding_a_reinitialize_put_in_place(world, monkeypatch): + """A tool call passes the gate under group ops, the instance is built again for group mods: the + call must not query with the mods binding (whose key reads server B) for the ops caller.""" + fake, host, home = world + _add_mods(fake, host) + provider = _ops(home) + arrived, go = threading.Event(), threading.Event() + real = _acc.current_access + + def current_access(): + if threading.current_thread().name == "race-t1" and not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + return real() + + monkeypatch.setattr(_acc, "current_access", current_access) + t1, box = _run(lambda: provider.handle_tool_call("ctx_search", {"query": "plans"})) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + assert provider._active, "mods is bound" + fake.reset_counters() + go.set() + result = _joined(t1, box) + assert "bravo knowledge" not in result and '"error"' in result + assert fake.count("/api/search") == 0 + + +def test_an_idle_digest_writes_only_through_the_binding_it_was_armed_under(world): + """The idle timer passes its generation check under group ops, the instance is built again for + group mods with the same session: the ops exchanges must not be stored through the mods writer.""" + fake, host, home = world + _add_mods(fake, host) + provider = _ops(home) + provider.sync_turn("q", "a", messages=pc._messages(12, tag="opsx")) + timer = provider._idle_timer + assert timer is not None, "the idle timer is armed" + timer.cancel() + arrived, go = threading.Event(), threading.Event() + real = provider._digest_state + + def digest_state(root): + if not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + return real(root) + + provider._digest_state = digest_state + t1, box = _run(lambda: provider._on_idle(*timer.args)) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + fake.reset_counters() + go.set() + _joined(t1, box) + pc._settle(provider) + assert fake.count("/api/store") == 0 + assert all(block["scope"] != A_MODS for block in fake.blocks.values()) From fba2ac70d65fb774ca806207508e15ff6fa0702f Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:14:50 +0100 Subject: [PATCH 29/65] fix(ctx_checkpoint): a governed access-group session is served only once its markers are on disk raise_markers logs a write it cannot make (full disk, busy lock) and returns; the build then bound and served the group although every later session without access kwargs (a direct message, a rolled-back Hermes) would find no marker. initialize now reads the markers back after raising them (a raise another process made meanwhile counts) and leaves the binding off while one it needs is missing; the next initialize tries again. Sessions that need no marker (no access group in play) are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/access.py | 5 +++-- .../plugin/ctx_checkpoint/memory/provider.py | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py index 41b245bc9..7e0138389 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -855,8 +855,9 @@ def raise_markers(hermes_home: str, **flags: bool) -> None: """Set the named markers (``restricted_seen=True``, ``governed_seen=True``), only from false to true, atomically, and only when one changes; ``False`` never lowers one (only ``access reset-marker`` does). A marker that cannot be written (or whose lock cannot be held) is a - WARNING, never an exception: the decision of this build stands, and the next build that sees - the same session raises it again.""" + WARNING, never an exception; the caller reads the markers back (``read_markers``, which also + finds a raise another process made meanwhile) and serves a governed session only once they + hold — the provider leaves it ``off`` otherwise, and the next build tries again.""" wanted = {name for name, value in _marker_flags(flags).items() if value} if not wanted or all(getattr(read_markers(hermes_home), name) for name in wanted): return # markers only rise: one already set needs no lock and no write diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index a59a9d08a..f24f73365 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -225,6 +225,11 @@ def _proof_cause(exc: CtxApiError) -> str: return ", ".join(part for part in parts if part) or "no answer" +def _markers_hold(markers: Any, needed: Mapping[str, bool]) -> bool: + """Whether every marker in ``needed`` (``access.seen_markers``) is set in ``markers`` as read back.""" + return all(getattr(markers, name, False) for name, wanted in needed.items() if wanted) + + def _write_limit(info: Any) -> int | None: """``whoami.rate_limit_write`` (writes per 60 s for this key, ctx with per-request narrowing) as reported: any int, ``0`` or less included (ctx: unlimited, which lifts a limit reported before); @@ -758,7 +763,19 @@ def _decide_access(self, kwargs: Mapping[str, Any]) -> None: markers, _access.access_supported(), ) - _access.raise_markers(home, **_access.seen_markers(init, decision)) + needed = _access.seen_markers(init, decision) + _access.raise_markers(home, **needed) + if decision.kind != "off" and not _markers_hold(_access.read_markers(home), needed): + # A session of a governed group is served only once the markers it raises are on disk: + # every later session without access kwargs (a direct message, a rolled-back Hermes) + # must find them. A re-read counts a raise another process made meanwhile; the next + # initialize tries again. + decision = _access.Decision( + "off", + "the access-group markers could not be written to ctx_state (full disk or busy lock)", + context=decision.context, + strict=decision.strict, + ) except Exception as exc: # never a binding the table did not give settings = _access.SETTINGS_DEFAULTS decision = _access.Decision("off", f"the access decision failed ({type(exc).__name__})", strict=True) From 60943c45abd458ac9a682f2f5652cc54cf48fe7d Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:16:11 +0100 Subject: [PATCH 30/65] fix(ctx_checkpoint): a whoami that ran out of one caller's short budget is no proof for a caller with time left The proof store remembered every failure 15 s for all bindings of the same key and header set, so a base-block hook that started a whoami with 100 ms left could make a provider with its full verify budget fail at once. What the server answered (identity, refusal, failure envelope, an answer without the echo) still holds for every caller; a call that got no answer is remembered with the budget it had and serves only callers with no more time; a refusal of the client itself is never remembered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/narrowing.py | 46 +++++++++++++------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py index 679c0fef8..a6fac6773 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py @@ -118,11 +118,18 @@ def expected_label(platform: str, scope_id: str, profile: str) -> str: @dataclass(frozen=True) class _Proof: - """One remembered ``whoami``: the raw answer, or the failure as (message, status, code).""" + """One remembered ``whoami``: the raw answer, or the failure as (message, status, code). + ``budget``: for a failure without an answer from the server (connection error, time out), the + budget it had — it is no answer for a caller with more time left; ``None`` for answers.""" expires: float answer: Mapping[str, Any] | None = None failure: tuple[str, int | None, str] | None = None + budget: float | None = None + + def serves(self, now: float, left: float) -> bool: + """Whether this proof answers a caller with ``left`` seconds of budget at ``now``.""" + return self.expires > now and (self.budget is None or left <= self.budget) _PROOFS: dict[tuple[str, str, str], _Proof] = {} @@ -151,11 +158,13 @@ def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping The store is a state of the credentials, not of a binding: its slot is (base URL, key digest, header set), so every binding with the same key and narrowing reads the same raw answer and judges it itself (:func:`evaluate`). Callers that miss the store together ask once: the others - wait for that answer within their own budget. Only answers of the server are remembered: a client - that is off after a lost narrowing refuses without asking, and a budget used up before the call - is the caller's; neither touches the store. ``ValueError`` for a narrowed proof of a client - without a narrowing.""" - from .client import NARROWING_LOST, CtxApiError, is_failure_envelope, response_code + wait for that answer within their own budget. What the server answered (an identity, a refusal, + a failure envelope) is remembered for every caller; a call that got no answer (connection error, + time out) only for callers with no more time than it had, so a caller with a short budget never + takes the proof from one with time left; a refusal of the client itself (off after a lost + narrowing, a binding no longer current) and a budget used up before the call are the caller's + and never touch the store. ``ValueError`` for a narrowed proof of a client without a narrowing.""" + from .client import CtxApiError, is_failure_envelope, response_code narrowing = client.narrowing if narrowed and narrowing is None: @@ -167,7 +176,8 @@ def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping while True: with _PROOFS_LOCK: proof = _PROOFS.get(slot) - fresh = proof is not None and proof.expires > time.monotonic() + now = time.monotonic() + fresh = proof is not None and proof.serves(now, deadline - now) asking = None if fresh else _ASKING.get(slot) if not fresh and asking is None: asking = _ASKING[slot] = threading.Event() @@ -181,21 +191,29 @@ def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping if left <= 0 or not asking.wait(left): raise CtxApiError("connection error: timed out") # this caller's budget, not the server's answer try: - if budget_s <= 0: + budget = deadline - time.monotonic() + if budget <= 0: raise CtxApiError("connection error: timed out") # nothing sent, nothing remembered + answered = False try: - answer = client.whoami(timeout=budget_s, unnarrowed=not narrowed) + answer = client.whoami(timeout=budget, unnarrowed=not narrowed) + answered = True if is_failure_envelope(answer): error = answer.get("error") if isinstance(answer, dict) else None raise CtxApiError( f"whoami answered no identity: {str(error or 'no answer')[:300]}", code=response_code(answer) ) except CtxApiError as exc: - # A refusal of the client itself (another thread lost the narrowing meanwhile) carries no - # status; an answer without the echo carries the answer's status and is remembered. - if not (exc.code == NARROWING_LOST and exc.status is None): - failure = (str(exc), exc.status, exc.code) - _remember(slot, _Proof(expires=time.monotonic() + PROOF_TTL_FAILED_S, failure=failure)) + # An answer of the server (a refusal, an answer without the echo: they carry the answer's + # status; a failure envelope) holds for every caller. No answer within this caller's + # budget holds for callers with no more time. A refusal of the client itself carries a + # code and no status (off after a lost narrowing, a binding no longer current): never. + failure = (str(exc), exc.status, exc.code) + expires = time.monotonic() + PROOF_TTL_FAILED_S + if answered or exc.status is not None: + _remember(slot, _Proof(expires=expires, failure=failure)) + elif not exc.code: + _remember(slot, _Proof(expires=expires, failure=failure, budget=budget)) raise _remember(slot, _Proof(expires=time.monotonic() + PROOF_TTL_OK_S, answer=copy.deepcopy(dict(answer)))) return copy.deepcopy(dict(answer)) From 69eb951c7d9ad38776e7bd831cb4bdd338588d11 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:16:54 +0100 Subject: [PATCH 31/65] fix(ctx_checkpoint): a turn-off and a proof's publication of the binding take one lock, so the turn-off is never overwritten _prove_group checked the binding and published it under the access lock while _turn_off ran under a lock of its own: a turn-off between the check and the publication left the provider off and active with a client at once. Every change of the binding's state (Step 0, publication, refusal, turn-off) now runs under one binding lock, which a proof holds only to publish, never across its whoami; a refusal clears only the group it was made for. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/provider.py | 60 +++++++++++-------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index f24f73365..cac9c4c41 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -344,8 +344,11 @@ def __init__(self): self._group: _GroupBinding | None = None self._bound_turn: tuple[str, ...] | None = None self._access_off = "" + # ``_access_lock``: one proof at a time (held across its whoami). ``_binding_lock``: every + # change of the binding's state (Step 0, publication, refusal, turn-off) and every snapshot + # of it, never held across the network; taken after ``_access_lock`` where both are held. self._access_lock = threading.RLock() - self._off_lock = threading.Lock() + self._binding_lock = threading.RLock() # The write limit per 60 s the ctx server reports for the writing key (whoami # ``rate_limit_write``); the chain writer follows it (P-G). self._rate_limit_write: int | None = None @@ -471,16 +474,17 @@ def _checkpoint_root(self) -> str: def _drop_binding(self) -> None: """Forget the current binding: no client, key, whoami identity or checkpoint writer stays, and no group binding; the keys stay known for redaction.""" - self._remember_secrets() - self._active = False - self._client = None - self._chain_writer = None - self._group = None - self._api_key = "" - self._base_url = "" - self._home_scope = "" - self._whoami_label = "" - self._rate_limit_write = None + with self._binding_lock: + self._remember_secrets() + self._active = False + self._client = None + self._chain_writer = None + self._group = None + self._api_key = "" + self._base_url = "" + self._home_scope = "" + self._whoami_label = "" + self._rate_limit_write = None def _connect(self) -> None: """Bind credentials and the client; sets ``_active``/``_client``. Default: REST. The access @@ -662,12 +666,13 @@ def initialize(self, session_id: str, **kwargs) -> None: # Step 0 (design 02 §4.2): the previous binding goes before anything is checked. Hermes keeps # calling a provider whose initialize raised; nothing of the last binding may answer then. - self._drop_binding() + with self._binding_lock: + self._drop_binding() + self._binding_generation += 1 + self._decision = None + self._bound_turn = None + self._access_off = "the latest initialize did not finish" self._cancel_idle_timer() - self._binding_generation += 1 - self._decision = None - self._bound_turn = None - self._access_off = "the latest initialize did not finish" # A re-initialization starts a new binding: no recall cached (or still being warmed) # for the previous one is served under it. self._invalidate_prefetch() @@ -962,7 +967,7 @@ def left() -> float: if failed: self._group_refused(context, ", ".join(failed), rules=detail, group=group) return - with self._access_lock: + with self._access_lock, self._binding_lock: # a turn-off waits for the publication, never lost if self._group is not group or self._access_off: return # re-initialized or turned off meanwhile group.proven.add("group") @@ -995,11 +1000,13 @@ def _group_refused( """A group that does not bind: off for the rest of this agent, with the reason (never a key value) in the log and the binding's status file. ``group``: the binding the proof was for; a proof that ends after a re-initialization changes nothing of the new binding.""" - if group is not None and self._group is not group: - return - self._access_off = f"group binding refused: {reason}" - self._active = False - self._client = None + with self._binding_lock: + if group is not None and self._group is not group: + return + refused = self._group + self._access_off = f"group binding refused: {reason}" + self._active = False + self._client = None logger.warning( "CTX access group not bound (profile=%s, platform=%s, server=%s, group=%s): %s%s", self._profile, @@ -1010,7 +1017,9 @@ def _group_refused( "".join(f"; {rule}: expected {text}" for rule, text in (rules or {}).items()), ) self._record_access_state(context, f"off: {reason}", rules=rules) - self._group = None + with self._binding_lock: + if self._group is refused: # never the group of a binding built meanwhile + self._group = None def _retry_group_proof(self) -> None: """A group proof the network or the time failed, asked again at most every @@ -1127,8 +1136,9 @@ def _access_gate(self) -> bool: def _turn_off(self, reason: str) -> None: """Off for the rest of this agent (trip wire, lost narrowing): no client, no recall, no write. - Its own lock: a proof in flight (which holds the access lock) does not delay it.""" - with self._off_lock: + Under the binding lock, which a proof holds only to publish (never across its whoami): it + waits for a publication in progress and is never overwritten by it.""" + with self._binding_lock: if self._access_off: return self._access_off = reason From 154e6a300fd95d072ae561bac607c136f65aa5a5 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:29:33 +0100 Subject: [PATCH 32/65] fix(ctx_checkpoint): every path that sends for an access group works on one snapshot of the binding, and a stale snapshot sends nothing The gate checked the binding, and the call then read _group, _client or the writer again: a re-initialization in between handed a read tool the next group's client (its data to the old caller), an idle digest the next group's writer (the old group's exchanges into the new chain), and a store proof that completed after a turn-off still passed its client to the dispatch. The gate now takes one snapshot of the binding under the binding lock (generation, group, client, access context) before it checks the turn, and every path selects its client, writer, store client, tags and chain provenance from that snapshot: tool calls, recall and its warm-up, the mirror, the checkpoint and its facts, rolling, end and idle digests (the idle timer's snapshot must be of the generation it was armed under), the prompt block and the tool list. A group's clients are tied to their binding and refuse to send once it is no longer current (binding_stale, a client code the proof store never remembers); a write or store proof that completes after the binding changed or went off counts for nothing. A checkpoint records its head under the binding it started under. Without access groups the profile's connection is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/__init__.py | 29 +- .../ctx_checkpoint/memory/checkpoint.py | 3 +- .../plugin/ctx_checkpoint/memory/provider.py | 418 ++++++++++++------ .../memory/tests/test_host_contract.py | 2 +- .../tests/test_access_binding_races.py | 50 +++ .../tests/test_access_pg_window.py | 6 +- .../tests/test_error_text_redaction.py | 2 +- 7 files changed, 363 insertions(+), 147 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index 3f584cb23..7b6270a44 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -966,19 +966,23 @@ def on_pre_compress( forget = getattr(self._client, "forget_host_refusal", None) if callable(forget): forget() + # The head this checkpoint records belongs to the binding it started under, even when the + # instance is built again before it ends: never named to the next binding. + binding = self._pointer_binding() try: receipt_text = super().on_pre_compress( messages, require_checkpoint=require_checkpoint, tool_evidence=tool_evidence, **kwargs ) except Exception as exc: - self._record_outcome(bool(require_checkpoint), exc) + self._record_outcome(bool(require_checkpoint), exc, binding) raise - self._record_outcome(bool(require_checkpoint), self._last_chain_error) + self._record_outcome(bool(require_checkpoint), self._last_chain_error, binding) return receipt_text - def _record_outcome(self, required: bool, error: Exception | None) -> None: + def _record_outcome(self, required: bool, error: Exception | None, binding: str | None = None) -> None: """Outcome file + user notice. Never raises: it must not turn a checkpoint into a failure, - nor replace the exception a failed one raises.""" + nor replace the exception a failed one raises. ``binding``: the pointer binding the + checkpoint started under (default: the binding now).""" try: receipt = self._last_chain_receipt skipped = "" if (error is not None or receipt is not None) else self._skip_reason() @@ -998,7 +1002,7 @@ def _record_outcome(self, required: bool, error: Exception | None) -> None: outcome, root=self._checkpoint_root(), head_id=str(receipt.head_id or "") if receipt is not None else "", - binding=self._pointer_binding(), + binding=binding if binding is not None else self._pointer_binding(), ) if outcome["error"]: self._notify_user(_st.failure_warning(outcome, self._server_name())) @@ -1053,17 +1057,19 @@ def system_prompt_block(self) -> str: for the session root — in both modes. Without either it is empty, as before 0.9.0. A group binding names the pointer only where its read tools read its write scope; a session the access decision turned off gets nothing.""" - if not self._active or not self._access_gate(): + lease = self._lease() + if lease is None or not lease.active: return "" blocks = [] if self.memory_enabled: block = super().system_prompt_block() if block: blocks.append(f"{block}\nSkill: {self.name}:{SKILL_NAME} explains how to use the store well.") - pointer = self._checkpoint_pointer() if self._chain_readable() else "" + pointer = self._checkpoint_pointer() if self._chain_readable(lease) else "" if pointer: blocks.append(pointer) - return "\n\n".join(blocks) + # Built from one snapshot: a binding replaced or turned off meanwhile shows nothing. + return "\n\n".join(blocks) if self._lease_current(lease) else "" # -- checkpoint read path (system prompt block, receipt) ----------------------- @@ -1081,11 +1087,12 @@ def _pointer_binding(self) -> str: raw += f"\0{key}\0{context.platform}\0{context.scope_id}\0{context.group}" return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] - def _chain_readable(self) -> bool: + def _chain_readable(self, lease: Any = None) -> bool: """Whether the session's model can read the chain it writes: always on the profile's connection; a group binding only through its own read tools, and only when its read set - holds its write scope (the receipt and the pointer name a head only then).""" - group = self._group + holds its write scope (the receipt and the pointer name a head only then). ``lease``: the + call's snapshot (default: the binding now).""" + group = lease.group if lease is not None else self._group return group is None or (self.memory_enabled and group.read_client is not None and group.write in group.read) def _read_tools(self) -> _cp.ReadTools: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py index 90222fce9..bf49dcd9d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py @@ -588,7 +588,8 @@ def redact_text(text: str, secret: str | Iterable[str] = ()) -> str: # Codes the plugin's clients set themselves (``mcp_client``: staged write, abandoned call; ``client``: # an answer without the echo of the client's narrowing, after which the client sends nothing more). -_CLIENT_CODES = frozenset({"confirm_writes", "timeout", "narrowing_lost"}) +# ``binding_stale``: a group client whose binding is no longer the provider's current one sends nothing. +_CLIENT_CODES = frozenset({"confirm_writes", "timeout", "narrowing_lost", "binding_stale"}) # What an error text says when its redaction failed (it is withheld, never passed on raw). ERROR_WITHHELD = "(details withheld: redaction failed)" # A URL in an error text (``_shown_urls``): ``scheme://`` up to white space, a quote or an angle bracket. diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index cac9c4c41..da5057012 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -147,6 +147,38 @@ def spawn_context_thread( # store client (offered to unrestricted groups only, design 02 §4.2 step 6). READ_TOOLS = ("ctx_query", "ctx_search", "ctx_get") STORE_TOOL = "ctx_store" +# A request through a group client whose binding is no longer the provider's current one (a +# re-initialization or a turn-off since the call took its snapshot): refused before it is sent. +BINDING_STALE = "binding_stale" +BINDING_STALE_TEXT = "ctx access-group binding is no longer current; its client sends nothing more" +# "The binding as it is now" for the helpers a call may also pass its snapshot to. +_CURRENT: Any = object() + + +class _BindingClient: + """A group client tied to the binding it was built for: before every call it checks that this + binding is still the provider's current one and not off, and refuses otherwise + (``CtxApiError(code=BINDING_STALE)``) — a client of a stale binding sends nothing, however a + call got hold of it. Attributes pass through unchanged.""" + + __slots__ = ("_current", "_inner") + + def __init__(self, inner: Any, current: Callable[[], bool]) -> None: + self._inner = inner + self._current = current + + def __getattr__(self, name: str) -> Any: + value = getattr(self._inner, name) + if not callable(value): + return value + current = self._current + + def call(*args: Any, **kwargs: Any) -> Any: + if not current(): + raise CtxApiError(BINDING_STALE_TEXT, code=BINDING_STALE) + return value(*args, **kwargs) + + return call @dataclass @@ -184,6 +216,24 @@ def clients(self) -> tuple[CtxClient, ...]: return tuple(c for c in (self.read_client, self.write_client, self.store_client) if c is not None) +@dataclass(frozen=True) +class _Lease: + """One snapshot of the binding, taken under the binding lock by the gate (:meth:`_lease`): a call + selects its group, clients and access context from it alone, never from what a + re-initialization put in place meanwhile, and a group's clients refuse to send once it is stale. + ``generation`` counts the ``initialize`` calls; ``decided``: an access decision was taken.""" + + generation: int + group: _GroupBinding | None + client: Any + context: Any + active: bool + base_url: str + home_scope: str + bound_turn: tuple[str, ...] | None + decided: bool + + def _plain(value: Any) -> Any: """``value`` with every mapping a dict and every tuple a list (a stable JSON form).""" if isinstance(value, Mapping): @@ -868,14 +918,16 @@ def _bind_group(self, decision: Any) -> None: ) self._prove_group(self._group) - def _group_client(self, narrowing: Any) -> CtxClient: - return CtxClient( + def _group_client(self, narrowing: Any, group: _GroupBinding) -> Any: + """A client of ``group``'s binding: it sends only while that binding is current.""" + inner = CtxClient( self._base_url, self._api_key, timeout=float(self._config.get("api_timeout") or 10.0), synthesis_timeout=float(self._config.get("synthesis_timeout") or 90.0), narrowing=narrowing, ) + return _BindingClient(inner, lambda: self._group_current(group)) def _resolve_group(self, group: _GroupBinding, budget: float) -> str: """The group's read set, write and store scope and its clients (``""``), or why it cannot @@ -884,7 +936,7 @@ def _resolve_group(self, group: _GroupBinding, budget: float) -> str: ``whoami``, raised as ``CtxApiError`` when it fails).""" read, write = group.fields_read, group.fields_write if not (read and write): - raw = _narrowing.whoami_raw(self._group_client(None), narrowed=False, budget_s=budget) + raw = _narrowing.whoami_raw(self._group_client(None, group), narrowed=False, budget_s=budget) home, scopes = raw.get("home_scope"), raw.get("read_scopes") if not isinstance(home, str) or not home or not isinstance(scopes, list): return "the key's whoami names no home scope or read scopes" @@ -894,12 +946,14 @@ def _resolve_group(self, group: _GroupBinding, budget: float) -> str: return f"the key reads more than {_access.READ_MAX} scopes; name the group's in field read" group.read, group.write = tuple(read), write group.store = "" if group.strict else (group.fields_store or write) - group.read_client = self._group_client(_narrowing.Narrowing(read=group.read)) if group.read else None + group.read_client = self._group_client(_narrowing.Narrowing(read=group.read), group) if group.read else None group.write_client = ( - self._group_client(_narrowing.Narrowing(read=(write,), write=write)) if group.capture else None + self._group_client(_narrowing.Narrowing(read=(write,), write=write), group) if group.capture else None ) group.store_client = ( - self._group_client(_narrowing.Narrowing(read=(group.store,), write=group.store)) if group.store else None + self._group_client(_narrowing.Narrowing(read=(group.store,), write=group.store), group) + if group.store + else None ) return "" @@ -1037,16 +1091,28 @@ def _retry_group_proof(self) -> None: self._note_verified_binding(previous) self._invalidate_prefetch() - def _client_proven(self, kind: str, client: Any) -> bool: + def _group_current(self, group: _GroupBinding | None) -> bool: + """Whether ``group`` is still the binding of this instance and the instance is not off (a + group object belongs to one ``initialize``).""" + return group is not None and not self._access_off and self._group is group + + def _lease_current(self, lease: _Lease) -> bool: + """Whether the binding ``lease`` was taken from is still the current one and not off.""" + return not self._access_off and self._binding_generation == lease.generation and self._group is lease.group + + def _client_proven(self, kind: str, client: Any, group: Any = _CURRENT) -> bool: """The write (``"write"``) or the store client's (``"store"``) own proof before its first write (design 02 §4.2 step 5): its narrowed ``whoami`` reports its narrowing (E5), names the group's tenant when the group does (E2), and the write client's scope is the key's home (E3). Once per binding; a network failure is asked again after :data:`PROOF_RETRY_S`, a - refusal never. The profile's connection was proven on connect (True).""" - group = self._group + refusal never; a proof that completes after the binding changed or went off counts for + nothing. ``group``: the binding of the call's snapshot (default: the current one). The + profile's connection was proven on connect (True).""" + if group is _CURRENT: + group = self._group if group is None: return not self._access_off - if self._access_off or client is None or "group" not in group.proven: + if not self._group_current(group) or client is None or "group" not in group.proven: return False if client is not (group.write_client if kind == "write" else group.store_client): return False # pinned to an earlier binding @@ -1060,6 +1126,8 @@ def _client_proven(self, kind: str, client: Any) -> bool: client, narrowed=True, budget_s=float(self._access_settings.get("verify_timeout_s") or 3) ) except CtxApiError as exc: + if exc.code == BINDING_STALE: + return False # the binding changed or went off while the proof waited if _proof_transient(exc): group.retry_at[kind] = self._now() + PROOF_RETRY_S logger.warning( @@ -1100,9 +1168,12 @@ def _client_proven(self, kind: str, client: Any) -> bool: ) self._record_clients_refused(group) return False - group.proven.add(kind) - if kind == "write" and self._group is group: - self._rate_limit_write = _write_limit(raw) + with self._binding_lock: + if not self._group_current(group): + return False # turned off or re-initialized while the whoami was on its way + group.proven.add(kind) + if kind == "write": + self._rate_limit_write = _write_limit(raw) return True def _record_clients_refused(self, group: _GroupBinding) -> None: @@ -1115,31 +1186,53 @@ def _record_clients_refused(self, group: _GroupBinding) -> None: self._record_access_state(group.context, f"bound; {reasons}", rules=group.refused_rules) def _access_gate(self) -> bool: - """Whether this instance may reach ctx now (design 02 §4.3, §4.6): it is not off, the turn - (when one runs) serves the access group and fields the agent was built for, and no narrowed - client lost its narrowing. A mismatch or a lost narrowing turns the instance off for the rest - of the agent, never rebinds it. Without an access decision (no ``initialize`` yet) there is - nothing to compare.""" - if self._access_off: - return False - if self._decision is None: - return True + """Whether this instance may reach ctx now (:meth:`_lease`).""" + return self._lease() is not None + + def _snapshot(self) -> _Lease | None: + """The binding as it is now, taken under the binding lock; None while the instance is off.""" + with self._binding_lock: + if self._access_off: + return None + return _Lease( + generation=self._binding_generation, + group=self._group, + client=self._client, + context=self._access_context(), + active=self._active, + base_url=self._base_url, + home_scope=self._home_scope, + bound_turn=self._bound_turn, + decided=self._decision is not None, + ) + + def _lease(self) -> _Lease | None: + """The gate (design 02 §4.3, §4.6) and the one snapshot a call works on: the instance is not + off, the turn (when one runs) serves the access group and fields the snapshot's binding was + built for, and none of its narrowed clients lost its narrowing. A mismatch or a lost + narrowing turns that binding off for the rest of the agent, never rebinds it. The snapshot + is taken first, so a re-initialization while the gate runs cannot slip its binding under the + call. Without an access decision (no ``initialize`` yet) there is nothing to compare.""" + lease = self._snapshot() + if lease is None or not lease.decided: + return lease current = _access.current_access() - if current is not None and _turn_key(current) != self._bound_turn: - self._turn_off("trip wire: this turn's access group or fields differ from the agent's binding") - return False - group = self._group + if current is not None and _turn_key(current) != lease.bound_turn: + self._turn_off("trip wire: this turn's access group or fields differ from the agent's binding", lease) + return None + group = lease.group if group is not None and any(client.narrowing_lost for client in group.clients()): - self._turn_off("narrowing_lost: a ctx answer came without the echo of this binding's narrowing") - return False - return True + self._turn_off("narrowing_lost: a ctx answer came without the echo of this binding's narrowing", lease) + return None + return lease - def _turn_off(self, reason: str) -> None: + def _turn_off(self, reason: str, lease: _Lease | None = None) -> None: """Off for the rest of this agent (trip wire, lost narrowing): no client, no recall, no write. Under the binding lock, which a proof holds only to publish (never across its whoami): it - waits for a publication in progress and is never overwritten by it.""" + waits for a publication in progress and is never overwritten by it. ``lease``: the snapshot + that found the cause; a binding built since is not turned off for it.""" with self._binding_lock: - if self._access_off: + if self._access_off or (lease is not None and not self._lease_current(lease)): return self._access_off = reason self._active = False @@ -1174,36 +1267,44 @@ def _record_access_state(self, context: Any, state: str, *, rules: Mapping[str, except Exception: logger.debug("CTX access status not recorded", exc_info=True) - def _recall_allowed(self) -> bool: + def _recall_allowed(self, lease: Any = _CURRENT) -> bool: """Recall before a turn: always on the profile's connection, a group only with ``recall``.""" - group = self._group + group = self._group if lease is _CURRENT else (lease.group if lease is not None else None) return group is None or group.recall - def _writer_client(self) -> Any: - """The client automatic writes go through (chain, facts, digests, mirror), without network: - the profile's one client, or a proven group's write client (it exists with ``capture`` only); - None when nothing is written.""" - if self._access_off: + def _writer_client(self, lease: Any = _CURRENT) -> Any: + """The client automatic writes go through (chain, facts, digests, mirror), without network, + from the call's snapshot (default: the binding now): the profile's one client, or a proven + group's write client (it exists with ``capture`` only); None when nothing is written.""" + if lease is _CURRENT: + lease = self._snapshot() + if lease is None: return None - group = self._group + group = lease.group if group is None: - return self._client + return lease.client if "group" not in group.proven or "write" in group.refused: return None return group.write_client - def _ready_writer(self) -> Any: + def _ready_writer(self, lease: Any = _CURRENT) -> Any: """:meth:`_writer_client` once its own proof holds (the group's write client proves itself before its first write), else None.""" - client = self._writer_client() - return client if client is not None and self._client_proven("write", client) else None + if lease is _CURRENT: + lease = self._snapshot() + client = self._writer_client(lease) + if client is None or lease is None: + return None + return client if self._client_proven("write", client, lease.group) else None - def _no_writer_reason(self) -> str: + def _no_writer_reason(self, lease: Any = _CURRENT) -> str: """Why a compaction has no client to write through: ``inactive`` (0.19.1's word) on the profile's connection, otherwise :data:`NO_BINDING` with the cause (no key value).""" - group = self._group - if self._access_off: - return f"{NO_BINDING} ({self._access_off})" + if lease is _CURRENT: + lease = self._snapshot() + group = lease.group if lease is not None else None + if self._access_off or lease is None: + return f"{NO_BINDING} ({self._access_off or 'the binding changed'})" if group is None: return "inactive" if "group" not in group.proven: @@ -1216,27 +1317,29 @@ def _no_writer_reason(self) -> str: def _tool_client(self, tool_name: str) -> tuple[Any, str]: """The client an agent tool goes through, or None and why not (``""``: the provider is not - active): the profile's one client; a group's read client for the read tools and its store - client, once proven, for ``ctx_store`` (unrestricted groups only).""" - if not self._access_gate(): + active), from the one snapshot the gate took: the profile's one client; a group's read client + for the read tools and its store client, once proven, for ``ctx_store`` (unrestricted groups + only). A group's client sends only while its binding is current.""" + lease = self._lease() + if lease is None: return None, f"CTX is off for this session ({NO_BINDING})" - group = self._group - if not self._active: + if not lease.active: return None, "" + group = lease.group if group is None: - return self._client, "" + return lease.client, "" if tool_name == STORE_TOOL: client = group.store_client - if client is not None and self._client_proven("store", client): + if client is not None and self._client_proven("store", client, group): return client, "" return None, f"CTX tool {STORE_TOOL} is not available for this access group" - if tool_name in READ_TOOLS and self._client is not None: - return self._client, "" + if tool_name in READ_TOOLS and lease.client is not None: + return lease.client, "" return None, f"CTX tool {tool_name} is not available for this access group" - def _offered_tools(self) -> tuple[str, ...] | None: + def _offered_tools(self, lease: Any = _CURRENT) -> tuple[str, ...] | None: """The agent tools a group binding offers (``None``: the profile's connection, all of them).""" - group = self._group + group = self._group if lease is _CURRENT else lease.group if group is None: return None offered = READ_TOOLS if group.read_client is not None else () @@ -1244,20 +1347,23 @@ def _offered_tools(self) -> tuple[str, ...] | None: offered = (*offered, STORE_TOOL) return offered - def _write_tags(self, agent_tags: Any, hook: str) -> list[str]: + def _write_tags(self, agent_tags: Any, hook: str, context: Any = _CURRENT) -> list[str]: """The tags of one write: the agent's (reserved prefixes dropped), the origin tags and, for a - session of an access group, ``server:<platform>:<server>`` and ``group:<group>``.""" + session of an access group (``context``: of the call's snapshot, default the binding now), + ``server:<platform>:<server>`` and ``group:<group>``.""" tags = merge_tags(agent_tags, self._profile, hook) - context = self._access_context() + if context is _CURRENT: + context = self._access_context() if context is not None: for tag in (f"server:{context.platform}:{context.scope_id}", f"group:{context.group}"): if len(tag) <= _MAX_TAG_LEN and tag not in tags: tags.append(tag) return tags - def _access_metadata(self) -> dict[str, str] | None: + def _access_metadata(self, context: Any = _CURRENT) -> dict[str, str] | None: """``ctx_plugin.access`` of the chain: where it was written from (provenance, no rights).""" - context = self._access_context() + if context is _CURRENT: + context = self._access_context() if context is None: return None return { @@ -1269,7 +1375,7 @@ def _access_metadata(self) -> dict[str, str] | None: def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None: """Per-turn tick: the trip wire (design 02 §4.6).""" - self._access_gate() + self._lease() def _invalidate_prefetch(self) -> None: """Drop the pre-warmed recall and orphan warm-ups still in flight.""" @@ -1338,11 +1444,13 @@ def get_tool_schemas(self) -> list[dict[str, Any]]: binding the read tools with a read client and ``ctx_store`` with a store client.""" from .tools import get_tool_schemas as _schemas - if not self._access_gate(): + lease = self._lease() + if lease is None: return [] - offered = self._offered_tools() + offered = self._offered_tools(lease) schemas = _schemas() - return schemas if offered is None else [schema for schema in schemas if schema.get("name") in offered] + chosen = schemas if offered is None else [schema for schema in schemas if schema.get("name") in offered] + return chosen if self._lease_current(lease) else [] def handle_tool_call(self, tool_name: str, args: dict[str, Any], **kwargs) -> str: from .tools import handle_tool_call as _handle @@ -1352,14 +1460,16 @@ def handle_tool_call(self, tool_name: str, args: dict[str, Any], **kwargs) -> st # -- Static prompt block --------------------------------------------------- def system_prompt_block(self) -> str: - if not self._active or not self._access_gate(): + lease = self._lease() + if lease is None or not lease.active: return "" - offered = self._offered_tools() + offered = self._offered_tools(lease) if offered is not None: - return self._group_prompt_block(offered) + block = self._group_prompt_block(offered, lease) + return block if self._lease_current(lease) else "" lines = [ "# CTX Long-Term Memory", - f"Active. Server: {display_url(self._base_url)} · scope: {self._home_scope or '?'}.", + f"Active. Server: {display_url(lease.base_url)} · scope: {lease.home_scope or '?'}.", "Tools: ctx_query (recall, optional LLM synthesis), ctx_store (persist), ctx_search (lightweight), " "ctx_get (block detail).", "Conventions: one fact per block (~1–1.5k chars); store curated facts, never raw dialog dumps.", @@ -1367,9 +1477,9 @@ def system_prompt_block(self) -> str: ] return "\n".join(lines) - def _group_prompt_block(self, offered: tuple[str, ...]) -> str: + def _group_prompt_block(self, offered: tuple[str, ...], lease: _Lease) -> str: """The block of a group binding: server, tenant and write scope, and only the tools offered.""" - group = self._group + group = lease.group if group is None or not offered: return "" described = { @@ -1380,7 +1490,7 @@ def _group_prompt_block(self, offered: tuple[str, ...]) -> str: } lines = [ "# CTX Long-Term Memory", - f"Active for this access group. Server: {display_url(self._base_url)} · tenant: " + f"Active for this access group. Server: {display_url(lease.base_url)} · tenant: " f"{group.tenant or group.tenant_seen or '?'} · write scope: {group.write or '?'}.", "Tools: " + ", ".join(described[name] for name in described if name in offered) + ".", ] @@ -1400,12 +1510,13 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: fresh pre-warmed cache entry when available, otherwise queries now. """ self._last_recall_count = 0 - if not self._access_gate() or not self._recall_allowed(): - return "" - # One read: the gate and the recall see the same binding (a re-init after the gate + # One snapshot: the gate and the recall see the same binding (a re-init after the gate # neither redirects this turn's query nor leaves a None for _recall to resolve). - client = self._client - if not self._active or not self._config.get("auto_recall", True) or not client: + lease = self._lease() + if lease is None or not self._recall_allowed(lease): + return "" + client = lease.client + if not lease.active or not self._config.get("auto_recall", True) or not client: return "" entry = self._recall_entry() q = (query or "").strip() @@ -1436,22 +1547,21 @@ def queue_prefetch(self, query: str, *, session_id: str = "") -> None: if not self._access_gate(): return self._retry_group_proof() - if not self._active or not self._config.get("auto_recall", True) or not self._client: - return - if not self._recall_allowed(): - return q = (query or "").strip() if not q: return - # Generation first, then the client: a re-init in between bumps the generation past + # Generation first, then the snapshot: a re-init in between bumps the generation past # this warm-up, so a pinned previous client can never publish under the new one. with self._prefetch_lock: generation = self._prefetch_generation # Pin the warm-up to the binding it was queued under: a re-init replaces # ``_client``, and the query must not reach the next binding's server. - client = self._client - if client is None: + lease = self._lease() + if lease is None or not lease.active or not self._config.get("auto_recall", True) or not lease.client: + return + if not self._recall_allowed(lease): return + client = lease.client entry = self._recall_entry() def _warm() -> None: @@ -1723,10 +1833,19 @@ def _auto_store( *, block_type: str | None = None, entry: _cp.EntryState | None = None, + access_context: Any = _CURRENT, ) -> bool: """One automatic store with provenance tags + result logging. Never raises.""" return self._auto_store_result( - client, hook, category, title, content, sensitivity, block_type=block_type, entry=entry + client, + hook, + category, + title, + content, + sensitivity, + block_type=block_type, + entry=entry, + access_context=access_context, )[0] def _auto_store_result( @@ -1742,6 +1861,7 @@ def _auto_store_result( timeout: float | None = None, block_type: str | None = None, entry: _cp.EntryState | None = None, + access_context: Any = _CURRENT, ) -> tuple: """Like ``_auto_store`` but returns ``(ok, block_id)``. Never raises. ``timeout`` bounds the store (the required facts pass the time their deadline leaves); without it the client's own. @@ -1756,7 +1876,7 @@ def _auto_store_result( "CTX %s store skipped: no client (profile=%s, %s/%s)", hook, self._profile, category, log_title ) return False, "" - tags = self._write_tags(None, hook) + tags = self._write_tags(None, hook, access_context) extra: dict[str, Any] = {} if metadata: extra["metadata"] = metadata @@ -1877,11 +1997,12 @@ def on_memory_write(self, action: str, target: str, content: str, metadata: dict no delete-by-key API — the old block stays, Dream mode can supersede). A group binding mirrors through its write client (``capture``), proven before its first write. """ - if not self._access_gate(): + lease = self._lease() + if lease is None: return - client = self._writer_client() + client = self._writer_client(lease) if ( - not self._active + not lease.active or not self._write_enabled or not self._config.get("auto_capture", True) or not self._config.get("auto_memory_mirror", True) @@ -1896,12 +2017,20 @@ def on_memory_write(self, action: str, target: str, content: str, metadata: dict sensitivity = self._config.get("sensitivity_default") def _run() -> None: - if not self._client_proven("write", client): + if not self._client_proven("write", client, lease.group): return safe = self._redacted(content) if safe is None: return - self._auto_store(client, "memory_write", category, derive_title(safe, prefix=prefix), safe, sensitivity) + self._auto_store( + client, + "memory_write", + category, + derive_title(safe, prefix=prefix), + safe, + sensitivity, + access_context=lease.context, + ) self._spawn_write(_run) @@ -1975,8 +2104,9 @@ def _pre_compress( api_version = self.pre_compress_checkpoint_api_version # A group binding writes through its write client (``capture``), proven before its first # write; a session the access decision or the trip wire turned off writes nothing. - client = self._ready_writer() if self._access_gate() else None - connected = bool(self._active and client) + lease = self._lease() + client = self._ready_writer(lease) if lease is not None else None + connected = bool(lease is not None and lease.active and client) # The chain archives evidence in every agent context (labelled, never dropped); # facts stay behind the cron/flush/subagent write gate. chain_set = bool(self._config.get("checkpoint_chain", True)) @@ -1989,7 +2119,7 @@ def _pre_compress( if not (chain_on or facts_on): if require_checkpoint: reason = ( - self._no_writer_reason() + self._no_writer_reason(lease) if not connected else ( "checkpoint_chain disabled and facts write-gated for this agent context" @@ -2001,7 +2131,8 @@ def _pre_compress( return "" # #299: the chain and the required facts after it write against the process-wide state of # this server entry (its error answers in a row, its booked writes of the window). - entry = self._chain().entry = _cp.entry_state(self._entry_key()) + chain = self._chain(client, lease) + entry = chain.entry = _cp.entry_state(self._entry_key()) # P4: select facts BEFORE the chain write so their dedupe keys ride in the head/ # manifest metadata (``fact_hashes``); keys already stored for this root are skipped. @@ -2035,6 +2166,7 @@ def _pre_compress( # The required facts are stored in the chain's run after it (#299): planned with it. extra_writes=len(facts) if require_checkpoint else 0, runs=runs, + chain=chain, ) except CtxCheckpointError as exc: self._last_chain_error = exc @@ -2107,7 +2239,7 @@ def _pre_compress( # one was written: paced against the entry's window, counted in its error answers. run = getattr(receipt, "run", None) if run is None: - run = self._chain().new_run( + run = chain.new_run( started=started, deadline=deadline, budget_s=budget, @@ -2117,20 +2249,21 @@ def _pre_compress( ) runs.append(run) facts_text = self._checkpoint_facts_sync( - _PacedFactStore(self._chain(), run), + _PacedFactStore(chain, run), facts, sensitivity, len(source), deadline=run.deadline, ledger=ledger, chain_stored=bool(chain_text), + access_context=lease.context, ) return self._join_receipt(chain_text, facts_text) if not facts: return chain_text def _run() -> None: - self._store_facts(client, facts, sensitivity, ledger=ledger, entry=entry) + self._store_facts(client, facts, sensitivity, ledger=ledger, entry=entry, access_context=lease.context) self._spawn_write(_run) lines = "\n".join(f"- {shorten(self._redacted(f) or '', 300)}" for f in facts) @@ -2152,15 +2285,18 @@ def _join_receipt(chain_text: str, facts_text: str) -> str: facts_text = shorten(facts_text, max(0, room)) return f"{chain_text}\n\n{facts_text}" if facts_text else chain_text - def _chain(self) -> ChainWriter: - """The chain writer of the current write client (:meth:`_writer_client`), with the tags and - the ``ctx_plugin.access`` provenance of the session's access group.""" - client = self._writer_client() + def _chain(self, client: Any = _CURRENT, lease: Any = _CURRENT) -> ChainWriter: + """The chain writer of ``client`` (default: the current write client, :meth:`_writer_client`), + with the tags and the ``ctx_plugin.access`` provenance of the access group of ``lease`` (the + call's snapshot; default: the binding now).""" + if client is _CURRENT: + client = self._writer_client() + context = self._access_context() if lease is _CURRENT else (lease.context if lease is not None else None) if self._chain_writer is None or self._chain_writer.client is not client: write_tags = self._write_tags def _tags(base: list[str]) -> list[str]: - return write_tags(list(base), "checkpoint") + return write_tags(list(base), "checkpoint", context) self._chain_writer = ChainWriter( client=client, @@ -2173,7 +2309,7 @@ def _tags(base: list[str]) -> list[str]: profile=self._profile, secret=self._bound_secrets(), notify=self._checkpoint_notice, - access=self._access_metadata(), + access=self._access_metadata(context), **self._chain_writer_seams(), ) # The write limit the writing key's whoami reported (P-G follows it; None: not reported). @@ -2203,12 +2339,13 @@ def _write_chain( host_wait_s: float = 0.0, extra_writes: int = 0, runs: list[Any] | None = None, + chain: ChainWriter | None = None, ) -> str: """Synchronous chain write; raises ``CtxCheckpointError``. Returns the upstream receipt frame. A run the chain leaves open for the required facts (``extra_writes``) goes to ``runs``.""" root = self._checkpoint_root() host_api = self._probe_host_api() - receipt = self._chain().write( + receipt = (chain or self._chain()).write( source, host_api=host_api, negotiated_api=self._negotiate(host_api), @@ -2258,6 +2395,7 @@ def _checkpoint_facts_sync( deadline: float | None = None, ledger: FactLedger | None = None, chain_stored: bool = False, + access_context: Any = _CURRENT, ) -> str: """Required path: store every fact now within the deadline (each store bounded by the time left), return a receipt with block IDs. @@ -2320,6 +2458,7 @@ def _left(i: int, reason: str) -> str: sensitivity, timeout=max(0.5, min(api_timeout, remaining)), block_type=SESSION_DIGEST_TYPE, + access_context=access_context, ) if safe is not None else (False, "") @@ -2364,6 +2503,7 @@ def _store_facts( ledger: FactLedger | None = None, *, entry: _cp.EntryState | None = None, + access_context: Any = _CURRENT, ) -> dict[str, int]: """``entry``: the server entry of ``client``, taken with it when the write was scheduled (:meth:`_store_typed`).""" @@ -2379,6 +2519,7 @@ def _store_facts( sensitivity, block_type=SESSION_DIGEST_TYPE, entry=entry, + access_context=access_context, ): stored += 1 else: @@ -2397,12 +2538,15 @@ def _store_facts( # -- P5: session digests per segment ------------------------------------------------ - def _digest_enabled(self) -> bool: + def _digest_enabled(self, lease: Any = _CURRENT) -> bool: """Digests are written (a group binding: through its write client, with ``capture``).""" + if lease is _CURRENT: + lease = self._snapshot() return bool( - self._active + lease is not None + and lease.active and self._write_enabled - and self._writer_client() + and self._writer_client(lease) and self._config.get("auto_capture", True) and self._config.get("auto_session_digest", True) ) @@ -2429,10 +2573,11 @@ def on_session_end(self, messages: list[dict[str, Any]]) -> None: trigger = "compaction" if self._compaction_pending else "end" self._compaction_pending = False self._cancel_idle_timer() - if not self._access_gate(): + lease = self._lease() + if lease is None: return - if not self._digest_enabled(): - if self._active: + if not self._digest_enabled(lease): + if lease.active: logger.info( "CTX session_end digest skipped (profile=%s, trigger=%s): %s", self._profile, @@ -2442,7 +2587,7 @@ def on_session_end(self, messages: list[dict[str, Any]]) -> None: else "auto_capture/auto_session_digest off", ) return - self._digest(messages, trigger, hook="session_end") + self._digest(messages, trigger, hook="session_end", lease=lease) def sync_turn( self, @@ -2460,7 +2605,8 @@ def sync_turn( if not self._access_gate(): return self._retry_group_proof() - if not self._digest_enabled() or messages is None: + lease = self._lease() + if lease is None or not self._digest_enabled(lease) or messages is None: return try: root = self._root_session_id or self._session_id or "unknown" @@ -2472,12 +2618,12 @@ def sync_turn( if (every_n > 0 and pending >= every_n) or ( every_h > 0 and pending >= min_n and (time.time() - state.since_ts) >= every_h * 3600.0 ): - self._digest(messages, "rolling", hook="digest_rolling") - self._arm_idle_timer(messages) + self._digest(messages, "rolling", hook="digest_rolling", lease=lease) + self._arm_idle_timer(messages, lease.generation) except Exception as exc: # never break the host worker logger.debug("CTX sync_turn digest check failed: %s", _cp.redacted_traceback(exc, self._bound_secrets())) - def _arm_idle_timer(self, messages: list[dict[str, Any]]) -> None: + def _arm_idle_timer(self, messages: list[dict[str, Any]], generation: int | None = None) -> None: minutes = float(self._config.get("idle_digest_minutes") or 0.0) if minutes <= 0: return @@ -2487,7 +2633,9 @@ def _arm_idle_timer(self, messages: list[dict[str, Any]]) -> None: if self._idle_timer is not None: self._idle_timer.cancel() timer = threading.Timer( - minutes * 60.0, ctx_bound(self._on_idle), args=(snapshot, root, self._binding_generation) + minutes * 60.0, + ctx_bound(self._on_idle), + args=(snapshot, root, self._binding_generation if generation is None else generation), ) timer.daemon = True timer.name = "ctx-idle-digest" @@ -2501,22 +2649,28 @@ def _cancel_idle_timer(self) -> None: self._idle_timer = None def _on_idle(self, snapshot: list[dict[str, Any]], root: str, generation: int | None = None) -> None: - """The idle digest of the binding the timer was armed under (``generation``): after a - re-initialization it writes nothing, even for the same session root.""" + """The idle digest of the binding the timer was armed under (``generation``): its snapshot + is taken once and checked against that generation, and the digest is stored through that + snapshot's writer only; after a re-initialization it writes nothing, even for the same + session root.""" with self._idle_lock: self._idle_timer = None - if generation is not None and generation != self._binding_generation: + lease = self._lease() + if lease is None or (generation is not None and generation != lease.generation): return - if root != (self._root_session_id or self._session_id or "unknown") or not self._digest_enabled(): + if root != (self._root_session_id or self._session_id or "unknown") or not self._digest_enabled(lease): return try: - self._digest(snapshot, "idle", hook="digest_idle") + self._digest(snapshot, "idle", hook="digest_idle", lease=lease) except Exception as exc: logger.debug("CTX idle digest failed: %s", _cp.redacted_traceback(exc, self._bound_secrets())) - def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: str) -> bool: - """Claim the next segment for the not-yet-digested exchanges and store it async. - Returns True when a store was scheduled.""" + def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: str, lease: Any = _CURRENT) -> bool: + """Claim the next segment for the not-yet-digested exchanges and store it async through the + writer of ``lease`` (the call's snapshot; default: the binding now); a stale snapshot stores + nothing and releases the exchanges. Returns True when a store was scheduled.""" + if lease is _CURRENT: + lease = self._snapshot() root = self._root_session_id or self._session_id or "unknown" state = self._digest_state(root) min_n = int(self._config.get("digest_min_exchanges") or 4) @@ -2559,7 +2713,9 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: if manifest_id: metadata["manifest_id"] = manifest_id sensitivity = self._config.get("sensitivity_default") - client = self._writer_client() + client = self._writer_client(lease) + group = lease.group if lease is not None else None + context = lease.context if lease is not None else None entry = _cp.entry_state(self._entry_key()) logger.info( "CTX %s digest scheduled (profile=%s, trigger=%s, root=%s, seg=%d, exchanges=%d)", @@ -2572,7 +2728,8 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: ) def _run() -> None: - if not self._client_proven("write", client): # a group's write client proves itself first + # A group's write client proves itself first; a snapshot gone stale writes nothing. + if client is None or not self._client_proven("write", client, group): state.release(new) return safe = self._redacted(digest) @@ -2587,6 +2744,7 @@ def _run() -> None: metadata=metadata, block_type=SESSION_DIGEST_TYPE, entry=entry, + access_context=context, ) if safe is not None else (False, "") diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_host_contract.py b/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_host_contract.py index fa9ab1820..d71c3dfa2 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_host_contract.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_host_contract.py @@ -87,7 +87,7 @@ def test_write_threads_inherit_the_callers_context(make_provider, monkeypatch): def test_idle_timer_runs_in_the_callers_context(make_provider, monkeypatch): p, _ = make_provider(config={"idle_digest_minutes": 0.005, "digest_every_exchanges": 0}) seen = [] - monkeypatch.setattr(p, "_digest", lambda messages, trigger, *, hook: seen.append(PROFILE_VAR.get())) + monkeypatch.setattr(p, "_digest", lambda messages, trigger, *, hook, **_lease: seen.append(PROFILE_VAR.get())) token = PROFILE_VAR.set("profile-b") try: p.sync_turn("u", "a", messages=[{"role": "user", "content": "x"}]) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py index c1fbbd117..3fd62fced 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py @@ -314,3 +314,53 @@ def digest_state(root): pc._settle(provider) assert fake.count("/api/store") == 0 assert all(block["scope"] != A_MODS for block in fake.blocks.values()) + + +def test_a_store_proof_answered_after_a_turn_off_counts_for_nothing(world, monkeypatch): + """The whoami is sent and answered, the turn-off comes before the proof is entered: the store + client stays unproven and nothing is stored.""" + fake, _host, home = world + fields = {**pc.OPS_FIELDS, "store": pc.A_K} + provider = pc._provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + group = provider._group + answered, go = threading.Event(), threading.Event() + real = _nar.whoami_raw + + def whoami_raw(client, *, narrowed, budget_s): + answer = real(client, narrowed=narrowed, budget_s=budget_s) + narrowing = getattr(client, "narrowing", None) + if narrowed and narrowing is not None and narrowing.write == pc.A_K: + answered.set() + assert go.wait(WAIT_S) + return answer + + monkeypatch.setattr(_nar, "whoami_raw", whoami_raw) + fake.reset_counters() + t1, box = _run(lambda: provider.handle_tool_call("ctx_store", {"category": "c", "title": "t", "content": "x"})) + assert answered.wait(WAIT_S) + provider._turn_off("trip wire: a turn of another group") + go.set() + assert '"error"' in _joined(t1, box) + assert "store" not in group.proven and fake.count("/api/store") == 0 + + +def test_a_client_that_refused_itself_leaves_the_proof_store_alone(world): + """A group client of a binding no longer current refuses before it sends; that refusal is the + caller's and never answers the next binding's proof with the same key and narrowing.""" + fake, _host, home = world + provider = _ops(home) + stale = provider._group.read_client + _nar.reset_proofs() + provider.initialize( + "s-2", + hermes_home=str(home), + platform="discord", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=pc.OPS_FIELDS), + ) + _nar.reset_proofs() + with pytest.raises(_client.CtxApiError) as refused: + _nar.whoami_raw(stale, narrowed=True, budget_s=3.0) + assert refused.value.code == "binding_stale" + fake.reset_counters() + assert _nar.whoami_raw(provider._group.read_client, narrowed=True, budget_s=3.0)["narrowed"]["read"] == [pc.A_K] + assert fake.count("/api/whoami") == 1 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py index 485477c12..3c4b395e1 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py @@ -216,10 +216,10 @@ def _checkpoint( provider.initialize(session, platform="cli", warning_callback=notices.append) chain = provider._chain - def bound_chain(): + def bound_chain(*args, **kwargs): # The binding sets the limit on the writer each checkpoint uses; so does the test, whatever - # builds or rebinds the writer in between. - writer = chain() + # builds or rebinds the writer in between (the checkpoint passes its snapshot's client). + writer = chain(*args, **kwargs) writer.rate_limit_write = reported return writer diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_error_text_redaction.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_error_text_redaction.py index 09996d103..965db0d81 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_error_text_redaction.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_error_text_redaction.py @@ -395,7 +395,7 @@ def test_digest_debug_lines_carry_no_key(home, caplog, monkeypatch): def boom(*args, **kwargs): raise CtxApiError(f"digest refused for key {CTX_KEY}") - monkeypatch.setattr(provider, "_digest_enabled", lambda: True) + monkeypatch.setattr(provider, "_digest_enabled", lambda *_lease: True) monkeypatch.setattr(provider, "_digest_state", boom) monkeypatch.setattr(provider, "_digest", boom) with caplog.at_level(logging.DEBUG): From b9f2f13157035d6b5bb4d15df2d62ce7b69a0ca4 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:33:12 +0100 Subject: [PATCH 33/65] test(ctx_checkpoint): a trip found on an old snapshot spares the binding built since, a head is recorded under its own binding, and a refusal of a stale client is nobody's proof Pins what the first mutant run of the snapshot fix left open: the turn-off of a binding built after a call took its snapshot, the pointer binding a checkpoint records its head under when the instance is built again before it ends, a binding_stale refusal kept out of the proof store for a caller with less time, and a store proof cut short by a turn-off not taken for a refusal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../tests/test_access_binding_races.py | 70 ++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py index 3fd62fced..68c1323b8 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py @@ -256,6 +256,7 @@ def whoami_raw(client, *, narrowed, budget_s): result = _joined(t1, box) assert '"error"' in result assert fake.count("/api/store") == 0 + assert "store" not in provider._group.refused, "a proof the turn-off cut short is no refusal of the client" def test_a_read_tool_never_answers_from_the_binding_a_reinitialize_put_in_place(world, monkeypatch): @@ -362,5 +363,72 @@ def test_a_client_that_refused_itself_leaves_the_proof_store_alone(world): _nar.whoami_raw(stale, narrowed=True, budget_s=3.0) assert refused.value.code == "binding_stale" fake.reset_counters() - assert _nar.whoami_raw(provider._group.read_client, narrowed=True, budget_s=3.0)["narrowed"]["read"] == [pc.A_K] + # A caller with less time than the refused one had: a remembered refusal would answer it. + assert _nar.whoami_raw(provider._group.read_client, narrowed=True, budget_s=1.0)["narrowed"]["read"] == [pc.A_K] assert fake.count("/api/whoami") == 1 + + +def test_a_trip_found_on_an_old_snapshot_never_turns_off_the_binding_built_since(world, monkeypatch): + """A call of group ops runs in a turn of group mods: its gate finds the mismatch only after the + instance was built again for mods — the old snapshot is refused, the mods binding stays.""" + fake, host, home = world + _add_mods(fake, host) + provider = _ops(home) + arrived, go = threading.Event(), threading.Event() + real = _acc.current_access + + def current_access(): + if threading.current_thread().name == "race-t1" and not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + return real() + + monkeypatch.setattr(_acc, "current_access", current_access) + mods_turn = ah.make_access(group="mods", profile="members", restricted=False, fields=MODS_FIELDS) + + def call_in_a_mods_turn(): + with ah.turn(mods_turn): + return provider.handle_tool_call("ctx_search", {"query": "plans"}) + + t1, box = _run(call_in_a_mods_turn) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + go.set() + assert '"error"' in _joined(t1, box) + assert provider._active and not provider._access_off, "the mods binding stands" + with ah.turn(mods_turn): + assert "bravo knowledge" in provider.handle_tool_call("ctx_search", {"query": "plans"}) + + +def test_a_checkpoint_records_its_head_under_the_binding_it_started_under(world, monkeypatch): + """The instance is built again for group mods while an ops checkpoint ends: the ops head is never + named to mods (whose read tools read its own chain).""" + fake, host, home = world + _add_mods(fake, host) + provider = _ops(home) + status = ah.plugin_module(pc._PKG, "memory.status") + arrived, go = threading.Event(), threading.Event() + real = status.checkpoint_outcome + + def checkpoint_outcome(**kwargs): + if not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + return real(**kwargs) + + monkeypatch.setattr(status, "checkpoint_outcome", checkpoint_outcome) + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + t1, box = _run(lambda: provider.on_pre_compress(pc._messages(tag="o"), require_checkpoint=True)) + assert arrived.wait(WAIT_S) + provider.initialize( + "s-1", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs( + scope_id="111", group="mods", group_restricted=False, fields={**MODS_FIELDS, "read": [pc.B_K, A_MODS]} + ), + ) + go.set() + head = _joined(t1, box).split("`")[1] + assert provider._active and head not in provider.system_prompt_block() From da331a32978ff197ae3c11ee8367b362873f3d18 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:33:12 +0100 Subject: [PATCH 34/65] docs(ctx_checkpoint): a governed session waits for its markers on disk, and a write of a replaced binding is dropped, not finished README (sessions without an access group; what this does not promise) and CHANGELOG 0.20.0 name the changed promises: a governed session is served only once its markers are written (a full disk or a busy lock leaves it off until a later initialize); every call works on one snapshot of the binding, a client of a binding replaced or turned off since sends nothing (binding_stale), and a write the old binding had not sent is dropped; a whoami without an answer within one caller's short budget is no proof for a caller with more time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- integrations/hermes/plugin/ctx_checkpoint/README.md | 9 +++++++-- .../hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md | 8 +++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 349f3bab5..12a05f293 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -458,7 +458,9 @@ The platform of a session is the one the gateway bound for its turn, else the on agent before a turn). A profile that has served a restricted group gets no ctx for any session without its group, on any Hermes. Both are markers in `ctx_state/access-mode.json` (`governed_seen`, `restricted_seen`): they only rise, survive the state -pruning, and only `hermes ctx_checkpoint access reset-marker` lowers them. +pruning, and only `hermes ctx_checkpoint access reset-marker` lowers them. A session of a governed group +is served only once the markers it raises are on disk: while `ctx_state` cannot be written (a full disk, +a lock another process holds), that session gets no ctx, and the next `initialize` tries again. A fork (`delegate_task`, a checkpoint fork) counts as local when its parent session was: Hermes binds the platform of a gateway session to the session, and for a CLI or TUI session the plugin takes the @@ -681,7 +683,10 @@ settings write with a tenant-admin key of the group's home scope, or ctx's globa - **Rights changed after a binding** are proven again at the next agent build; until then the reads stay within the narrowing. A deactivated key fails from its next request on; a base-block text already given to a session stays in its prompt until a new session or `base_rev`. -- **Writes after a group change**: a worker of the old agent finishes in the old group's scope. +- **Writes after a group change**: every call works on the binding the gate checked; a client of a + binding that was replaced or turned off since sends nothing, so a write the old binding scheduled and + had not sent is dropped (its exchanges count again for the next digest). A request already on its way + when the change happens finishes in the old group's scope. - **Without access groups in Hermes** the plugin cannot tell a member from an operator: `ungoverned: local` keeps Discord sessions out of an operator profile, and the member profiles of `ctx_discord_policy` carry no memory provider. diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 526e9a063..ce359ca4f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -35,7 +35,13 @@ older server a group binding is off and the profile's own connection works as be required narrowing, exact read and write sets, label `hermes:<platform>:<server>:<profile>`, the narrowing echoed, no foreign key with file tools in the profile). A lost echo, a group change within a turn or a failed proof turns the agent off. Blocks a group writes carry `server:`/`group:` tags - and the chain `ctx_plugin.access`. + and the chain `ctx_plugin.access`. A governed session is served only once its markers are on disk + (a full disk or a busy lock leaves it off until a later `initialize`). Every call works on one + snapshot of the binding: a client of a binding that was replaced or turned off since sends nothing + (client code `binding_stale`), a proof that completes after that counts for nothing, and a turn-off + is never overwritten by a proof's publication. A `whoami` that got no answer within one caller's + short budget is no proof for a caller with more time (what ctx answered still holds for every + caller of the key). - **Base blocks** (`base_blocks.py`): the hook answers with the group's base blocks as its prompt text, after the same proof, in one `get` with `ids` (one per id on a server without it), never a partial text; its own thread pool (`base_workers`, default 32, measured) and budget (`base_timeout_s`, at From 1e7a61daad763462cb5d72833679f108444de43b Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:23:49 +0100 Subject: [PATCH 35/65] =?UTF-8?q?fix(ctx=5Fcheckpoint):=20a=20first=20prov?= =?UTF-8?q?ision=20run=20deactivates=20no=20key=20=E2=80=94=20only=20--rep?= =?UTF-8?q?lace=20sends=20replace=5Flabel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two first runs for different groups of one server and profile could both pass the key check; both sent replace_label, so the later commit deactivated the earlier group's key although nobody asked for --replace (PR #596 review, comment 4815624939). Now only --replace sends replace_label. A run that stopped between ctx and its .env line is still repeated without a switch: the profile home records in ctx_state/access-provision.pending that it sent a set for the label, and the repeat deactivates, by id (api-key-update), the member keys of the label in the group's scope that the .env does not hold, before it asks for a new one; a key of the label that is no member key is refused, as replace_label refuses it. A key of the label that the .env does not hold and no run of this home left (another machine with a profile of the same name, or a removed .env line) is refused without --replace. A set ctx refused (4xx) leaves no record. ctx mints a second active key of a label when replace_label is not sent (store/keyset.go keysetReplaceTx returns before any check; context_api_keys.label is not unique), so two machines that provision one server with a profile of the same name at the same moment can both end with an active key; neither deactivates the other's. The fake answers api-key-update as ctx does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 22 +- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 4 +- .../ctx_checkpoint/memory/access_cli.py | 115 ++++++-- .../ctx_checkpoint/tests/fakes/ctx_server.py | 43 ++- .../tests/test_access_pe_rules.py | 2 +- .../tests/test_access_pe_tools.py | 3 +- .../test_access_seam_provision_conflicts.py | 5 +- .../tests/test_access_seam_provision_race.py | 246 ++++++++++++++++++ 8 files changed, 400 insertions(+), 40 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 349f3bab5..e0b994697 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -602,11 +602,17 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co per server and profile: give the second group a profile of its own) and a group whose scope is the home of another key (another group of the server whose name maps to the same scope); the same group again is refused while its key is in the profile's `.env`, and `--replace` rotates it (a new key, the - earlier one deactivated). Nothing is written when ctx refuses (a 4xx answer; a reached `max_keys` or - `max_scopes` answers 429). Without a clear answer (no answer in time, a 5xx or a proxy error) the set - may have been created and the earlier key of the label may already be inactive: run the same command - again — `replace_label` deactivates the key of the earlier run, so one key per label stays active and - lands in the `.env`. The `.env` is read again just before the write, so a line another writer added + earlier one deactivated); only `--replace` sends `replace_label`, so a first run deactivates no key. A + key of the label that the `.env` does not hold is refused as well (another machine with a profile of + this name), unless a run of this profile left it: the profile notes in + `ctx_state/access-provision.pending` that it sent a set, until the set's `.env` line is written. + Nothing is written when ctx refuses (a 4xx answer; a reached `max_keys` or `max_scopes` answers 429). + Without a clear answer (no answer in time, a 5xx or a proxy error) the set may have been created (with + `--replace`, the earlier key of the label may already be inactive): run the same command again — it + deactivates the key the earlier run made, by its id, so one key per label stays active and lands in + the `.env`. ctx itself makes a second active key of a label when `replace_label` is not sent, so two + machines that provision one server with a profile of the same name at the same moment can both end + with a key. The `.env` is read again just before the write, so a line another writer added meanwhile stays. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id or group name no scope or variable name can hold, a `--profile` other than the profile the command @@ -858,7 +864,8 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). to the ctx server a group's fields name (else the profile's), with the group's key and the narrowing headers: `whoami` to prove a binding, the group's recall, tools and writes, and from the hook one `get` for the group's base blocks; `hermes ctx_checkpoint access check` and - `access provision` call `whoami` and `keyset-provision` when you run them. No third-party + `access provision` call `whoami` and `keyset-provision` (`provision` also `api-key-list`, and + `api-key-update` for the key of a run that stopped before its `.env` line) when you run them. No third-party services, no telemetry. - **Data sent:** direct user/assistant text of the turns about to be compacted; with memory features on also the mirrored `MEMORY.md`/`USER.md` entries, the @@ -930,7 +937,8 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). base blocks, mode 0600, written only on a change) with the lock `access.lock`, and `ctx_state/access-sessions.state` (once per platform and connection: messaging sessions that ran without an access group, also on a Hermes without access groups). `access provision` writes one - line into the profile's `.env` (under `ctx_state/env-provision.lock`) and + line into the profile's `.env` (under `ctx_state/env-provision.lock`), + `ctx_state/access-provision.pending` (the labels it sent a set for and wrote no line for yet) and `memory.ctx_checkpoint.ungoverned` into `config.yaml`; `access reset-marker` writes the markers. - **No** shell commands, background network beyond the above, stored credentials (but the key `access provision` writes into the profile's `.env` when you run it) or self-updating code. diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 526e9a063..39e85cd74 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -50,7 +50,9 @@ older server a group binding is off and the profile's own connection works as be `hermes memory status` is not ok while a binding, or one of its clients, is off for another reason than its group's own fields. `provision` replaces no key silently: it asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope another key homes; the same group - again needs `--replace` while its key is in the `.env`. `access check` reads the group's key from the + again needs `--replace` while its key is in the `.env`. Only `--replace` sends `replace_label`: the + repeat of a run that stopped before its `.env` line deactivates that run's key by its id, and a key + of the label no run of the profile left is refused. `access check` reads the group's key from the profile's `.env` and secret sources only, never from the shell's environment. - Fixed before release: the state pruning (`state_retention_days`) deleted the markers after 30 days and a session whose root id was `access-mode` wrote its fact ledger over them (both kept now); a diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index b7f87f380..919e5dc95 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -3,9 +3,10 @@ Operator tools for access-group bindings (design 02 §4.7): ``status`` reads the per-binding status files without network; ``check`` proves a group's fields (E1 to E7) and names every broken rule with the expected value, then the configuration warnings; ``provision`` computes scope names and the -label, calls ctx's ``keyset-provision`` with ``replace_label`` and a tenant-admin key read from a named -variable (never stored), adds the new key to the profile's ``.env`` and prints the ``/policy`` lines -(``--emit-yaml``: the whole group entry); ``reset-marker`` lowers the profile's markers. +label, checks ctx's list of the tenant's keys, calls ``keyset-provision`` (``replace_label`` only with +``--replace``) with a tenant-admin key read from a named variable (never stored), adds the new key to +the profile's ``.env`` and prints the ``/policy`` lines (``--emit-yaml``: the whole group entry); +``reset-marker`` lowers the profile's markers. Every command works on the home it is given (the CLI's: the profile ``hermes -p <profile>`` runs in). The plugin never reads the core's ``gateway.access_groups`` (design 02 A02-L9): ``check`` takes the @@ -70,6 +71,10 @@ _BASE_URL_ENV = re.compile(r"^(?:CTX_BASE_URL|CTX_BASE_URL_[A-Z0-9_]+)$") # Serializes this tool's writes of a profile's .env (in ctx_state/; Hermes' own writers take none). ENV_LOCK_FILE = "env-provision.lock" +# The labels this profile home sent a keyset-provision for and wrote no .env line for yet (in ctx_state/, +# a JSON object label -> time; no .json name, so the state pruning keeps it). Only a key of such a run is +# retired without --replace; a key of the label this home never sent a set for is another machine's. +PENDING_FILE = "access-provision.pending" _STANDARD_KEYS = ("CTX_KEY", "CTX_API_KEY") _BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz" _REVOKE = ( @@ -687,6 +692,20 @@ def _write_env_line(home: str, env_path: Path, name: str, value: str) -> None: _atomic_write(env_path, _env_with(current, name, value)) +def _stopped_runs(home: str) -> dict[str, Any]: + """The labels of :data:`PENDING_FILE` (a missing or unreadable file: none).""" + return _status._read_json_file(Path(home) / FACT_STATE_DIR / PENDING_FILE) or {} + + +def _record_run(home: str, label: str, *, sent: bool) -> None: + """Note in :data:`PENDING_FILE` that this home sent a set for *label* (``sent``) or that the run is + over (its ``.env`` line is written, or ctx refused the set). Raises ``OSError`` on a failed write.""" + runs = {name: when for name, when in _stopped_runs(home).items() if name != label} + if sent: + runs[label] = _status._now_text() + _status._write_json_file(Path(home) / FACT_STATE_DIR / PENDING_FILE, runs) + + def _manage_once(url: str, key: str, payload: Mapping[str, Any]) -> dict[str, Any]: """One ``POST /api/manage`` with *key*, without the client's 429 retry (a refused set wrote nothing; asking again changes nothing). Errors are ``CtxApiError`` with the key redacted.""" @@ -791,7 +810,7 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: print(f" ✗ {missing} is not set; nothing was sent") return 1 try: - conflict = _key_conflict( + conflict, stopped_keys = _key_conflict( url, admin_key, label=label, @@ -799,6 +818,7 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: variable=variable, env_value=_env_values(home).get(variable, ""), replace=args.replace, + stopped=label in _stopped_runs(home), ) except ValueError: # a URL CtxClient does not take (no http(s), no host) print(f" ✗ {_status.display_url(url) or url!r} is no http(s) URL of a ctx server; nothing was sent") @@ -810,6 +830,25 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: if conflict: print(f" ✗ {conflict}. Nothing was created") return 1 + try: # before ctx changes: a run that stops from here on is recognized by the repeat + _record_run(home, label, sent=True) + except OSError as exc: + record = Path(home) / FACT_STATE_DIR / PENDING_FILE + print(f" ✗ {record} cannot be written ({type(exc).__name__}); nothing was sent") + return 1 + for key_id in stopped_keys: # the keys a stopped run of this home made, by id (never the label's others) + retire = {"action": "api-key-update", "data": {"id": key_id, "active": False}} + try: + retired = _manage_once(url, admin_key, retire) + except _client.CtxApiError as exc: + retired = {"error": _status.redact_error(exc, (admin_key,))} + if retired.get("success") is not True: + print( + f" ✗ ctx did not deactivate the key {key_id} a stopped run of this profile made " + f"({str(retired.get('error') or '')[:120]}); nothing was created" + ) + return 1 + print(f" key {key_id} of a run that stopped before its .env line: deactivated") request = { "action": "keyset-provision", "data": { @@ -821,7 +860,7 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: "allowed_scopes": [knowledge, *extra], "write_scopes": [], "scope_narrowing": "required", - "replace_label": True, + "replace_label": bool(args.replace), # a first run or a repeat deactivates no key of the label } ], }, @@ -834,19 +873,21 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: except _client.CtxApiError as exc: cause = _status.redact_error(exc, (admin_key,)) if exc.status is not None and 400 <= exc.status < 500: + with contextlib.suppress(OSError): # nothing was made: no stopped run to repeat + _record_run(home, label, sent=False) print(f" ✗ ctx refused the key set, nothing was created: {cause}") else: # no answer, or a server or proxy error: ctx may have committed the set print( - f" ✗ no clear answer from ctx ({cause}): whether the key set was created is unknown, and the key " - "of an earlier run of this label may be inactive now. Run the same command again: it replaces " - "any key of this label (replace_label), so one key stays active and lands in the .env" + f" ✗ no clear answer from ctx ({cause}): whether the key set was created is unknown (with " + "--replace, the earlier key of this label may be inactive now). Run the same command again: it " + "deactivates the key this run may have made, so one key stays active and lands in the .env" ) return 1 made = _made_key(answer, label, own, [_full_name(scope) for scope in (knowledge, *extra)]) if isinstance(made, str): print( - f" ✗ {made}. A key may have been created at ctx; run the same command again: it replaces it " - "(replace_label), so one key stays active" + f" ✗ {made}. A key may have been created at ctx; run the same command again: it deactivates " + "that key, so one key stays active" ) return 1 secret, slug, scopes = made @@ -855,14 +896,16 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: except (OSError, ValueError) as exc: print( f" ✗ the key was created at ctx but {env_path} could not be written ({type(exc).__name__}); run the same " - "command again: it replaces the key (replace_label), so one key stays active" + "command again: it deactivates that key, so one key stays active" ) return 1 + with contextlib.suppress(OSError): # the run is over; a record that stays only allows its own repeat + _record_run(home, label, sent=False) for entry in scopes: print(f" ctx scope {entry.get('scope')} ({'created' if entry.get('created') else 'there already'})") print( - f" key: {variable} in {env_path} (label {label}, key digest {narrowing.key_digest(secret)}); " - "an earlier key of this label is inactive now" + f" key: {variable} in {env_path} (label {label}, key digest {narrowing.key_digest(secret)})" + + ("; an earlier key of this label is inactive now" if args.replace else "") ) print( f" sessions bound with an earlier key of this label lose ctx until their agent is rebuilt; " @@ -893,15 +936,19 @@ def _env_values(home: str) -> dict[str, str]: def _key_conflict( - url: str, admin_key: str, *, label: str, own: str, variable: str, env_value: str, replace: bool -) -> str: + url: str, admin_key: str, *, label: str, own: str, variable: str, env_value: str, replace: bool, stopped: bool +) -> tuple[str, list[str]]: """Why this set would replace something it must not, from ctx's own list of the tenant's active keys - (``api-key-list`` with the tenant-admin key; ``""``: nothing). A key serves one group per server and - profile: its label names them, its home is the group's scope. Refused: (1) the label's key homed in - another group's scope; (2) the group's scope homing a key of another label (another server, profile - or group whose name maps to the same scope); (3) without *replace*, a key of this group in the - ``.env`` already (rotation is asked for, not done by a repeat). A run that stopped before its - ``.env`` line finds its key at ctx and none in the ``.env``: it repeats.""" + (``api-key-list`` with the tenant-admin key; ``""``: nothing), and the ids of the keys a stopped run + of this home left (to retire before the set). A key serves one group per server and profile: its + label names them, its home is the group's scope. Refused: (1) the label's key homed in another + group's scope; (2) the group's scope homing a key of another label (another server, profile or group + whose name maps to the same scope); (3) without *replace*, a key of this group in the ``.env`` + already (rotation is asked for, not done by a repeat); (4) without *replace*, a key of the label at + ctx that the ``.env`` does not hold and no stopped run of this home (*stopped*: the home recorded + that it sent a set for the label and wrote no line) explains — another machine's key. With + *stopped*, those keys are the stopped run's: the repeat retires them by id, without + ``replace_label`` (only *replace* sends it), so it never deactivates another group's key.""" who = _client.CtxClient(url, admin_key, timeout=REQUEST_TIMEOUT_S).whoami() slug = who.get("tenant_slug") if isinstance(who, Mapping) and who.get("success") is not False else None if not isinstance(slug, str) or not access.SLUG_PATTERN.match(slug): @@ -924,21 +971,35 @@ def _key_conflict( f"the key {label} of this server and profile is homed in {key.get('home_scope')}, the scope of " f"another group: a key serves one group per server and profile, so give this group another " f"profile (or deactivate that key first if its group is gone)" - ) + ), [] for key in mine: if key.get("home_scope") == target and key.get("label") != label: return ( f"{target} is the home of the key {key.get('label') or '(no label)'}: another group of this server " f"uses that scope (group names that differ only in _ and - share it); give this group another name" - ) - if env_value and not replace: - held = any(key.get("label") == label for key in mine) + ), [] + held = [key for key in mine if key.get("label") == label] + if replace: + return "", [] + if env_value: where = f"its key {label} is active at ctx" if held else f"ctx has no active key {label}" return ( f"{variable} in the profile's .env holds a key for this server and profile already ({where}); " f"--replace makes a new key for this same group and deactivates the earlier one" - ) - return "" + ), [] + if held and not stopped: + return ( + f"ctx has an active key {label} of this group that the profile's .env does not hold, and no run of " + f"this profile left it (another machine with a profile of this name, or a line removed from the " + f".env); --replace makes a new key for this group and deactivates that one" + ), [] + for key in held: # provision makes member keys only; ctx's replace_label spares every other key too + if key.get("tenant_role") != "member": + return ( + f"the key {key.get('id')} labelled {label} is a {key.get('tenant_role') or 'non-member'} key, not " + f"one provision made; revoke it with api-key-delete" + ), [] + return "", [str(key.get("id") or "") for key in held] def _full_name(scope: str) -> str: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py index 43080d6b6..1a8d34847 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -52,7 +52,7 @@ ) NARROWED_ACTIONS = frozenset({"get", "type-list"}) # The actions of /api/manage the fake answers; ctx knows more, the plugin sends no other. -MANAGE_ACTIONS = frozenset({"get", "type-list", "keyset-provision", "api-key-list"}) +MANAGE_ACTIONS = frozenset({"get", "type-list", "keyset-provision", "api-key-list", "api-key-update"}) MAX_READ_SCOPES = 8 MAX_IDS = 16 MIN_ID_PREFIX = 8 # store.MinIDPrefixLen @@ -475,9 +475,50 @@ def _manage( return 403, {"success": False, "error": "admin key required"}, echo if action == "api-key-list": return 200, self._api_key_list(key, body), echo + if action == "api-key-update": + status, payload = self._api_key_update(key, body) + return status, payload, echo status, payload = self._keyset_provision(key, body) return status, payload, echo + def _api_key_update(self, caller: FakeKey, body: Mapping[str, Any]) -> tuple[int, dict[str, Any]]: + """``api-key-update`` with ``active`` only, the one field the plugin sends + (go:context_manage.go handleApiKeyUpdate, store.UpdateApiKey): ``id`` required (400), something + to change (400); the caller's tenant (a ctx server admin: any) — another tenant's key, no key or + a malformed id answer 200 ``key not found``; a server-admin key only a server admin changes, an + owner key only an owner (403). The answer carries the changed key.""" + data = body.get("data") if isinstance(body.get("data"), dict) else {} + active = data.get("active") + if active is not None and not isinstance(active, bool): # the decode fails first + return _plain(400, "Invalid data: expected {id, tenant_role?, active?}") + key_id = str(data.get("id") or "") + if not key_id: + return _plain(400, "id is required") + if active is None: + text = "nothing to update (provide tenant_role, active, write_scopes and/or scope_narrowing)" + return _plain(400, text) + with self.lock: + target = next((k for k in self.keys.values() if k.id == key_id), None) + if target is None or not (caller.admin or target.tenant == caller.tenant): + return 200, {"success": False, "error": "key not found"} + if target.admin and not caller.admin: + return _plain(403, "server-admin key may only be managed by a server-admin") + if target.role == "owner" and not (caller.admin or caller.role == "owner"): + return _plain(403, "owner key may only be managed by an owner or server-admin") + target.active = active + shown = { + "id": target.id, + "label": target.label, + "home_scope": target.home, + "allowed_scopes": list(target.allowed), + "tenant_role": target.role, + "write_scopes": list(target.write_scopes), + "scope_narrowing": target.scope_narrowing, + "active": target.active, + "created_at": NOW, + } + return 200, {"success": True, "key": shown} + def _api_key_list(self, caller: FakeKey, body: Mapping[str, Any]) -> dict[str, Any]: """``api-key-list`` (go:context_manage.go handleApiKeyList, store.ListApiKeys): the caller's tenant (a ctx server admin: every tenant), active keys unless ``data.active_only`` is false, diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py index 15c16a51f..551a97878 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -492,7 +492,7 @@ def test_provision_sends_only_what_ctx_decodes(admin): (spec,) = call["data"]["keys"] assert set(spec) == {"label", "home_scope", "allowed_scopes", "write_scopes", "scope_narrowing", "replace_label"} assert spec["label"] == LABEL and spec["scope_narrowing"] == "required" and spec["write_scopes"] == [] - assert spec["replace_label"] is True and spec["home_scope"] in call["data"]["scopes"] + assert spec["replace_label"] is False and spec["home_scope"] in call["data"]["scopes"] # a first run assert spec["allowed_scopes"][1:] == ["t:d111-extra"] assert all(cli.SCOPE_NAME.match(name) for name in call["data"]["scopes"]) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py index 0aee04ad7..fa0138ed6 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py @@ -102,7 +102,8 @@ def test_provision_twice_leaves_one_active_key_per_label(fake_ctx, monkeypatch, assert _provision(tmp_path, "--emit-yaml") == 0 assert _provision(tmp_path, "--replace") == 0 # rotating the group's key is asked for (fresh review, finding 2) calls = [r.body for r in fake_ctx.requests("/api/manage") if r.action == "keyset-provision"] - assert len(calls) == 2 and all(k.get("replace_label") for c in calls for k in c["data"]["keys"]) + # Only the rotation sends replace_label: a first run deactivates no key (PR review, 4815624939). + assert [k.get("replace_label") for c in calls for k in c["data"]["keys"]] == [False, True] labels = [k.label for k in fake_ctx.keys.values() if k.active and k.label.startswith("hermes:")] assert labels == ["hermes:discord:111:members"] out = capsys.readouterr().out diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py index fcc61fe6d..fb1566801 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py @@ -8,8 +8,9 @@ - the same group again is refused while its key is in the profile's ``.env``; ``--replace`` rotates it. A run that stopped before it wrote the ``.env`` line repeats without ``--replace``: ctx holds the key of -the same label in the same scope, the ``.env`` holds none, and ``replace_label`` deactivates it. The -one-call collision of ``a_b``/``a-b`` (S1, L-PE-3) is unchanged and tested where it was.""" +the same label in the same scope, the ``.env`` holds none, the home recorded the run, and the repeat +deactivates that key by id (``test_access_seam_provision_race.py``). The one-call collision of +``a_b``/``a-b`` (S1, L-PE-3) is unchanged and tested where it was.""" from __future__ import annotations diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py new file mode 100644 index 000000000..84904d807 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py @@ -0,0 +1,246 @@ +"""``access provision`` against runs that interleave (PR review of the plugin layer). The interleavings +are made with event barriers around the manage call that changes ctx, never by guessing with sleeps. + +A first run never deactivates a key: only ``--replace`` sends ``replace_label``. A run that stopped +between ctx and its ``.env`` line is repeated without a switch: the profile home recorded that it sent +the set, and the repeat deactivates exactly the keys of that run (by id, ``api-key-update``), never a +key of the label another machine made. ctx itself mints a key of a label that an active key already +carries when ``replace_label`` is not sent (go:internal/store/keyset.go ``keysetReplaceTx`` returns +before any check without it; ``context_api_keys.label`` is not unique, go:migrations/113_baseline.sql +around line 5221), so two machines that serve one server with a profile of the same name can end with +two active keys of that label; neither run deactivates the other's.""" + +from __future__ import annotations + +import threading + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_provision_race") +cli = ah.plugin_module(_PKG, "memory.access_cli") + +ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_race" +LABEL = "hermes:discord:111:members" +WAIT_S = 10.0 # the most a barrier waits: a run that never reaches it fails the test, it does not hang + + +@pytest.fixture +def ctx(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "process-home")) + return fake_ctx + + +def _home(root, profile="members"): + home = root / "profiles" / profile + home.mkdir(parents=True, exist_ok=True) + return home + + +def _provision(home, group, *extra): + argv = ["provision", "--server", "discord:111", "--profile", "members", "--group", group] + return cli.run_access([*argv, "--admin-key-env", "CTX_ADMIN", *extra], hermes_home=str(home)) + + +def _labelled(fake): + return [key for key in fake.keys.values() if key.label == LABEL] + + +def _env(home): + return (home / ".env").read_text(encoding="utf-8") + + +def _sent(fake, action): + return [r.body for r in fake.requests("/api/manage") if r.action == action] + + +class _Gate: + """Holds the run of one thread at its ``keyset-provision`` call: ``before`` (the call not sent yet, + the key check passed) or ``after`` (ctx committed, the answer not handed back yet), until + ``finish``. Runs of other threads pass.""" + + def __init__(self, monkeypatch, where: str) -> None: + self.reached = threading.Event() + self.release = threading.Event() + self.thread: threading.Thread | None = None + real = cli._manage_once + + def gated(url, key, payload): + mine = threading.current_thread() is self.thread and payload.get("action") == "keyset-provision" + if mine and where == "before": + self.reached.set() + assert self.release.wait(WAIT_S), "the gate was never released" + answer = real(url, key, payload) + if mine and where == "after": + self.reached.set() + assert self.release.wait(WAIT_S), "the gate was never released" + return answer + + monkeypatch.setattr(cli, "_manage_once", gated) + + def start(self, run) -> list: + result: list = [] + self.thread = threading.Thread(target=lambda: result.append(run()), daemon=True) + self.thread.start() + assert self.reached.wait(WAIT_S), "the held run never reached its keyset-provision call" + return result + + def finish(self) -> None: + self.release.set() + assert self.thread is not None + self.thread.join(WAIT_S) + assert not self.thread.is_alive() + + +def _stop_before_the_env_line(monkeypatch, home, group="members"): + """One run that made its key at ctx and stopped before its ``.env`` line (the disk refused it).""" + real = cli._atomic_write + + def broken(path, data): + raise OSError("disk full") + + monkeypatch.setattr(cli, "_atomic_write", broken) + assert _provision(home, group) == 1 + monkeypatch.setattr(cli, "_atomic_write", real) + + +# -- finding 4815624939: a first run deactivates no key ------------------------------------------- + + +def test_a_first_run_sends_no_replace_label_and_replace_sends_it(ctx, tmp_path): + home = _home(tmp_path) + assert _provision(home, "members") == 0 + assert _provision(home, "members", "--replace") == 0 + sent = [call["data"]["keys"][0]["replace_label"] for call in _sent(ctx, "keyset-provision")] + assert sent == [False, True] + + +def test_two_first_runs_on_two_machines_deactivate_no_key(ctx, tmp_path, monkeypatch): + """Two machines serve server 111 with a profile named ``members`` each (one label, no shared lock). + Run A (group members) passed its key check and is about to send its set; run B (group mods) runs + whole meanwhile. A's commit must not deactivate B's key, which nobody asked to replace.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + gate = _Gate(monkeypatch, "before") + result = gate.start(lambda: _provision(host_a, "members")) + assert _provision(host_b, "mods") == 0 + gate.finish() + assert result == [0] + (b_key,) = [key for key in _labelled(ctx) if key.home.endswith("-mods")] + assert b_key.active, "the first run of another machine deactivated a key nobody asked to replace" + assert _env(host_b) == f"CTX_KEY_111_MEMBERS={b_key.secret}\n" + # ctx refuses no second active key of a label without replace_label: both stay (the named gap). + assert sorted(key.home.rsplit("-", 1)[-1] for key in _labelled(ctx) if key.active) == ["members", "mods"] + + +def test_a_key_of_this_group_that_another_machine_holds_is_not_replaced_without_replace(ctx, tmp_path, capsys): + """ctx holds an active key of the label in the group's own scope and this profile's ``.env`` none, + but this home never sent a set for it: another machine's key, not a stopped run of this one.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + assert _provision(host_b, "members") == 0 + (b_key,) = _labelled(ctx) + capsys.readouterr() + assert _provision(host_a, "members") == 1 + out = capsys.readouterr().out + assert "--replace" in out and LABEL in out, out + assert b_key.active and len(_sent(ctx, "keyset-provision")) == 1 and not _sent(ctx, "api-key-update") + assert not (host_a / ".env").exists() + assert _provision(host_a, "members", "--replace") == 0 # asked for: replaced + assert not b_key.active + + +def test_a_stopped_run_is_repeated_without_a_switch_and_retires_only_its_own_key(ctx, tmp_path, monkeypatch): + home = _home(tmp_path) + _stop_before_the_env_line(monkeypatch, home) + (stopped,) = _labelled(ctx) + assert stopped.active and not (home / ".env").exists() + assert _provision(home, "members") == 0 + first, second = _sent(ctx, "keyset-provision") + assert first["data"]["keys"][0]["replace_label"] is False and second["data"]["keys"][0]["replace_label"] is False + assert _sent(ctx, "api-key-update") == [{"action": "api-key-update", "data": {"id": stopped.id, "active": False}}] + (active,) = [key for key in _labelled(ctx) if key.active] + assert not stopped.active and active is not stopped + assert _env(home) == f"CTX_KEY_111_MEMBERS={active.secret}\n" + + +def test_a_stopped_run_s_key_ctx_keeps_active_stops_the_repeat_before_a_new_set(ctx, tmp_path, monkeypatch, capsys): + home = _home(tmp_path) + _stop_before_the_env_line(monkeypatch, home) + (stopped,) = _labelled(ctx) + real = cli._manage_once + + def refusing(url, key, payload): + if payload.get("action") == "api-key-update": + return {"success": False, "error": "key not found"} + return real(url, key, payload) + + monkeypatch.setattr(cli, "_manage_once", refusing) + capsys.readouterr() + assert _provision(home, "members") == 1 + out = capsys.readouterr().out + assert stopped.id in out and "key not found" in out and "nothing was created" in out, out + assert len(_sent(ctx, "keyset-provision")) == 1 and stopped.active and not (home / ".env").exists() + + +def test_the_repeat_retires_no_key_of_the_label_that_is_not_a_member_key(ctx, tmp_path, monkeypatch, capsys): + """provision makes member keys only (as ctx's replace_label spares every other key): an admin key that + carries the label in the group's scope is not a stopped run's key, whoever runs the repeat.""" + home = _home(tmp_path) + _stop_before_the_env_line(monkeypatch, home) + (stopped,) = _labelled(ctx) + admin = ctx.add_key(secret="ctx_admin_key_with_label_1", tenant="t", home=stopped.home, label=LABEL, role="admin") + capsys.readouterr() + assert _provision(home, "members") == 1 + out = capsys.readouterr().out + assert admin.id in out and "api-key-delete" in out, out + assert admin.active and stopped.active and not _sent(ctx, "api-key-update") + assert len(_sent(ctx, "keyset-provision")) == 1 + + +def test_a_key_whose_env_line_the_operator_removed_is_not_taken_for_a_stopped_run(ctx, tmp_path, capsys): + """A run that wrote its line forgets that it sent the set: the key is no stopped run's any more.""" + home = _home(tmp_path) + assert _provision(home, "members") == 0 + (key,) = _labelled(ctx) + (home / ".env").write_text("", encoding="utf-8") + capsys.readouterr() + assert _provision(home, "members") == 1 + assert "--replace" in capsys.readouterr().out + assert key.active and len(_sent(ctx, "keyset-provision")) == 1 and not _sent(ctx, "api-key-update") + + +def test_a_set_ctx_refused_leaves_no_stopped_run_behind(ctx, tmp_path, capsys): + """ctx refused the set (its key quota): nothing was made, so a key of the label that another + machine makes afterwards is not this home's stopped run.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + ctx.max_keys = len([key for key in ctx.keys.values() if key.active]) + assert _provision(host_a, "members") == 1 + assert "nothing was created" in capsys.readouterr().out + ctx.max_keys = None + assert _provision(host_b, "members") == 0 + (b_key,) = _labelled(ctx) + assert _provision(host_a, "members") == 1 + assert b_key.active and not _sent(ctx, "api-key-update") + + +def test_the_fake_deactivates_a_key_by_id_as_ctx_does(ctx): + """``api-key-update`` (go:internal/handler/context_manage.go handleApiKeyUpdate): ``{id, active}``, + the caller's tenant only; another tenant's key or no key answers 200 ``key not found``.""" + member = ctx.add_key(secret="ctx_member_key_for_update_1", tenant="t", home="t:d2ix-members", label=LABEL) + foreign = ctx.add_key(secret="ctx_foreign_key_for_update_1", tenant="u", home="u:main", label=LABEL) + + def update(data): + body = {"action": "api-key-update", "data": data} + return ctx._answer("POST", "/api/manage", "api-key-update", body, ADMIN_KEY, [], [])[:2] + + status, body = update({"id": foreign.id, "active": False}) + assert (status, body) == (200, {"success": False, "error": "key not found"}) and foreign.active + status, body = update({"id": member.id}) + assert status == 400 and body["success"] is False and member.active + status, body = update({"id": member.id, "active": "false"}) + assert (status, body["error"]) == (400, "Invalid data: expected {id, tenant_role?, active?}") and member.active + status, body = update({"id": member.id, "active": False}) + assert status == 200 and body["success"] is True and body["key"]["id"] == member.id + assert body["key"]["active"] is False and not member.active From b84fcb3a7050a661f78313fc08b9ca0b5a45f013 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 08:31:29 +0100 Subject: [PATCH 36/65] fix(ctx_checkpoint): provision runs of one profile home take turns from the key check to the .env line Two rotations of one group could commit K1 and then K2 at ctx and get their answers in reverse order: the later answer wrote K2 into the .env first, the earlier one then wrote the deactivated K1 over it, and both runs reported success (PR #596 review, comment 4815624942). The lock of the .env write alone could not keep the commit order; it also wrote unserialized when it was busy. Now one lock per profile home (ctx_state/access-provision.lock, flock) is held from the key check through the requests that change ctx, the .env line and the record of the run. It fails closed: a run that cannot have it within 5 s, or on a platform or file system without file locks, returns before it sends anything. In one home a second run therefore sees what the first committed (this also turns away a second group of the same server and profile that would have shared its .env variable), and the .env ends with the key ctx committed last. Two machines share no lock; the README says what that leaves open. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 21 ++- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 7 +- .../ctx_checkpoint/memory/access_cli.py | 120 +++++++++++-- .../tests/test_access_seam_provision_race.py | 159 +++++++++++++++++- 4 files changed, 282 insertions(+), 25 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index e0b994697..7a413d8b1 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -609,12 +609,19 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co Nothing is written when ctx refuses (a 4xx answer; a reached `max_keys` or `max_scopes` answers 429). Without a clear answer (no answer in time, a 5xx or a proxy error) the set may have been created (with `--replace`, the earlier key of the label may already be inactive): run the same command again — it - deactivates the key the earlier run made, by its id, so one key per label stays active and lands in - the `.env`. ctx itself makes a second active key of a label when `replace_label` is not sent, so two - machines that provision one server with a profile of the same name at the same moment can both end - with a key. The `.env` is read again just before the write, so a line another writer added - meanwhile stays. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising - `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id + deactivates, by id, the member keys of the label in the group's scope that the `.env` does not hold + (the earlier run's), so one key per label stays active and lands in the `.env`. Runs in one profile + home take turns under `ctx_state/access-provision.lock`, held from the check to the `.env` line: a + second run sees what the first committed, and the `.env` ends with the key ctx committed last. A run + that cannot have the lock within 5 s, or on a platform or file system without file locks, sends + nothing. Two machines share no lock: ctx itself makes a second active key of a label when + `replace_label` is not sent, so two machines that provision one server with a profile of the same + name at the same moment can both end with a key; two rotations there leave one machine with a + deactivated key; and a key the other machine makes for the label after a run here stopped is taken + for that run's key when the run is repeated here (the note does not expire). The `.env` is read again + just before the write, so a line another writer added meanwhile stays. Sessions bound with an earlier + key lose ctx until their agent is rebuilt; raising `ctx_checkpoint.base_rev` of the group rebuilds + them at once. Refused before any request: a server id or group name no scope or variable name can hold, a `--profile` other than the profile the command runs in where the home's profile name is known (`…/profiles/<name>` or the account's default home; run it with `hermes -p <profile>`), a URL that is no http(s) URL, a profile URL of plain `http://` to a @@ -937,7 +944,7 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). base blocks, mode 0600, written only on a change) with the lock `access.lock`, and `ctx_state/access-sessions.state` (once per platform and connection: messaging sessions that ran without an access group, also on a Hermes without access groups). `access provision` writes one - line into the profile's `.env` (under `ctx_state/env-provision.lock`), + line into the profile's `.env` (under `ctx_state/access-provision.lock`), `ctx_state/access-provision.pending` (the labels it sent a set for and wrote no line for yet) and `memory.ctx_checkpoint.ungoverned` into `config.yaml`; `access reset-marker` writes the markers. - **No** shell commands, background network beyond the above, stored credentials (but the key diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 39e85cd74..6f3a35ca4 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -51,8 +51,11 @@ older server a group binding is off and the profile's own connection works as be than its group's own fields. `provision` replaces no key silently: it asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope another key homes; the same group again needs `--replace` while its key is in the `.env`. Only `--replace` sends `replace_label`: the - repeat of a run that stopped before its `.env` line deactivates that run's key by its id, and a key - of the label no run of the profile left is refused. `access check` reads the group's key from the + repeat of a run that stopped before its `.env` line deactivates, by id, the member keys of the label + in the group's scope that the `.env` does not hold, and a key + of the label no run of the profile left is refused. Runs in one profile home take turns under a lock + that fails closed (`ctx_state/access-provision.lock`), from the check to the `.env` line, so the + `.env` ends with the key ctx committed last. `access check` reads the group's key from the profile's `.env` and secret sources only, never from the shell's environment. - Fixed before release: the state pruning (`state_retention_days`) deleted the markers after 30 days and a session whose root id was `access-mode` wrote its fact ledger over them (both kept now); a diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 919e5dc95..9b0f541be 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -5,8 +5,8 @@ the expected value, then the configuration warnings; ``provision`` computes scope names and the label, checks ctx's list of the tenant's keys, calls ``keyset-provision`` (``replace_label`` only with ``--replace``) with a tenant-admin key read from a named variable (never stored), adds the new key to -the profile's ``.env`` and prints the ``/policy`` lines (``--emit-yaml``: the whole group entry); -``reset-marker`` lowers the profile's markers. +the profile's ``.env`` — check, requests and line under the profile's provision lock — and prints the +``/policy`` lines (``--emit-yaml``: the whole group entry); ``reset-marker`` lowers the profile's markers. Every command works on the home it is given (the CLI's: the profile ``hermes -p <profile>`` runs in). The plugin never reads the core's ``gateway.access_groups`` (design 02 A02-L9): ``check`` takes the @@ -34,9 +34,10 @@ import os import re import tempfile +import time import urllib.error import urllib.request -from collections.abc import Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from pathlib import Path from typing import Any @@ -46,6 +47,11 @@ from . import status as _status from .config import FACT_STATE_DIR, derive_profile_name, env_secret, umbrella_section +try: + import fcntl +except ImportError: # no file lock on this platform: provision refuses (its lock fails closed) + fcntl = None # type: ignore[assignment] + # ctx: go/internal/handler/tenant_manage.go scopeNamePattern (name part of <slug>:<name>). SCOPE_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,22}[a-z0-9])?$") # Hermes: hermes_cli/access_fields.py ENV_NAME. @@ -69,8 +75,13 @@ # Bound of one operator request (keyset-provision runs one transaction under the tenant's lock). REQUEST_TIMEOUT_S = 30.0 _BASE_URL_ENV = re.compile(r"^(?:CTX_BASE_URL|CTX_BASE_URL_[A-Z0-9_]+)$") -# Serializes this tool's writes of a profile's .env (in ctx_state/; Hermes' own writers take none). -ENV_LOCK_FILE = "env-provision.lock" +# One provision at a time per profile home (in ctx_state/): its key check, the requests that change ctx, +# its .env line and its record run under this lock, which fails closed — a run that cannot have it +# within PROVISION_LOCK_WAIT_S sends nothing. Hermes' own .env writers take no lock. It binds the runs of +# one machine; runs on two machines share none. +PROVISION_LOCK_FILE = "access-provision.lock" +PROVISION_LOCK_WAIT_S = 5.0 +PROVISION_LOCK_POLL_S = 0.05 # The labels this profile home sent a keyset-provision for and wrote no .env line for yet (in ctx_state/, # a JSON object label -> time; no .json name, so the state pruning keeps it). Only a key of such a run is # retired without --replace; a key of the label this home never sent a set for is another machine's. @@ -683,13 +694,48 @@ def _env_with(text: str, name: str, value: str) -> str: return "".join(out) -def _write_env_line(home: str, env_path: Path, name: str, value: str) -> None: - """``name=value`` into the profile's ``.env``: read again and replaced under a lock just before the - write, so a line another writer added while ctx answered stays (the first read only proved the file - readable). Raises ``OSError``/``ValueError`` when it cannot be read or written.""" - with _status._state_lock(Path(home) / FACT_STATE_DIR, ENV_LOCK_FILE): - current = env_path.read_text(encoding="utf-8") if env_path.exists() else "" - _atomic_write(env_path, _env_with(current, name, value)) +def _write_env_line(env_path: Path, name: str, value: str) -> None: + """``name=value`` into the profile's ``.env`` (the caller holds the provision lock): read again just + before the write, so a line another writer added while ctx answered stays (the first read only proved + the file readable). Raises ``OSError``/``ValueError`` when it cannot be read or written.""" + current = env_path.read_text(encoding="utf-8") if env_path.exists() else "" + _atomic_write(env_path, _env_with(current, name, value)) + + +class _Busy(Exception): + """The provision lock of the profile home cannot be had: nothing was sent.""" + + +@contextlib.contextmanager +def _provision_lock(home: str) -> Iterator[None]: + """The provision lock of *home* (:data:`PROVISION_LOCK_FILE`), held for the key check, the requests + that change ctx and the ``.env`` line. Fails closed: without a file lock on this platform, with a lock + file that cannot be opened, or while another run holds it past :data:`PROVISION_LOCK_WAIT_S`, + ``_Busy`` — before anything is sent. A ``flock`` binds the runs of one machine (and of one file + system that passes it on); runs on two machines share none.""" + if fcntl is None: + raise _Busy("this platform offers no file lock (fcntl), and provision runs only under one") + directory = Path(home) / FACT_STATE_DIR + try: + directory.mkdir(parents=True, exist_ok=True) + fd = os.open(str(directory / PROVISION_LOCK_FILE), os.O_RDWR | os.O_CREAT, 0o600) + except OSError as exc: + raise _Busy(f"the lock file in {directory} cannot be opened ({type(exc).__name__})") from None + try: + deadline = time.monotonic() + PROVISION_LOCK_WAIT_S + while True: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= deadline: + raise _Busy("another provision runs in this profile") from None + time.sleep(PROVISION_LOCK_POLL_S) + except OSError as exc: # a file system without flock (ENOLCK, EINVAL): no lock, no run + raise _Busy(f"the lock file in {directory} cannot be locked ({type(exc).__name__})") from None + yield + finally: + os.close(fd) # releases the lock def _stopped_runs(home: str) -> dict[str, Any]: @@ -809,6 +855,54 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: missing = "the ctx server URL (CTX_BASE_URL or rest_base_url)" if not url else args.admin_key_env print(f" ✗ {missing} is not set; nothing was sent") return 1 + try: + with _provision_lock(home): + return _provision_locked( + args, + home, + platform=platform, + scope_id=scope_id, + profile=profile, + group=group, + roles=roles, + users=users, + knowledge=knowledge, + own=own, + extra=extra, + variable=variable, + label=label, + env_path=env_path, + url=url, + admin_key=admin_key, + ) + except _Busy as exc: + print(f" ✗ {exc}; nothing was sent") + return 1 + + +def _provision_locked( + args: argparse.Namespace, + home: str, + *, + platform: str, + scope_id: str, + profile: str, + group: str, + roles: list[str], + users: list[str], + knowledge: str, + own: str, + extra: list[str], + variable: str, + label: str, + env_path: Path, + url: str, + admin_key: str, +) -> int: + """The part of ``provision`` under the profile's provision lock (:func:`_provision_lock`): the key + check, the retired keys of a stopped run, the set at ctx, the ``.env`` line and the record of the run + — so a second run in this home sees what the first committed, and the ``.env`` ends with the key ctx + committed last. Then the fields.""" try: conflict, stopped_keys = _key_conflict( url, @@ -892,7 +986,7 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: return 1 secret, slug, scopes = made try: - _write_env_line(home, env_path, variable, secret) + _write_env_line(env_path, variable, secret) except (OSError, ValueError) as exc: print( f" ✗ the key was created at ctx but {env_path} could not be written ({type(exc).__name__}); run the same " diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py index 84904d807..399e609e4 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py @@ -3,15 +3,21 @@ A first run never deactivates a key: only ``--replace`` sends ``replace_label``. A run that stopped between ctx and its ``.env`` line is repeated without a switch: the profile home recorded that it sent -the set, and the repeat deactivates exactly the keys of that run (by id, ``api-key-update``), never a -key of the label another machine made. ctx itself mints a key of a label that an active key already +the set, and the repeat deactivates, by id (``api-key-update``), the member keys of the label in the +group's scope that the ``.env`` does not hold — never a key of another group, nor one of the label this +home sent no set for. ctx itself mints a key of a label that an active key already carries when ``replace_label`` is not sent (go:internal/store/keyset.go ``keysetReplaceTx`` returns before any check without it; ``context_api_keys.label`` is not unique, go:migrations/113_baseline.sql around line 5221), so two machines that serve one server with a profile of the same name can end with -two active keys of that label; neither run deactivates the other's.""" +two active keys of that label; neither run deactivates the other's. + +In one profile home, runs take turns under a lock that fails closed, held from the key check through +the requests that change ctx to the ``.env`` line: a second run sees what the first committed, and the +``.env`` ends with the key ctx committed last. A run that cannot have the lock sends nothing.""" from __future__ import annotations +import errno import threading import pytest @@ -244,3 +250,150 @@ def update(data): status, body = update({"id": member.id, "active": False}) assert status == 200 and body["success"] is True and body["key"]["id"] == member.id assert body["key"]["active"] is False and not member.active + + +# -- finding 4815624942: one provision at a time per profile home, check to .env line ------------ +# A run that cannot have the profile's lock within its wait (shortened here: the held run holds it until +# the test releases it, so the wait only bounds the test) returns before it sends anything. + +LOCK_WAIT_S = 0.2 + + +def test_two_rotations_in_one_profile_home_leave_the_active_key_in_the_env(ctx, tmp_path, monkeypatch, capsys): + """Rotation A committed K1 at ctx and its answer is held; rotation B runs meanwhile. Without a lock + around request and line, B would commit K2 (deactivating K1) and save it first, then A would save + the inactive K1.""" + monkeypatch.setattr(cli, "PROVISION_LOCK_WAIT_S", LOCK_WAIT_S) + home = _home(tmp_path) + assert _provision(home, "members") == 0 + gate = _Gate(monkeypatch, "after") + result = gate.start(lambda: _provision(home, "members", "--replace")) + sent = ctx.count() + capsys.readouterr() + assert _provision(home, "members", "--replace") == 1 + out = capsys.readouterr().out + assert "another provision runs in this profile" in out and "nothing was sent" in out, out + assert ctx.count() == sent, "the run without the lock sent a request" + gate.finish() + assert result == [0] + (active,) = [key for key in _labelled(ctx) if key.active] + assert _env(home) == f"CTX_KEY_111_MEMBERS={active.secret}\n" + + +def test_two_first_runs_in_one_profile_home_do_not_share_the_variable(ctx, tmp_path, monkeypatch, capsys): + """Run A (group members) passed its key check and is about to send its set; run B (group mods) runs in + the same profile home meanwhile. Both would pass the check and write the one variable of the server and + profile, the later line naming the other group's key.""" + monkeypatch.setattr(cli, "PROVISION_LOCK_WAIT_S", LOCK_WAIT_S) + home = _home(tmp_path) + gate = _Gate(monkeypatch, "before") + result = gate.start(lambda: _provision(home, "members")) + sent = ctx.count() + capsys.readouterr() + assert _provision(home, "mods") == 1 + assert "another provision runs in this profile" in capsys.readouterr().out + assert ctx.count() == sent + gate.finish() + assert result == [0] + (key,) = _labelled(ctx) + assert key.active and key.home.endswith("-members") and _env(home) == f"CTX_KEY_111_MEMBERS={key.secret}\n" + + +def test_the_lock_is_held_until_the_env_line_is_written(ctx, tmp_path, monkeypatch, capsys): + """Rotation A has its answer and is about to write its ``.env`` line (held at the write); rotation B + runs meanwhile. A lock released with the answer would let B commit and save its key, and A would + then save its own, deactivated one.""" + monkeypatch.setattr(cli, "PROVISION_LOCK_WAIT_S", LOCK_WAIT_S) + home = _home(tmp_path) + assert _provision(home, "members") == 0 + reached, release, held = threading.Event(), threading.Event(), {} + real = cli._atomic_write + + def writing(path, data): + if threading.current_thread() is held.get("thread"): + reached.set() + assert release.wait(WAIT_S), "the write was never released" + return real(path, data) + + monkeypatch.setattr(cli, "_atomic_write", writing) + result: list = [] + run_a = threading.Thread(target=lambda: result.append(_provision(home, "members", "--replace")), daemon=True) + held["thread"] = run_a + run_a.start() + try: + assert reached.wait(WAIT_S), "rotation A never reached its .env line" + sent = ctx.count() + capsys.readouterr() + rc_b = _provision(home, "members", "--replace") + out_b = capsys.readouterr().out + finally: + release.set() + run_a.join(WAIT_S) + assert rc_b == 1 and "another provision runs in this profile" in out_b, out_b + assert ctx.count() == sent and result == [0] + (active,) = [key for key in _labelled(ctx) if key.active] + assert _env(home) == f"CTX_KEY_111_MEMBERS={active.secret}\n" + + +def test_a_second_run_that_gets_the_lock_within_its_wait_goes_on(ctx, tmp_path, monkeypatch): + """The lock is held elsewhere when the run starts and freed while it waits (the barrier: its first + wait step); the run then takes it and provisions.""" + fcntl = pytest.importorskip("fcntl") + home = _home(tmp_path) + (home / "ctx_state").mkdir() + waiting, runner = threading.Event(), {} + real_sleep = cli.time.sleep + + def sleep(seconds): + if threading.current_thread() is runner.get("thread"): + waiting.set() + real_sleep(seconds) + + monkeypatch.setattr(cli.time, "sleep", sleep) + result: list = [] + with open(home / "ctx_state" / "access-provision.lock", "w") as other: + fcntl.flock(other, fcntl.LOCK_EX) + runner["thread"] = threading.Thread(target=lambda: result.append(_provision(home, "members")), daemon=True) + runner["thread"].start() + assert waiting.wait(WAIT_S), "the run never waited for the lock" + assert ctx.count() == 0 + runner["thread"].join(WAIT_S) + assert result == [0] and len(_sent(ctx, "keyset-provision")) == 1 + + +def test_a_provision_lock_another_process_holds_changes_nothing_at_ctx(ctx, tmp_path, monkeypatch, capsys): + fcntl = pytest.importorskip("fcntl") + monkeypatch.setattr(cli, "PROVISION_LOCK_WAIT_S", LOCK_WAIT_S) + home = _home(tmp_path) + (home / "ctx_state").mkdir() + with open(home / "ctx_state" / "access-provision.lock", "w") as held: + fcntl.flock(held, fcntl.LOCK_EX) + assert _provision(home, "members") == 1 + assert "another provision runs in this profile" in capsys.readouterr().out + assert ctx.count() == 0 and not (home / ".env").exists() + assert _provision(home, "members") == 0 + + +def test_a_file_system_that_refuses_the_lock_lets_provision_send_nothing(ctx, tmp_path, monkeypatch, capsys): + real = pytest.importorskip("fcntl") + + class NoLocks: + LOCK_EX, LOCK_NB = real.LOCK_EX, real.LOCK_NB + + @staticmethod + def flock(fd, operation): + raise OSError(errno.ENOLCK, "No locks available") + + monkeypatch.setattr(cli, "fcntl", NoLocks) + home = _home(tmp_path) + assert _provision(home, "members") == 1 + assert "cannot be locked" in capsys.readouterr().out + assert ctx.count() == 0 and not (home / ".env").exists() + + +def test_without_a_file_lock_provision_sends_nothing(ctx, tmp_path, monkeypatch, capsys): + monkeypatch.setattr(cli, "fcntl", None) + home = _home(tmp_path) + assert _provision(home, "members") == 1 + assert "no file lock" in capsys.readouterr().out + assert ctx.count() == 0 and not (home / ".env").exists() From d526ce655bb36bcfdc341b52b557a946bcd48970 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 09:52:49 +0100 Subject: [PATCH 37/65] fix(ctx_checkpoint): provision names ctx's refusal of a taken label, and a repeat retires only the key its note explains ctx now refuses a keyset-provision set without replace_label whose label an active key of the tenant carries (409 with the labels, under the tenant lock, nothing made; a deactivated key does not count). Of two first runs for one label on two machines one gets the key, the other the refusal. provision reads that 409 (status and labels) and says what to do: --replace for a new key of the same group, else a profile of its own, because another group or machine holds the label. It writes no .env line and drops its note, so a later repeat does not take the other key for its own. The note of a stopped run now keeps the key's id once ctx answered; the repeat deactivates only that id, or, when the answer never came, a member key of the label made within 5 minutes of the note (ctx's created_at against the note's time). Any other key of the label is refused without --replace, so a stale note no longer retires a key another machine made since. The repeat deactivates first and then sends without replace_label, which ctx takes because a deactivated key holds no label. If another machine takes the label in between, ctx refuses the repeat's set instead of leaving two active keys. The fake refuses a taken label as ctx does (before scopes and quotas, labels sorted, deactivated keys not counted, the 409 of replace_label at an administrative key with labels too) and stamps created_at. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 38 ++-- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 7 +- .../ctx_checkpoint/memory/access_cli.py | 157 +++++++++++++---- .../ctx_checkpoint/tests/fakes/ctx_server.py | 18 +- .../tests/test_access_seam_provision_race.py | 166 ++++++++++++++++-- .../tests/test_fake_ctx_wire.py | 7 +- 6 files changed, 316 insertions(+), 77 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 9d45d722a..0800405c6 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -604,23 +604,27 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co per server and profile: give the second group a profile of its own) and a group whose scope is the home of another key (another group of the server whose name maps to the same scope); the same group again is refused while its key is in the profile's `.env`, and `--replace` rotates it (a new key, the - earlier one deactivated); only `--replace` sends `replace_label`, so a first run deactivates no key. A - key of the label that the `.env` does not hold is refused as well (another machine with a profile of - this name), unless a run of this profile left it: the profile notes in - `ctx_state/access-provision.pending` that it sent a set, until the set's `.env` line is written. - Nothing is written when ctx refuses (a 4xx answer; a reached `max_keys` or `max_scopes` answers 429). - Without a clear answer (no answer in time, a 5xx or a proxy error) the set may have been created (with - `--replace`, the earlier key of the label may already be inactive): run the same command again — it - deactivates, by id, the member keys of the label in the group's scope that the `.env` does not hold - (the earlier run's), so one key per label stays active and lands in the `.env`. Runs in one profile - home take turns under `ctx_state/access-provision.lock`, held from the check to the `.env` line: a - second run sees what the first committed, and the `.env` ends with the key ctx committed last. A run - that cannot have the lock within 5 s, or on a platform or file system without file locks, sends - nothing. Two machines share no lock: ctx itself makes a second active key of a label when - `replace_label` is not sent, so two machines that provision one server with a profile of the same - name at the same moment can both end with a key; two rotations there leave one machine with a - deactivated key; and a key the other machine makes for the label after a run here stopped is taken - for that run's key when the run is repeated here (the note does not expire). The `.env` is read again + earlier one deactivated); only `--replace` sends `replace_label`, so a first run deactivates no key, + and ctx refuses its set while an active key carries the label (409 naming the labels; the command + then says to use `--replace` for the same group, or a profile of its own when another group or + machine holds the label). A key of the label that the `.env` does not hold is refused as well + (another machine with a profile of this name), unless a run of this profile left it: the profile + notes in `ctx_state/access-provision.pending` that it sent a set and, once ctx answered, the key's + id, until the set's `.env` line is written. Nothing is written when ctx refuses (a 4xx answer; a + reached `max_keys` or `max_scopes` answers 429). Without a clear answer (no answer in time, a 5xx or + a proxy error) the set may have been created (with `--replace`, the earlier key of the label may + already be inactive): run the same command again — it deactivates by id the key the note explains + (the noted id, or without one a member key of the label in the group's scope that ctx made within + 5 minutes of the noted time, by ctx's and this computer's clocks), then asks for a new key, so one + key per label stays active and lands in the `.env`; a key it cannot place that way is refused like + another machine's. Runs in one profile home take turns under `ctx_state/access-provision.lock`, held + from the check to the `.env` line: a second run sees what the first committed, and the `.env` ends + with the key ctx committed last. A run that cannot have the lock within 5 s, or on a platform or file + system without file locks, sends nothing. Two machines share no lock, but ctx decides the label under + its tenant lock: of two first runs at the same moment one gets the key and the other the refusal. + Still open across machines: two rotations with `--replace` leave one machine with a deactivated key; + and a key of the label the other machine made within those 5 minutes of a run here whose answer was + lost is taken for that run's key when the run is repeated here. The `.env` is read again just before the write, so a line another writer added meanwhile stays. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 44c2fb9ac..c2ac74c5a 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -56,9 +56,10 @@ older server a group binding is off and the profile's own connection works as be `hermes memory status` is not ok while a binding, or one of its clients, is off for another reason than its group's own fields. `provision` replaces no key silently: it asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope another key homes; the same group - again needs `--replace` while its key is in the `.env`. Only `--replace` sends `replace_label`: the - repeat of a run that stopped before its `.env` line deactivates, by id, the member keys of the label - in the group's scope that the `.env` does not hold, and a key + again needs `--replace` while its key is in the `.env`. Only `--replace` sends `replace_label`, and + ctx's refusal of a set whose label an active key carries (409 with `labels`) is named with what to do: + the repeat of a run that stopped before its `.env` line deactivates by id the key the run's note + explains (the id ctx answered, or a key made within 5 minutes of the note), and a key of the label no run of the profile left is refused. Runs in one profile home take turns under a lock that fails closed (`ctx_state/access-provision.lock`), from the check to the `.env` line, so the `.env` ends with the key ctx committed last. `access check` reads the group's key from the diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 9b0f541be..b9945b4da 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -38,6 +38,7 @@ import urllib.error import urllib.request from collections.abc import Iterator, Mapping, Sequence +from datetime import datetime from pathlib import Path from typing import Any @@ -83,9 +84,16 @@ PROVISION_LOCK_WAIT_S = 5.0 PROVISION_LOCK_POLL_S = 0.05 # The labels this profile home sent a keyset-provision for and wrote no .env line for yet (in ctx_state/, -# a JSON object label -> time; no .json name, so the state pruning keeps it). Only a key of such a run is -# retired without --replace; a key of the label this home never sent a set for is another machine's. +# a JSON object label -> {"sent": time, "id": the key's id once ctx answered}; no .json name, so the +# state pruning keeps it). Only the key such a note explains is retired without --replace: the noted id, +# or without one a key ctx made within STOPPED_RUN_SLACK_S of the noted time; every other key of the +# label is another machine's. PENDING_FILE = "access-provision.pending" +# How far ctx's created_at of a stopped run's key may lie from the time the run noted before it sent: +# the request's own bound (REQUEST_TIMEOUT_S per step) and the difference of this computer's clock and +# ctx's. A key outside it is not taken for the stopped run's; a clock further off makes the repeat ask +# for --replace instead (it never retires a key it cannot place). +STOPPED_RUN_SLACK_S = 300.0 _STANDARD_KEYS = ("CTX_KEY", "CTX_API_KEY") _BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz" _REVOKE = ( @@ -738,18 +746,75 @@ def _provision_lock(home: str) -> Iterator[None]: os.close(fd) # releases the lock -def _stopped_runs(home: str) -> dict[str, Any]: - """The labels of :data:`PENDING_FILE` (a missing or unreadable file: none).""" - return _status._read_json_file(Path(home) / FACT_STATE_DIR / PENDING_FILE) or {} +def _stopped_runs(home: str) -> dict[str, dict[str, str]]: + """The notes of :data:`PENDING_FILE` by label, ``{"sent": time[, "id": key id]}`` (a missing or + unreadable file: none).""" + notes: dict[str, dict[str, str]] = {} + for label, note in (_status._read_json_file(Path(home) / FACT_STATE_DIR / PENDING_FILE) or {}).items(): + if isinstance(note, Mapping): + kept = {name: note.get(name) for name in ("sent", "id")} + notes[str(label)] = {name: value for name, value in kept.items() if isinstance(value, str)} + return notes + + +def _record_run(home: str, label: str, *, sent: bool, key_id: str = "") -> None: + """Note in :data:`PENDING_FILE` that this home sends a set for *label* (``sent``; with *key_id*: the + id ctx answered for it, the time of the note kept) or that the run is over (its ``.env`` line is + written, or ctx refused the set). Raises ``OSError`` on a failed write.""" + runs = _stopped_runs(home) + note = runs.pop(label, {}) + if sent and key_id: + runs[label] = {"sent": note.get("sent") or _status._now_text(), "id": key_id} + elif sent: + runs[label] = {"sent": _status._now_text()} + _status._write_json_file(Path(home) / FACT_STATE_DIR / PENDING_FILE, runs) -def _record_run(home: str, label: str, *, sent: bool) -> None: - """Note in :data:`PENDING_FILE` that this home sent a set for *label* (``sent``) or that the run is - over (its ``.env`` line is written, or ctx refused the set). Raises ``OSError`` on a failed write.""" - runs = {name: when for name, when in _stopped_runs(home).items() if name != label} - if sent: - runs[label] = _status._now_text() - _status._write_json_file(Path(home) / FACT_STATE_DIR / PENDING_FILE, runs) +def _instant(text: Any) -> datetime | None: + """A time as ctx (``created_at``, RFC 3339) and :data:`PENDING_FILE` write it; ``None`` if it is none.""" + if not isinstance(text, str): + return None + try: + value = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError: + return None + return value if value.tzinfo is not None else None + + +def _left_by(key: Mapping[str, Any], note: Mapping[str, str]) -> bool: + """Whether *key* is the one the stopped run of *note* made: the id ctx answered it, or — when the + answer never came — a creation time within :data:`STOPPED_RUN_SLACK_S` of the note's.""" + if note.get("id"): + return str(key.get("id") or "") == note["id"] + sent, made = _instant(note.get("sent")), _instant(key.get("created_at")) + return sent is not None and made is not None and abs((made - sent).total_seconds()) <= STOPPED_RUN_SLACK_S + + +class _LabelsTaken(_client.CtxApiError): + """ctx's 409 of ``keyset-provision`` that names ``labels``: without ``replace_label`` an active key of + the tenant carries one of them; with it, such a key is no member key (go:keyset_provision.go + ``writeKeysetError``).""" + + def __init__(self, message: str, labels: list[str]) -> None: + super().__init__(message, status=409) + self.labels = labels + + +def _conflict(exc: urllib.error.HTTPError, client: _client.CtxClient) -> _client.CtxApiError: + """A 409 answer as an error: :class:`_LabelsTaken` when it names labels, else as the client words it.""" + try: + body = exc.read(16384).decode("utf-8", "replace") + except Exception: # an unreadable body: the status alone + body = "" + code, text = _client._parse_error_body(body) + message = f"HTTP 409{f' [{code}]' if code else ''}: {(client._redact(text) or client._redact(body))[:300]}" + try: + labels = json.loads(body).get("labels") + except (ValueError, AttributeError): + labels = None + if isinstance(labels, list) and labels and all(isinstance(item, str) and 0 < len(item) <= 200 for item in labels): + return _LabelsTaken(message, [client._redact(item) for item in labels[:64]]) + return _client.CtxApiError(message, status=409, code=code) def _manage_once(url: str, key: str, payload: Mapping[str, Any]) -> dict[str, Any]: @@ -769,7 +834,7 @@ def _manage_once(url: str, key: str, payload: Mapping[str, Any]) -> dict[str, An with _client._urlopen(request, timeout=REQUEST_TIMEOUT_S) as answer: raw = answer.read().decode("utf-8", "replace") except urllib.error.HTTPError as exc: - failure = client._http_failure(exc) + failure = _conflict(exc, client) if exc.code == 409 else client._http_failure(exc) except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException) as exc: failure = _client.CtxApiError(f"connection error: {client._redact(exc)}") except ValueError: @@ -912,7 +977,7 @@ def _provision_locked( variable=variable, env_value=_env_values(home).get(variable, ""), replace=args.replace, - stopped=label in _stopped_runs(home), + stopped=_stopped_runs(home).get(label), ) except ValueError: # a URL CtxClient does not take (no http(s), no host) print(f" ✗ {_status.display_url(url) or url!r} is no http(s) URL of a ctx server; nothing was sent") @@ -924,13 +989,7 @@ def _provision_locked( if conflict: print(f" ✗ {conflict}. Nothing was created") return 1 - try: # before ctx changes: a run that stops from here on is recognized by the repeat - _record_run(home, label, sent=True) - except OSError as exc: - record = Path(home) / FACT_STATE_DIR / PENDING_FILE - print(f" ✗ {record} cannot be written ({type(exc).__name__}); nothing was sent") - return 1 - for key_id in stopped_keys: # the keys a stopped run of this home made, by id (never the label's others) + for key_id in stopped_keys: # the key a stopped run of this home made, by id (never the label's others) retire = {"action": "api-key-update", "data": {"id": key_id, "active": False}} try: retired = _manage_once(url, admin_key, retire) @@ -943,6 +1002,12 @@ def _provision_locked( ) return 1 print(f" key {key_id} of a run that stopped before its .env line: deactivated") + try: # before the set is sent (a failed retire above keeps the earlier note): the repeat finds this run + _record_run(home, label, sent=True) + except OSError as exc: + record = Path(home) / FACT_STATE_DIR / PENDING_FILE + print(f" ✗ {record} cannot be written ({type(exc).__name__}); no key set was sent") + return 1 request = { "action": "keyset-provision", "data": { @@ -969,7 +1034,16 @@ def _provision_locked( if exc.status is not None and 400 <= exc.status < 500: with contextlib.suppress(OSError): # nothing was made: no stopped run to repeat _record_run(home, label, sent=False) - print(f" ✗ ctx refused the key set, nothing was created: {cause}") + taken = exc.labels if isinstance(exc, _LabelsTaken) and not args.replace else [] + if taken: # without replace_label: an active key of the tenant carries the label (ctx's lock decided) + print( + f" ✗ ctx refused the key set, nothing was created: an active key of the tenant already carries " + f"the label {', '.join(taken)}. For a new key of this same group run it again with --replace (the " + f"earlier key is deactivated); otherwise another group of this server and profile, or another " + f"machine with a profile of this name, holds the label: give this group a profile of its own" + ) + else: + print(f" ✗ ctx refused the key set, nothing was created: {cause}") else: # no answer, or a server or proxy error: ctx may have committed the set print( f" ✗ no clear answer from ctx ({cause}): whether the key set was created is unknown (with " @@ -977,6 +1051,11 @@ def _provision_locked( "deactivates the key this run may have made, so one key stays active and lands in the .env" ) return 1 + keys = answer.get("keys") + key_id = keys[0].get("id") if isinstance(keys, list) and keys and isinstance(keys[0], Mapping) else None + if isinstance(key_id, str) and key_id: # the repeat of a run that stops from here retires exactly this key + with contextlib.suppress(OSError): + _record_run(home, label, sent=True, key_id=key_id) made = _made_key(answer, label, own, [_full_name(scope) for scope in (knowledge, *extra)]) if isinstance(made, str): print( @@ -1030,19 +1109,28 @@ def _env_values(home: str) -> dict[str, str]: def _key_conflict( - url: str, admin_key: str, *, label: str, own: str, variable: str, env_value: str, replace: bool, stopped: bool + url: str, + admin_key: str, + *, + label: str, + own: str, + variable: str, + env_value: str, + replace: bool, + stopped: Mapping[str, str] | None, ) -> tuple[str, list[str]]: """Why this set would replace something it must not, from ctx's own list of the tenant's active keys - (``api-key-list`` with the tenant-admin key; ``""``: nothing), and the ids of the keys a stopped run + (``api-key-list`` with the tenant-admin key; ``""``: nothing), and the id of the key a stopped run of this home left (to retire before the set). A key serves one group per server and profile: its label names them, its home is the group's scope. Refused: (1) the label's key homed in another group's scope; (2) the group's scope homing a key of another label (another server, profile or group whose name maps to the same scope); (3) without *replace*, a key of this group in the ``.env`` already (rotation is asked for, not done by a repeat); (4) without *replace*, a key of the label at - ctx that the ``.env`` does not hold and no stopped run of this home (*stopped*: the home recorded - that it sent a set for the label and wrote no line) explains — another machine's key. With - *stopped*, those keys are the stopped run's: the repeat retires them by id, without - ``replace_label`` (only *replace* sends it), so it never deactivates another group's key.""" + ctx that the ``.env`` does not hold and the note of a stopped run of this home (*stopped*, see + :func:`_left_by`) does not explain — another machine's key; (5) such a key that is no member key. + The key the note explains is the stopped run's: the repeat retires it by id, without + ``replace_label`` (only *replace* sends it), so it never deactivates another group's key, and ctx + takes the new set (a deactivated key does not hold the label).""" who = _client.CtxClient(url, admin_key, timeout=REQUEST_TIMEOUT_S).whoami() slug = who.get("tenant_slug") if isinstance(who, Mapping) and who.get("success") is not False else None if not isinstance(slug, str) or not access.SLUG_PATTERN.match(slug): @@ -1081,18 +1169,19 @@ def _key_conflict( f"{variable} in the profile's .env holds a key for this server and profile already ({where}); " f"--replace makes a new key for this same group and deactivates the earlier one" ), [] - if held and not stopped: - return ( - f"ctx has an active key {label} of this group that the profile's .env does not hold, and no run of " - f"this profile left it (another machine with a profile of this name, or a line removed from the " - f".env); --replace makes a new key for this group and deactivates that one" - ), [] for key in held: # provision makes member keys only; ctx's replace_label spares every other key too if key.get("tenant_role") != "member": return ( f"the key {key.get('id')} labelled {label} is a {key.get('tenant_role') or 'non-member'} key, not " f"one provision made; revoke it with api-key-delete" ), [] + foreign = [key for key in held if stopped is None or not _left_by(key, stopped)] + if foreign: + return ( + f"ctx has an active key {label} of this group ({foreign[0].get('id')}) that the profile's .env does " + f"not hold, and no run of this profile left it (another machine with a profile of this name, or a " + f"line removed from the .env); --replace makes a new key for this group and deactivates that one" + ), [] return "", [str(key.get("id") or "") for key in held] diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py index 1a8d34847..3512bc4a9 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -88,6 +88,7 @@ class FakeKey: admin: bool = False confirm_writes: bool = False active: bool = True + created_at: str = NOW # keyset-provision stamps the time it made the key @property def id(self) -> str: @@ -515,7 +516,7 @@ def _api_key_update(self, caller: FakeKey, body: Mapping[str, Any]) -> tuple[int "write_scopes": list(target.write_scopes), "scope_narrowing": target.scope_narrowing, "active": target.active, - "created_at": NOW, + "created_at": target.created_at, } return 200, {"success": True, "key": shown} @@ -537,7 +538,7 @@ def _api_key_list(self, caller: FakeKey, body: Mapping[str, Any]) -> dict[str, A "write_scopes": list(key.write_scopes), "scope_narrowing": key.scope_narrowing, "active": key.active, - "created_at": NOW, + "created_at": key.created_at, } for key in reversed(keys) if (caller.admin or key.tenant == caller.tenant) and (key.active or not active_only) @@ -673,7 +674,15 @@ def _keyset_provision(self, admin: FakeKey, body: Mapping[str, Any]) -> tuple[in return _plain(400, "scope_narrowing must be optional or required") resolved["scope_narrowing"] = narrowing made.append(resolved) - # -- the transaction, under the tenant's lock + # -- the transaction, under the tenant's lock. First a label a key without replace_label would take + # from an active key of the tenant (a deactivated key does not count): 409 with the labels sorted + # bytewise, before the scopes and the quotas (go:store/keyset.go keysetLabelsTakenTx). + carried = {k.label for k in self.keys.values() if k.tenant == tenant and k.active} + taken = sorted({spec["label"] for spec in made if not spec["replace"]} & carried) + if taken: + quoted = ", ".join(json.dumps(label) for label in taken) + text = f"an active key of the tenant already carries the label {quoted}; name replace_label to replace it" + return 409, {"success": False, "error": text, "labels": taken} have = self.tenant_scopes(tenant) named = list(wanted) + [ scope for spec in made for scope in (spec["home_scope"], *spec["allowed_scopes"], *spec["write_scopes"]) @@ -692,7 +701,7 @@ def _keyset_provision(self, admin: FakeKey, body: Mapping[str, Any]) -> tuple[in f'replace_label: an active key labelled "{guarded[0]}" is not a member key; ' "revoke it with api-key-delete" ) - return _plain(409, text) + return 409, {"success": False, "error": text, "labels": [guarded[0]]} count = len([k for k in active if k not in replaced]) if self.max_keys is not None and count + len(made) > self.max_keys: return _quota("tenant key quota exceeded", self.max_keys, count, len(made)) @@ -717,6 +726,7 @@ def _keyset_provision(self, admin: FakeKey, body: Mapping[str, Any]) -> tuple[in write_scopes=tuple(spec["write_scopes"]), scope_narrowing=spec["scope_narrowing"], label=spec["label"], + created_at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), # the database's now() ) out.append( { diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py index 399e609e4..869eca315 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py @@ -1,15 +1,15 @@ """``access provision`` against runs that interleave (PR review of the plugin layer). The interleavings are made with event barriers around the manage call that changes ctx, never by guessing with sleeps. -A first run never deactivates a key: only ``--replace`` sends ``replace_label``. A run that stopped -between ctx and its ``.env`` line is repeated without a switch: the profile home recorded that it sent -the set, and the repeat deactivates, by id (``api-key-update``), the member keys of the label in the -group's scope that the ``.env`` does not hold — never a key of another group, nor one of the label this -home sent no set for. ctx itself mints a key of a label that an active key already -carries when ``replace_label`` is not sent (go:internal/store/keyset.go ``keysetReplaceTx`` returns -before any check without it; ``context_api_keys.label`` is not unique, go:migrations/113_baseline.sql -around line 5221), so two machines that serve one server with a profile of the same name can end with -two active keys of that label; neither run deactivates the other's. +A first run never deactivates a key: only ``--replace`` sends ``replace_label``. ctx refuses a set +without ``replace_label`` whose label an active key of the tenant carries (409 with ``labels``, under the +tenant lock, nothing made; a deactivated key does not count — go:internal/store/keyset.go +``keysetLabelsTakenTx``), so of two machines that provision one label at once, one gets the key and the +other the refusal. A run that stopped between ctx and its ``.env`` line is repeated without a switch: +the profile home noted that it sent the set (and the key's id once ctx answered), and the repeat +deactivates by id the key the note explains — the noted id, or without one a member key of the label in +the group's scope made around the noted time — then sends without ``replace_label``; any other key of +the label is another machine's and refused without ``--replace``. In one profile home, runs take turns under a lock that fails closed, held from the key check through the requests that change ctx to the ``.env`` line: a second run sees what the first committed, and the @@ -19,6 +19,7 @@ import errno import threading +from datetime import datetime, timedelta, timezone import pytest from fakes import access_host as ah @@ -124,21 +125,24 @@ def test_a_first_run_sends_no_replace_label_and_replace_sends_it(ctx, tmp_path): assert sent == [False, True] -def test_two_first_runs_on_two_machines_deactivate_no_key(ctx, tmp_path, monkeypatch): +def test_two_first_runs_on_two_machines_end_with_one_key_and_ctx_s_refusal(ctx, tmp_path, monkeypatch, capsys): """Two machines serve server 111 with a profile named ``members`` each (one label, no shared lock). Run A (group members) passed its key check and is about to send its set; run B (group mods) runs - whole meanwhile. A's commit must not deactivate B's key, which nobody asked to replace.""" + whole meanwhile. A's set must neither deactivate B's key nor add a second active key of the label: + ctx refuses it (409, the label taken), and A says what to do and writes nothing.""" host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") gate = _Gate(monkeypatch, "before") result = gate.start(lambda: _provision(host_a, "members")) assert _provision(host_b, "mods") == 0 + capsys.readouterr() gate.finish() - assert result == [0] - (b_key,) = [key for key in _labelled(ctx) if key.home.endswith("-mods")] - assert b_key.active, "the first run of another machine deactivated a key nobody asked to replace" - assert _env(host_b) == f"CTX_KEY_111_MEMBERS={b_key.secret}\n" - # ctx refuses no second active key of a label without replace_label: both stay (the named gap). - assert sorted(key.home.rsplit("-", 1)[-1] for key in _labelled(ctx) if key.active) == ["members", "mods"] + assert result == [1] + out = capsys.readouterr().out + assert "nothing was created" in out and LABEL in out and "--replace" in out and "another machine" in out, out + (b_key,) = _labelled(ctx) + assert b_key.active and b_key.home.endswith("-mods"), "a key nobody asked to replace was deactivated" + assert _env(host_b) == f"CTX_KEY_111_MEMBERS={b_key.secret}\n" and not (host_a / ".env").exists() + assert LABEL not in cli._stopped_runs(str(host_a)), "a refused set leaves no stopped run to repeat" def test_a_key_of_this_group_that_another_machine_holds_is_not_replaced_without_replace(ctx, tmp_path, capsys): @@ -231,6 +235,99 @@ def test_a_set_ctx_refused_leaves_no_stopped_run_behind(ctx, tmp_path, capsys): assert b_key.active and not _sent(ctx, "api-key-update") +def test_a_repeat_whose_label_another_machine_takes_meanwhile_is_refused(ctx, tmp_path, monkeypatch, capsys): + """The repeat of a stopped run deactivated that run's key by id; before it sends its new set, another + machine (a profile of the same name, no shared lock) provisions the label. ctx refuses the repeat's + set (409: a deactivated key does not count, the other machine's does), so one key of the label stays + active. The repeat writes no line and forgets the stopped run, so a later repeat does not take the + other machine's key for it.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + _stop_before_the_env_line(monkeypatch, host_a) + (stopped,) = _labelled(ctx) + real, other = cli._manage_once, {} + + def meanwhile(url, key, payload): + answer = real(url, key, payload) + if payload.get("action") == "api-key-update" and not other: + other["started"] = True + other["rc"] = _provision(host_b, "members") + return answer + + monkeypatch.setattr(cli, "_manage_once", meanwhile) + capsys.readouterr() + assert _provision(host_a, "members") == 1 + out = capsys.readouterr().out + assert other["rc"] == 0 and "nothing was created" in out and LABEL in out and "--replace" in out, out + (b_key,) = [key for key in _labelled(ctx) if key.active] + assert not stopped.active and b_key is not stopped and _env(host_b) == f"CTX_KEY_111_MEMBERS={b_key.secret}\n" + assert not (host_a / ".env").exists() + assert _provision(host_a, "members") == 1 # no stopped run any more: B's key is not retired + assert b_key.active and len(_sent(ctx, "api-key-update")) == 1 + + +def test_a_repeat_retires_only_the_key_ctx_named_to_its_stopped_run(ctx, tmp_path, monkeypatch, capsys): + """The stopped run got ctx's answer (its key's id) and failed at the ``.env`` line. Its key is revoked + by hand later and another machine provisions the label; the repeat here must not take that key for + the stopped run's.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + _stop_before_the_env_line(monkeypatch, host_a) + (stopped,) = _labelled(ctx) + stopped.active = False # revoked by hand (api-key-update active=false) + assert _provision(host_b, "members") == 0 + (b_key,) = [key for key in _labelled(ctx) if key.active] + capsys.readouterr() + assert _provision(host_a, "members") == 1 + out = capsys.readouterr().out + assert LABEL in out and "--replace" in out, out + assert b_key.active and not _sent(ctx, "api-key-update") and not (host_a / ".env").exists() + + +def _lose_the_answer(monkeypatch): + """ctx commits the set; its answer is lost on the way back (no key id reaches the run).""" + real = cli._manage_once + + def lost(url, key, payload): + answer = real(url, key, payload) + if payload.get("action") == "keyset-provision": + raise cli._client.CtxApiError("connection error: reset by peer") + return answer + + monkeypatch.setattr(cli, "_manage_once", lost) + return real + + +def test_a_run_whose_answer_was_lost_is_repeated_and_retires_the_key_made_at_its_time(ctx, tmp_path, monkeypatch): + home = _home(tmp_path) + real = _lose_the_answer(monkeypatch) + assert _provision(home, "members") == 1 + monkeypatch.setattr(cli, "_manage_once", real) + (stopped,) = _labelled(ctx) + assert _provision(home, "members") == 0 + assert _sent(ctx, "api-key-update") == [{"action": "api-key-update", "data": {"id": stopped.id, "active": False}}] + (active,) = [key for key in _labelled(ctx) if key.active] + assert _env(home) == f"CTX_KEY_111_MEMBERS={active.secret}\n" + + +def test_a_note_without_a_key_id_retires_no_key_made_long_after_it(ctx, tmp_path, monkeypatch, capsys): + """A run lost ctx's answer a day ago and was never repeated; its key was revoked by hand since, and + another machine has just provisioned the label. The note's time does not fit that key.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + real = _lose_the_answer(monkeypatch) + yesterday = (datetime.now(timezone.utc) - timedelta(days=1)).strftime("%Y-%m-%dT%H:%M:%SZ") + with monkeypatch.context() as earlier: + earlier.setattr(cli._status, "_now_text", lambda: yesterday) + assert _provision(host_a, "members") == 1 + monkeypatch.setattr(cli, "_manage_once", real) + (stopped,) = _labelled(ctx) + stopped.active = False + assert _provision(host_b, "members") == 0 + (b_key,) = [key for key in _labelled(ctx) if key.active] + capsys.readouterr() + assert _provision(host_a, "members") == 1 + assert "--replace" in capsys.readouterr().out + assert b_key.active and not _sent(ctx, "api-key-update") + + def test_the_fake_deactivates_a_key_by_id_as_ctx_does(ctx): """``api-key-update`` (go:internal/handler/context_manage.go handleApiKeyUpdate): ``{id, active}``, the caller's tenant only; another tenant's key or no key answers 200 ``key not found``.""" @@ -252,6 +349,41 @@ def update(data): assert body["key"]["active"] is False and not member.active +def test_the_fake_refuses_a_set_whose_label_an_active_key_carries_as_ctx_does(ctx): + """keyset-provision (go:internal/store/keyset.go ``keysetLabelsTakenTx``, handler ``writeKeysetError``): + a key without ``replace_label`` whose label an active key of the tenant carries refuses the whole set + with 409 ``{success, error, labels}`` (labels sorted bytewise, no ``code``), checked under the tenant + lock before the scopes (403) and the quotas (429); nothing is made, no scope either. A deactivated key + does not count, ``replace_label`` is not checked, another tenant's key does not count; the 409 of + ``replace_label`` at an administrative key carries ``labels`` too.""" + ctx.add_key(secret="ctx_member_lab_b_000001", tenant="t", home="t:main", label="lab-b") + ctx.add_key(secret="ctx_member_lab_c_000001", tenant="t", home="t:main", label="Lab-c") + gone = ctx.add_key(secret="ctx_member_lab_d_000001", tenant="t", home="t:main", label="lab-d", active=False) + ctx.add_key(secret="ctx_foreign_lab_e_00001", tenant="u", home="u:main", label="lab-e") + ctx.add_key(secret="ctx_admin_lab_f_0000001", tenant="t", home="t:main", label="lab-f", role="admin") + + def provision(*keys, scopes=("s1",)): + specs = [{"label": label, "home_scope": home, "replace_label": replace} for label, home, replace in keys] + body = {"action": "keyset-provision", "data": {"scopes": list(scopes), "keys": specs}} + status, answer, _echo = ctx._answer("POST", "/api/manage", "keyset-provision", body, ADMIN_KEY, [], []) + return status, answer + + before = len(ctx.keys) + status, answer = provision(("lab-b", "s1", False), ("Lab-c", "s1", False), ("lab-new", "s1", False)) + assert status == 409 and set(answer) == {"success", "error", "labels"} and answer["success"] is False + assert answer["labels"] == ["Lab-c", "lab-b"] and "lab-b" in answer["error"] + assert len(ctx.keys) == before and "t:s1" not in ctx.scopes + assert provision(("lab-b", "u:main", False))[0] == 409, "the label is checked before the scopes (403)" + ctx.max_scopes = 0 + assert provision(("lab-b", "s1", False))[0] == 409, "the label is checked before the quotas (429)" + ctx.max_scopes = None + assert provision(("lab-d", "s1", False))[0] == 200 and not gone.active, "a deactivated key does not count" + assert provision(("lab-e", "s1", False))[0] == 200, "another tenant's key does not count" + assert provision(("lab-b", "s1", True))[0] == 200, "replace_label replaces, it is not refused" + status, answer = provision(("lab-f", "s1", True)) + assert status == 409 and answer["labels"] == ["lab-f"] and "not a member key" in answer["error"] + + # -- finding 4815624942: one provision at a time per profile home, check to .env line ------------ # A run that cannot have the profile's lock within its wait (shortened here: the held run holds it until # the test releases it, so the wait only bounds the test) returns before it sends anything. diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py index 35acd1364..fcb4606df 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py @@ -246,11 +246,14 @@ def test_keyset_for_a_member_key_is_403_admin_key_required(fake): def test_keyset_quota_is_429_with_limit_count_and_requested(fake): - """go:keyset_provision.go:250-262, go:store/keyset.go:344-360: count after the replacements.""" + """go:keyset_provision.go:250-262, go:store/keyset.go:344-360: count after the replacements. A set + whose label an active key carries is refused before the quota (409, keysetLabelsTakenTx).""" fake.add_key(secret="ctx_old", tenant="t", home="t:d111-members", label="hermes:discord:111:members") fake.max_keys = 3 # member, admin, old - status, body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec()]}) + status, body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec(label="hermes:discord:111:x")]}) assert (status, body["limit"], body["count"], body["requested"]) == (429, 3, 3, 1) and "code" not in body + status, body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec()]}) + assert (status, body["labels"]) == (409, ["hermes:discord:111:members"]) and "code" not in body status, body = _keyset(fake, {"scopes": ["d111-k", "d111-members"], "keys": [_spec(replace_label=True)]}) assert status == 200, "the replaced key does not count" assert not fake.keys["ctx_old"].active From caab3c28918a050c214eab9b411667142a46dc66 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 10:22:35 +0100 Subject: [PATCH 38/65] test(ctx_checkpoint): the runs against a real ctxd and against Hermes with access groups follow the driver and cover the taken label, the stopped run, the guard verdict, the markers and the hygiene agent Against a real ctxd (tests/test_s3_real_ctxd.py, needs a throwaway ctxd, skipped otherwise): the capture test records writes at the CtxClient class, since group clients are _BindingClient with __slots__; the proxy records JSON bodies and can swallow the answer of a /api/manage action. New cases: two first runs of one label race and ctx refuses the second (409 with the labels), a later first run on a third machine is refused before it sends, a run that lost its answer is repeated by its note and ctx's created_at, a note older than the slack explains no key and --replace rotates it, a run whose .env line failed is repeated by the key id it noted, and a narrowed write over a guarded block names no block outside its read set. Against Hermes with access groups (tests/test_s3_core_contract.py with CTX_S3_HERMES_SRC, skipped otherwise): a group session is served only once its markers are on disk, an unreadable ctx_state reads as both markers set, and the gateway's hygiene agent gets no profile connection under ungoverned: local. Two strict xfails pin what the README promises and the code does not hold yet: no ctx at all reaches a session whose markers cannot be written (the base-block hook still reads ctx), and a group session is not served while ctx_state is a file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ctx_checkpoint/tests/s3_core_child.py | 180 +++++++++- .../tests/test_s3_core_contract.py | 82 ++++- .../ctx_checkpoint/tests/test_s3_real_ctxd.py | 338 +++++++++++++++++- 3 files changed, 587 insertions(+), 13 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py b/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py index 8dee46bd0..b3d1d1b81 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py @@ -41,6 +41,7 @@ KEY_VAR = f"CTX_KEY_{GUILD}_MEMBERS" MEMBER_KEY = "ctx_member_s3_secret_value_0001" DEFAULT_KEY = "ctx_default_s3_secret_value_0002" # the same variable name in the default profile's .env +PROFILE_KEY = "ctx_profile_s3_secret_value_0003" # a default key (CTX_KEY) of the default profile LABEL = f"hermes:discord:{GUILD}:members" ACCESS_KEYS = ("scope_id", "access_group", "access_group_restricted", "access_fields", "restricted_profile") UNSET = "<absent>" @@ -64,6 +65,9 @@ def __init__( latency: dict[str, float] | None = None, checkpoint_required: bool = False, members_extra: dict[str, Any] | None = None, + default_ungoverned: str = "off", + default_key: bool = False, + member_recall: bool = False, ) -> None: sys.path.insert(0, str(TESTS)) from fakes.ctx_server import FakeCtx @@ -109,6 +113,8 @@ def __init__( "base_blocks": [self.ids["one"], self.ids["foreign"], self.ids["own"]], } } + if member_recall: + fields["ctx_checkpoint"]["recall"] = True operators = {"name": "operators", "users": [OWNER], "profile": "default", "restricted": False, "admin": True} members = {"name": "members", "roles": [GUILD], "profile": "members", "prompt": "Be brief."} if fields is not None: @@ -116,7 +122,7 @@ def __init__( self.groups = [operators, members] root_config = { "gateway": {"multiplex_profiles": True, "access_groups": {"discord": {GUILD: {"groups": self.groups}}}}, - "memory": {"provider": "ctx_checkpoint", "ctx_checkpoint": {"ungoverned": "off"}}, + "memory": {"provider": "ctx_checkpoint", "ctx_checkpoint": {"ungoverned": default_ungoverned}}, } # The restricted profile of Hermes' documented recipe (tests/gateway/test_access_check.py ``_recipe``), # with ctx_checkpoint as its memory provider and no default key (``ungoverned: off``). @@ -135,6 +141,11 @@ def __init__( }, "approvals": {"mode": "manual"}, } + if member_recall: + # Recall for the restricted group: its field, the profile's permission and the memory features. + members_config["memory"]["ctx_checkpoint"].update( + {"restricted_allow": ["recall"], "memory": True, "prefetch_mode": "search"} + ) if hook_timeout is not None: members_config["plugins"] = {"hook_callback_timeout": hook_timeout} if checkpoint_required: @@ -147,7 +158,12 @@ def __init__( (self.members / "workspace" / ".git").mkdir(parents=True, exist_ok=True) (self.home / "config.yaml").write_text(_yaml(root_config), encoding="utf-8") (self.members / "config.yaml").write_text(_yaml(members_config), encoding="utf-8") - (self.home / ".env").write_text(f"CTX_BASE_URL={self.fake.url}\n{KEY_VAR}={DEFAULT_KEY}\n", encoding="utf-8") + default_env = f"CTX_BASE_URL={self.fake.url}\n{KEY_VAR}={DEFAULT_KEY}\n" + if default_key: + # The profile's own connection: an unnarrowed key that ctx would answer. + self.fake.add_key(secret=PROFILE_KEY, tenant="t", home="t:ops", allowed=(K,), role="member") + default_env += f"CTX_KEY={PROFILE_KEY}\n" + (self.home / ".env").write_text(default_env, encoding="utf-8") (self.members / ".env").write_text(f"CTX_BASE_URL={self.fake.url}\n{KEY_VAR}={MEMBER_KEY}\n", encoding="utf-8") for home in (self.home, self.members): shutil.copytree( @@ -311,7 +327,7 @@ def requests(self) -> dict[str, Any]: from fakes.ctx_server import digest seen = self.fake.requests() - names = {digest(MEMBER_KEY): "member", digest(DEFAULT_KEY): "default"} + names = {digest(MEMBER_KEY): "member", digest(DEFAULT_KEY): "default", digest(PROFILE_KEY): "profile"} return { "keys": sorted({names.get(s.key_digest, s.key_digest) for s in seen}), "routes": sorted({f"{s.method} {s.path}{':' + s.action if s.action else ''}" for s in seen}), @@ -322,7 +338,9 @@ def requests(self) -> dict[str, Any]: def status(self, home: Path) -> list[dict[str, Any]]: path = home / "ctx_state" / "access" out = [] - for file in sorted(path.glob("*.json")) if path.is_dir() else []: + if not path.is_dir(): + return out + for file in sorted(path.glob("*.json")): data = json.loads(file.read_text(encoding="utf-8")) out.append({"file": file.name, "state": data.get("state"), "base": data.get("base_blocks")}) return out @@ -704,6 +722,157 @@ def scenario_available(world: World) -> dict[str, Any]: return out +def _member_turn_markers(world: World, runner, source, key: str) -> dict[str, Any]: + """One member turn in two phases: setup (the base-block hook) and the agent build (``initialize``, + then a prefetch); ctx's requests are counted per phase.""" + from gateway.run import _async_profile_runtime_scope + + out: dict[str, Any] = {} + + async def turn(): + with patch("gateway.run._gateway_runner_ref", lambda: runner): + async with _async_profile_runtime_scope(world.members): + with _turn_env(runner, source, key): + world.fake.reset_counters() + out["pinned"] = await world.setup_prompt(runner, source, key) + out["hook_requests"] = world.requests() + world.fake.reset_counters() + world.inits.clear() + started = time.monotonic() + agent = world.build_agent( + "discord", session_id=key.rsplit(":", 1)[-1], gateway_session_key=key, user_id=MEMBER + ) + out["build_seconds"] = round(time.monotonic() - started, 3) + manager = agent._memory_manager + out["prefetch"] = manager.prefetch_all("what are the house rules?") if manager else None + out["tools"] = sorted( + schema.get("name", "?") + for provider in (manager.providers if manager else []) + for schema in (provider.get_tool_schemas() or []) + ) + out["inits"] = list(world.inits) + out["build_requests"] = world.requests() + with contextlib.suppress(Exception): + agent.close() + + asyncio.run(turn()) + return out + + +def scenario_markers(world: World) -> dict[str, Any]: + """New (fba2ac70): a session of a governed group is served only once its markers are on disk. The + write is made impossible for root by a lock another holder keeps (``flock`` on the markers' lock file, + the plugin's ``_markers_lock`` waits and gives up): the first member session is refused; once the + lock is free, the next session binds and the markers are on disk.""" + import fcntl + + state = world.members / "ctx_state" + state.mkdir(parents=True, exist_ok=True) + out: dict[str, Any] = {} + with _served(world): + world.discover() + access = _plugin_access_module() + markers = world.members / access.MARKERS_FILE + runner = world.runner() + source = world.inbound(runner, MEMBER, roles={GUILD}) + + async def admit(): + with patch("gateway.run._gateway_runner_ref", lambda: runner): + return await world.admitted(runner, source) + + out["admitted"] = asyncio.run(admit()) + holder = os.open(str(state / access._MARKERS_LOCK_FILE), os.O_RDWR | os.O_CREAT, 0o600) + try: + fcntl.flock(holder, fcntl.LOCK_EX) + out["locked"] = _member_turn_markers(world, runner, source, "agent:members:discord:group:s-m1") + out["locked"]["markers_file"] = markers.exists() + out["locked"]["status"] = world.status(world.members) + finally: + os.close(holder) + out["free"] = _member_turn_markers(world, runner, source, "agent:members:discord:group:s-m2") + out["free"]["markers"] = json.loads(markers.read_text(encoding="utf-8")) if markers.exists() else None + out["free"]["status"] = world.status(world.members) + return out + + +def scenario_markers_file(world: World) -> dict[str, Any]: + """The other root-proof way to make the markers unwritable: ``ctx_state`` is a file. The read-back + then fails as well and counts as both markers set (``read_markers``).""" + (world.members / "ctx_state").write_text("not a directory\n", encoding="utf-8") + out: dict[str, Any] = {} + with _served(world): + world.discover() + access = _plugin_access_module() + runner = world.runner() + source = world.inbound(runner, MEMBER, roles={GUILD}) + + async def admit(): + with patch("gateway.run._gateway_runner_ref", lambda: runner): + return await world.admitted(runner, source) + + out["admitted"] = asyncio.run(admit()) + out["turn"] = _member_turn_markers(world, runner, source, "agent:members:discord:group:s-f1") + read = access.read_markers(str(world.members)) + out["read_markers"] = {"restricted_seen": read.restricted_seen, "governed_seen": read.governed_seen} + return out + + +def scenario_hygiene(world: World) -> dict[str, Any]: + """New (5fc7db57): the gateway's hygiene agent (``_hmwa_hygiene_build_agent``, built without a platform: + Hermes passes ``cli`` to ``initialize``) of a session without an access group, in a profile with + ``ungoverned: local``, ``compression.checkpoint_required`` and a default key: ``off``, no request. Built + inside the turn's session variables, as ``_hmwa_prepare_turn`` binds them before its hygiene (and, as a + contrast, outside them).""" + from gateway.config import Platform + from gateway.run import _async_profile_runtime_scope + + out: dict[str, Any] = {} + with _served(world): + world.discover() + runner = world.runner() + runner.session_store = runner._session_db_pinned = None # no store (persistence None): an empty prompt + adapter = world.inbound(runner, OWNER) # registers the adapter; the source below is a direct message + del adapter + dm = runner.adapters[Platform.DISCORD].build_source( + chat_id="800000000000000008", chat_type="dm", user_id=OWNER, guild_id=None + ) + other = runner.adapters[Platform.DISCORD].build_source( + chat_id=CHAT, chat_type="group", user_id=OWNER, guild_id="100000000000000009" + ) + runtime = {"api_key": "test-key-1234567890", "base_url": "http://127.0.0.1:9/v1"} + + async def hygiene(label, source, *, bound=True): + key = f"agent:main:discord:{source.chat_type}:{source.chat_id}" + entry = SimpleNamespace(session_id=f"s-hyg-{label}") + world.inits.clear() + world.fake.reset_counters() + with patch("gateway.run._gateway_runner_ref", lambda: runner): + async with _async_profile_runtime_scope(world.home): + with _turn_env(runner, source, key) if bound else contextlib.nullcontext(): + with ( + patch("tools.schemas.get_tool_definitions", return_value=[]), + patch("tools.schemas.check_toolset_requirements", return_value={}), + patch("agent.process_bootstrap.OpenAI"), + ): + agent, _db = await runner._hmwa_hygiene_build_agent("m", dict(runtime), entry) + out[label] = { + "agent_platform": agent.platform, + "provider_loaded": agent._memory_manager is not None, + "inits": list(world.inits), + "requests": world.requests(), + } + with contextlib.suppress(Exception): + agent.close() + + async def run(): + await hygiene("dm", dm) + await hygiene("ungoverned_server", other) + await hygiene("dm_unbound", dm, bound=False) + + asyncio.run(run()) + return out + + SCENARIOS = { "load": (scenario_load, {}), "gateway": (scenario_gateway, {}), @@ -712,6 +881,9 @@ def scenario_available(world: World) -> dict[str, Any]: "delegate": (scenario_delegate, {"checkpoint_required": True}), "r7": (scenario_r7, {}), "available": (scenario_available, {}), + "markers": (scenario_markers, {"member_recall": True}), + "markers_file": (scenario_markers_file, {"member_recall": True}), + "hygiene": (scenario_hygiene, {"checkpoint_required": True, "default_ungoverned": "local", "default_key": True}), } diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py index 66c0c3184..f67ab296f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py @@ -16,7 +16,10 @@ the memory manager's worker and a ``delegate_task`` child see the group (V6a, H-2, VB-3); a CLI session binds no ``HERMES_SESSION_PLATFORM``; R7 admits the restricted profile exactly when the group carries the fields; the provider is available without a default key under ``ungoverned: off|local`` -(H-1). +(H-1); a group session is served only once its markers are on disk (a held marker lock keeps it off, +the next session binds); the gateway's hygiene agent gets no profile connection under +``ungoverned: local``. Two strict xfails name findings S3-B4 and S3-B5 (what the README promises for a +session whose markers cannot be written). """ from __future__ import annotations @@ -243,3 +246,80 @@ def test_the_provider_is_available_without_a_default_key_under_off_and_local(tmp [init] = result[mode]["inits"] assert init["restricted_profile"] is True and init["decisions"][0]["kind"] == "off" # row 5 assert result["profile"]["provider_kept"] is False + + +MARKERS_OFF = "the access-group markers could not be written to ctx_state" + + +def test_a_group_session_is_served_only_once_its_markers_are_on_disk(tmp_path_factory): + """fba2ac70: the markers' lock is held by another holder (``flock``, root-proof), so the first member + session cannot write them: its binding is off, sends nothing and recalls nothing, and its status says + why; once the lock is free the next session writes the markers and binds (narrowed recall).""" + result, _ = _run("markers", tmp_path_factory) + assert result["admitted"] is True + locked, free = result["locked"], result["free"] + [init] = locked["inits"] + assert init["decisions"][0]["kind"] == "off" and init["decisions"][0]["reason"].startswith(MARKERS_OFF) + assert locked["build_requests"]["n"] == 0 and locked["prefetch"] == "" and locked["tools"] == [] + assert locked["markers_file"] is False and locked["build_seconds"] >= 4.0 # waited for the lock, then gave up + assert locked["status"][0]["state"].startswith(f"off: {MARKERS_OFF}") + [init] = free["inits"] + assert (init["decisions"][0]["kind"], init["decisions"][0]["reason"]) == ("group", "row 2: group binding") + assert free["markers"]["restricted_seen"] is True and free["markers"]["governed_seen"] is True + assert free["status"][0]["state"] == "bound" + assert "<ctx-context>" in free["prefetch"] and free["tools"] + assert free["build_requests"]["keys"] == ["member"] and free["build_requests"]["narrowed"] == ["t:d1-k"] + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="S3 finding S3-B4: the base-block hook still reads ctx and fills the group's prompt while the markers" + " cannot be written; the README says such a session gets no ctx", +) +def test_no_ctx_at_all_reaches_a_session_whose_markers_cannot_be_written(tmp_path_factory): + """README (access groups): "while ctx_state cannot be written (a full disk, a lock another process holds), + that session gets no ctx". The provider holds that (test above); the base-block hook does not look at + the markers.""" + result, _ = _run("markers", tmp_path_factory) + locked = result["locked"] + assert locked["hook_requests"]["n"] == 0, locked["hook_requests"] + assert HEADING not in locked["pinned"][0] + + +def test_an_unreadable_ctx_state_reads_as_both_markers_set(tmp_path_factory): + """``ctx_state`` is a file: the markers can be neither written nor read; ``read_markers`` counts that as + both set, so every later session without its group stays off (the purpose of the markers holds).""" + result, _ = _run("markers_file", tmp_path_factory) + assert result["read_markers"] == {"restricted_seen": True, "governed_seen": True} + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="S3 finding S3-B5: with ctx_state a file the markers cannot be written, yet they read back as set and" + " the group session is served; the README says such a session gets no ctx", +) +def test_a_group_session_is_not_served_while_ctx_state_is_a_file(tmp_path_factory): + result, _ = _run("markers_file", tmp_path_factory) + [init] = result["turn"]["inits"] + assert init["decisions"][0]["kind"] == "off", init["decisions"][0] + + +def test_the_gateways_hygiene_agent_gets_no_profile_connection_under_local(tmp_path_factory): + """5fc7db57: the hygiene agent before a turn is built without a platform (Hermes passes ``cli`` to + ``initialize``, stamps ``gateway_hygiene`` afterwards). For a direct message and for a server without + access groups, in a profile with ``ungoverned: local``, ``checkpoint_required`` and a default key, it is + off and sends nothing, because the gateway bound the session's platform before (``_hmwa_prepare_turn``). + The same build outside the turn's session variables (no real path builds it there) would be local.""" + result, _ = _run("hygiene", tmp_path_factory) + for label in ("dm", "ungoverned_server"): + hygiene = result[label] + assert hygiene["agent_platform"] == "gateway_hygiene" and hygiene["provider_loaded"] is True + [init] = hygiene["inits"] + assert (init["platform"], init["access_group"], init["restricted_profile"]) == ("cli", None, False) + assert init["decisions"][0]["kind"] == "off", init["decisions"][0] + assert init["decisions"][0]["reason"] == "row 8: ungoverned local, not a local session" + assert hygiene["requests"]["n"] == 0 + [unbound] = result["dm_unbound"]["inits"] + assert unbound["decisions"][0]["kind"] == "profile" # the contrast: what the bound platform prevents diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py index 6c99fc67f..762fe4536 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py @@ -27,6 +27,7 @@ import os import re import threading +import time import urllib.error import urllib.parse import urllib.request @@ -65,6 +66,9 @@ SERVER_A, SERVER_B = "111", "222" TOOLSETS = "platform_toolsets:\n discord: [web]\n" WRITE_BUDGET = 40 # the tenant overlay of query.rate_limit_write this module sets +GUARD_TEXT = "The ferry to the north island leaves at seven and returns at five on weekdays only." +GUARD_KEYS = ("guard_matched_id", "guard_similarity", "guard_is_cross_scope") +GUARD_WAIT_S = 200.0 # the scheduler's guard ticker is 60 s; a tick may be deferred by interactive demand PROBE = "sthreeprobe" SEEN: dict[str, Any] = {"deviations": []} @@ -224,16 +228,24 @@ def _forward(self) -> None: if not k.lower().startswith("x-context-") or k.lower() == "x-context-key" } action = "" + parsed: Any = None if data: with contextlib.suppress(ValueError, AttributeError): parsed = json.loads(data) action = str(parsed.get("action") or "") + ("+ids" if "ids" in parsed else "") owner.seen.append((self.command, self.path, action, self.headers.get(nar.HEADER_READ_SCOPES, ""))) + owner.bodies.append(parsed) target = urllib.parse.urlsplit(owner.target) conn = http.client.HTTPConnection(target.hostname, target.port, timeout=60) conn.request(self.command, self.path, body=data, headers=headers) answer = conn.getresponse() raw = answer.read() + if action and action == owner.drop_answer_of: + # ctx has done the work; the client never hears of it (a connection lost after the commit) + owner.dropped.append((answer.status, raw.decode("utf-8", "replace"))) + conn.close() + self.close_connection = True + return self.send_response(answer.status) for name, value in answer.getheaders(): if name.lower() in ("connection", "transfer-encoding", "content-length"): @@ -255,12 +267,17 @@ class Proxy(_Serve): handler = _ProxyHandler - def __init__(self, *, strip_response_echo: bool = False, strip_request_narrowing: bool = False) -> None: + def __init__( + self, *, strip_response_echo: bool = False, strip_request_narrowing: bool = False, drop_answer_of: str = "" + ) -> None: super().__init__() self.target = URL self.strip_response_echo = strip_response_echo self.strip_request_narrowing = strip_request_narrowing + self.drop_answer_of = drop_answer_of # a /api/manage action whose answer is never passed on self.seen: list[tuple[str, str, str, str]] = [] + self.bodies: list[Any] = [] + self.dropped: list[tuple[int, str]] = [] @contextlib.contextmanager @@ -415,6 +432,34 @@ def store(name: str, key: str, title: str, content: str) -> None: store("membersA", keys["w-membersA"], "Member chatter", "Something another member said.") store("kB", keys["w-kB"], "Server B plans", "Bravo plans of server B.") store("main", owner, "Owner notes", "The owner's own notes.") + # Guard twins (S3 final): a block in the mods scope and one in the members' write scope with the + # same text. ctxd's scheduler runs the duplicate guard every 60 s after a write + # (go/internal/events/scheduler.go); across scopes it flags the later block needs_review and names + # the earlier one in guard_matched_id. A key homed in the write scope that also reads the mods scope + # sees the verdict; the query embeds both blocks first (the query backfill), as the server's own + # test does (go/cmd/ctxd/guard_verdict_answers_integration_test.go). + keys["gw-ctl"] = str( + must( + manage( + owner, + { + "action": "api-key-create", + "data": { + "label": "s3-guard-control", + "home_scope": scopes["membersA"], + "allowed_scopes": [scopes["modsA"]], + }, + }, + ), + "guard control key", + )["api_key"] + ) + store("guardTwin", keys["w-modsA"], "Guard twin", GUARD_TEXT) + store("guardTarget", keys["w-membersA"], "Guard target", GUARD_TEXT) + must( + call("POST", "/api/query", keys["gw-ctl"], {"query": "guard twin text", "synthesize": False}), + "query backfill of the guard twins", + ) yield { "owner": owner, "tenant_id": tenant_id, @@ -512,7 +557,8 @@ def test_the_write_budget_a_group_key_reports_is_its_home_scopes(world): "query.rate_limit_write set by the tenant's owner does not reach keys homed in other scopes of the " "tenant (a group key from keyset-provision reports the _global value)", seen, - "design 02 §1.4 (CC-7) and §3.5 C-1: 'je Tenant überschreibbar', 'nach Tenant-Overlay'; " + "design 02 §1.4 (CC-7) and §3.5 C-1: 'je Tenant überschreibbar', 'nach Tenant-Overlay' " + "(docs/api.md names the home scope's overlay since the server's 6f5c0574); " "tests/fakes/ctx_server.py reports one value per key", ) @@ -855,16 +901,18 @@ def test_group_capture_writes_only_its_write_scope_and_follows_the_write_budget( monkeypatch.setattr(_PKG, "_host_compaction_wait_s", lambda: None, raising=False) provider = _member_provider(world, _member_fields(world, capture=True)) assert provider._active, provider._access_off - writer = provider._group.write_client + # The group's clients are wrapped per binding (``_BindingClient``, no instance attributes): the + # answers of the write narrowing are recorded at the client class, the server's own answers. answers: list[Mapping[str, Any]] = [] - inner = writer.store + inner = CtxClient.store - def recording_store(*args: Any, **kwargs: Any) -> Any: - answer = inner(*args, **kwargs) - answers.append(answer) + def recording_store(self: Any, *args: Any, **kwargs: Any) -> Any: + answer = inner(self, *args, **kwargs) + if self.narrowing is not None and self.narrowing.write == scopes["membersA"]: + answers.append(answer) return answer - monkeypatch.setattr(writer, "store", recording_store) + monkeypatch.setattr(CtxClient, "store", recording_store) receipt = provider.on_pre_compress(_messages(), require_checkpoint=True) assert receipt, "the chain was written" assert provider._rate_limit_write == WRITE_BUDGET, provider._rate_limit_write @@ -987,6 +1035,280 @@ def test_an_incoming_tenant_grant_turns_every_restricted_binding_off(world, host _note("tenant_grant_answer", grant) +# -- S3 final: provision against the label rule of ctx (keyset-provision 409) and a stopped run ----- + + +class _PerThreadStdout: + """``sys.stdout`` for runs of ``provision`` on several threads at once: each thread writes into a + buffer of its own (``print`` reads ``sys.stdout`` at call time).""" + + def __init__(self) -> None: + self.buffers: dict[int, io.StringIO] = {} + self._lock = threading.Lock() + + def write(self, text: str) -> int: + with self._lock: + buffer = self.buffers.setdefault(threading.get_ident(), io.StringIO()) + return buffer.write(text) + + def flush(self) -> None: + return None + + def text(self, ident: int) -> str: + buffer = self.buffers.get(ident) + return buffer.getvalue() if buffer else "" + + +def _home(world, name: str, machine: str = "") -> Path: + home = world["homes"]["members"].parents[1] / (machine or "m0") / "profiles" / name + home.mkdir(parents=True, exist_ok=True) + if not (home / "config.yaml").exists(): + (home / "config.yaml").write_text(TOOLSETS, encoding="utf-8") + return home + + +def _label_keys(world, label: str) -> list[Mapping[str, Any]]: + body = must(manage(world["owner"], {"action": "api-key-list", "data": {"active_only": True}}), "api-key-list") + return [k for k in body.get("keys") or [] if k.get("label") == label and k.get("active") is not False] + + +def _pending(home: Path) -> dict[str, Any]: + path = home / "ctx_state" / cli.PENDING_FILE + return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + + +def _provision_via(host, monkeypatch, url: str) -> None: + """``provision`` of this thread reads the ctx URL *url* (the profile's CTX_BASE_URL).""" + host.secrets.set_base({"CTX_BASE_URL": url}) + monkeypatch.setenv("CTX_BASE_URL", url) + + +@pytest.fixture +def provisioning(world, host, monkeypatch): + """The fake host with the tenant-admin key in the shell's environment, as an operator runs provision.""" + monkeypatch.setenv("CTX_S3_TENANT_ADMIN", world["owner"]) + _provision_via(host, monkeypatch, URL) + return host + + +def test_two_first_runs_of_one_label_race_and_ctx_refuses_the_second(world, provisioning, monkeypatch): + """Two machines with a profile of the same name provision the same group at once: both list the + tenant's keys before either sends (a barrier after api-key-list), both send keyset-provision without + replace_label; ctx's tenant lock lets one through and answers the other 409 with the labels; that + run names them and writes no .env line.""" + label = nar.expected_label("discord", SERVER_A, "racer") + homes = [_home(world, "racer", "m1"), _home(world, "racer", "m2")] + barrier = threading.Barrier(2, timeout=20) + real = cli._manage_once + sent: list[Mapping[str, Any]] = [] + + def gated(url: str, key: str, payload: Mapping[str, Any]) -> dict[str, Any]: + if payload.get("action") == "keyset-provision": + sent.append(dict(payload)) # before the call: ctx's 409 raises out of it + answer = real(url, key, payload) + if payload.get("action") == "api-key-list": + barrier.wait() + return answer + + out = _PerThreadStdout() + results: dict[int, tuple[int, int]] = {} + + def run(index: int) -> None: + argv = ["provision", "--server", f"discord:{SERVER_A}", "--profile", "racer", "--group", "racer"] + rc = cli.run_access([*argv, "--admin-key-env", "CTX_S3_TENANT_ADMIN"], hermes_home=str(homes[index])) + results[index] = (rc, threading.get_ident()) + + with monkeypatch.context() as mp: + mp.setattr(cli, "_manage_once", gated) + mp.setattr("sys.stdout", out) + threads = [threading.Thread(target=run, args=(i,)) for i in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(60) + texts = {i: out.text(ident) for i, (_rc, ident) in results.items()} + rcs = sorted(rc for rc, _ident in results.values()) + assert rcs == [0, 1], (results, texts) + assert len(sent) == 2 and all(k.get("replace_label") is False for p in sent for k in p["data"]["keys"]), sent + loser = next(i for i, (rc, _ident) in results.items() if rc == 1) + winner = 1 - loser + assert f"an active key of the tenant already carries the label {label}" in texts[loser], texts[loser] + env = homes[loser] / ".env" + assert not env.exists() or "CTX_KEY_111_RACER" not in env.read_text(encoding="utf-8") + assert _env_value(homes[winner], "CTX_KEY_111_RACER") + assert _pending(homes[loser]) == {}, "a refused set leaves no note of a stopped run" + assert len(_label_keys(world, label)) == 1 + raw = manage( + world["owner"], + { + "action": "keyset-provision", + "data": { + "scopes": [], + "keys": [ + { + "label": label, + "home_scope": cli.scope_layout(SERVER_A, ["racer"])["racer"], + "allowed_scopes": [], + "write_scopes": [], + } + ], + }, + }, + ) + _note("keyset_provision_label_taken", {"status": raw[0], "body": raw[1]}) + assert raw[0] == 409 and raw[1].get("labels") == [label] and "code" not in raw[1], raw + + +def test_a_later_first_run_on_a_third_machine_is_refused_before_it_sends(world, provisioning, monkeypatch): + """The same label provisioned before (previous test or not: a key of the label is made here if none): + a first run elsewhere sees the label's key at ctx, which its .env does not hold and no note of its own + explains, and refuses without sending a set.""" + label = nar.expected_label("discord", SERVER_A, "racer") + if not _label_keys(world, label): + assert _provision(_home(world, "racer", "m1"), SERVER_A, "racer", "racer")[0] == 0 + with proxy() as fwd: + _provision_via(provisioning, monkeypatch, fwd.url) + rc, out = _provision(_home(world, "racer", "m3"), SERVER_A, "racer", "racer") + assert rc == 1 and "that the profile's .env does not hold" in out, out + assert [row[2] for row in fwd.seen if row[2] == "keyset-provision"] == [], fwd.seen + + +def _stopped_by_a_lost_answer(world, monkeypatch, host, name: str) -> tuple[Path, str, Mapping[str, Any]]: + """A provision whose keyset-provision ctx commits and whose answer never arrives: (home, label, the + orphan key as api-key-list names it).""" + home = _home(world, name) + label = nar.expected_label("discord", SERVER_A, name) + with proxy(drop_answer_of="keyset-provision") as fwd: + _provision_via(host, monkeypatch, fwd.url) + rc, out = _provision(home, SERVER_A, name, name) + dropped = list(fwd.dropped) + _provision_via(host, monkeypatch, URL) + assert rc == 1 and "no clear answer from ctx" in out, out + assert dropped and dropped[0][0] == 200, f"ctx committed the set: {dropped}" + note = _pending(home).get(label) or {} + assert set(note) == {"sent"}, f"a run whose answer was lost notes only the time: {note}" + [orphan] = _label_keys(world, label) + return home, label, orphan + + +def test_a_run_that_lost_its_answer_is_repeated_by_its_note_and_ctxs_created_at(world, provisioning, monkeypatch): + home, label, orphan = _stopped_by_a_lost_answer(world, monkeypatch, provisioning, "lost") + note = _pending(home)[label] + made, sent = cli._instant(orphan.get("created_at")), cli._instant(note["sent"]) + _note( + "created_at_against_the_note", + {"created_at": orphan.get("created_at"), "note_sent": note["sent"], "seconds": (made - sent).total_seconds()}, + ) + assert made is not None and sent is not None, "the plugin parses ctx's created_at" + with proxy() as fwd: + _provision_via(provisioning, monkeypatch, fwd.url) + rc, out = _provision(home, SERVER_A, "lost", "lost") + bodies = [ + b for b in fwd.bodies if isinstance(b, dict) and b.get("action") in ("api-key-update", "keyset-provision") + ] + assert rc == 0, out + assert bodies[0] == {"action": "api-key-update", "data": {"id": orphan["id"], "active": False}}, bodies + assert bodies[1]["action"] == "keyset-provision" and bodies[1]["data"]["keys"][0]["replace_label"] is False + new_key = _env_value(home, "CTX_KEY_111_LOST") + assert new_key and _pending(home) == {} + [active] = _label_keys(world, label) + assert active["id"] != orphan["id"] + lost_scope = _full(cli.scope_layout(SERVER_A, ["lost"])["lost"]) + narrowed, plain = _raws(new_key, (world["scopes"]["kA"],)) + expect = _expect(world, label=label, write=lost_scope, env_names=("CTX_KEY_111_LOST",)) + assert nar.evaluate(narrowed, plain, expect).ok + + +def test_a_note_older_than_the_slack_explains_no_key_and_replace_rotates_it(world, provisioning, monkeypatch): + home, label, orphan = _stopped_by_a_lost_answer(world, monkeypatch, provisioning, "stale") + pending = _pending(home) + sent = cli._instant(pending[label]["sent"]) + older = sent.timestamp() - (cli.STOPPED_RUN_SLACK_S + 60) + pending[label]["sent"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(older)) + (home / "ctx_state" / cli.PENDING_FILE).write_text(json.dumps(pending), encoding="utf-8") + with proxy() as fwd: + _provision_via(provisioning, monkeypatch, fwd.url) + rc, out = _provision(home, SERVER_A, "stale", "stale") + sets = [row for row in fwd.seen if row[2] in ("keyset-provision", "api-key-update")] + assert rc == 1 and "no run of this profile left it" in out and sets == [], (out, sets) + _provision_via(provisioning, monkeypatch, URL) + rc, out = _provision(home, SERVER_A, "stale", "stale", "--replace") + assert rc == 0 and "an earlier key of this label is inactive now" in out, out + [active] = _label_keys(world, label) + assert active["id"] != orphan["id"] + new_key = _env_value(home, "CTX_KEY_111_STALE") + stale_scope = _full(cli.scope_layout(SERVER_A, ["stale"])["stale"]) + narrowed, plain = _raws(new_key, (world["scopes"]["kA"],)) + expect = _expect(world, label=label, write=stale_scope, env_names=("CTX_KEY_111_STALE",)) + assert nar.evaluate(narrowed, plain, expect).ok + + +def test_a_run_whose_env_line_failed_is_repeated_by_the_key_id_it_noted(world, provisioning, monkeypatch): + home = _home(world, "idnote") + label = nar.expected_label("discord", SERVER_A, "idnote") + real = cli._write_env_line + + def fails_once(*args: Any, **kwargs: Any) -> None: + monkeypatch.setattr(cli, "_write_env_line", real) + raise OSError("disk full (S3 fault)") + + monkeypatch.setattr(cli, "_write_env_line", fails_once) + rc, out = _provision(home, SERVER_A, "idnote", "idnote") + assert rc == 1 and "could not be written" in out, out + [orphan] = _label_keys(world, label) + assert _pending(home)[label].get("id") == orphan["id"] + rc, out = _provision(home, SERVER_A, "idnote", "idnote") + assert rc == 0 and f"key {orphan['id']} of a run that stopped before its .env line: deactivated" in out, out + [active] = _label_keys(world, label) + assert active["id"] != orphan["id"] and _env_value(home, "CTX_KEY_111_IDNOTE") + + +# -- S3 final: the guard verdict in the answer of a narrowed write ------------------------------------ + + +def _guard_verdict(block: Mapping[str, Any]) -> dict[str, Any]: + metadata = block.get("metadata") if isinstance(block.get("metadata"), Mapping) else {} + return {key: metadata[key] for key in GUARD_KEYS if key in metadata} + + +def test_a_narrowed_write_over_a_guarded_block_names_no_block_outside_its_read_set(world, host): + """The guard flagged the target (members' write scope) as a twin of a block in the mods scope. A + write of the members group (narrowed to its write scope) that overwrites the target gets the block + back without the verdict; the control key, which reads the mods scope, gets it with the verdict.""" + blocks, scopes, keys = world["blocks"], world["scopes"], world["keys"] + deadline = time.monotonic() + GUARD_WAIT_S + seen: dict[str, Any] = {} + while time.monotonic() < deadline: + for name in ("guardTarget", "guardTwin"): + status, body, _ = manage(keys["gw-ctl"], {"action": "get", "id": blocks[name]}) + block = body.get("block") or {} + seen[name] = {"guard_status": block.get("guard_status"), **_guard_verdict(block)} + if seen["guardTarget"].get("guard_matched_id") == blocks["guardTwin"]: + break + time.sleep(5) + _note("guard_fixture", {"waited_s": round(GUARD_WAIT_S - (deadline - time.monotonic()), 1), **seen}) + assert seen["guardTarget"].get("guard_matched_id") == blocks["guardTwin"], ( + f"no guard verdict on the target within {GUARD_WAIT_S} s: {seen}" + ) + status, control, _ = call( + "POST", + "/api/store", + keys["gw-ctl"], + {"category": "learnings", "title": "Guard target", "content": GUARD_TEXT + " c"}, + ) + assert status == 200 and control["block"]["id"] == blocks["guardTarget"], control + assert set(_guard_verdict(control["block"])) == set(GUARD_KEYS), control["block"].get("metadata") + writer = CtxClient( + URL, keys["members"], timeout=30, narrowing=nar.Narrowing(read=(scopes["membersA"],), write=scopes["membersA"]) + ) + answer = writer.store(category="learnings", title="Guard target", content=GUARD_TEXT + " g") + block = answer.get("block") or {} + _note("guard_narrowed_write_answer", {"id": block.get("id"), "metadata": block.get("metadata")}) + assert block.get("id") == blocks["guardTarget"], answer + assert _guard_verdict(block) == {}, block.get("metadata") + assert blocks["guardTwin"] not in json.dumps(answer), "no reference to the block outside the read set" + + # -- a server without C-1 (CTX_S3_SERVER=before-c1, v5.94.0): every group binding fails closed ------ # Design 02 §3.7 row "ctx-Server ohne C-1" and §7.1 "Landung": the plugin lands before the server; a # group then never binds (no echo, E5), the hook gives no prompt, provision creates nothing. From 0fe190dbf0319b8b1320ac07b80585f3587ffcf3 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:01:12 +0100 Subject: [PATCH 39/65] =?UTF-8?q?fix(ctx=5Fcheckpoint):=20a=20group=20sess?= =?UTF-8?q?ion=20whose=20markers=20are=20not=20on=20disk=20gets=20no=20ctx?= =?UTF-8?q?=20at=20all=20=E2=80=94=20the=20base-block=20hook=20gives=20no?= =?UTF-8?q?=20text=20either,=20and=20an=20unreadable=20ctx=5Fstate=20is=20?= =?UTF-8?q?no=20marker=20on=20disk?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README promises that while ctx_state cannot be written (a full disk, a lock another process holds) a session of a governed group gets no ctx. The provider held that; two paths did not. The base-block hook read ctx and filled the group's prompt without looking at the markers. It now applies the provider's rule through the same function: access.markers_held raises the markers the group's session raises (seen_markers) and reads them back from disk, on the hook's pool, before the render cache is asked; not on disk means no text and no request (BaseBlocksUnavailable, so the core asks again on a later turn). The lock is waited for within the call's budget only, and a check that found the markers is reused for 5 s (MARKERS_HELD_S): markers only rise. The hook raises restricted_seen only for a group the core told is restricted, as initialize would. An unreadable ctx_state (a file where the directory belongs) read back as both markers set, so a group session was served. read_markers keeps that strict reading for every decision (sessions without a group stay off); the read-back before serving a group no longer takes it for markers on disk. The markers' lock now bounds the wait for the process's lock too (one wait for both). The README and the changelog name the case the hook cannot see: it knows the group's restriction, not the profile's. The strict xfails of the run against Hermes with access groups pass; their markers are gone. An installation without access groups is unchanged: no markers are needed, none are read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 6 +- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 9 +- .../plugin/ctx_checkpoint/memory/access.py | 54 +++++-- .../ctx_checkpoint/memory/base_blocks.py | 67 ++++++++- .../plugin/ctx_checkpoint/memory/provider.py | 17 +-- .../tests/test_access_binding_races.py | 25 ++++ .../tests/test_access_pd_base_blocks.py | 135 ++++++++++++++++++ .../tests/test_s3_core_contract.py | 27 ++-- 8 files changed, 293 insertions(+), 47 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 0800405c6..407d5c71e 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -460,7 +460,11 @@ restricted group gets no ctx for any session without its group, on any Hermes. B `ctx_state/access-mode.json` (`governed_seen`, `restricted_seen`): they only rise, survive the state pruning, and only `hermes ctx_checkpoint access reset-marker` lowers them. A session of a governed group is served only once the markers it raises are on disk: while `ctx_state` cannot be written (a full disk, -a lock another process holds), that session gets no ctx, and the next `initialize` tries again. +a lock another process holds, a file where the directory belongs), that session gets no ctx, its base +blocks included, and the next `initialize` tries again (the base-block hook on a later turn). The hook +knows the group's restriction, not the profile's: a session of an unrestricted group in a profile that +also serves a restricted group can get its base blocks while `governed_seen` is on disk and +`restricted_seen` cannot be written. A fork (`delegate_task`, a checkpoint fork) counts as local when its parent session was: Hermes binds the platform of a gateway session to the session, and for a CLI or TUI session the plugin takes the diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index c2ac74c5a..e6d64e309 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -36,10 +36,11 @@ older server a group binding is off and the profile's own connection works as be narrowing echoed, no foreign key with file tools in the profile). A lost echo, a group change within a turn or a failed proof turns the agent off. Blocks a group writes carry `server:`/`group:` tags and the chain `ctx_plugin.access`. A governed session is served only once its markers are on disk - (a full disk or a busy lock leaves it off until a later `initialize`). Every call works on one - snapshot of the binding: a client of a binding that was replaced or turned off since sends nothing - (client code `binding_stale`), a proof that completes after that counts for nothing, and a turn-off - is never overwritten by a proof's publication. A `whoami` that got no answer within one caller's + (a full disk, a busy lock or an unreadable `ctx_state` leaves it off until a later `initialize`); + the base-block hook checks its group's markers the same way before it gives a text. Every call + works on one snapshot of the binding: a client of a binding that was replaced or turned off since + sends nothing (client code `binding_stale`), a proof that completes after that counts for nothing, + and a turn-off is never overwritten by a proof's publication. A `whoami` that got no answer within one caller's short budget is no proof for a caller with more time (what ctx answered still holds for every caller of the key). - **Base blocks** (`base_blocks.py`): the hook answers with the group's base blocks as its prompt text, diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py index 7e0138389..87cf3e5fe 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -777,6 +777,12 @@ def read_markers(hermes_home: str) -> Markers: """The markers of ``<home>/ctx_state/access-mode.json``. A missing file is no marker; a file that cannot be read, does not parse, or holds anything but ``false`` for a marker counts as that marker set.""" + return _read_markers(hermes_home, unreadable=Markers(restricted_seen=True, governed_seen=True)) + + +def _read_markers(hermes_home: str, *, unreadable: Markers) -> Markers: + """``read_markers`` with ``unreadable`` for a file that cannot be read (``ctx_state`` no directory, + no permission, an I/O error).""" path = _markers_path(hermes_home) try: with path.open("rb") as handle: @@ -784,7 +790,7 @@ def read_markers(hermes_home: str) -> Markers: except FileNotFoundError: return Markers() except OSError: - return Markers(restricted_seen=True, governed_seen=True) + return unreadable try: data = json.loads(raw.decode("utf-8")) if len(raw) <= _MARKERS_MAX_BYTES else None except (UnicodeDecodeError, ValueError): @@ -798,18 +804,21 @@ def read_markers(hermes_home: str) -> Markers: @contextmanager -def _markers_lock(directory: Path) -> Iterator[None]: +def _markers_lock(directory: Path, wait_s: float | None = None) -> Iterator[None]: """Serialize the markers' read-modify-write across threads and processes (a lost update would lower a marker another writer raised). Raises ``OSError`` when the lock cannot be held within - the wait: nothing writes the markers unserialized.""" - with _PROCESS_MARKERS_LOCK: + the wait (``wait_s``, default ``_MARKERS_LOCK_WAIT_S``; the process's and the file's lock + together): nothing writes the markers unserialized.""" + deadline = time.monotonic() + (_MARKERS_LOCK_WAIT_S if wait_s is None else max(wait_s, 0.0)) + if not _PROCESS_MARKERS_LOCK.acquire(timeout=max(deadline - time.monotonic(), 0.0)): + raise OSError("the access-group marker lock is busy") + try: if fcntl is None: yield return directory.mkdir(parents=True, exist_ok=True) fd = os.open(str(directory / _MARKERS_LOCK_FILE), os.O_RDWR | os.O_CREAT, 0o600) try: - deadline = time.monotonic() + _MARKERS_LOCK_WAIT_S while True: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) @@ -821,6 +830,8 @@ def _markers_lock(directory: Path) -> Iterator[None]: yield finally: os.close(fd) # releases the lock + finally: + _PROCESS_MARKERS_LOCK.release() def _write_markers(path: Path, markers: Markers) -> None: @@ -855,15 +866,20 @@ def raise_markers(hermes_home: str, **flags: bool) -> None: """Set the named markers (``restricted_seen=True``, ``governed_seen=True``), only from false to true, atomically, and only when one changes; ``False`` never lowers one (only ``access reset-marker`` does). A marker that cannot be written (or whose lock cannot be held) is a - WARNING, never an exception; the caller reads the markers back (``read_markers``, which also - finds a raise another process made meanwhile) and serves a governed session only once they - hold — the provider leaves it ``off`` otherwise, and the next build tries again.""" - wanted = {name for name, value in _marker_flags(flags).items() if value} + WARNING, never an exception; a session of a governed group is served only once the markers it + raises read back as on disk (``markers_held``) — the provider leaves it ``off`` otherwise and the + base-block hook gives no text, and the next build tries again.""" + _raise_markers(hermes_home, {name for name, value in _marker_flags(flags).items() if value}, None) + + +def _raise_markers(hermes_home: str, wanted: set[str], wait_s: float | None) -> None: + """``raise_markers`` for the marker names ``wanted``, waiting at most ``wait_s`` for their lock + (``_markers_lock``).""" if not wanted or all(getattr(read_markers(hermes_home), name) for name in wanted): return # markers only rise: one already set needs no lock and no write path = _markers_path(hermes_home) try: - with _markers_lock(path.parent): + with _markers_lock(path.parent, wait_s): current = read_markers(hermes_home) raised = Markers( restricted_seen=current.restricted_seen or "restricted_seen" in wanted, @@ -875,6 +891,21 @@ def raise_markers(hermes_home: str, **flags: bool) -> None: logger.warning("ctx_checkpoint: the access-group marker file %s could not be written", path, exc_info=True) +def markers_held(hermes_home: str, needed: Mapping[str, bool], *, wait_s: float | None = None) -> bool: + """Whether a session of an access group may be served: the markers it raises (``needed``, from + ``seen_markers``) are raised (``raise_markers``, waiting at most ``wait_s`` for their lock) and then + read back from disk; a raise another process made meanwhile counts. The one rule of the provider's + ``initialize`` and the base-block hook. Unlike ``read_markers``, a file that cannot be read holds no + marker here: what a decision must read as set is not on disk, and a later reader that can read the + path again (``ctx_state`` replaced, permissions fixed) would not find it.""" + wanted = {name for name, value in _marker_flags(needed).items() if value} + if not wanted: + return True + _raise_markers(hermes_home, wanted, wait_s) + on_disk = _read_markers(hermes_home, unreadable=Markers()) + return all(getattr(on_disk, name) for name in wanted) + + def reset_markers(hermes_home: str, *, restricted: bool = False, governed: bool = False) -> None: """Lower the named markers (``access reset-marker``, the only way down), atomically; the other marker stays as read (an unreadable file counts as both set). File: ``MARKERS_FILE`` under the @@ -896,7 +927,7 @@ def reset_markers(hermes_home: str, *, restricted: bool = False, governed: bool def seen_markers(init_kwargs: Mapping[str, Any], decision: Decision) -> dict[str, bool]: - """The markers an agent build raises (``raise_markers(home, **seen_markers(init, decision))``, + """The markers an agent build raises (``markers_held(home, seen_markers(init, decision))``, design 02 §4.2 below the table): ``governed_seen`` for every session that serves an access group (rows 2 to 4), ``restricted_seen`` for ``restricted_profile: true`` and for every session of a restricted group, bound or not. Nothing here ever lowers a marker.""" @@ -1123,6 +1154,7 @@ def decide( "fork_parent_platform", "is_strict", "load_settings", + "markers_held", "parse_fields", "raise_markers", "read_markers", diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index d8ba9824d..df9975c8a 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -17,7 +17,12 @@ true, or not told), the rules of E1 (``access.parse_fields``) — pure, on the loop; 2. the profile's settings and the core's hook timeout, on the pool, within the shortest budget a profile can set; the call's budget is then ``base_timeout_s``, at most half the core's timeout; -3. the URL (a ``base_url`` field names an ``https`` value), then the key, then the E7 inputs of the +3. the markers this group's session raises, raised and read back on disk (``access.markers_held``, the + rule of the provider's ``initialize``; their lock waited for within the call's budget), before the + render cache is asked: not on disk (a full disk, a busy lock, an unreadable ``ctx_state``) means no + text and no request (``BaseBlocksUnavailable``), and a check that found them is reused for + ``MARKERS_HELD_S`` (markers only rise). Then the URL (a ``base_url`` field names an ``https`` + value), then the key, then the E7 inputs of the profile: the expectation the binding is judged by. The render cache key is that whole expectation (URL, key digest, fields, strictness, tenant, label, server, E7 inputs), so a cached text is only given to the expectation a proof passed for, and a hit costs no request; @@ -112,6 +117,7 @@ class _Request: profile: str strict: bool fields: access.GroupFields + restricted: bool | None = None # the group's restriction as the core told it (None: not told) @dataclass(frozen=True) @@ -164,6 +170,14 @@ class _Plan: # group without base blocks reports only when it differs (the hot paths stay one dict lookup). _REPORTED: dict[tuple[str, str, str, str], str | None] = {} REPORTED_MAX = 65_536 +# A check that found a home's markers on disk (``access.markers_held``) is reused this long, on the +# render cache's clock: markers only rise, so a reuse misses nothing but a lowering within it (``access +# reset-marker``, the file or ``ctx_state`` removed; the provider's ``initialize`` reads them anew for +# every session). The slots (home and the markers checked) are cleared whole when there are more than +# ``MARKERS_HELD_MAX``. +MARKERS_HELD_S = 5.0 +MARKERS_HELD_MAX = 65_536 +_MARKERS_HELD: dict[tuple[str, tuple[str, ...]], float] = {} def _submit(workers: int, fn: Callable[..., Any], *args: Any) -> concurrent.futures.Future: @@ -237,12 +251,14 @@ def _remember(plan: _Plan, text: str) -> None: def reset_state() -> None: - """Drop the render cache, the joined in-flight fetches and the thread pools (tests).""" + """Drop the render cache, the markers checks, the joined in-flight fetches and the thread pools + (tests).""" global _POOL, _POOL_SIZE, _CACHE_LIMIT, _REPORTS with _LOCK: pool, _POOL, _POOL_SIZE = _POOL, None, 0 reports, _REPORTS = _REPORTS, None _REPORTED.clear() + _MARKERS_HELD.clear() _CACHE.clear() _CACHE_LIMIT = 0 _INFLIGHT.clear() @@ -330,7 +346,8 @@ def _request_of( restricted=restricted if isinstance(restricted, bool) else None, ) # The hook knows no profile-wide restriction: a group whose restriction is not told is restricted - # (``restricted_profile=None``; the markers cannot change that answer, so no file is read here). + # (``restricted_profile=None``; the markers cannot change that answer, so no file is read here: the + # markers' check is step 3, on the pool). strict = access.is_strict(context, restricted_profile=None, markers=access.Markers()) parsed = access.parse_fields(own, scope_id=context.scope_id, strict=strict) shown = _Request(context.platform, context.scope_id, context.group, str(profile or ""), strict, None) @@ -352,7 +369,9 @@ def _request_of( if not parsed.key: _not_delivered(shown, "the group names no key (field key)") return None - return _Request(context.platform, context.scope_id, context.group, str(profile or ""), strict, parsed) + return _Request( + context.platform, context.scope_id, context.group, str(profile or ""), strict, parsed, context.restricted + ) def _core_hook_timeout() -> float: @@ -442,6 +461,39 @@ def _left(deadline: float) -> float: return left +def _markers_held(request: _Request, home: str, deadline: float) -> bool: + """Step 3's markers on the pool: whether the markers this group's session raises are on disk in the + serving profile's home (``access.markers_held`` with ``access.seen_markers``, as the provider's + ``initialize`` decides it), raised now when they are not, their lock waited for at most until + ``deadline``. A check that found them is reused for :data:`MARKERS_HELD_S`. + + The hook knows the group's restriction, not the profile's: ``restricted_seen`` only for a group the + core told is restricted (``initialize`` gets that as a bool; a restriction not told never raises the + marker that turns off every session without a group), ``governed_seen`` for every group. A session + of an unrestricted group in a profile that also serves a restricted one needs ``restricted_seen`` in + ``initialize``, not here.""" + known = request.restricted is True + context = access.AccessContext( + platform=request.platform, + scope_id=request.scope_id, + group=request.group, + profile=request.profile or None, + restricted=request.restricted, + ) + needed = access.seen_markers({}, access.Decision("group", "base blocks", context=context, strict=known)) + slot = (home, tuple(sorted(name for name, wanted in needed.items() if wanted))) + with _LOCK: + if _MARKERS_HELD.get(slot, 0.0) > _now(): + return True + if not access.markers_held(home, needed, wait_s=_left(deadline)): + return False + with _LOCK: + if len(_MARKERS_HELD) >= MARKERS_HELD_MAX: + _MARKERS_HELD.clear() + _MARKERS_HELD[slot] = _now() + MARKERS_HELD_S + return True + + def _expectation(request: _Request, home: str) -> _Expectation | None: """Step 3 on the pool, without network: the URL (a named one must be ``https``), only then the key, then the E7 inputs of a restricted group. ``None``: this binding gets no text.""" @@ -664,7 +716,12 @@ def _answer( queueing behind every other call's proof: ``None`` (no text for this binding), the text (cached or fetched now), or the future of the same key's fetch already on its way (the loop awaits it; a pool thread never waits for another). A fetch whose own deadline has passed is not joined: - it can only end without a text, so this call fetches itself.""" + it can only end without a text, so this call fetches itself. Markers not on disk: + ``BaseBlocksUnavailable`` before anything else.""" + if not _markers_held(request, home, deadline): + raise BaseBlocksUnavailable( + "the access-group markers could not be written to ctx_state (full disk, busy lock or unreadable ctx_state)" + ) expected = _expectation(request, home) if expected is None: return None diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index da5057012..f80841fa4 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -275,11 +275,6 @@ def _proof_cause(exc: CtxApiError) -> str: return ", ".join(part for part in parts if part) or "no answer" -def _markers_hold(markers: Any, needed: Mapping[str, bool]) -> bool: - """Whether every marker in ``needed`` (``access.seen_markers``) is set in ``markers`` as read back.""" - return all(getattr(markers, name, False) for name, wanted in needed.items() if wanted) - - def _write_limit(info: Any) -> int | None: """``whoami.rate_limit_write`` (writes per 60 s for this key, ctx with per-request narrowing) as reported: any int, ``0`` or less included (ctx: unlimited, which lifts a limit reported before); @@ -818,16 +813,16 @@ def _decide_access(self, kwargs: Mapping[str, Any]) -> None: markers, _access.access_supported(), ) - needed = _access.seen_markers(init, decision) - _access.raise_markers(home, **needed) - if decision.kind != "off" and not _markers_hold(_access.read_markers(home), needed): + held = _access.markers_held(home, _access.seen_markers(init, decision)) + if decision.kind != "off" and not held: # A session of a governed group is served only once the markers it raises are on disk: # every later session without access kwargs (a direct message, a rolled-back Hermes) - # must find them. A re-read counts a raise another process made meanwhile; the next - # initialize tries again. + # must find them. A re-read counts a raise another process made meanwhile, an unreadable + # ctx_state none; the next initialize tries again. decision = _access.Decision( "off", - "the access-group markers could not be written to ctx_state (full disk or busy lock)", + "the access-group markers could not be written to ctx_state (full disk, busy lock or" + " unreadable ctx_state)", context=decision.context, strict=decision.strict, ) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py index 68c1323b8..ac3a6cf45 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py @@ -146,6 +146,31 @@ def test_markers_another_writer_raised_meanwhile_count(world, monkeypatch): assert "alpha knowledge" in _ops(home).prefetch("plans?") +def test_a_group_session_is_not_served_while_ctx_state_is_unreadable(world): + """``ctx_state`` is a file: the markers can be neither written nor read back. For a decision that + reads as both set (the guard below); for serving a group it is no marker on disk: off, nothing sent.""" + fake, _host, home = world + (home / "ctx_state").write_text("not a directory\n", encoding="utf-8") + provider = _ops(home) + assert provider._decision.kind == "off", provider._decision + assert provider._decision.reason.startswith("the access-group markers could not be written to ctx_state") + assert provider.prefetch("plans?") == "" and provider.get_tool_schemas() == [] + assert fake.count() == 0 + + +@pytest.mark.parametrize("platform", ["cli", "discord"]) +def test_an_unreadable_ctx_state_keeps_a_session_without_a_group_off(world, monkeypatch, platform): + """Guard: unreadable markers count as both set for every session without a group; under the default + ``ungoverned: auto`` it stays off (row 6), as before.""" + fake, _host, home = world + (home / "ctx_state").write_text("not a directory\n", encoding="utf-8") + provider = pc.Provider(config={"transport": "rest", "memory": True}) + provider.initialize("s-1", hermes_home=str(home), platform=platform, agent_context="primary", **ah.v5_kwargs()) + decision = provider._decision + assert (decision.kind, decision.reason) == ("off", "row 6: a restricted group ran in this profile") + assert provider.prefetch("plans?") == "" and fake.count() == 0 + + @pytest.mark.parametrize("v8", [False, True], ids=["hermes-without-access-groups", "no-group-session"]) def test_a_full_disk_changes_nothing_without_access_groups(world, monkeypatch, v8): """Guard: with no access group in play no marker is needed; the profile's connection is 0.19.1's.""" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py index 1c7d0d1a7..5bd1e6671 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py @@ -11,7 +11,10 @@ from __future__ import annotations import asyncio +import errno import inspect +import os +import threading import time import pytest @@ -238,3 +241,135 @@ def test_secret_of_the_turn_scope_is_read_in_the_hook(world): with host.secrets.scoped({"CTX_BASE_URL": fake.url, "CTX_KEY_111_MEMBERS": MEMBER_KEY}): text = _prompt(_call(_fields(ids, "one"))) assert "House rules" in text and host.secrets.reads["CTX_KEY_111_MEMBERS"] >= 1 + + +# -- the markers: no base blocks for a session whose markers are not on disk (README, access groups) -- + +_acc = ah.plugin_module(_PKG, "memory.access") + + +def _full_disk(monkeypatch) -> dict: + """``ctx_state`` cannot be written (no space left) while ``state["full"]``.""" + state = {"full": True} + real = _acc._write_markers + + def write(path, markers): + if state["full"]: + raise OSError(errno.ENOSPC, "No space left on device") + return real(path, markers) + + monkeypatch.setattr(_acc, "_write_markers", write) + return state + + +def test_no_base_blocks_while_the_markers_cannot_be_written(world, monkeypatch): + """README: while ``ctx_state`` cannot be written, that session gets no ctx. The hook raises the + markers its session raises (as ``initialize`` does) and gives no text and reads nothing from ctx + while they are not on disk; it fails, so the core asks again on a later turn, which binds.""" + fake, _host, ids, home = world + disk = _full_disk(monkeypatch) + outcome = _call(_fields(ids, "one")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert fake.count() == 0 + assert _acc.read_markers(str(home)) == _acc.Markers() + disk["full"] = False + assert "House rules" in _prompt(_call(_fields(ids, "one"))) + # a restricted group's session raises both, as its ``initialize`` would + assert _acc.read_markers(str(home)) == _acc.Markers(restricted_seen=True, governed_seen=True) + + +@pytest.mark.parametrize("told", [False, None], ids=["unrestricted", "restriction-not-told"]) +def test_the_hook_raises_no_marker_its_sessions_initialize_would_not(world, told): + """``restricted_seen`` turns off every session without a group in the profile: the hook raises it + for a group it is told is restricted only (``initialize`` gets the group's restriction as a bool); + ``governed_seen`` for every group.""" + _fake, _host, ids, home = world + fields = _fields(ids, "one") + if told is False: + del fields["ctx_checkpoint"]["tenant"] # an unrestricted group's fields + kwargs = ah.hook_kwargs(fields=fields, restricted=bool(told)) + if told is None: + del kwargs["restricted"] # an older core: read as restricted (E1, E7, the label), served + outcome = asyncio.run(ah.ainvoke_hook_callback(bb.on_access_group_fields, **kwargs)) + assert "House rules" in _prompt(outcome) + assert _acc.read_markers(str(home)) == _acc.Markers(restricted_seen=False, governed_seen=True) + + +def test_no_base_blocks_while_ctx_state_is_unreadable(world): + """``ctx_state`` is a file: the markers can be neither written nor read back. Read for a decision, + that counts as both set; for serving a group it is no marker on disk.""" + fake, _host, ids, home = world + (home / "ctx_state").write_text("not a directory\n", encoding="utf-8") + outcome = _call(_fields(ids, "one")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert fake.count() == 0 + + +def test_a_cached_text_is_given_only_while_the_markers_are_on_disk(world, monkeypatch): + """The render cache answers without a request, not without the markers: a check that found them on + disk is reused only for a short while (markers only rise; ``access reset-marker`` lowers them).""" + fake, _host, ids, home = world + assert "House rules" in _prompt(_call(_fields(ids, "one"))) + (home / _acc.MARKERS_FILE).unlink(missing_ok=True) # an operator's ``access reset-marker`` + _full_disk(monkeypatch) + real = bb._now + monkeypatch.setattr(bb, "_now", lambda: real() + 600.0) # the text lives 900 s (base_cache_s) + fake.reset_counters() + outcome = _call(_fields(ids, "one")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert fake.count() == 0 + + +def test_the_marker_check_runs_on_the_pool_and_a_warm_call_reuses_it(world, monkeypatch): + """The check reads (and may wait for the markers' lock) off the gateway loop; a warm call within its + short reuse reads no marker file.""" + _fake, _host, ids, _home = world + threads: list[str] = [] + real = getattr(_acc, "markers_held", None) + + def held(*args, **kwargs): + threads.append(threading.current_thread().name) + return real(*args, **kwargs) + + monkeypatch.setattr(_acc, "markers_held", held, raising=False) + for _ in range(3): + assert "House rules" in _prompt(_call(_fields(ids, "one"))) + assert len(threads) == 1 and threads[0].startswith("ctx-base-blocks"), threads + + +@pytest.mark.skipif(_acc.fcntl is None, reason="the markers' file lock only on this platform") +@pytest.mark.parametrize("holder", ["another-process", "another-thread"]) +def test_a_busy_marker_lock_holds_the_hooks_thread_no_longer_than_its_budget(world, monkeypatch, holder): + """The markers' lock is held (by another process: its file lock; by another thread of this process, + say an ``initialize`` waiting for that file lock: the process's lock). The hook's check gives up at + the call's deadline (``base_timeout_s`` 1 s here), not after the markers' own wait of 5 s, so a stuck + lock never piles up the hook's threads.""" + import fcntl + + fake, _host, ids, home = world + settings = "memory:\n ctx_checkpoint:\n base_timeout_s: 1\n" + (home / "config.yaml").write_text(TOOLSETS + settings, encoding="utf-8") + returned = threading.Event() + real = _acc.markers_held + + def held(*args, **kwargs): + try: + return real(*args, **kwargs) + finally: + returned.set() + + monkeypatch.setattr(_acc, "markers_held", held) + (home / "ctx_state").mkdir() + fd = os.open(str(home / "ctx_state" / _acc._MARKERS_LOCK_FILE), os.O_RDWR | os.O_CREAT, 0o600) + taken = _acc._PROCESS_MARKERS_LOCK.acquire() if holder == "another-thread" else False + try: + fcntl.flock(fd, fcntl.LOCK_EX) + started = time.monotonic() + outcome = _call(_fields(ids, "one")) + assert not outcome.answered and isinstance(outcome.error, bb.BaseBlocksUnavailable), outcome + assert returned.wait(1.5), "the hook's thread still waits for the markers' lock after its budget" + assert time.monotonic() - started < 3.0 and fake.count() == 0 + finally: + if taken: + _acc._PROCESS_MARKERS_LOCK.release() + os.close(fd) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py index f67ab296f..7f1cedc55 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py @@ -271,20 +271,15 @@ def test_a_group_session_is_served_only_once_its_markers_are_on_disk(tmp_path_fa assert free["build_requests"]["keys"] == ["member"] and free["build_requests"]["narrowed"] == ["t:d1-k"] -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="S3 finding S3-B4: the base-block hook still reads ctx and fills the group's prompt while the markers" - " cannot be written; the README says such a session gets no ctx", -) def test_no_ctx_at_all_reaches_a_session_whose_markers_cannot_be_written(tmp_path_factory): """README (access groups): "while ctx_state cannot be written (a full disk, a lock another process holds), - that session gets no ctx". The provider holds that (test above); the base-block hook does not look at - the markers.""" + that session gets no ctx". The provider holds that (test above), and so does the base-block hook (S3-B4): + it gives no text and sends nothing while the markers are not on disk.""" result, _ = _run("markers", tmp_path_factory) locked = result["locked"] assert locked["hook_requests"]["n"] == 0, locked["hook_requests"] assert HEADING not in locked["pinned"][0] + assert HEADING in result["free"]["pinned"][0], "once the lock is free the hook is asked again and delivers" def test_an_unreadable_ctx_state_reads_as_both_markers_set(tmp_path_factory): @@ -294,16 +289,18 @@ def test_an_unreadable_ctx_state_reads_as_both_markers_set(tmp_path_factory): assert result["read_markers"] == {"restricted_seen": True, "governed_seen": True} -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="S3 finding S3-B5: with ctx_state a file the markers cannot be written, yet they read back as set and" - " the group session is served; the README says such a session gets no ctx", -) def test_a_group_session_is_not_served_while_ctx_state_is_a_file(tmp_path_factory): + """S3-B5: with ``ctx_state`` a file the markers can be neither written nor read back. For a decision + that reads as both set (test above); for serving a group it is no marker on disk: the provider is off + and the base-block hook gives no text and sends nothing.""" result, _ = _run("markers_file", tmp_path_factory) - [init] = result["turn"]["inits"] + turn = result["turn"] + [init] = turn["inits"] assert init["decisions"][0]["kind"] == "off", init["decisions"][0] + assert init["decisions"][0]["reason"].startswith(MARKERS_OFF) + assert turn["build_requests"]["n"] == 0 and turn["prefetch"] == "" and turn["tools"] == [] + assert turn["hook_requests"]["n"] == 0, turn["hook_requests"] + assert HEADING not in turn["pinned"][0] def test_the_gateways_hygiene_agent_gets_no_profile_connection_under_local(tmp_path_factory): From 5ebeb9f7aea72faaef609ba9e3d7a243f1879fb6 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:01:23 +0100 Subject: [PATCH 40/65] fix(ctx_checkpoint): a group client checks its binding before every HTTP request of a call, the retry after a 429 or a write_conflict included _BindingClient checked the binding once, before it called the inner client. CtxClient._request sends a call again once after a 429 or a write_conflict, after a wait of RATE_RETRY_WAIT_S; a binding turned off or replaced by a re-initialization in that wait still got its second attempt sent. The same held for a call that sends more than one request (query_types: the type list, then the query; get_block's second form; get_blocks' per-id fallback). CtxClient takes an optional before_send callable, called before every HTTP attempt; what it raises ends the call before that request goes out. Group clients pass one that refuses with binding_stale once their binding is no longer current (the check _BindingClient makes). A client without it (the profile's connection, the base-block hook's, the CLI's) sends as before. A group proof whose retry is stopped that way is no refusal by ctx: _prove_group returns on binding_stale, as the client proofs do, and the reason of the turn-off stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/client.py | 9 +- .../plugin/ctx_checkpoint/memory/provider.py | 21 +++- .../tests/test_access_binding_races.py | 115 ++++++++++++++++++ 3 files changed, 141 insertions(+), 4 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py index ade0f3da3..7bc0cb97b 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py @@ -39,7 +39,7 @@ import urllib.error import urllib.parse import urllib.request -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from typing import Any from .narrowing import HEADER_NARROWED, Narrowing, key_digest @@ -427,7 +427,11 @@ def __init__( timeout: float = 10.0, synthesis_timeout: float = 90.0, narrowing: Narrowing | None = None, + before_send: Callable[[], None] | None = None, ): + """``before_send``: called before every HTTP request this client sends (each attempt, the retry + after a 429 or a write_conflict included); whatever it raises ends the call before that request + goes out. ``None`` (the default): no call.""" parsed = urllib.parse.urlsplit(str(base_url or "").strip()) if parsed.scheme not in ("http", "https") or not parsed.netloc: # urllib would happily open file:// or other schemes; the store is an http(s) API. @@ -447,6 +451,7 @@ def __init__( # an answer lacks the right echo the client is off for good (``narrowing_lost``). self._narrowing = narrowing self._narrowing_lost = False + self._before_send = before_send # The server registry's type names (``query_types``), read once per client. self._type_names: frozenset[str] | None = None @@ -540,6 +545,8 @@ def _request( for attempt in (0, 1): # one retry on 429 (per-key write rate limit) or 409 write_conflict failure: CtxApiError | None = None + if self._before_send is not None: + self._before_send() # before every attempt; what it raises leaves this request unsent try: with _urlopen(req, timeout=t) as resp: if narrowing is not None and not _echo_matches(resp, narrowing): diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index f80841fa4..c8e570c45 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -159,7 +159,9 @@ class _BindingClient: """A group client tied to the binding it was built for: before every call it checks that this binding is still the provider's current one and not off, and refuses otherwise (``CtxApiError(code=BINDING_STALE)``) — a client of a stale binding sends nothing, however a - call got hold of it. Attributes pass through unchanged.""" + call got hold of it; the inner client checks the same before each request of a call + (``CtxClient(before_send=...)``, :meth:`CtxMemoryProvider._group_client`). Attributes + pass through unchanged.""" __slots__ = ("_current", "_inner") @@ -914,15 +916,26 @@ def _bind_group(self, decision: Any) -> None: self._prove_group(self._group) def _group_client(self, narrowing: Any, group: _GroupBinding) -> Any: - """A client of ``group``'s binding: it sends only while that binding is current.""" + """A client of ``group``'s binding: it sends only while that binding is current — checked before + each call and before each HTTP request of a call (a retry after a 429 or a write_conflict, the + second request of ``query_types`` or of a ``get`` fallback).""" + + def current() -> bool: + return self._group_current(group) + + def before_send() -> None: + if not current(): + raise CtxApiError(BINDING_STALE_TEXT, code=BINDING_STALE) + inner = CtxClient( self._base_url, self._api_key, timeout=float(self._config.get("api_timeout") or 10.0), synthesis_timeout=float(self._config.get("synthesis_timeout") or 90.0), narrowing=narrowing, + before_send=before_send, ) - return _BindingClient(inner, lambda: self._group_current(group)) + return _BindingClient(inner, current) def _resolve_group(self, group: _GroupBinding, budget: float) -> str: """The group's read set, write and store scope and its clients (``""``), or why it cannot @@ -1000,6 +1013,8 @@ def left() -> float: group.label = str(answer.get("label") or "") group.tenant_seen = str(narrowed.get("tenant_slug") or "") except CtxApiError as exc: + if exc.code == BINDING_STALE: + return # turned off or re-initialized while the proof waited: no refusal by ctx if _proof_transient(exc): group.retry_at["group"] = self._now() + PROOF_RETRY_S if self._group is not group: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py index ac3a6cf45..13309d8c8 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py @@ -457,3 +457,118 @@ def checkpoint_outcome(**kwargs): go.set() head = _joined(t1, box).split("`")[1] assert provider._active and head not in provider.system_prompt_block() + + +# -- every HTTP attempt of a group client checks its binding, not only the first (#4816055502) ----- + + +def _end_binding(how, provider, home): + if how == "turned-off": + provider._turn_off("trip wire: a turn of another group") + else: + _reinit_mods(provider, home) + assert provider._active, "mods is bound" + + +@pytest.mark.parametrize("how", ["turned-off", "replaced"]) +@pytest.mark.parametrize( + ("tool", "args", "path"), + [ + ("ctx_search", {"query": "plans"}, "/api/search"), + ("ctx_store", {"category": "c", "title": "t", "content": "x"}, "/api/store"), + ], + ids=["read", "store"], +) +def test_the_retry_after_a_429_is_not_sent_once_the_binding_ended_in_the_wait( + world, monkeypatch, how, tool, args, path +): + """``CtxClient`` sends a call again once after a 429 (or a write_conflict), after a wait. The binding + ends in that wait (turned off, or replaced by a re-initialization): the second attempt is not sent.""" + fake, host, home = world + _add_mods(fake, host) + fields = {**pc.OPS_FIELDS, "store": pc.A_K} + provider = pc._provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + waiting, go = threading.Event(), threading.Event() + + def sleep(seconds): + waiting.set() + assert go.wait(WAIT_S) + + monkeypatch.setattr(_client, "_sleep", sleep) + fake.reset_counters() + fake.throttle[path] = 1 + t1, box = _run(lambda: provider.handle_tool_call(tool, args)) + assert waiting.wait(WAIT_S), "the client waits before its retry" + _end_binding(how, provider, home) + go.set() + result = _joined(t1, box) + assert '"error"' in result and "bravo knowledge" not in result + assert fake.count(path) == 1, "only the attempt that met the 429" + + +def test_a_call_of_several_requests_sends_none_after_its_binding_ended(world, monkeypatch): + """A call that sends more than one request (``query_types``: the type list, then the query; also the + single-id ``get`` forms): the binding ends between them, the next request is not sent.""" + fake, _host, home = world + provider = _ops(home) + client = provider._group.read_client + arrived, go = threading.Event(), threading.Event() + sent: list[str] = [] + real = _client._urlopen + + def urlopen(req, *, timeout): + sent.append(req.full_url) + answer = real(req, timeout=timeout) + if len(sent) == 1: + arrived.set() + assert go.wait(WAIT_S) + return answer + + monkeypatch.setattr(_client, "_urlopen", urlopen) + fake.reset_counters() + t1, box = _run(lambda: client.query_types("plans", ["session-digest"], limit=3)) + assert arrived.wait(WAIT_S) + provider._turn_off("trip wire: a turn of another group") + go.set() + with pytest.raises(_client.CtxApiError) as refused: + _joined(t1, box) + assert refused.value.code == "binding_stale" + assert fake.count("/api/manage", "type-list") == 1 and fake.count("/api/query") == 0 + + +def test_a_proof_whose_retry_the_turn_off_stopped_keeps_the_turn_off_reason(world, monkeypatch): + """The group proof's ``whoami`` meets a 429; the binding is turned off in the wait, so the retry is + not sent (``binding_stale``). That is no refusal of the proof by ctx: the reason stays the turn-off's.""" + fake, _host, home = world + provider = _ops(home) + group = provider._group + _nar.reset_proofs() + waiting, go = threading.Event(), threading.Event() + + def sleep(seconds): + waiting.set() + assert go.wait(WAIT_S) + + monkeypatch.setattr(_client, "_sleep", sleep) + fake.reset_counters() + fake.throttle["/api/whoami"] = 1 + t1, box = _run(lambda: provider._prove_group(group)) + assert waiting.wait(WAIT_S), "the proof's client waits before its retry" + provider._turn_off("trip wire: a turn of another group") + go.set() + _joined(t1, box) + assert provider._access_off == "trip wire: a turn of another group" + assert fake.count("/api/whoami") == 1 + + +def test_the_profile_connection_retries_after_a_429_as_before(world, monkeypatch): + """Guard: a client without a binding (the profile's connection) is 0.19.1's: one retry after a 429.""" + fake, _host, home = world + slept: list[float] = [] + monkeypatch.setattr(_client, "_sleep", slept.append) + provider = pc._provider(home, platform="cli", **ah.v5_kwargs()) + assert provider._decision.kind == "profile" and provider._group is None + fake.reset_counters() + fake.throttle["/api/search"] = 1 + assert "alpha knowledge" in provider.handle_tool_call("ctx_search", {"query": "plans"}) + assert fake.count("/api/search") == 2 and slept == [_client.RATE_RETRY_WAIT_S] From 631f0e97747588bf1d6c2343b5e7b13207b49c00 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:54:47 +0100 Subject: [PATCH 41/65] fix(ctx_checkpoint): a restricted group's proof needs scope_narrowing required in the narrowed answer as well as the unnarrowed one E2 judged scope_narrowing only in the unnarrowed whoami answer. The proof store keeps the narrowed and the unnarrowed answer in separate slots, so a remembered unnarrowed answer could still say required while a fresh narrowed answer of the same key already said optional (the key was changed in between), and the restricted proof passed. ctx reports the field on both forms; a restricted proof now fails E2 unless both say required. Unrestricted proofs do not ask for the field. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/narrowing.py | 18 +++--- .../tests/test_access_review_r3.py | 55 +++++++++++++++++++ 2 files changed, 66 insertions(+), 7 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py index a6fac6773..d86b0898f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py @@ -257,11 +257,12 @@ def evaluate(raw_narrowed: Mapping[str, Any], raw_unnarrowed: Mapping[str, Any] """E2 to E5 and E7 over raw answers, pure, without network (design 02 §3.3). E5 (every binding): the narrowed answer reports exactly the narrowing sent. E2: the tenant, when - expected, in every answer; restricted (``strict``) also ``admin: false``, ``role: member`` and - ``scope_narrowing: required`` in the unnarrowed answer (a narrowed answer always reports member and - no admin). E3: the group's write scope is the key's home; restricted also the key's write set - exactly ``{write}``, its unnarrowed read set exactly ``read ∪ {write}`` and ``confirm_writes`` - off; unrestricted the read set within the key's. E4: the label, when expected, and always for + expected, in every answer; restricted (``strict``) also ``admin: false`` and ``role: member`` in the + unnarrowed answer (a narrowed answer always reports member and no admin) and ``scope_narrowing: + required`` in both (each answer comes from its own slot of the proof store). E3: the group's write + scope is the key's home; restricted also the key's write set exactly ``{write}``, its unnarrowed + read set exactly ``read ∪ {write}`` and ``confirm_writes`` off; unrestricted the read set within + the key's. E4: the label, when expected, and always for restricted groups. E7 (restricted): no foreign ctx key in the ``.env`` while the platform's toolsets read files or run commands. Restricted groups need an unnarrowed answer that reports no narrowing (and is of the same key, when both answers name it); without one E2 to E4 fail. A @@ -318,8 +319,11 @@ def fail(rule: str, text: str) -> None: fail("E2", "admin false") if key_answer.get("role") != "member": fail("E2", "role member") - if key_answer.get("scope_narrowing") != "required": - fail("E2", "scope_narrowing required") + # Both answers report the key's scope_narrowing, and each comes from its own slot of the proof store + # (one can be remembered from before the key changed): a restricted proof needs both to say it. + judged = [answer for answer in (narrowed, key_answer) if answer is not None] + if expect.strict and any(answer.get("scope_narrowing") != "required" for answer in judged): + fail("E2", "scope_narrowing required") # E3: the write scope is the key's home; restricted: the key's sets exactly the group's. if write is None: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py new file mode 100644 index 000000000..2233a9eab --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -0,0 +1,55 @@ +"""The third review round of the group binding (GottZ/ctx#596): each test builds the input or the +interleaving one finding names — a proof that judges a stale answer, a marker that is not explicitly +on disk, a cache entry used for a binding it did not come from, a writer that reports an older limit — +and shows that nothing is sent, served or planned on it. + +The interleavings are made with event barriers at the named points, never by guessing with sleeps.""" + +from __future__ import annotations + +import pytest +import test_access_pc_binding as pc +from fakes import access_host as ah + +pytestmark = pytest.mark.access_cluster("P-C") + +world = pc.world # the P-C world: fake ctx, host with the core PR's surface, a profile home +_nar = ah.plugin_module(pc._PKG, "memory.narrowing") + +K, M = pc.A_K, pc.A_MEMBERS +WAIT_S = 20.0 # a barrier that is not reached within this fails the test (no hang) + + +# -- E2: a restricted proof needs scope_narrowing required in both answers (#4816373553) ---------- + + +def _member_expect(**overrides): + values = { + "narrowing": _nar.Narrowing(read=(K,)), + "strict": True, + "tenant": "t", + "label": pc.MEMBER_LABEL, + "env_names": ("CTX_KEY_111_MEMBERS",), + "platform_toolsets": ("web",), + "scope_id": "111", + "write": M, + } + values.update(overrides) + return _nar.Expect(**values) + + +def test_a_restricted_proof_fails_when_the_narrowed_answer_reports_optional_narrowing(fake_ctx): + """The two answers live in separate slots of the proof store: the unnarrowed one can still say + ``required`` (remembered) while a fresh narrowed one already says ``optional`` (the key was changed). + Both answers report the field; a restricted proof takes neither alone.""" + fake_ctx.add_key( + secret=pc.MEMBER_KEY, tenant="t", home=M, allowed=(K,), scope_narrowing="required", label=pc.MEMBER_LABEL + ) + narrowed, key = fake_ctx.whoami_answer(pc.MEMBER_KEY, (K,), ""), fake_ctx.whoami_answer(pc.MEMBER_KEY) + assert _nar.evaluate(narrowed, key, _member_expect()).ok, "guard: both answers say required" + fresh = dict(narrowed, scope_narrowing="optional") + verdict = _nar.evaluate(fresh, key, _member_expect()) + assert not verdict.ok and verdict.failed == ("E2",), verdict + assert "scope_narrowing required" in verdict.detail["E2"] + unrestricted = _member_expect(strict=False, tenant=None, label=None, env_names=(), platform_toolsets=(), write=None) + assert _nar.evaluate(fresh, None, unrestricted).ok, "an unrestricted proof does not ask for the field" From cd4d75e1dda1c7f094e4593720d5b4b813b4cc4b Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:55:25 +0100 Subject: [PATCH 42/65] fix(ctx_checkpoint): provision checks the group's fields with every --read scope qualified before it sends the key set A --read scope named as <tenant>:<name> passed the check against the knowledge and the group's own scope, which compared bare names: the qualified knowledge scope gave a read list with a scope twice, the qualified own scope a write within read, one scope in its two forms a repeat, and a scope of another tenant a field the binding refuses. The command saved a key for fields that cannot bind. Now whoami runs first, every --read scope is qualified with the tenant's slug, and the fields the command will print are parsed the way the binding parses them (access.parse_fields, strict) before anything at ctx changes. Distinct scopes in either form are still taken. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 6 +- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 5 +- .../ctx_checkpoint/memory/access_cli.py | 55 +++++++++--- .../test_access_seam_provision_fields.py | 88 +++++++++++++++++++ 4 files changed, 141 insertions(+), 13 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 407d5c71e..1dfdc9688 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -602,7 +602,11 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co kept), sets `memory.ctx_checkpoint.ungoverned: local` (an `off` stays), and prints the `/policy field` line for an existing group and the `/policy group` line for a new one; `--emit-yaml` adds the whole group entry with its fields for `gateway.access_groups` (one write, so the group never exists without - its fields). A `--read` scope must already be a scope of the tenant. It replaces nothing silently: + its fields). A `--read` scope must already be a scope of the tenant, named `<name>` or + `<tenant>:<name>`; once `whoami` names the tenant, every scope is qualified and the fields the + command prints are checked the way the binding parses them, so a scope named twice (in either form), + the group's own or the knowledge scope, or a scope of another tenant is refused before anything is + created. It replaces nothing silently: before the set is made it asks ctx for the tenant's active keys (`api-key-list`) and refuses, naming what is there, a second group for a server and profile whose key another group's scope homes (one key per server and profile: give the second group a profile of its own) and a group whose scope is the diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index e6d64e309..cba513381 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -55,8 +55,9 @@ older server a group binding is off and the profile's own connection works as be check | provision | reset-marker`; a status file per binding (`ctx_state/access/`) with the outcome of its base blocks and the write or store client ctx refused (`bound; write client off: …`); `hermes memory status` is not ok while a binding, or one of its clients, is off for another reason - than its group's own fields. `provision` replaces no key silently: it asks ctx for the tenant's keys first - and refuses a second group of a server and profile and a scope another key homes; the same group + than its group's own fields. `provision` checks the fields it will print, with every `--read` scope + qualified, the way the binding parses them before it sends the set. It replaces no key silently: it + asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope another key homes; the same group again needs `--replace` while its key is in the `.env`. Only `--replace` sends `replace_label`, and ctx's refusal of a set whose label an active key carries (409 with `labels`) is named with what to do: the repeat of a run that stopped before its `.env` line deactivates by id the key the run's note diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index b9945b4da..60215b722 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -968,10 +968,30 @@ def _provision_locked( check, the retired keys of a stopped run, the set at ctx, the ``.env`` line and the record of the run — so a second run in this home sees what the first committed, and the ``.env`` ends with the key ctx committed last. Then the fields.""" + try: + slug = _tenant_slug(url, admin_key) + except ValueError: # a URL CtxClient does not take (no http(s), no host) + print(f" ✗ {_status.display_url(url) or url!r} is no http(s) URL of a ctx server; nothing was sent") + return 1 + except _client.CtxApiError as exc: + cause = _status.redact_error(exc, (admin_key,)) + print(f" ✗ ctx did not list the tenant's keys ({cause}); nothing was created") + return 1 + extra = [_full(scope, slug) for scope in extra] + fields, problem = _bound_fields( + slug, scope_id=scope_id, knowledge=knowledge, own=own, extra=extra, base_url_env=args.base_url_env, key=variable + ) + if problem: # every scope qualified now: the fields the binding parses, before anything changes at ctx + print( + f" ✗ the group's fields would not bind ({problem}): name each --read scope once, neither the group's " + f"own nor the knowledge scope, and only scopes of tenant {slug}; nothing was created" + ) + return 1 try: conflict, stopped_keys = _key_conflict( url, admin_key, + slug=slug, label=label, own=own, variable=variable, @@ -1063,7 +1083,7 @@ def _provision_locked( "that key, so one key stays active" ) return 1 - secret, slug, scopes = made + secret, _slug, scopes = made try: _write_env_line(env_path, variable, secret) except (OSError, ValueError) as exc: @@ -1085,11 +1105,6 @@ def _provision_locked( f"/policy field {group} server={scope_id} {access.NAMESPACE}.base_rev=<n+1> rebuilds them at once" ) rc = _ungoverned_local(home) - fields: dict[str, Any] = {"key": variable, "tenant": slug, "read": [_full(knowledge, slug)]} - fields["read"] += [_full(scope, slug) for scope in extra] - fields["write"] = _full(own, slug) - if args.base_url_env: - fields["base_url"] = args.base_url_env print(f" {_REVOKE}") _print_fields(platform, scope_id, profile, group, fields, roles, users, emit_yaml=args.emit_yaml) return rc @@ -1108,10 +1123,34 @@ def _env_values(home: str) -> dict[str, str]: return {} +def _tenant_slug(url: str, admin_key: str) -> str: + """The tenant slug ``whoami`` of the tenant-admin key names; ``CtxApiError`` when it names none.""" + who = _client.CtxClient(url, admin_key, timeout=REQUEST_TIMEOUT_S).whoami() + slug = who.get("tenant_slug") if isinstance(who, Mapping) and who.get("success") is not False else None + if not isinstance(slug, str) or not access.SLUG_PATTERN.match(slug): + raise _client.CtxApiError("whoami of the tenant-admin key names no tenant") + return slug + + +def _bound_fields( + slug: str, *, scope_id: str, knowledge: str, own: str, extra: Sequence[str], base_url_env: str | None, key: str +) -> tuple[dict[str, Any], str]: + """The group's fields as ``provision`` prints them (every scope ``<slug>:<name>``), and why the binding + would refuse them (``access.parse_fields``, strict: a scope named twice, ``write`` within ``read``, a + scope of another tenant); ``""`` when they bind.""" + fields: dict[str, Any] = {"key": key, "tenant": slug, "read": [_full(knowledge, slug), *extra]} + fields["write"] = _full(own, slug) + if base_url_env: + fields["base_url"] = base_url_env + parsed = access.parse_fields(fields, scope_id=scope_id, strict=True) + return fields, (f"{parsed.field}: {parsed.reason}" if isinstance(parsed, access.FieldError) else "") + + def _key_conflict( url: str, admin_key: str, *, + slug: str, label: str, own: str, variable: str, @@ -1131,10 +1170,6 @@ def _key_conflict( The key the note explains is the stopped run's: the repeat retires it by id, without ``replace_label`` (only *replace* sends it), so it never deactivates another group's key, and ctx takes the new set (a deactivated key does not hold the label).""" - who = _client.CtxClient(url, admin_key, timeout=REQUEST_TIMEOUT_S).whoami() - slug = who.get("tenant_slug") if isinstance(who, Mapping) and who.get("success") is not False else None - if not isinstance(slug, str) or not access.SLUG_PATTERN.match(slug): - raise _client.CtxApiError("whoami of the tenant-admin key names no tenant") listed = _manage_once(url, admin_key, {"action": "api-key-list", "data": {"active_only": True}}) keys = listed.get("keys") if listed.get("success") is not True or not isinstance(keys, list): diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py new file mode 100644 index 000000000..6e60f5bbc --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py @@ -0,0 +1,88 @@ +"""``access provision`` and the fields it prints (PR review of the plugin layer): what it sends to ctx +must give a group whose fields bind. ``--read`` takes a scope as ``<name>`` or ``<tenant>:<name>``; +once ``whoami`` names the tenant, every scope is qualified and the restricted fields the command will +print (``key``, ``tenant``, ``read``, ``write``, ``base_url``) are checked the way the binding parses +them (``access.parse_fields``, strict) before ``keyset-provision`` is sent: a scope named twice in its +two forms, the group's own or the knowledge scope named again, or a scope of another tenant are refused +with nothing created.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_provision_fields") +cli = ah.plugin_module(_PKG, "memory.access_cli") +acc = ah.plugin_module(_PKG, "memory.access") + +ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_fields" + + +@pytest.fixture +def ctx(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + fake_ctx.add_scope("t:d33-faq") + fake_ctx.add_scope("t:d33-rules") + fake_ctx.add_scope("u:d33-faq") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "process-home")) + return fake_ctx + + +def _home(root, profile="members"): + home = root / "profiles" / profile + home.mkdir(parents=True, exist_ok=True) + return home + + +def _provision(home, *extra): + argv = ["provision", "--server", "discord:111", "--profile", "members", "--group", "members"] + return cli.run_access([*argv, "--admin-key-env", "CTX_ADMIN", *extra], hermes_home=str(home)) + + +def _sets(fake): + return [r.body for r in fake.requests("/api/manage") if r.action == "keyset-provision"] + + +def _fields(out): + """The fields of the ``/policy field`` line the command printed.""" + (line,) = [line for line in out.splitlines() if line.strip().startswith("/policy field ")] + fields = {} + for pair in line.split()[4:]: + name, _eq, value = pair.partition("=") + name = name.removeprefix("ctx_checkpoint.") + fields[name] = value.split(",") if name == "read" else value + return fields + + +# -- finding 4816373524: --read is checked after the names are qualified -------------------------- + + +@pytest.mark.parametrize( + "read", + [ + ["t:d33-k"], # the knowledge scope, qualified: read twice + ["t:d33-members"], # the group's own scope, qualified: write within read + ["d33-faq", "t:d33-faq"], # one scope in its two forms + ["d33-faq", "d33-faq"], # one scope twice + ["u:d33-faq"], # a scope of another tenant + ], +) +def test_a_read_scope_the_bound_fields_would_refuse_creates_nothing(ctx, tmp_path, capsys, read): + home = _home(tmp_path) + rc = _provision(home, "--read", *read) + out = capsys.readouterr().out + assert rc != 0 and "--read" in out and "nothing was" in out, out + assert _sets(ctx) == [], "a key set whose fields cannot bind was sent" + assert not (home / ".env").exists() + assert "hermes:discord:111:members" not in cli._stopped_runs(str(home)) + + +def test_distinct_read_scopes_in_either_form_give_fields_that_bind(ctx, tmp_path, capsys): + home = _home(tmp_path) + assert _provision(home, "--read", "d33-faq", "t:d33-rules") == 0 + fields = _fields(capsys.readouterr().out) + assert fields["read"] == ["t:d33-k", "t:d33-faq", "t:d33-rules"] and fields["write"] == "t:d33-members" + parsed = acc.parse_fields(fields, scope_id="111", strict=True) + assert isinstance(parsed, acc.GroupFields), parsed From 071e62a64cd0e6846db3c54906ee48b1bdca2363 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:56:08 +0100 Subject: [PATCH 43/65] fix(ctx_checkpoint): a proof that meets a 5xx with a code is asked again, not taken as a refusal ctx answers an internal failure with HTTP 500 and the code internal. _proof_transient filtered coded errors before it looked at the status, so such an answer to a group proof turned the group off until the next agent build, and to a write or store client proof switched that client off for the binding; an uncoded 5xx left the proof pending. The base-block hook's _refused did the same and answered None, which the core keeps for the whole session. Both now classify a 5xx by its status first: a failure of the server, asked again (the proof stays pending, the hook raises BaseBlocksUnavailable). Refusals of the key or its narrowing (4xx with a code, 401/403) and the client's own refusals (a lost narrowing, a binding no longer current) stay final. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ctx_checkpoint/memory/base_blocks.py | 5 +- .../plugin/ctx_checkpoint/memory/provider.py | 8 +- .../tests/test_access_review_r3.py | 78 +++++++++++++++++++ 3 files changed, 88 insertions(+), 3 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index df9975c8a..7af66e5bb 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -442,7 +442,10 @@ def _profile_base_url(home: str) -> str: def _refused(error: CtxApiError) -> bool: """A failure that says this binding gets no text (a key or narrowing the server refuses, a lost - narrowing), as against one to try again later (network, time, 429, 5xx).""" + narrowing), as against one to try again later (network, time, 429, 5xx: a 5xx is the server's + failure whatever code it carries, ctx answers one with ``internal``).""" + if error.status is not None and error.status >= 500: + return False if error.code == "narrowing_lost" or error.status in (401, 403): return True return bool(error.code) and error.permanent diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index c8e570c45..b9bc0fb93 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -265,10 +265,14 @@ def _turn_key(context: Any) -> tuple[str, ...]: def _proof_transient(exc: CtxApiError) -> bool: """A proof that failed on the network, on time or on the server (no answer, 5xx, 429), not on a - refusal of the key or its narrowing; only such a proof is asked again.""" + refusal of the key or its narrowing; only such a proof is asked again. A 5xx is the server's + failure whatever code it carries (ctx answers one with ``internal``); a refusal of the client itself + (a lost narrowing, a binding no longer current) carries no 5xx.""" + if exc.status is not None and exc.status >= 500: + return True if exc.code and exc.code not in RETRYABLE_CODES: return False - return exc.status is None or exc.status == 429 or exc.status >= 500 + return exc.status is None or exc.status == 429 def _proof_cause(exc: CtxApiError) -> str: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 2233a9eab..2e5f798be 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -53,3 +53,81 @@ def test_a_restricted_proof_fails_when_the_narrowed_answer_reports_optional_narr assert "scope_narrowing required" in verdict.detail["E2"] unrestricted = _member_expect(strict=False, tenant=None, label=None, env_names=(), platform_toolsets=(), write=None) assert _nar.evaluate(fresh, None, unrestricted).ok, "an unrestricted proof does not ask for the field" + + +# -- a 5xx with a code is a failure of the server, asked again, never a refusal (#4816373556) ------- + +_prov = ah.plugin_module(pc._PKG, "memory.provider") +_bb = ah.plugin_module(pc._PKG, "memory.base_blocks") + + +def _ops(home, fields=None): + v5 = ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields or pc.OPS_FIELDS) + return pc._provider(home, **v5) + + +def _server_error(monkeypatch, fake, route: str, times: int) -> dict: + """The next ``times`` requests to ``route`` get ctx's answer to an internal failure: HTTP 500 with + ``{"success": false, "code": "internal"}`` (go:errcode.go ``classInternal``).""" + state = {"left": times} + real = fake._answer + + def answer(method, path, action, body, secret, read_values, write_values): + if path == route and state["left"] > 0: + state["left"] -= 1 + return 500, {"success": False, "error": "internal error", "code": "internal"}, None + return real(method, path, action, body, secret, read_values, write_values) + + monkeypatch.setattr(fake, "_answer", answer) + return state + + +def test_a_group_proof_that_meets_a_coded_5xx_stays_pending_and_binds_once_the_server_answers(world, monkeypatch): + fake, _host, home = world + clock = [1000.0] + monkeypatch.setattr(pc._PKG, "_monotonic", lambda: clock[0]) + _nar.reset_proofs() + _server_error(monkeypatch, fake, "/api/whoami", 1) + provider = _ops(home) + assert provider._access_off == "", f"a server failure turned the group off: {provider._access_off}" + assert provider._group is not None and "group" not in provider._group.proven + _nar.reset_proofs() # the failure the proof store keeps 15 s + clock[0] += _prov.PROOF_RETRY_S + 1 + provider.queue_prefetch("plans?") + pc._settle(provider) + assert provider._active and "alpha knowledge" in provider.prefetch("plans?") + + +def test_a_store_client_proof_that_meets_a_coded_5xx_is_asked_again(world, monkeypatch): + fake, _host, home = world + clock = [1000.0] + monkeypatch.setattr(pc._PKG, "_monotonic", lambda: clock[0]) + fields = {**pc.OPS_FIELDS, "store": K} + provider = pc._provider(home, **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=fields)) + assert provider._active + _nar.reset_proofs() + _server_error(monkeypatch, fake, "/api/whoami", 1) + assert '"error"' in provider.handle_tool_call("ctx_store", {"category": "c", "title": "t", "content": "x"}) + assert "store" not in provider._group.refused, provider._group.refused + _nar.reset_proofs() + clock[0] += _prov.PROOF_RETRY_S + 1 + assert '"error"' not in provider.handle_tool_call("ctx_store", {"category": "c", "title": "t", "content": "x"}) + + +def test_a_base_block_proof_that_meets_a_coded_5xx_is_unavailable_not_none(world, monkeypatch): + """``None`` is kept by the core for the whole session; a failure of the server must leave it asking.""" + import asyncio + + fake, _host, _home = world + _bb.reset_state() + _nar.reset_proofs() + block = fake.add_block(K, "House rules", "Be kind.") + fields = {"ctx_checkpoint": {**pc.OPS_FIELDS, "base_blocks": [block]}} + _server_error(monkeypatch, fake, "/api/whoami", 1) + kwargs = ah.hook_kwargs(fields=fields, restricted=False, scope_id="111", group="ops") + outcome = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert not outcome.answered and isinstance(outcome.error, _bb.BaseBlocksUnavailable), outcome + _nar.reset_proofs() + outcome = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert outcome.answered and "House rules" in outcome.result["prompt"], outcome + _bb.reset_state() From edab0bfcec71a1b671e951062502c2386f83cd99 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:57:36 +0100 Subject: [PATCH 44/65] fix(ctx_checkpoint): provision reads --base-url-env from the profile's .env and secret sources, as the binding does The variable --base-url-env names was read through the secret scope and then the shell's environment. A value only the shell held made provision create a key at that server and print a base_url field that access check and the gateway resolve from the profile's own .env and secret sources, where it is missing: a binding that cannot connect. Now the value comes from the profile's secrets only (the mapping the binding uses); a variable that is not there sends nothing and names the shell when it holds one. The tenant-admin key is still read from the shell's environment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 4 +- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 3 +- .../ctx_checkpoint/memory/access_cli.py | 20 +++++++--- .../test_access_seam_provision_fields.py | 37 +++++++++++++++++++ 4 files changed, 57 insertions(+), 7 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 1dfdc9688..96df1a0f9 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -606,7 +606,9 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co `<tenant>:<name>`; once `whoami` names the tenant, every scope is qualified and the fields the command prints are checked the way the binding parses them, so a scope named twice (in either form), the group's own or the knowledge scope, or a scope of another tenant is refused before anything is - created. It replaces nothing silently: + created. `--base-url-env` names the variable of another ctx server, read from the profile's `.env` + and secret sources only, where the gateway and `access check` read the group's `base_url` (a value + only the shell's environment holds sends nothing). It replaces nothing silently: before the set is made it asks ctx for the tenant's active keys (`api-key-list`) and refuses, naming what is there, a second group for a server and profile whose key another group's scope homes (one key per server and profile: give the second group a profile of its own) and a group whose scope is the diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index cba513381..2500d564c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -56,7 +56,8 @@ older server a group binding is off and the profile's own connection works as be its base blocks and the write or store client ctx refused (`bound; write client off: …`); `hermes memory status` is not ok while a binding, or one of its clients, is off for another reason than its group's own fields. `provision` checks the fields it will print, with every `--read` scope - qualified, the way the binding parses them before it sends the set. It replaces no key silently: it + qualified, the way the binding parses them before it sends the set, and reads `--base-url-env` from + the profile's `.env` and secret sources only, as the binding does. It replaces no key silently: it asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope another key homes; the same group again needs `--replace` while its key is in the `.env`. Only `--replace` sends `replace_label`, and ctx's refusal of a set whose label an active key carries (409 with `labels`) is named with what to do: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 60215b722..7798777e1 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -310,9 +310,9 @@ def _ids(text: str, option: str) -> list[str]: def _secret(name: str) -> str: - """A variable for ``provision`` (the tenant-admin key, which belongs in the shell's environment, and - ``--base-url-env``): the secret scope, then the process environment; never printed. ``check`` reads - the group's variables from the profile only (:func:`_profile_secrets`).""" + """The tenant-admin key of ``provision``, which belongs in the shell's environment: the secret scope, + then the process environment; never printed. ``check`` and ``provision --base-url-env`` read the + group's variables from the profile only (:func:`_profile_secrets`), as the binding does.""" try: value = env_secret(name) except Exception: @@ -902,8 +902,18 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: f" ⚠ {args.admin_key_env} is in this profile's .env: a tenant-admin key in a profile that serves " "groups is within reach of its tools; keep it in the shell's environment for this command only" ) - if args.base_url_env: - url = _secret(args.base_url_env) + if args.base_url_env: # read where the binding and access check read it: never the shell's environment + secrets = _profile_secrets(home) + if secrets is None: + print(" ✗ the profile's .env and secret sources cannot be read; nothing was sent") + return 1 + url = secrets.get(args.base_url_env, "").strip() + if not url: + print( + f" ✗ {args.base_url_env} is not in the profile's .env or its secret sources, where the gateway " + f"and access check read it{_shell_has(args.base_url_env)}; nothing was sent" + ) + return 1 if not access.valid_base_url(url): print(f" ✗ {args.base_url_env} holds no https URL of a ctx server; nothing was sent") return 1 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py index 6e60f5bbc..cc5325453 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py @@ -86,3 +86,40 @@ def test_distinct_read_scopes_in_either_form_give_fields_that_bind(ctx, tmp_path assert fields["read"] == ["t:d33-k", "t:d33-faq", "t:d33-rules"] and fields["write"] == "t:d33-members" parsed = acc.parse_fields(fields, scope_id="111", strict=True) assert isinstance(parsed, acc.GroupFields), parsed + + +# -- finding 4816373530: --base-url-env is read where the binding reads it ------------------------ + + +@pytest.fixture +def plain_http(monkeypatch): + """The fake serves plain http on 127.0.0.1; a ``base_url`` value must be https. This seam lets the + fake stand for the other ctx server so the test can see where the command sends its set.""" + monkeypatch.setattr(acc, "valid_base_url", lambda url: url.startswith(("http://", "https://"))) + + +def test_a_base_url_variable_only_the_shell_holds_sends_nothing(ctx, tmp_path, monkeypatch, plain_http, capsys): + """``access check`` and the gateway read ``base_url`` from the profile's ``.env`` and secret sources; + a key made at the server a shell variable names would give a binding that cannot connect.""" + monkeypatch.setenv("CTX_BASE_URL_OTHER", ctx.url) + home = _home(tmp_path) + rc = _provision(home, "--base-url-env", "CTX_BASE_URL_OTHER") + out = capsys.readouterr().out + assert rc == 1 and "CTX_BASE_URL_OTHER" in out and ".env" in out and "nothing was sent" in out, out + assert ctx.count() == 0 and not (home / ".env").exists() + + +def test_the_base_url_variable_of_the_profile_wins_over_the_shell(ctx, tmp_path, monkeypatch, plain_http, capsys): + monkeypatch.setenv("CTX_BASE_URL_OTHER", "https://shell.invalid") + home = _home(tmp_path) + (home / ".env").write_text(f"CTX_BASE_URL_OTHER={ctx.url}\n", encoding="utf-8") + assert _provision(home, "--base-url-env", "CTX_BASE_URL_OTHER") == 0 + assert len(_sets(ctx)) == 1 + assert _fields(capsys.readouterr().out)["base_url"] == "CTX_BASE_URL_OTHER" + + +def test_the_admin_key_is_still_taken_from_the_shell(ctx, tmp_path, monkeypatch, capsys): + """Only ``--base-url-env`` moves to the profile: the tenant-admin key belongs in the shell.""" + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": ctx.url}) + home = _home(tmp_path) + assert _provision(home) == 0 and len(_sets(ctx)) == 1 From ff53a0afce07cde6893cd58c859e1ba31adcaa36 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:58:24 +0100 Subject: [PATCH 45/65] fix(ctx_checkpoint): a marker counts as on disk for serving a group only where the file holds an explicit true for it markers_held read the markers back with the decisions' reading, in which a file that is an empty object, does not parse, is no object or holds anything but false for a marker counts that marker as set; _raise_markers skipped its write for the same reason. A governed session was then served (and the base-block hook gave its text) without the marker being persisted explicitly, also when it could not have been written. The confirmation now reads the file strictly (access.markers_on_disk): each marker the session needs must be JSON true. _raise_markers writes whenever a wanted marker is not explicitly true, with every marker the decisions read as set kept set, now explicitly. read_markers, which decisions and the sessions without a group read, is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/access.py | 85 +++++++++++------ .../tests/test_access_review_r3.py | 93 +++++++++++++++++++ 2 files changed, 151 insertions(+), 27 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py index 87cf3e5fe..523646209 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -777,30 +777,48 @@ def read_markers(hermes_home: str) -> Markers: """The markers of ``<home>/ctx_state/access-mode.json``. A missing file is no marker; a file that cannot be read, does not parse, or holds anything but ``false`` for a marker counts as that marker set.""" - return _read_markers(hermes_home, unreadable=Markers(restricted_seen=True, governed_seen=True)) + found, data = _markers_data(hermes_home) + if not found: + return Markers() + if not isinstance(data, dict): + return Markers(restricted_seen=True, governed_seen=True) + return Markers( + restricted_seen=data.get("restricted_seen") is not False, + governed_seen=data.get("governed_seen") is not False, + ) + + +def _markers_on_disk(hermes_home: str) -> Markers: + """The markers the file holds explicitly: a marker is set only where the file is a JSON object with + ``true`` for it. A missing, unreadable or unparsable file, or any other value, holds none.""" + found, data = _markers_data(hermes_home) + if not found or not isinstance(data, dict): + return Markers() + return Markers( + restricted_seen=data.get("restricted_seen") is True, + governed_seen=data.get("governed_seen") is True, + ) -def _read_markers(hermes_home: str, *, unreadable: Markers) -> Markers: - """``read_markers`` with ``unreadable`` for a file that cannot be read (``ctx_state`` no directory, - no permission, an I/O error).""" +_UNREADABLE = object() + + +def _markers_data(hermes_home: str) -> tuple[bool, Any]: + """(whether the marker file exists, its parsed JSON); a file that cannot be read (``ctx_state`` no + directory, no permission, an I/O error) or parsed, or is too large, exists with data that is no + object.""" path = _markers_path(hermes_home) try: with path.open("rb") as handle: raw = handle.read(_MARKERS_MAX_BYTES + 1) except FileNotFoundError: - return Markers() + return False, None except OSError: - return unreadable + return True, _UNREADABLE try: - data = json.loads(raw.decode("utf-8")) if len(raw) <= _MARKERS_MAX_BYTES else None + return True, json.loads(raw.decode("utf-8")) if len(raw) <= _MARKERS_MAX_BYTES else None except (UnicodeDecodeError, ValueError): - data = None - if not isinstance(data, dict): - return Markers(restricted_seen=True, governed_seen=True) - return Markers( - restricted_seen=data.get("restricted_seen") is not False, - governed_seen=data.get("governed_seen") is not False, - ) + return True, None @contextmanager @@ -874,19 +892,24 @@ def raise_markers(hermes_home: str, **flags: bool) -> None: def _raise_markers(hermes_home: str, wanted: set[str], wait_s: float | None) -> None: """``raise_markers`` for the marker names ``wanted``, waiting at most ``wait_s`` for their lock - (``_markers_lock``).""" - if not wanted or all(getattr(read_markers(hermes_home), name) for name in wanted): - return # markers only rise: one already set needs no lock and no write + (``_markers_lock``). A marker counts as raised only where the file holds it explicitly + (``_markers_on_disk``); the file written keeps every marker a decision reads as set + (``read_markers``), now explicitly.""" + if not wanted or all(getattr(_markers_on_disk(hermes_home), name) for name in wanted): + return # markers only rise: one already on disk needs no lock and no write path = _markers_path(hermes_home) try: with _markers_lock(path.parent, wait_s): + if all(getattr(_markers_on_disk(hermes_home), name) for name in wanted): + return # another writer raised them meanwhile current = read_markers(hermes_home) - raised = Markers( - restricted_seen=current.restricted_seen or "restricted_seen" in wanted, - governed_seen=current.governed_seen or "governed_seen" in wanted, + _write_markers( + path, + Markers( + restricted_seen=current.restricted_seen or "restricted_seen" in wanted, + governed_seen=current.governed_seen or "governed_seen" in wanted, + ), ) - if raised != current: - _write_markers(path, raised) except Exception: logger.warning("ctx_checkpoint: the access-group marker file %s could not be written", path, exc_info=True) @@ -895,15 +918,22 @@ def markers_held(hermes_home: str, needed: Mapping[str, bool], *, wait_s: float """Whether a session of an access group may be served: the markers it raises (``needed``, from ``seen_markers``) are raised (``raise_markers``, waiting at most ``wait_s`` for their lock) and then read back from disk; a raise another process made meanwhile counts. The one rule of the provider's - ``initialize`` and the base-block hook. Unlike ``read_markers``, a file that cannot be read holds no - marker here: what a decision must read as set is not on disk, and a later reader that can read the - path again (``ctx_state`` replaced, permissions fixed) would not find it.""" + ``initialize`` and the base-block hook. Unlike ``read_markers``, only an explicit ``true`` in the file + holds a marker here (``markers_on_disk``): a file that cannot be read, does not parse or names no + ``true`` for it is no proof that a later reader (another plugin version, the path readable again, + the file repaired by hand) finds it set.""" wanted = {name for name, value in _marker_flags(needed).items() if value} if not wanted: return True _raise_markers(hermes_home, wanted, wait_s) - on_disk = _read_markers(hermes_home, unreadable=Markers()) - return all(getattr(on_disk, name) for name in wanted) + return markers_on_disk(hermes_home, needed) + + +def markers_on_disk(hermes_home: str, needed: Mapping[str, bool]) -> bool: + """Whether every marker ``needed`` names (from ``seen_markers``) is an explicit ``true`` in the + marker file now; read only, no lock, nothing raised.""" + on_disk = _markers_on_disk(hermes_home) + return all(getattr(on_disk, name) for name, value in _marker_flags(needed).items() if value) def reset_markers(hermes_home: str, *, restricted: bool = False, governed: bool = False) -> None: @@ -1155,6 +1185,7 @@ def decide( "is_strict", "load_settings", "markers_held", + "markers_on_disk", "parse_fields", "raise_markers", "read_markers", diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 2e5f798be..85d6876ab 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -131,3 +131,96 @@ def test_a_base_block_proof_that_meets_a_coded_5xx_is_unavailable_not_none(world outcome = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) assert outcome.answered and "House rules" in outcome.result["prompt"], outcome _bb.reset_state() + + +# -- markers on disk: each marker a session needs is an explicit true in the file (#4816373536) ----- + +_acc = ah.plugin_module(pc._PKG, "memory.access") +NOT_EXPLICIT = { + "empty-object": "{}", + "malformed": "{not json", + "not-an-object": "[]", + "not-true": '{"restricted_seen": false, "governed_seen": "yes"}', +} + + +def _marker_file(home, text: str): + path = home / _acc.MARKERS_FILE + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + +def _full_disk(monkeypatch) -> dict: + state = {"full": True} + real = _acc._write_markers + + def write(path, markers): + if state["full"]: + raise OSError(28, "No space left on device") + return real(path, markers) + + monkeypatch.setattr(_acc, "_write_markers", write) + return state + + +@pytest.mark.parametrize("text", NOT_EXPLICIT.values(), ids=NOT_EXPLICIT.keys()) +def test_a_group_is_not_served_on_a_marker_file_without_an_explicit_true_it_cannot_write(world, monkeypatch, text): + """Read for a decision, such a file counts as both markers set (the guard at the end); as proof that + a governed session's marker is on disk it holds none, and the marker cannot be written.""" + fake, _host, home = world + _marker_file(home, text) + read = _acc.read_markers(str(home)) + assert read.governed_seen, "guard: a decision reads the governed marker as set" + _full_disk(monkeypatch) + provider = _ops(home) + assert provider._decision.kind == "off", provider._decision + assert provider.prefetch("plans?") == "" and fake.count() == 0 + assert _acc.read_markers(str(home)) == read, "the decisions' reading is unchanged" + + +@pytest.mark.parametrize("text", NOT_EXPLICIT.values(), ids=NOT_EXPLICIT.keys()) +def test_a_marker_without_an_explicit_true_is_written_before_its_group_is_served(world, text): + import json + + _fake, _host, home = world + path = _marker_file(home, text) + read = _acc.read_markers(str(home)) + assert "alpha knowledge" in _ops(home).prefetch("plans?") + try: + data = json.loads(path.read_text(encoding="utf-8")) + except ValueError: + data = None + # Raised over what a decision read: every marker it read as set stays set, now explicitly. + explicit = ( + isinstance(data, dict) + and data.get("governed_seen") is True + and data.get("restricted_seen") is read.restricted_seen + ) + assert explicit, f"the marker file was served without an explicit true: {path.read_text(encoding='utf-8')!r}" + + +def test_the_base_block_hook_gives_no_text_on_a_marker_file_without_an_explicit_true(world, monkeypatch): + import asyncio + + fake, _host, _home = world + _bb.reset_state() + hook_home = ah_home() + _marker_file(hook_home, "{}") + _full_disk(monkeypatch) + block = fake.add_block(K, "House rules", "Be kind.") + fields = {"ctx_checkpoint": {**pc.OPS_FIELDS, "base_blocks": [block]}} + kwargs = ah.hook_kwargs(fields=fields, restricted=False, scope_id="111", group="ops") + fake.reset_counters() + outcome = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert not outcome.answered and isinstance(outcome.error, _bb.BaseBlocksUnavailable), outcome + assert fake.count() == 0 + _bb.reset_state() + + +def ah_home(): + """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" + import os + from pathlib import Path + + return Path(os.environ["HERMES_HOME"]) From 099db02acaef85194035dd4dd0be7c8ed06df441 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:58:58 +0100 Subject: [PATCH 46/65] docs(ctx_checkpoint): a deactivated key's base blocks can still come from the render cache for up to base_cache_s The README said a deactivated key fails from its next request on, which read as a cut-off for everything the group gets. A base-block text in the render cache is given without a request (the cache hit comes before the proof), so a new session of the group can still receive it until the entry expires (base_cache_s, 900 s by default) or is pushed out; raising the group's base_rev changes the cache key at once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- integrations/hermes/plugin/ctx_checkpoint/README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 96df1a0f9..bda84f506 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -708,8 +708,11 @@ settings write with a tenant-admin key of the group's home scope, or ctx's globa `scope_narrowing: required` refuses a client that leaves it out (E2 demands it of restricted groups, not of unrestricted ones). - **Rights changed after a binding** are proven again at the next agent build; until then the reads - stay within the narrowing. A deactivated key fails from its next request on; a base-block text - already given to a session stays in its prompt until a new session or `base_rev`. + stay within the narrowing. A deactivated key fails from its next request on, but the base blocks are + not a request when the render cache holds their text: a new session of the group can still get it + for up to `base_cache_s` (900 s by default) after the deactivation, until the entry expires or is + pushed out (raising the group's `base_rev` changes the cache key at once). A base-block text already + given to a session stays in its prompt until a new session or `base_rev`. - **Writes after a group change**: every call works on the binding the gate checked; a client of a binding that was replaced or turned off since sends nothing, so a write the old binding scheduled and had not sent is dropped (its exchanges count again for the next digest). A request already on its way From 9b31cfbe567f8b1a187c9634ecf70bfebcb82dd8 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 11:59:47 +0100 Subject: [PATCH 47/65] fix(ctx_checkpoint): the base-block hook reads a group's markers back on every call, also within the reuse of a check that found them A check that raised and found the markers on disk was reused for MARKERS_HELD_S (5 s) without any read: a ctx_state that became unreadable (or a marker lowered) within those seconds still counted as confirmed, and the hook served its cached text for a session the provider refuses. Within the reuse a call now reads the markers back strictly (access.markers_on_disk; no lock, no write); a call that no longer finds them runs the full check, which raises them again or gives no text (BaseBlocksUnavailable). README and CHANGELOG say the markers must be an explicit true and are read back on every call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 8 +++-- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 7 +++-- .../ctx_checkpoint/memory/base_blocks.py | 22 +++++++------- .../tests/test_access_pd_base_blocks.py | 2 +- .../tests/test_access_review_r3.py | 29 +++++++++++++++++++ 5 files changed, 51 insertions(+), 17 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 407d5c71e..29fcb7b76 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -459,9 +459,11 @@ agent before a turn). A profile that has served a restricted group gets no ctx for any session without its group, on any Hermes. Both are markers in `ctx_state/access-mode.json` (`governed_seen`, `restricted_seen`): they only rise, survive the state pruning, and only `hermes ctx_checkpoint access reset-marker` lowers them. A session of a governed group -is served only once the markers it raises are on disk: while `ctx_state` cannot be written (a full disk, -a lock another process holds, a file where the directory belongs), that session gets no ctx, its base -blocks included, and the next `initialize` tries again (the base-block hook on a later turn). The hook +is served only once the markers it raises are on disk, each an explicit `true` in the file (a file that +is empty, broken or names no `true` for it is rewritten first): while `ctx_state` cannot be written (a +full disk, a lock another process holds, a file where the directory belongs), that session gets no ctx, +its base blocks included (the hook reads the markers back on every call), and the next `initialize` +tries again (the base-block hook on a later turn). The hook knows the group's restriction, not the profile's: a session of an unrestricted group in a profile that also serves a restricted group can get its base blocks while `governed_seen` is on disk and `restricted_seen` cannot be written. diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index e6d64e309..df15fc4c3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -35,9 +35,10 @@ older server a group binding is off and the profile's own connection works as be required narrowing, exact read and write sets, label `hermes:<platform>:<server>:<profile>`, the narrowing echoed, no foreign key with file tools in the profile). A lost echo, a group change within a turn or a failed proof turns the agent off. Blocks a group writes carry `server:`/`group:` tags - and the chain `ctx_plugin.access`. A governed session is served only once its markers are on disk - (a full disk, a busy lock or an unreadable `ctx_state` leaves it off until a later `initialize`); - the base-block hook checks its group's markers the same way before it gives a text. Every call + and the chain `ctx_plugin.access`. A governed session is served only once its markers are on disk, + each an explicit `true` in the file (a full disk, a busy lock or an unreadable `ctx_state` leaves it + off until a later `initialize`); the base-block hook checks its group's markers the same way, and + reads them back on every call, before it gives a text. Every call works on one snapshot of the binding: a client of a binding that was replaced or turned off since sends nothing (client code `binding_stale`), a proof that completes after that counts for nothing, and a turn-off is never overwritten by a proof's publication. A `whoami` that got no answer within one caller's diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index 7af66e5bb..9ffa0c6c3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -20,8 +20,8 @@ 3. the markers this group's session raises, raised and read back on disk (``access.markers_held``, the rule of the provider's ``initialize``; their lock waited for within the call's budget), before the render cache is asked: not on disk (a full disk, a busy lock, an unreadable ``ctx_state``) means no - text and no request (``BaseBlocksUnavailable``), and a check that found them is reused for - ``MARKERS_HELD_S`` (markers only rise). Then the URL (a ``base_url`` field names an ``https`` + text and no request (``BaseBlocksUnavailable``); within ``MARKERS_HELD_S`` of a check that found + them a call only reads them back, without their lock. Then the URL (a ``base_url`` field names an ``https`` value), then the key, then the E7 inputs of the profile: the expectation the binding is judged by. The render cache key is that whole expectation (URL, key digest, fields, strictness, tenant, label, server, E7 inputs), so a cached text is only @@ -170,11 +170,11 @@ class _Plan: # group without base blocks reports only when it differs (the hot paths stay one dict lookup). _REPORTED: dict[tuple[str, str, str, str], str | None] = {} REPORTED_MAX = 65_536 -# A check that found a home's markers on disk (``access.markers_held``) is reused this long, on the -# render cache's clock: markers only rise, so a reuse misses nothing but a lowering within it (``access -# reset-marker``, the file or ``ctx_state`` removed; the provider's ``initialize`` reads them anew for -# every session). The slots (home and the markers checked) are cleared whole when there are more than -# ``MARKERS_HELD_MAX``. +# A check that raised and found a home's markers on disk (``access.markers_held``) spares the next calls +# its lock and write this long, on the render cache's clock: they only read the markers back +# (``access.markers_on_disk``), so a lowering within it (``access reset-marker``, the file or +# ``ctx_state`` removed or unreadable) is seen by the next call, which then checks in full. The slots +# (home and the markers checked) are cleared whole when there are more than ``MARKERS_HELD_MAX``. MARKERS_HELD_S = 5.0 MARKERS_HELD_MAX = 65_536 _MARKERS_HELD: dict[tuple[str, tuple[str, ...]], float] = {} @@ -468,7 +468,8 @@ def _markers_held(request: _Request, home: str, deadline: float) -> bool: """Step 3's markers on the pool: whether the markers this group's session raises are on disk in the serving profile's home (``access.markers_held`` with ``access.seen_markers``, as the provider's ``initialize`` decides it), raised now when they are not, their lock waited for at most until - ``deadline``. A check that found them is reused for :data:`MARKERS_HELD_S`. + ``deadline``. Within :data:`MARKERS_HELD_S` of a check that found them, a call only reads them back + (``access.markers_on_disk``); one that no longer finds them checks in full. The hook knows the group's restriction, not the profile's: ``restricted_seen`` only for a group the core told is restricted (``initialize`` gets that as a bool; a restriction not told never raises the @@ -486,8 +487,9 @@ def _markers_held(request: _Request, home: str, deadline: float) -> bool: needed = access.seen_markers({}, access.Decision("group", "base blocks", context=context, strict=known)) slot = (home, tuple(sorted(name for name, wanted in needed.items() if wanted))) with _LOCK: - if _MARKERS_HELD.get(slot, 0.0) > _now(): - return True + reused = _MARKERS_HELD.get(slot, 0.0) > _now() + if reused and access.markers_on_disk(home, needed): + return True # raised within the reuse and still on disk now: no lock, no write if not access.markers_held(home, needed, wait_s=_left(deadline)): return False with _LOCK: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py index 5bd1e6671..dd7757e61 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py @@ -322,7 +322,7 @@ def test_a_cached_text_is_given_only_while_the_markers_are_on_disk(world, monkey def test_the_marker_check_runs_on_the_pool_and_a_warm_call_reuses_it(world, monkeypatch): """The check reads (and may wait for the markers' lock) off the gateway loop; a warm call within its - short reuse reads no marker file.""" + short reuse only reads the markers back (no lock, no write).""" _fake, _host, ids, _home = world threads: list[str] = [] real = getattr(_acc, "markers_held", None) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 85d6876ab..585213c58 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -218,6 +218,35 @@ def test_the_base_block_hook_gives_no_text_on_a_marker_file_without_an_explicit_ _bb.reset_state() +# -- the hook's reuse of a markers check reads them back every call (#4816373540) ------------------- + + +def test_a_reused_markers_check_gives_no_text_once_ctx_state_became_unreadable(world): + """The first call raises and confirms the markers; ``ctx_state`` then becomes unreadable (here: a + file), well within the check's reuse and the text's cache life (no clock moves). The provider + refuses such a session; the hook must not serve it from its cache either.""" + import asyncio + import shutil + + fake, _host, _home = world + _bb.reset_state() + block = fake.add_block(K, "House rules", "Be kind.") + fields = {"ctx_checkpoint": {**pc.OPS_FIELDS, "base_blocks": [block]}} + kwargs = ah.hook_kwargs(fields=fields, restricted=False, scope_id="111", group="ops") + first = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert first.answered and "House rules" in first.result["prompt"], first + if _bb._REPORTS is not None: # the outcome file of the first call is written: ctx_state is ours now + _bb._REPORTS.submit(lambda: None).result(WAIT_S) + state = ah_home() / "ctx_state" + shutil.rmtree(state) + state.write_text("not a directory\n", encoding="utf-8") + fake.reset_counters() + second = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert not second.answered and isinstance(second.error, _bb.BaseBlocksUnavailable), second + assert fake.count() == 0 + _bb.reset_state() + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From d2489e1775b1508225a5ad5ec8ecaf9bdfa02607 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:01:01 +0100 Subject: [PATCH 48/65] fix(ctx_checkpoint): an unrestricted group without read never reads the key's home scope, also when it names another write scope The README says that a group without read reads the key's read set without its home scope. _resolve_group removed only the group's write scope: for a key homed in one scope and a group that names write: <another scope> (with capture off its write scope is not checked against the home), the home scope stayed in the read set, and recall and the read tools read it. The default read set now leaves out both the key's home scope and the group's write scope; an explicit read list is unchanged. The base-block hook was not affected: its proof checks a named write scope against the key's home for every group (E3), so such a group gets no base-block text; a guard test pins that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/provider.py | 6 +- .../tests/test_access_review_r3.py | 56 +++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index b9bc0fb93..8eaf66142 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -944,8 +944,8 @@ def before_send() -> None: def _resolve_group(self, group: _GroupBinding, budget: float) -> str: """The group's read set, write and store scope and its clients (``""``), or why it cannot bind. An unrestricted group that names no ``read``/``write`` takes the key's: the key's home - scope is the write scope, the key's read set without it the read set (one unnarrowed - ``whoami``, raised as ``CtxApiError`` when it fails).""" + scope is the write scope, the key's read set without its home scope and without the group's + write scope the read set (one unnarrowed ``whoami``, raised as ``CtxApiError`` when it fails).""" read, write = group.fields_read, group.fields_write if not (read and write): raw = _narrowing.whoami_raw(self._group_client(None, group), narrowed=False, budget_s=budget) @@ -953,7 +953,7 @@ def _resolve_group(self, group: _GroupBinding, budget: float) -> str: if not isinstance(home, str) or not home or not isinstance(scopes, list): return "the key's whoami names no home scope or read scopes" write = write or home - read = read or tuple(str(scope) for scope in scopes if scope != write) + read = read or tuple(str(scope) for scope in scopes if scope not in (home, write)) if len(read) > _access.READ_MAX: return f"the key reads more than {_access.READ_MAX} scopes; name the group's in field read" group.read, group.write = tuple(read), write diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 585213c58..ca79c79ca 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -247,6 +247,62 @@ def test_a_reused_markers_check_gives_no_text_once_ctx_state_became_unreadable(w _bb.reset_state() +# -- a group without read reads the key's read set without its home scope and its write scope ------ +# (#4816373544, #4816373559) + +GH, GW, GO = "t:d111-gh", "t:d111-gw", "t:d111-go" +GH_KEY = "ctx_gh_key" +GH_FIELDS = {"key": "CTX_KEY_111_GH", "write": GW, "capture": False} + + +def _home_layout(fake, host): + """A key homed in ``GH`` that also reads ``GW`` and ``GO``; a group of it names ``write: GW`` and no + ``read`` (capture off: its write scope is not checked against the home).""" + fake.add_key(secret=GH_KEY, tenant="t", home=GH, allowed=(GW, GO)) + host.secrets.set_base({**host.secrets.var.get(), "CTX_KEY_111_GH": GH_KEY}) + return { + "home": fake.add_block(GH, "home notes", "homed knowledge"), + "write": fake.add_block(GW, "written notes", "written knowledge"), + "other": fake.add_block(GO, "other notes", "other knowledge"), + } + + +def test_a_group_without_read_never_reads_the_keys_home_scope(world): + fake, host, home = world + _home_layout(fake, host) + provider = _ops(home, GH_FIELDS) + assert provider._active, provider._access_off + assert provider._group.read == (GO,), provider._group.read + text = provider.prefetch("notes?") + assert "other knowledge" in text + assert "homed knowledge" not in text and "written knowledge" not in text + + +def test_the_base_block_hook_reads_no_block_of_the_keys_home_scope_for_a_group_without_read(world): + """Guard (the hook's side of the same layout): its proof checks ``write`` against the key's home + for every group that names one (E3), so a group whose ``write`` is not the home gets no text and no + block is fetched; without ``write`` the home is the write scope and is left out of the read set.""" + import asyncio + + fake, host, _home = world + _bb.reset_state() + _nar.reset_proofs() + ids = _home_layout(fake, host) + fields = {"ctx_checkpoint": {**GH_FIELDS, "base_blocks": [ids["home"], ids["other"]]}} + kwargs = ah.hook_kwargs(fields=fields, restricted=False, scope_id="111", group="ops") + fake.reset_counters() + outcome = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert outcome.answered and outcome.result is None, outcome + assert fake.count("/api/manage", "get") == 0 + _bb.reset_state() + without_write = {"ctx_checkpoint": {"key": GH_FIELDS["key"], "base_blocks": [ids["home"], ids["other"]]}} + kwargs = ah.hook_kwargs(fields=without_write, restricted=False, scope_id="111", group="ops") + outcome = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert outcome.answered and "other notes" in outcome.result["prompt"], outcome + assert "home notes" not in outcome.result["prompt"] + _bb.reset_state() + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From 8d14048553773c6c21e151825b9039f77c3c85fb Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:02:40 +0100 Subject: [PATCH 49/65] fix(ctx_checkpoint): a base-block fetch that a later fetch of the same key superseded never replaces the newer text in the render cache A fetch whose call's budget ended can still be reading; the next call for the same key then starts its own fetch. When the first fetch went on after the second had kept the edited block's text, it replaced that text with its older one and gave it a fresh base_cache_s. Fetches are numbered when they start. _remember keeps a text only while no fetch of its key that started later has kept its own or is on its way; a superseded fetch keeps and records nothing (its callers still get its text). A late fetch that nothing superseded still warms the cache. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../ctx_checkpoint/memory/base_blocks.py | 44 +++++++++----- .../tests/test_access_review_r3.py | 59 +++++++++++++++++++ 2 files changed, 88 insertions(+), 15 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py index 9ffa0c6c3..f7077838c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -39,6 +39,7 @@ import concurrent.futures import contextvars import hashlib +import itertools import json import logging import threading @@ -153,11 +154,15 @@ class _Plan: _LOCK = threading.RLock() _POOL: concurrent.futures.ThreadPoolExecutor | None = None _POOL_SIZE = 0 -# Render cache: full key -> (expiry on ``_now()``, text); least recently used first. -_CACHE: OrderedDict[tuple[Any, ...], tuple[float, str]] = OrderedDict() +# Render cache: full key -> (expiry on ``_now()``, text, the number of the fetch that read it); least +# recently used first. +_CACHE: OrderedDict[tuple[Any, ...], tuple[float, str, int]] = OrderedDict() _CACHE_LIMIT = 0 -# Fetches on their way: full key -> (future, the deadline of the call that started it). -_INFLIGHT: dict[tuple[Any, ...], tuple[concurrent.futures.Future, float]] = {} +# Fetches on their way: full key -> (future, the deadline of the call that started it, its number). +_INFLIGHT: dict[tuple[Any, ...], tuple[concurrent.futures.Future, float, int]] = {} +# Every fetch is numbered when it starts: a text is kept only while no fetch of its key that started +# later has kept its own or is on its way (a late fetch never replaces a newer text). +_FETCHES = itertools.count(1) _WARNED: set[tuple[str, ...]] = set() # The render cache's clock (a seam: the loop's own clock must stay the real one). _now = time.monotonic @@ -238,16 +243,22 @@ def _cached(key: tuple[Any, ...]) -> str | None: return entry[1] -def _remember(plan: _Plan, text: str) -> None: - """Keep *text* for ``base_cache_s``; the cache holds the largest ``base_cache_entries`` a serving - profile set, least recently used out first.""" +def _remember(plan: _Plan, text: str, number: int) -> bool: + """Keep *text*, read by fetch *number*, for ``base_cache_s``, unless a fetch of the same key that + started later kept its text or is on its way (False: superseded, nothing kept); the cache holds the + largest ``base_cache_entries`` a serving profile set, least recently used out first.""" global _CACHE_LIMIT with _LOCK: + newer = _INFLIGHT.get(plan.key) + kept = _CACHE.get(plan.key) + if (newer is not None and newer[2] > number) or (kept is not None and kept[2] > number): + return False _CACHE_LIMIT = max(_CACHE_LIMIT, plan.cache_entries) - _CACHE[plan.key] = (_now() + plan.cache_s, text) + _CACHE[plan.key] = (_now() + plan.cache_s, text, number) _CACHE.move_to_end(plan.key) while len(_CACHE) > _CACHE_LIMIT: _CACHE.popitem(last=False) + return True def reset_state() -> None: @@ -652,10 +663,11 @@ def _prove(request: _Request, expected: _Expectation, settings: Mapping[str, Any # -- step 4: fetch, E6, render ------------------------------------------------------------------------------- -def _fetch(plan: _Plan, deadline: float, request: _Request) -> str: - """One fetch of the plan's blocks through the read narrowing, E6 per block, the text rendered and - kept in the render cache, its outcome recorded for the request's group. A transient failure or an - entry that is no answer raises: never a partial text.""" +def _fetch(plan: _Plan, deadline: float, request: _Request, number: int) -> str: + """One fetch (*number*) of the plan's blocks through the read narrowing, E6 per block, the text + rendered and kept in the render cache, its outcome recorded for the request's group; a fetch a later + one superseded keeps and records nothing (its callers still get its text). A transient failure or + an entry that is no answer raises: never a partial text.""" try: entries = plan.client.get_blocks(plan.ids, timeout=_left(deadline)) except CtxApiError as exc: @@ -698,7 +710,8 @@ def _fetch(plan: _Plan, deadline: float, request: _Request) -> str: ", ".join(f"{block_id} ({reason})" for block_id, reason in sorted(skipped.items())), ) # A whole text that arrives after its waiter's budget is still kept: the next call is a hit. - _remember(plan, text) + if not _remember(plan, text, number): + return text if text: outcome = {"state": "delivered", "loaded": len(blocks), "skipped": skipped} _report(request, {**outcome, "cut": text.endswith(TRUNCATED_MARK)}) @@ -746,11 +759,12 @@ def _answer( else: joined = None own: concurrent.futures.Future = concurrent.futures.Future() - _INFLIGHT[plan.key] = (own, deadline) + number = next(_FETCHES) + _INFLIGHT[plan.key] = (own, deadline, number) if joined is not None: return joined try: - text = _fetch(plan, deadline, request) + text = _fetch(plan, deadline, request, number) except BaseException as exc: own.set_exception(exc) raise diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index ca79c79ca..6e278012d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -303,6 +303,65 @@ def test_the_base_block_hook_reads_no_block_of_the_keys_home_scope_for_a_group_w _bb.reset_state() +# -- a superseded base-block fetch never replaces the text of a newer one (#4816373547) ------------- + + +def test_a_late_base_block_fetch_does_not_replace_the_text_of_the_fetch_that_superseded_it(world, monkeypatch): + """Fetch A reads the block and stops before it publishes; its call's budget ends, so the next call + for the same key fetches anew (B) and reads the edited block. When A goes on, its older text must + not replace B's in the render cache.""" + import asyncio + import threading + + fake, _host, _home = world + _bb.reset_state() + (ah_home() / "config.yaml").write_text("memory:\n ctx_checkpoint:\n base_timeout_s: 1\n", encoding="utf-8") + block = fake.add_block(K, "House rules", "the old rules") + fields = {"ctx_checkpoint": {**pc.OPS_FIELDS, "base_blocks": [block]}} + kwargs = ah.hook_kwargs(fields=fields, restricted=False, scope_id="111", group="ops") + rendered, go = threading.Event(), threading.Event() + real = _bb.render + + def render(blocks, max_chars, *, redact=()): + text = real(blocks, max_chars, redact=redact) + if not rendered.is_set(): # fetch A: stop between reading the blocks and publishing them + rendered.set() + assert go.wait(WAIT_S) + return text + + monkeypatch.setattr(_bb, "render", render) + ended: list = [] + both_ended = threading.Event() + real_done = _bb._done + + def done(key, future): + real_done(key, future) + ended.append(future) + if len(ended) == 2: + both_ended.set() + + monkeypatch.setattr(_bb, "_done", done) + box: dict = {} + first = threading.Thread( + target=lambda: box.setdefault("a", asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs))), + daemon=True, + ) + first.start() + assert rendered.wait(WAIT_S) + first.join(WAIT_S) # A's call gives up at its budget; its fetch still waits in render + assert not first.is_alive() and not box["a"].answered, box + fake.blocks[block]["content"] = "the new rules" + second = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert second.answered and "the new rules" in second.result["prompt"], second + go.set() + assert both_ended.wait(WAIT_S), "fetch A has ended (B ended before it)" + fake.reset_counters() + third = asyncio.run(ah.ainvoke_hook_callback(_bb.on_access_group_fields, **kwargs)) + assert third.answered and "the new rules" in third.result["prompt"], third + assert fake.count("/api/manage", "get") == 0, "a cache hit" + _bb.reset_state() + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From db511463dc2b66bad863833792f7b21cd1ddb242 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:02:37 +0100 Subject: [PATCH 50/65] fix(ctx_checkpoint): provision writes its .env line through Hermes' own .env writer, under Hermes' .env lock provision read the profile's .env and replaced the whole file with its own copy. Its provision lock keeps other provision runs out, not Hermes: a variable Hermes saved (save_env_value) between that read and the replace was lost, and a Hermes write that read before provision's replace dropped the key line. Now the line goes through hermes_cli.config.save_env_value pointed at the profile home (the way Hermes' own memory setup writes a profile's variables): it reads, changes the one line and replaces the file under Hermes' .env lock, so either writer starts from the other's file. Hermes' refusal of the variable (a managed install) is asked before ctx is. The line is read back through Hermes' tokenizer: a later line that sets the variable again (which Hermes' writer keeps) is named and the run counts as stopped, so its repeat retires the key. A new .env gets Hermes' mode (0600 outside a container), an existing one keeps its mode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 12 +- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 3 +- .../ctx_checkpoint/memory/access_cli.py | 87 +++++----- .../tests/test_access_pe_rules.py | 20 +-- .../test_access_seam_provision_conflicts.py | 8 +- .../tests/test_access_seam_provision_env.py | 151 ++++++++++++++++++ .../tests/test_access_seam_provision_race.py | 16 +- 7 files changed, 223 insertions(+), 74 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index bda84f506..0393111da 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -598,8 +598,11 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co key's label (`hermes:<platform>:<server>:<profile>`), creates the scopes and a member key that requires narrowing in one `keyset-provision` call with the tenant-admin key from `<VAR>` (read, sent once, never stored or printed; a key that requires narrowing cannot be that admin key), writes the new - key as one line `CTX_KEY_<server>_<PROFILE>=…` into the profile's `.env` (mode 0600, every other line - kept), sets `memory.ctx_checkpoint.ungoverned: local` (an `off` stays), and prints the `/policy field` + key as one line `CTX_KEY_<server>_<PROFILE>=…` into the profile's `.env` through Hermes' own `.env` + writer (`save_env_value`: under Hermes' `.env` lock, so a variable Hermes saves meanwhile is neither + lost nor overwrites the line; every other line kept; a new file gets mode 0600 outside a container, an + existing one keeps its mode; a variable that a later line sets again is named and the run counts as + stopped), sets `memory.ctx_checkpoint.ungoverned: local` (an `off` stays), and prints the `/policy field` line for an existing group and the `/policy group` line for a new one; `--emit-yaml` adds the whole group entry with its fields for `gateway.access_groups` (one write, so the group never exists without its fields). A `--read` scope must already be a scope of the tenant, named `<name>` or @@ -634,8 +637,7 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co its tenant lock: of two first runs at the same moment one gets the key and the other the refusal. Still open across machines: two rotations with `--replace` leave one machine with a deactivated key; and a key of the label the other machine made within those 5 minutes of a run here whose answer was - lost is taken for that run's key when the run is repeated here. The `.env` is read again - just before the write, so a line another writer added meanwhile stays. Sessions bound with an earlier + lost is taken for that run's key when the run is repeated here. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id or group name no scope or variable name can hold, a `--profile` other than the profile the command @@ -966,7 +968,7 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). base blocks, mode 0600, written only on a change) with the lock `access.lock`, and `ctx_state/access-sessions.state` (once per platform and connection: messaging sessions that ran without an access group, also on a Hermes without access groups). `access provision` writes one - line into the profile's `.env` (under `ctx_state/access-provision.lock`), + line into the profile's `.env` (under `ctx_state/access-provision.lock`, through Hermes' `.env` writer), `ctx_state/access-provision.pending` (the labels it sent a set for and wrote no line for yet) and `memory.ctx_checkpoint.ungoverned` into `config.yaml`; `access reset-marker` writes the markers. - **No** shell commands, background network beyond the above, stored credentials (but the key diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 2500d564c..1885c200b 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -65,7 +65,8 @@ older server a group binding is off and the profile's own connection works as be explains (the id ctx answered, or a key made within 5 minutes of the note), and a key of the label no run of the profile left is refused. Runs in one profile home take turns under a lock that fails closed (`ctx_state/access-provision.lock`), from the check to the `.env` line, so the - `.env` ends with the key ctx committed last. `access check` reads the group's key from the + `.env` ends with the key ctx committed last; the line is written through Hermes' own `.env` writer + (`save_env_value`, under Hermes' `.env` lock), so a variable Hermes saves meanwhile is kept. `access check` reads the group's key from the profile's `.env` and secret sources only, never from the shell's environment. - Fixed before release: the state pruning (`state_retention_days`) deleted the markers after 30 days and a session whose root id was `access-mode` wrote its fact ledger over them (both kept now); a diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 7798777e1..11b95481d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -11,7 +11,7 @@ Every command works on the home it is given (the CLI's: the profile ``hermes -p <profile>`` runs in). The plugin never reads the core's ``gateway.access_groups`` (design 02 A02-L9): ``check`` takes the group's fields as ``--field name=value``, as ``/policy field`` takes them. No key value is printed, -logged or written anywhere but the one ``.env`` line ``provision`` adds (mode 0600). +logged or written anywhere but the one ``.env`` line ``provision`` adds (through Hermes' ``.env`` writer). Naming (design 02 §3.4): a ctx scope name is 1 to 24 characters of lowercase letters, digits and inner hyphens (ctx ``scopeNamePattern``). Group names may hold ``_``, ``-`` and 32 characters: ``_`` @@ -33,7 +33,6 @@ import json import os import re -import tempfile import time import urllib.error import urllib.request @@ -78,8 +77,8 @@ _BASE_URL_ENV = re.compile(r"^(?:CTX_BASE_URL|CTX_BASE_URL_[A-Z0-9_]+)$") # One provision at a time per profile home (in ctx_state/): its key check, the requests that change ctx, # its .env line and its record run under this lock, which fails closed — a run that cannot have it -# within PROVISION_LOCK_WAIT_S sends nothing. Hermes' own .env writers take no lock. It binds the runs of -# one machine; runs on two machines share none. +# within PROVISION_LOCK_WAIT_S sends nothing. The .env line itself is written through Hermes' own .env +# writer, under Hermes' .env lock. It binds the runs of one machine; runs on two machines share none. PROVISION_LOCK_FILE = "access-provision.lock" PROVISION_LOCK_WAIT_S = 5.0 PROVISION_LOCK_POLL_S = 0.05 @@ -667,47 +666,35 @@ def _warnings(home: str, platform: str, strict: bool, proof: Mapping[str, Any]) # -- provision ----------------------------------------------------------------------------------- -def _atomic_write(path: Path, data: str) -> None: - """Replace *path* with *data* atomically, mode 0600 (the test seam of an abort).""" - target = Path(os.path.realpath(path)) - fd, tmp = tempfile.mkstemp(prefix=".env-", dir=str(target.parent)) +def _env_writable(name: str) -> None: + """``ValueError`` when Hermes' ``.env`` writer refuses *name* (a managed install, a variable the + administrator pins): asked before ctx is, since ``save_env_value`` refuses by returning.""" try: - with os.fdopen(fd, "w", encoding="utf-8") as handle: - handle.write(data) - os.chmod(tmp, 0o600) - os.replace(tmp, target) - except BaseException: - with contextlib.suppress(OSError): - os.unlink(tmp) - raise - - -def _env_with(text: str, name: str, value: str) -> str: - """*text* (a ``.env``) with ``name=value``: the first line that sets *name* replaced, later ones - dropped, every other line as it was; appended when none sets it.""" - setter = re.compile(rf"^\s*(?:export\s+)?{re.escape(name)}\s*=") - out: list[str] = [] - done = False - for line in text.splitlines(keepends=True): - if setter.match(line): - if not done: - out.append(f"{name}={value}\n") - done = True - continue - out.append(line) - if not done: - if out and not out[-1].endswith("\n"): - out[-1] += "\n" - out.append(f"{name}={value}\n") - return "".join(out) - - -def _write_env_line(env_path: Path, name: str, value: str) -> None: - """``name=value`` into the profile's ``.env`` (the caller holds the provision lock): read again just - before the write, so a line another writer added while ctx answered stays (the first read only proved - the file readable). Raises ``OSError``/``ValueError`` when it cannot be read or written.""" - current = env_path.read_text(encoding="utf-8") if env_path.exists() else "" - _atomic_write(env_path, _env_with(current, name, value)) + from hermes_cli.config import require_env_writable + except ImportError as exc: + raise ValueError("this Hermes offers no .env writer to plugins (hermes_cli.config)") from exc + require_env_writable(name, "set") + + +def _write_env_line(home: str, name: str, value: str) -> None: + """``name=value`` into the profile's ``.env`` through Hermes' own writer (``hermes_cli.config + .save_env_value``, pointed at *home*): it reads the file, replaces the first line that sets *name* (or + appends one) and replaces the file under Hermes' ``.env`` lock, so a variable Hermes saves meanwhile is + neither lost nor overwrites this line; a new file gets Hermes' mode (0600 outside a container), an + existing one keeps its mode. The caller holds the provision lock. Read back through Hermes' tokenizer: + raises ``OSError`` when the profile then gives *name* another value (a later line that sets it too), + ``OSError``/``ValueError`` when it cannot be written.""" + _env_writable(name) + from hermes_cli.config import save_env_value + from hermes_constants import reset_hermes_home_override, set_hermes_home_override + + token = set_hermes_home_override(home) # Hermes' writer, pointed at this home for this call + try: + save_env_value(name, value) + finally: + reset_hermes_home_override(token) + if _env_values(home).get(name) != value: + raise OSError(f"{name} is set by more than one line of the profile's .env, and a later one wins") class _Busy(Exception): @@ -897,6 +884,11 @@ def _cmd_provision(args: argparse.Namespace, home: str) -> int: except (OSError, UnicodeDecodeError) as exc: print(f" ✗ {env_path} cannot be read ({type(exc).__name__}); nothing was sent") return 1 + try: + _env_writable(variable) + except ValueError as exc: + print(f" ✗ Hermes' .env writer does not set {variable} here ({str(exc)[:200]}); nothing was sent") + return 1 if args.admin_key_env in _env_names(home): print( f" ⚠ {args.admin_key_env} is in this profile's .env: a tenant-admin key in a profile that serves " @@ -1095,11 +1087,12 @@ def _provision_locked( return 1 secret, _slug, scopes = made try: - _write_env_line(env_path, variable, secret) + _write_env_line(home, variable, secret) except (OSError, ValueError) as exc: + cause = _status.redact_error(exc, (secret, admin_key)) print( - f" ✗ the key was created at ctx but {env_path} could not be written ({type(exc).__name__}); run the same " - "command again: it deactivates that key, so one key stays active" + f" ✗ the key was created at ctx but {env_path} could not be written ({type(exc).__name__}: {cause}); " + "run the same command again: it deactivates that key, so one key stays active" ) return 1 with contextlib.suppress(OSError): # the run is over; a record that stays only allows its own repeat diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py index 551a97878..edca3492a 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -451,32 +451,34 @@ def _new_keys(fake): return [k for k in fake.keys.values() if k.label.startswith("hermes:")] -def test_provision_writes_one_env_line_0600_and_keeps_every_other_line(admin, capsys): +def test_provision_writes_one_env_line_and_keeps_every_other_line(admin, capsys): + """Through Hermes' own .env writer: the line that sets the variable is replaced in place (a variable + set twice is test_access_seam_provision_env's), every other line and the file's mode stay.""" fake, home = admin - before = "FOO=bar\n# a comment\nCTX_KEY_111_MEMBERS=old-value\nexport OTHER='x y'\nCTX_KEY_111_MEMBERS=older\n" + before = "FOO=bar\n# a comment\nCTX_KEY_111_MEMBERS=\nexport OTHER='x y'\n" (home / ".env").write_text(before, encoding="utf-8") - os.chmod(home / ".env", 0o644) - assert _provision(home, "--replace") == 0 + os.chmod(home / ".env", 0o640) + assert _provision(home) == 0 (key,) = [k for k in _new_keys(fake) if k.active] after = (home / ".env").read_text(encoding="utf-8") assert after == f"FOO=bar\n# a comment\nCTX_KEY_111_MEMBERS={key.secret}\nexport OTHER='x y'\n" - assert stat.S_IMODE((home / ".env").stat().st_mode) == 0o600 + assert stat.S_IMODE((home / ".env").stat().st_mode) == 0o640 out = capsys.readouterr().out assert key.secret not in out and ADMIN_KEY not in out def test_provision_after_an_abort_between_ctx_and_the_env_is_repeatable(admin, monkeypatch, capsys): fake, home = admin - real = cli._atomic_write + real = cli._write_env_line - def broken(path, data): + def broken(home, name, value): raise OSError("disk full") - monkeypatch.setattr(cli, "_atomic_write", broken) + monkeypatch.setattr(cli, "_write_env_line", broken) assert _provision(home) == 1 assert not (home / ".env").exists() assert "again" in capsys.readouterr().out - monkeypatch.setattr(cli, "_atomic_write", real) + monkeypatch.setattr(cli, "_write_env_line", real) assert _provision(home) == 0 active = [k for k in _new_keys(fake) if k.active] assert len(active) == 1 and len(_new_keys(fake)) == 2 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py index fb1566801..0cb0b6203 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py @@ -127,14 +127,14 @@ def test_a_key_in_the_env_without_its_key_at_ctx_needs_replace(ctx, tmp_path, ca def test_a_run_that_stopped_before_its_env_line_repeats_without_replace(ctx, tmp_path, monkeypatch): home = _home(tmp_path, "members") - real = cli._atomic_write + real = cli._write_env_line - def broken(path, data): + def broken(home, name, value): raise OSError("disk full") - monkeypatch.setattr(cli, "_atomic_write", broken) + monkeypatch.setattr(cli, "_write_env_line", broken) assert _provision(home, "members", "members") == 1 - monkeypatch.setattr(cli, "_atomic_write", real) + monkeypatch.setattr(cli, "_write_env_line", real) assert _provision(home, "members", "members") == 0 assert _sets(ctx) == 2 and len(_active(ctx)) == 1 diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py new file mode 100644 index 000000000..a1dae6b7d --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py @@ -0,0 +1,151 @@ +"""``access provision`` and Hermes' own ``.env`` writers (PR review of the plugin layer). Hermes saves a +profile's variables with ``hermes_cli.config.save_env_value``: it reads the ``.env``, changes one line and +replaces the file under its ``.env`` lock. ``provision`` writes its key line through that same writer +(pointed at the profile home), so a variable Hermes saves while ``provision`` is between its read and its +replace is neither lost nor overwrites the key line. The interleaving is made with event barriers (the +writer that waits for the lock reports it), never by guessing with sleeps.""" + +from __future__ import annotations + +import os +import stat +import threading + +import hermes_cli.auth as hermes_auth +import hermes_cli.config as hermes_config +import hermes_constants +import pytest +from fakes import access_host as ah +from hermes_constants import reset_hermes_home_override, set_hermes_home_override + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_provision_env") +cli = ah.plugin_module(_PKG, "memory.access_cli") + +ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_env" +LABEL = "hermes:discord:111:members" +VAR = "CTX_KEY_111_MEMBERS" +WAIT_S = 10.0 # the most a barrier waits: a run that never reaches it fails the test, it does not hang + + +@pytest.fixture +def ctx(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "process-home")) + return fake_ctx + + +def _home(root, profile="members"): + home = root / "profiles" / profile + home.mkdir(parents=True, exist_ok=True) + return home + + +def _provision(home, *extra): + argv = ["provision", "--server", "discord:111", "--profile", "members", "--group", "members"] + return cli.run_access([*argv, "--admin-key-env", "CTX_ADMIN", *extra], hermes_home=str(home)) + + +def _active(fake): + return [key for key in fake.keys.values() if key.label == LABEL and key.active] + + +def _hermes_saves(home, name, value): + token = set_hermes_home_override(str(home)) + try: + hermes_config.save_env_value(name, value) + finally: + reset_hermes_home_override(token) + + +# -- finding 4816373523: a variable Hermes saves meanwhile is kept -------------------------------- + + +def test_a_variable_hermes_saves_between_provision_s_read_and_replace_is_kept(ctx, tmp_path, monkeypatch): + """``provision`` has read the ``.env`` and is about to replace it; Hermes saves another variable of + the profile then. Whichever writer goes second must start from the other's file.""" + home = _home(tmp_path) + (home / ".env").write_text("FIRST=1\n", encoding="utf-8") + provisioner, other, progress = threading.current_thread(), {}, threading.Event() + + def hermes_writer(): + try: + _hermes_saves(home, "SAVED_BY_HERMES", "1") + finally: + progress.set() + + real_contention = hermes_auth._is_lock_contention + + def contention(exc): # Hermes' writer found the .env lock held: it waits for it + if threading.current_thread() is other.get("thread"): + progress.set() + return real_contention(exc) + + def between_read_and_replace(real): + def replace(*args, **kwargs): + if threading.current_thread() is provisioner and "thread" not in other: + other["thread"] = threading.Thread(target=hermes_writer, daemon=True) + other["thread"].start() + assert progress.wait(WAIT_S), "Hermes' writer neither wrote nor waited for the .env lock" + return real(*args, **kwargs) + + return replace + + monkeypatch.setattr(hermes_auth, "_is_lock_contention", contention) + monkeypatch.setattr(hermes_config, "_write_env_lines", between_read_and_replace(hermes_config._write_env_lines)) + assert _provision(home) == 0 + assert "thread" in other, "provision never replaced the .env" + other["thread"].join(WAIT_S) + assert not other["thread"].is_alive() + (key,) = _active(ctx) + values = cli._env_values(str(home)) + assert values.get("SAVED_BY_HERMES") == "1", "the variable Hermes saved meanwhile was lost" + assert values.get(VAR) == key.secret and values.get("FIRST") == "1" + + +def test_a_new_env_is_0600_and_an_existing_one_keeps_its_lines_and_mode(ctx, tmp_path): + home = _home(tmp_path) + assert _provision(home) == 0 + if not hermes_constants._container_or_chmod_skipped(): # Hermes' rule: no chmod inside a container + assert stat.S_IMODE((home / ".env").stat().st_mode) == 0o600 + other = _home(tmp_path / "second", "members") + (other / ".env").write_text("FOO=bar\n# a comment\nexport OTHER='x y'\n", encoding="utf-8") + os.chmod(other / ".env", 0o640) + for key in _active(ctx): # revoked by hand: the second home is a first run of the label + key.active = False + assert _provision(other) == 0 + (key,) = _active(ctx) + text = (other / ".env").read_text(encoding="utf-8") + assert text == f"FOO=bar\n# a comment\nexport OTHER='x y'\n{VAR}={key.secret}\n" + assert stat.S_IMODE((other / ".env").stat().st_mode) == 0o640, "Hermes' writer keeps an existing file's mode" + + +def test_a_variable_set_twice_in_the_env_is_named_and_the_run_can_be_repeated(ctx, tmp_path, capsys): + """Hermes' writer replaces the first line that sets the variable; a later line would still win when the + profile reads the file. The run says so, writes no second key, and its repeat retires the key it made.""" + home = _home(tmp_path) + (home / ".env").write_text(f"{VAR}=\nKEEP=1\n{VAR}=\n", encoding="utf-8") + rc = _provision(home) + out = capsys.readouterr().out + assert rc == 1 and VAR in out and "again" in out, out + (made,) = _active(ctx) + assert cli._stopped_runs(str(home))[LABEL].get("id") == made.id + (home / ".env").write_text("KEEP=1\n", encoding="utf-8") + assert _provision(home) == 0 + (active,) = _active(ctx) + assert active is not made and cli._env_values(str(home)) == {"KEEP": "1", VAR: active.secret} + + +def test_a_variable_hermes_does_not_let_the_profile_set_creates_no_key(ctx, tmp_path, monkeypatch, capsys): + """``save_env_value`` refuses a pinned variable by returning; the refusal is asked before ctx is.""" + + def pinned(key, action): + raise ValueError(f"Cannot {action} {key}: it is managed by your administrator") + + monkeypatch.setattr(hermes_config, "require_env_writable", pinned) + home = _home(tmp_path) + rc = _provision(home) + out = capsys.readouterr().out + assert rc == 1 and "managed by your administrator" in out and "nothing was sent" in out, out + assert ctx.count() == 0 and not (home / ".env").exists() diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py index 869eca315..9b6379116 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py @@ -104,14 +104,14 @@ def finish(self) -> None: def _stop_before_the_env_line(monkeypatch, home, group="members"): """One run that made its key at ctx and stopped before its ``.env`` line (the disk refused it).""" - real = cli._atomic_write + real = cli._write_env_line - def broken(path, data): + def broken(home, name, value): raise OSError("disk full") - monkeypatch.setattr(cli, "_atomic_write", broken) + monkeypatch.setattr(cli, "_write_env_line", broken) assert _provision(home, group) == 1 - monkeypatch.setattr(cli, "_atomic_write", real) + monkeypatch.setattr(cli, "_write_env_line", real) # -- finding 4815624939: a first run deactivates no key ------------------------------------------- @@ -439,15 +439,15 @@ def test_the_lock_is_held_until_the_env_line_is_written(ctx, tmp_path, monkeypat home = _home(tmp_path) assert _provision(home, "members") == 0 reached, release, held = threading.Event(), threading.Event(), {} - real = cli._atomic_write + real = cli._write_env_line - def writing(path, data): + def writing(home, name, value): if threading.current_thread() is held.get("thread"): reached.set() assert release.wait(WAIT_S), "the write was never released" - return real(path, data) + return real(home, name, value) - monkeypatch.setattr(cli, "_atomic_write", writing) + monkeypatch.setattr(cli, "_write_env_line", writing) result: list = [] run_a = threading.Thread(target=lambda: result.append(_provision(home, "members", "--replace")), daemon=True) held["thread"] = run_a From 124c4f458ad5d0e543224682871920e06aebdd07 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:03:53 +0100 Subject: [PATCH 51/65] fix(ctx_checkpoint): a narrowed client checks for a lost narrowing before every HTTP attempt, the retry after a 429 included CtxClient._request checked _narrowing_lost once, before its first attempt. A call that met a 429 (or a write_conflict) waited and then sent its second attempt even when another call of the same client had meanwhile received an answer without the narrowing's echo; before_send only checks that the group binding is current, and the lost echo turns the provider off only at its next gate. The check now runs at the start of every attempt; a client that never lost its narrowing retries as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/client.py | 4 +- .../tests/test_access_review_r3.py | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py index 7bc0cb97b..ba6e0efcc 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/client.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py @@ -523,8 +523,6 @@ def _request( refusal of an accepted narrowing too, the refusals of the narrowing itself not; neither is read).""" if self._url_refused: raise CtxApiError(BASE_URL_REFUSED) - if self._narrowing_lost: - raise self.narrowing_lost_error() narrowing = None if unnarrowed else self._narrowing url = f"{self._base}{path}" headers = { @@ -545,6 +543,8 @@ def _request( for attempt in (0, 1): # one retry on 429 (per-key write rate limit) or 409 write_conflict failure: CtxApiError | None = None + if self._narrowing_lost: # before every attempt: another call of this client may have lost it + raise self.narrowing_lost_error() if self._before_send is not None: self._before_send() # before every attempt; what it raises leaves this request unsent try: diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 6e278012d..13c306a94 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -362,6 +362,51 @@ def done(key, future): _bb.reset_state() +# -- a client that lost its narrowing sends no retry either (#4816373550) -------------------------- + +_client = ah.plugin_module(pc._PKG, "memory.client") + + +def test_the_retry_after_a_429_is_not_sent_once_another_call_of_the_client_lost_its_narrowing(world, monkeypatch): + """Call A meets a 429 and waits to send again; call B of the same client gets an answer without the + narrowing's echo (the client is off from then on). A's second attempt must not go out.""" + import threading + + fake, _host, _home = world + client = _client.CtxClient(fake.url, pc.OPS_A_KEY, narrowing=_nar.Narrowing(read=(K,))) + waiting, go = threading.Event(), threading.Event() + + def sleep(seconds): + waiting.set() + assert go.wait(WAIT_S) + + monkeypatch.setattr(_client, "_sleep", sleep) + fake.reset_counters() + fake.throttle["/api/search"] = 1 + box: dict = {} + + def call_a(): + try: + box["result"] = client.search("plans") + except _client.CtxApiError as exc: + box["error"] = exc + + first = threading.Thread(target=call_a, daemon=True) + first.start() + assert waiting.wait(WAIT_S), "A waits before its retry" + fake.echo_missing = True + with pytest.raises(_client.CtxApiError) as lost: + client.search("plans") + assert lost.value.code == "narrowing_lost" and client.narrowing_lost + fake.echo_missing = False + go.set() + first.join(WAIT_S) + assert not first.is_alive() + assert "result" not in box, f"A's retry was sent and answered: {box}" + assert box["error"].code == "narrowing_lost" + assert fake.count("/api/search") == 2, "A's first attempt and B's, no retry" + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From 9b6c4620d8e18ed2ec0811a627ba2472b5d2b291 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:05:12 +0100 Subject: [PATCH 52/65] fix(ctx_checkpoint): a group that reads nothing is bound only on a narrowed proof of the client it writes with An unrestricted group whose key reads only its home scope and names no read gets an empty read set and no read client. _prove_group skipped the narrowed proof for it and published the binding as bound, also on a ctx server without per-request narrowing: access status said bound and ctx_store was offered before any narrowed answer had been seen (the first write then failed its own proof). Such a group is now proven by the narrowed whoami of its write client (its store client when capture is off), judged as that client's own proof (E5, the tenant, and for the write client the home scope); a failed proof refuses the group, a network failure leaves it pending, and a passed one counts as the client's proof too. The client proof's expectation is one helper for both paths. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/provider.py | 55 +++++++++++++------ .../tests/test_access_review_r3.py | 35 ++++++++++++ 2 files changed, 73 insertions(+), 17 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 8eaf66142..7011c652b 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -974,8 +974,9 @@ def _prove_group(self, group: _GroupBinding) -> None: narrowing's ``whoami`` and, for a restricted group, the key's unnarrowed one, judged by ``narrowing.evaluate`` (E2 to E5, E7) with what this binding expects. The binding becomes active, stays pending (no answer in time: asked again in the background) or goes off (a rule, - a refusal: until the next agent build). A group that reads nothing proves itself with its - writes (:meth:`_client_proven`).""" + a refusal: until the next agent build). A group that reads nothing (no read set) is proven by the + narrowed ``whoami`` of the client it writes with (the write client, else the store client), judged + as that client's own proof (:meth:`_client_proven`), which then holds too.""" context = group.context deadline = self._now() + float(self._access_settings.get("verify_timeout_s") or 3) @@ -984,13 +985,26 @@ def left() -> float: failed: list[str] = [] detail: dict[str, str] = {} + own: tuple[str, Any] | None = None # the client proof a group that reads nothing is bound on try: if not group.write: why = self._resolve_group(group, left()) if why: self._group_refused(context, why, group=group) return - if group.read_client is not None: + if group.read_client is None: + kind = "write" if group.write_client is not None else "store" + client = group.write_client or group.store_client + if client is None or group.strict: + self._group_refused(context, "the group reads nothing and has no client to prove", group=group) + return + narrowed = _narrowing.whoami_raw(client, narrowed=True, budget_s=left()) + result = _narrowing.evaluate(narrowed, None, self._client_expect(kind, client, group)) + failed, detail = list(result.failed), dict(result.detail) + group.label = str(narrowed.get("label") or "") + group.tenant_seen = str(narrowed.get("tenant_slug") or "") + own = (kind, narrowed) + else: narrowed = _narrowing.whoami_raw(group.read_client, narrowed=True, budget_s=left()) key_answer = ( _narrowing.whoami_raw(group.read_client, narrowed=False, budget_s=left()) if group.strict else None @@ -1038,6 +1052,10 @@ def left() -> float: with self._access_lock, self._binding_lock: # a turn-off waits for the publication, never lost if self._group is not group or self._access_off: return # re-initialized or turned off meanwhile + if own is not None: # the client's own proof (``_client_proven``) is part of this one + group.proven.add(own[0]) + if own[0] == "write": + self._rate_limit_write = _write_limit(own[1]) group.proven.add("group") self._client = group.read_client self._home_scope = group.write @@ -1157,20 +1175,7 @@ def _client_proven(self, kind: str, client: Any, group: Any = _CURRENT) -> bool: logger.warning("CTX %s client off (profile=%s): %s", kind, self._profile, group.refused[kind]) self._record_clients_refused(group) return False - result = _narrowing.evaluate( - raw, - None, - _narrowing.Expect( - narrowing=client.narrowing, - strict=False, - tenant=group.tenant or None, - label=None, - env_names=(), - platform_toolsets=(), - scope_id=str(group.context.scope_id), - write=group.write if kind == "write" else None, - ), - ) + result = _narrowing.evaluate(raw, None, self._client_expect(kind, client, group)) if not result.ok: group.refused[kind] = ", ".join(result.failed) group.refused_rules.update({f"{kind} client {rule}": text for rule, text in result.detail.items()}) @@ -1190,6 +1195,22 @@ def _client_proven(self, kind: str, client: Any, group: Any = _CURRENT) -> bool: self._rate_limit_write = _write_limit(raw) return True + @staticmethod + def _client_expect(kind: str, client: Any, group: _GroupBinding) -> Any: + """What the write (``"write"``) or the store client's (``"store"``) narrowed ``whoami`` is judged + by: its narrowing (E5), the group's tenant when it names one (E2), and for the write client the + group's write scope as the key's home (E3).""" + return _narrowing.Expect( + narrowing=client.narrowing, + strict=False, + tenant=group.tenant or None, + label=None, + env_names=(), + platform_toolsets=(), + scope_id=str(group.context.scope_id), + write=group.write if kind == "write" else None, + ) + def _record_clients_refused(self, group: _GroupBinding) -> None: """A write or store client ctx refused is part of the binding's state: the group reads, but what that client writes is not written, so the status says ``bound; write client off: <why>`` diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 13c306a94..b50951b20 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -407,6 +407,41 @@ def call_a(): assert fake.count("/api/search") == 2, "A's first attempt and B's, no retry" +# -- a group that reads nothing is bound only on a narrowed proof of the client it writes with ----- +# (#4816373564) + +SOLO = "t:d111-solo" +SOLO_KEY = "ctx_solo_key" + + +def _solo(fake, host, home, **fields): + """An unrestricted group whose key reads only its home scope and names no read or write: its read + set is empty, so it has no read client.""" + fake.add_key(secret=SOLO_KEY, tenant="t", home=SOLO) + host.secrets.set_base({**host.secrets.var.get(), "CTX_KEY_111_SOLO": SOLO_KEY}) + return _ops(home, {"key": "CTX_KEY_111_SOLO", **fields}) + + +def test_a_group_that_reads_nothing_is_not_bound_on_a_server_without_narrowing(world): + fake, host, home = world + fake.without_c1 = True + provider = _solo(fake, host, home) + assert provider._group is None or provider._group.read_client is None + assert not provider._active, "bound without any narrowed answer" + assert provider.get_tool_schemas() == [] and provider.system_prompt_block() == "" + assert provider._access_off.startswith("group binding refused"), provider._access_off + + +@pytest.mark.parametrize(("capture", "kind"), [(None, "write"), (False, "store")]) +def test_a_group_that_reads_nothing_is_bound_on_the_proof_of_its_write_or_store_client(world, capture, kind): + fake, host, home = world + fields = {} if capture is None else {"capture": capture} + provider = _solo(fake, host, home, **fields) + assert provider._active and provider._group.read_client is None + assert kind in provider._group.proven, "the client's own proof is the group's" + assert [s["name"] for s in provider.get_tool_schemas()] == ["ctx_store"] + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From e26bbeb47ee41faf8a9ee945982cb3d89dc731cc Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:10:11 +0100 Subject: [PATCH 53/65] fix(ctx_checkpoint): a warmed recall carries the binding it was warmed under, and a background call that asks a proof again keeps the binding it started under prefetch checked the warm cache by query and age only. A recall of one group that had passed its gate could read the cache after a re-initialization had bound another group and that group had warmed the same question: the first group's call returned the second group's text, without its own client and its send guard. Cache entries now carry the binding generation they were warmed under; prefetch takes one only for its own, still current snapshot, and a warm-up publishes only while its snapshot is current. The recall count recall_status reports is set only by a call whose binding is still current. sync_turn and queue_prefetch took the gate, asked a pending proof again, then took a second snapshot of whatever binding was current: a re-initialization during the retry made the digest (and the idle timer it arms) or the warm-up run the first call's messages or question through the new group's writer or client. The second snapshot (which sees what the retry published) is now used only when it is of the same binding as the first. The unused _access_gate is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/provider.py | 59 +++++-- .../tests/test_access_review_r3.py | 146 ++++++++++++++++++ 2 files changed, 188 insertions(+), 17 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 7011c652b..ba95e7ecb 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -369,7 +369,8 @@ def __init__(self): self._whoami_label = "" self._active = False self._write_enabled = True - # prefetch pre-warm cache: (query, context, hit count, monotonic_ts) + # prefetch pre-warm cache: (query, context, hit count, monotonic_ts, the binding generation it + # was warmed under); served only to a call whose snapshot has that generation and is current. self._prefetch_cache: tuple | None = None self._prefetch_lock = threading.Lock() # Bumped whenever the cache is invalidated; a warm-up publishes only into the @@ -1132,6 +1133,12 @@ def _lease_current(self, lease: _Lease) -> bool: """Whether the binding ``lease`` was taken from is still the current one and not off.""" return not self._access_off and self._binding_generation == lease.generation and self._group is lease.group + @staticmethod + def _same_binding(first: _Lease, then: _Lease) -> bool: + """Whether two snapshots of one call are of the same binding (a later snapshot may see what a + proof published meanwhile, never a binding a re-initialization put in place).""" + return then.generation == first.generation and then.group is first.group + def _client_proven(self, kind: str, client: Any, group: Any = _CURRENT) -> bool: """The write (``"write"``) or the store client's (``"store"``) own proof before its first write (design 02 §4.2 step 5): its narrowed ``whoami`` reports its narrowing (E5), names the @@ -1220,10 +1227,6 @@ def _record_clients_refused(self, group: _GroupBinding) -> None: reasons = "; ".join(f"{kind} client off: {why}" for kind, why in sorted(group.refused.items())) self._record_access_state(group.context, f"bound; {reasons}", rules=group.refused_rules) - def _access_gate(self) -> bool: - """Whether this instance may reach ctx now (:meth:`_lease`).""" - return self._lease() is not None - def _snapshot(self) -> _Lease | None: """The binding as it is now, taken under the binding lock; None while the instance is off.""" with self._binding_lock: @@ -1544,10 +1547,10 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: Runs inside the MemoryManager's daemon thread (8s budget). Consumes a fresh pre-warmed cache entry when available, otherwise queries now. """ - self._last_recall_count = 0 # One snapshot: the gate and the recall see the same binding (a re-init after the gate # neither redirects this turn's query nor leaves a None for _recall to resolve). lease = self._lease() + self._note_recall(0, lease) if lease is None or not self._recall_allowed(lease): return "" client = lease.client @@ -1559,17 +1562,31 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: return "" with self._prefetch_lock: cached = self._prefetch_cache - if cached and cached[0] == q and (self._now() - cached[3]) < _PREFETCH_CACHE_TTL_S: + if ( + cached + and len(cached) > 4 + and cached[4] == lease.generation # warmed under this call's binding, never another's + and cached[0] == q + and (self._now() - cached[3]) < _PREFETCH_CACHE_TTL_S + and self._lease_current(lease) + ): self._prefetch_cache = None - self._last_recall_count = cached[2] + self._note_recall(cached[2], lease) return cached[1] try: - context, self._last_recall_count = self._recall(q, client, entry, within_host_wait=True) + context, count = self._recall(q, client, entry, within_host_wait=True) + self._note_recall(count, lease) return context except Exception as exc: logger.debug("CTX prefetch failed (non-fatal): %s", self._error_text(exc)) return "" + def _note_recall(self, count: int, lease: _Lease | None) -> None: + """What a prefetch recalled, for :meth:`recall_status`: only from a call whose binding is still + the current one (a call of a replaced binding that ends late changes nothing).""" + if lease is None or self._lease_current(lease): + self._last_recall_count = count + def recall_status(self): """What the most recent :meth:`prefetch` injected (host recall indicator); None = nothing.""" if RecallStatus is None or self._last_recall_count <= 0: @@ -1579,7 +1596,8 @@ def recall_status(self): def queue_prefetch(self, query: str, *, session_id: str = "") -> None: """Pre-warm the recall cache for the next turn (background worker). A group proof the network failed is asked again here first (at most every :data:`PROOF_RETRY_S`).""" - if not self._access_gate(): + first = self._lease() + if first is None: return self._retry_group_proof() q = (query or "").strip() @@ -1590,9 +1608,12 @@ def queue_prefetch(self, query: str, *, session_id: str = "") -> None: with self._prefetch_lock: generation = self._prefetch_generation # Pin the warm-up to the binding it was queued under: a re-init replaces - # ``_client``, and the query must not reach the next binding's server. + # ``_client``, and the query must not reach the next binding's server. The snapshot after the + # proof retry sees what the retry published, and only for the binding the call started under. lease = self._lease() - if lease is None or not lease.active or not self._config.get("auto_recall", True) or not lease.client: + if lease is None or not self._same_binding(first, lease): + return + if not lease.active or not self._config.get("auto_recall", True) or not lease.client: return if not self._recall_allowed(lease): return @@ -1603,9 +1624,10 @@ def _warm() -> None: try: context, count = self._recall(q, client, entry) with self._prefetch_lock: - # A re-init or session switch since the start invalidated this warm-up. - if generation == self._prefetch_generation: - self._prefetch_cache = (q, context, count, self._now()) + # A re-init or session switch since the start invalidated this warm-up; the entry + # carries the binding it was warmed under. + if generation == self._prefetch_generation and self._lease_current(lease): + self._prefetch_cache = (q, context, count, self._now(), lease.generation) except Exception as exc: logger.debug("CTX prefetch warm-up failed (non-fatal): %s", self._error_text(exc)) @@ -2637,11 +2659,14 @@ def sync_turn( rolling digest at ``digest_every_exchanges`` / ``digest_every_hours``, and (re)arms the idle timer (``idle_digest_minutes``) on the host's background worker. A group proof the network failed is asked again here first (at most every :data:`PROOF_RETRY_S`).""" - if not self._access_gate(): + first = self._lease() + if first is None: return self._retry_group_proof() + # The snapshot after the retry sees what it published, and only for the binding this call + # started under: a re-initialization in between gets nothing of this turn. lease = self._lease() - if lease is None or not self._digest_enabled(lease) or messages is None: + if lease is None or not self._same_binding(first, lease) or not self._digest_enabled(lease) or messages is None: return try: root = self._root_session_id or self._session_id or "unknown" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index b50951b20..b75064188 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -442,6 +442,152 @@ def test_a_group_that_reads_nothing_is_bound_on_the_proof_of_its_write_or_store_ assert [s["name"] for s in provider.get_tool_schemas()] == ["ctx_store"] +# -- one snapshot per call: caches and writers carry the binding they came from (#4816373569, +# #4816373573, #4816373577, #4816373521) ----------------------------------------------------------- + +A_MODS = "t:d111-mods" +MODS_KEY = "ctx_mods_a" +MODS_FIELDS = {"key": "CTX_KEY_111_MODS", "read": [pc.B_K], "write": A_MODS} + + +def _add_mods(fake, host): + """A second unrestricted group of server 111 with its own key, reading server B's knowledge.""" + fake.add_key(secret=MODS_KEY, tenant="t", home=A_MODS, allowed=(pc.B_K,)) + host.secrets.set_base({**host.secrets.var.get(), "CTX_KEY_111_MODS": MODS_KEY}) + + +def _reinit_mods(provider, home, session="s-1", fields=None): + provider.initialize( + session, + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="mods", group_restricted=False, fields=fields or MODS_FIELDS), + ) + assert provider._active, provider._access_off + + +def _run(target, name="race-t1"): + import threading + + box: dict = {} + + def body(): + try: + box["result"] = target() + except BaseException as exc: # reported to the test + box["error"] = exc + + thread = threading.Thread(target=body, name=name, daemon=True) + thread.start() + return thread, box + + +def _joined(thread, box): + thread.join(WAIT_S) + assert not thread.is_alive(), "the first thread did not finish" + if "error" in box: + raise box["error"] + return box.get("result") + + +def _gate_barrier(monkeypatch): + """Stop the first gate of thread ``race-t1`` right after it took its snapshot (in the trip-wire + read of the turn's access group). Returns (arrived, go).""" + import threading + + arrived, go = threading.Event(), threading.Event() + real = _acc.current_access + + def current_access(): + if threading.current_thread().name == "race-t1" and not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + return real() + + monkeypatch.setattr(_acc, "current_access", current_access) + return arrived, go + + +def test_a_recall_never_takes_the_warmed_text_of_the_binding_a_reinitialize_put_in_place(world, monkeypatch): + """Group ops' recall passes its gate and stops before it reads the warm cache; the instance is + built again for group mods, which warms the same question with its key (server B's knowledge). + The ops call must not return the mods text.""" + fake, host, home = world + _add_mods(fake, host) + provider = _ops(home) + arrived, go = _gate_barrier(monkeypatch) + t1, box = _run(lambda: provider.prefetch("plans?")) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + provider.queue_prefetch("plans?") + pc._settle(provider) + assert provider._prefetch_cache is not None and "bravo knowledge" in provider._prefetch_cache[1] + go.set() + text = _joined(t1, box) + assert "bravo knowledge" not in text, "the ops call got the mods binding's recall" + assert "bravo knowledge" in provider.prefetch("plans?"), "the mods binding keeps its own recall" + + +def _retry_barrier(provider): + """Stop the proof retry of thread ``race-t1`` (between the gate and the call's work). Returns + (arrived, go).""" + import threading + + arrived, go = threading.Event(), threading.Event() + real = provider._retry_group_proof + + def retry(): + if threading.current_thread().name == "race-t1" and not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + return real() + + provider._retry_group_proof = retry + return arrived, go + + +def test_a_turn_counted_under_one_binding_never_arms_the_idle_digest_of_the_next(world): + """``sync_turn`` of group ops passes its gate; while it asks a pending proof again, the instance is + built again for group mods. The ops exchanges must not be digested through the mods writer (here: + the idle digest it arms).""" + fake, host, home = world + _add_mods(fake, host) + provider = _ops(home) + arrived, go = _retry_barrier(provider) + t1, box = _run(lambda: provider.sync_turn("q", "a", messages=pc._messages(12, tag="opsx"))) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + generation = provider._binding_generation + go.set() + _joined(t1, box) + timer = provider._idle_timer + if timer is not None: + timer.cancel() + assert timer.args[2] != generation, "the ops turn armed the mods binding's idle digest" + fake.reset_counters() + provider._on_idle(*timer.args) + pc._settle(provider) + assert fake.count("/api/store") == 0 + assert all("opsx" not in block["content"] for block in fake.blocks.values() if block["scope"] == A_MODS) + + +def test_a_warm_up_queued_under_one_binding_never_queries_through_the_next(world): + fake, host, home = world + _add_mods(fake, host) + provider = _ops(home) + arrived, go = _retry_barrier(provider) + t1, box = _run(lambda: provider.queue_prefetch("the ops question")) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + fake.reset_counters() + go.set() + _joined(t1, box) + pc._settle(provider) + assert fake.count("/api/query") == 0 and fake.count("/api/search") == 0, "the ops question went to mods" + assert provider._prefetch_cache is None + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From 684d935e13546092c5a893ebc585c74dba49e220 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:09:43 +0100 Subject: [PATCH 54/65] fix(ctx_checkpoint): provision --replace rotates only keys the profile recorded making for the same platform, server and group --replace took a key of the label homed in the group's scope for the group's own. Neither identifies the group: the label names server and profile, the scope name turns _ into - (a_b and a-b share both), so --replace for a-b deactivated a_b's key, and a repeat of a_b's stopped run could be finished by a-b. A key another machine made was rotated as well. The label is the binding's rule E4 and ctx stores no other field, so the profile home records it: when ctx answers a set, ctx_state/ access-provision.keys gets the key id with platform, server, the group's name as given, label, variable and the key's digest (never the key); a run that wrote its .env line keeps only its key's record of the label. The note of a stopped run names its group. A key recorded for another group of the scope is refused with and without --replace; --replace goes ahead only when every active key of the label is recorded for this group or left by this group's own stopped run. Any other key is refused with the way to check and replace it by hand (api-key-list, api-key-update with active=false, remove the line, run without --replace). A stopped rotation is still repeated with the same command. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 17 +- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 7 +- .../ctx_checkpoint/memory/access_cli.py | 146 +++++++++++---- .../test_access_seam_provision_identity.py | 168 ++++++++++++++++++ .../tests/test_access_seam_provision_race.py | 7 +- .../ctx_checkpoint/tests/test_s3_real_ctxd.py | 11 +- 6 files changed, 312 insertions(+), 44 deletions(-) create mode 100644 integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 0393111da..4819bc4a0 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -617,7 +617,15 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co per server and profile: give the second group a profile of its own) and a group whose scope is the home of another key (another group of the server whose name maps to the same scope); the same group again is refused while its key is in the profile's `.env`, and `--replace` rotates it (a new key, the - earlier one deactivated); only `--replace` sends `replace_label`, so a first run deactivates no key, + earlier one deactivated). What ctx stores of a key cannot tell its group (the label names server and + profile, the scope name turns `_` into `-`), so the profile records, when ctx answers a set, the + platform, server and group name (as given) each key was made for, with the key's digest and never the + key (`ctx_state/access-provision.keys`): `--replace` rotates only keys recorded there for this group or + left by this group's own stopped run, and a key recorded for another group of the same scope is refused + with and without it. A key without such a record (another machine, a key made by hand) is refused with + the way to replace it by hand: check it with `ctx manage api-key-list`, deactivate it with `ctx manage + api-key-update` and `active=false`, remove the line from the `.env`, and run `provision` again without + `--replace`. Only `--replace` sends `replace_label`, so a first run deactivates no key, and ctx refuses its set while an active key carries the label (409 naming the labels; the command then says to use `--replace` for the same group, or a profile of its own when another group or machine holds the label). A key of the label that the `.env` does not hold is refused as well @@ -655,7 +663,8 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co Scope names (one tenant per operator, the default): `d<server id in base 36>-k` for the server's knowledge and `d<server id in base 36>-<group>` for the group, at most 24 characters; `_` in a group name becomes `-`, so `a_b` and `a-b` get the same scope name (refused within one command, and across -runs because `provision` asks ctx which key homes that scope: give one of them another name); a group +runs because `provision` asks ctx which key homes that scope and the profile records which group it made +a key for: give one of them another name); a group part longer than 9 characters is cut and ends in a 4-character hash. With `--per-community` (a tenant of this server alone): `k` and `<group>`. The key's label and variable name the server and the profile, not the group: one key per server and profile, so `provision` refuses a second group served by the same @@ -969,7 +978,9 @@ entry did not connect when Hermes started (wrong key, server down, URL wrong). `ctx_state/access-sessions.state` (once per platform and connection: messaging sessions that ran without an access group, also on a Hermes without access groups). `access provision` writes one line into the profile's `.env` (under `ctx_state/access-provision.lock`, through Hermes' `.env` writer), - `ctx_state/access-provision.pending` (the labels it sent a set for and wrote no line for yet) and + `ctx_state/access-provision.pending` (the labels it sent a set for and wrote no line for yet), + `ctx_state/access-provision.keys` (the platform, server and group each key it made is for, with the + key's digest) and `memory.ctx_checkpoint.ungoverned` into `config.yaml`; `access reset-marker` writes the markers. - **No** shell commands, background network beyond the above, stored credentials (but the key `access provision` writes into the profile's `.env` when you run it) or self-updating code. diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 1885c200b..e93aedecd 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -58,8 +58,11 @@ older server a group binding is off and the profile's own connection works as be than its group's own fields. `provision` checks the fields it will print, with every `--read` scope qualified, the way the binding parses them before it sends the set, and reads `--base-url-env` from the profile's `.env` and secret sources only, as the binding does. It replaces no key silently: it - asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope another key homes; the same group - again needs `--replace` while its key is in the `.env`. Only `--replace` sends `replace_label`, and + asks ctx for the tenant's keys first and refuses a second group of a server and profile and a scope + another key homes; the same group again needs `--replace` while its key is in the `.env`, and + `--replace` rotates only keys the profile recorded making for this platform, server and group name + (`ctx_state/access-provision.keys`; `a_b` and `a-b` share scope and label) or this group's own stopped + run left — any other key is refused with the way to replace it by hand. Only `--replace` sends `replace_label`, and ctx's refusal of a set whose label an active key carries (409 with `labels`) is named with what to do: the repeat of a run that stopped before its `.env` line deactivates by id the key the run's note explains (the id ctx answered, or a key made within 5 minutes of the note), and a key diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 11b95481d..e5ee3a213 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -83,11 +83,19 @@ PROVISION_LOCK_WAIT_S = 5.0 PROVISION_LOCK_POLL_S = 0.05 # The labels this profile home sent a keyset-provision for and wrote no .env line for yet (in ctx_state/, -# a JSON object label -> {"sent": time, "id": the key's id once ctx answered}; no .json name, so the -# state pruning keeps it). Only the key such a note explains is retired without --replace: the noted id, -# or without one a key ctx made within STOPPED_RUN_SLACK_S of the noted time; every other key of the -# label is another machine's. +# a JSON object label -> {"sent": time, "group": the group's name, "id": the key's id once ctx answered}; +# no .json name, so the state pruning keeps it). Only the key such a note of the same group explains is +# retired without --replace: the noted id, or without one a key ctx made within STOPPED_RUN_SLACK_S of the +# noted time; every other key of the label is another machine's. PENDING_FILE = "access-provision.pending" +# The keys this profile home made (in ctx_state/, a JSON object key id -> {"label", "platform", "server", +# "group", "variable", "digest"}, the digest of the key as narrowing.key_digest gives it, never the key; no +# .json name, so the state pruning keeps it), written when ctx answers the set. What ctx stores of a key +# cannot tell its group: the label names server and profile, the home scope the group's name with "_" as +# "-". --replace rotates only keys recorded here for the same platform, server and group (or explained by +# that group's own stopped run); a run that wrote its .env line keeps only its key's record of the label. +KEYS_FILE = "access-provision.keys" +_KEY_RECORD = ("label", "platform", "server", "group", "variable", "digest") # How far ctx's created_at of a stopped run's key may lie from the time the run noted before it sent: # the request's own bound (REQUEST_TIMEOUT_S per step) and the difference of this computer's clock and # ctx's. A key outside it is not taken for the stopped run's; a clock further off makes the repeat ask @@ -733,30 +741,57 @@ def _provision_lock(home: str) -> Iterator[None]: os.close(fd) # releases the lock -def _stopped_runs(home: str) -> dict[str, dict[str, str]]: - """The notes of :data:`PENDING_FILE` by label, ``{"sent": time[, "id": key id]}`` (a missing or +def _state_records(home: str, name: str, fields: Sequence[str]) -> dict[str, dict[str, str]]: + """The entries of the JSON object in ``ctx_state/<name>`` with their string *fields* (a missing or unreadable file: none).""" - notes: dict[str, dict[str, str]] = {} - for label, note in (_status._read_json_file(Path(home) / FACT_STATE_DIR / PENDING_FILE) or {}).items(): - if isinstance(note, Mapping): - kept = {name: note.get(name) for name in ("sent", "id")} - notes[str(label)] = {name: value for name, value in kept.items() if isinstance(value, str)} - return notes - - -def _record_run(home: str, label: str, *, sent: bool, key_id: str = "") -> None: - """Note in :data:`PENDING_FILE` that this home sends a set for *label* (``sent``; with *key_id*: the - id ctx answered for it, the time of the note kept) or that the run is over (its ``.env`` line is - written, or ctx refused the set). Raises ``OSError`` on a failed write.""" + data = _status._read_json_file(Path(home) / FACT_STATE_DIR / name) + entries: dict[str, dict[str, str]] = {} + for item, entry in (data if isinstance(data, Mapping) else {}).items(): + if isinstance(entry, Mapping): + entries[str(item)] = {field: entry[field] for field in fields if isinstance(entry.get(field), str)} + return entries + + +def _stopped_runs(home: str) -> dict[str, dict[str, str]]: + """The notes of :data:`PENDING_FILE` by label, ``{"sent": time, "group": name[, "id": key id]}``.""" + return _state_records(home, PENDING_FILE, ("sent", "group", "id")) + + +def _record_run(home: str, label: str, *, sent: bool, group: str = "", key_id: str = "") -> None: + """Note in :data:`PENDING_FILE` that this home sends a set for *label* of *group* (``sent``; with + *key_id*: the id ctx answered for it, the note's time and group kept) or that the run is over (its + ``.env`` line is written, or ctx refused the set). Raises ``OSError`` on a failed write.""" runs = _stopped_runs(home) note = runs.pop(label, {}) if sent and key_id: - runs[label] = {"sent": note.get("sent") or _status._now_text(), "id": key_id} + runs[label] = {"sent": note.get("sent") or _status._now_text(), "group": note.get("group") or group} + runs[label]["id"] = key_id elif sent: - runs[label] = {"sent": _status._now_text()} + runs[label] = {"sent": _status._now_text(), "group": group} _status._write_json_file(Path(home) / FACT_STATE_DIR / PENDING_FILE, runs) +def _made_keys(home: str) -> dict[str, dict[str, str]]: + """The records of :data:`KEYS_FILE` by key id.""" + return _state_records(home, KEYS_FILE, _KEY_RECORD) + + +def _record_key(home: str, key_id: str, record: Mapping[str, str], *, last: bool) -> None: + """Record that this home made *key_id* for *record*'s group; *last* (its ``.env`` line is written): + the other records of its label go, since ctx keeps no other active key of a label after a set. + Raises ``OSError`` on a failed write.""" + records = _made_keys(home) + if last: + records = {item: entry for item, entry in records.items() if entry.get("label") != record.get("label")} + records[key_id] = {field: str(record[field]) for field in _KEY_RECORD} + _status._write_json_file(Path(home) / FACT_STATE_DIR / KEYS_FILE, records) + + +def _of_group(entry: Mapping[str, str] | None, group: tuple[str, str, str]) -> bool: + """Whether a record names the group ``(platform, server id, group name as given)``.""" + return entry is not None and (entry.get("platform"), entry.get("server"), entry.get("group")) == group + + def _instant(text: Any) -> datetime | None: """A time as ctx (``created_at``, RFC 3339) and :data:`PENDING_FILE` write it; ``None`` if it is none.""" if not isinstance(text, str): @@ -1000,6 +1035,8 @@ def _provision_locked( env_value=_env_values(home).get(variable, ""), replace=args.replace, stopped=_stopped_runs(home).get(label), + made=_made_keys(home), + group=(platform, scope_id, group), ) except ValueError: # a URL CtxClient does not take (no http(s), no host) print(f" ✗ {_status.display_url(url) or url!r} is no http(s) URL of a ctx server; nothing was sent") @@ -1025,7 +1062,7 @@ def _provision_locked( return 1 print(f" key {key_id} of a run that stopped before its .env line: deactivated") try: # before the set is sent (a failed retire above keeps the earlier note): the repeat finds this run - _record_run(home, label, sent=True) + _record_run(home, label, sent=True, group=group) except OSError as exc: record = Path(home) / FACT_STATE_DIR / PENDING_FILE print(f" ✗ {record} cannot be written ({type(exc).__name__}); no key set was sent") @@ -1086,6 +1123,11 @@ def _provision_locked( ) return 1 secret, _slug, scopes = made + record = {"label": label, "platform": platform, "server": scope_id, "group": group, "variable": variable} + record["digest"] = narrowing.key_digest(secret) + if isinstance(key_id, str) and key_id: # before the line: a stopped run's key is tied to its group too + with contextlib.suppress(OSError): + _record_key(home, key_id, record, last=False) try: _write_env_line(home, variable, secret) except (OSError, ValueError) as exc: @@ -1097,6 +1139,9 @@ def _provision_locked( return 1 with contextlib.suppress(OSError): # the run is over; a record that stays only allows its own repeat _record_run(home, label, sent=False) + if isinstance(key_id, str) and key_id: + with contextlib.suppress(OSError): + _record_key(home, key_id, record, last=True) for entry in scopes: print(f" ctx scope {entry.get('scope')} ({'created' if entry.get('created') else 'there already'})") print( @@ -1160,16 +1205,21 @@ def _key_conflict( env_value: str, replace: bool, stopped: Mapping[str, str] | None, + made: Mapping[str, Mapping[str, str]], + group: tuple[str, str, str], ) -> tuple[str, list[str]]: """Why this set would replace something it must not, from ctx's own list of the tenant's active keys (``api-key-list`` with the tenant-admin key; ``""``: nothing), and the id of the key a stopped run of this home left (to retire before the set). A key serves one group per server and profile: its - label names them, its home is the group's scope. Refused: (1) the label's key homed in another - group's scope; (2) the group's scope homing a key of another label (another server, profile or group - whose name maps to the same scope); (3) without *replace*, a key of this group in the ``.env`` - already (rotation is asked for, not done by a repeat); (4) without *replace*, a key of the label at - ctx that the ``.env`` does not hold and the note of a stopped run of this home (*stopped*, see - :func:`_left_by`) does not explain — another machine's key; (5) such a key that is no member key. + label names them, its home is the group's scope; which group (*group*: platform, server id, name as + given) only this home's records tell (*made*, :data:`KEYS_FILE`). Refused: (1) the label's key homed + in another group's scope; (2) the group's scope homing a key of another label (another server, profile + or group whose name maps to the same scope); (3) a key of the label recorded here for another group + (``a_b`` and ``a-b`` share scope and label); with *replace*, (4) a key of the label neither recorded + here for this group nor left by this group's stopped run — the way by hand is named; without + *replace*, (5) a key of this group in the ``.env`` already (rotation is asked for, not done by a + repeat), (6) a key of the label that is no member key, (7) a key of the label that the ``.env`` does + not hold and the note of this group's stopped run (*stopped*, see :func:`_left_by`) does not explain. The key the note explains is the stopped run's: the repeat retires it by id, without ``replace_label`` (only *replace* sends it), so it never deactivates another group's key, and ctx takes the new set (a deactivated key does not hold the label).""" @@ -1199,7 +1249,24 @@ def _key_conflict( f"uses that scope (group names that differ only in _ and - share it); give this group another name" ), [] held = [key for key in mine if key.get("label") == label] + for key in held: + entry = made.get(str(key.get("id") or "")) + if entry is not None and not _of_group(entry, group): + return ( + f"the key {key.get('id')} {label} was made in this profile for group {entry.get('group')} of " + f"{entry.get('platform')}:{entry.get('server')}, and the name {group[2]} gives the same scope " + f"{target} (_ and - give the same scope name): give this group another name" + ), [] + ours = stopped is not None and stopped.get("group") == group[2] # a stopped run of this very group if replace: + for key in held: + if not (_of_group(made.get(str(key.get("id") or "")), group) or (ours and _left_by(key, stopped))): + return _by_hand( + f"ctx has an active key {label} ({key.get('id')}) that this profile has no record of making for " + f"group {group[2]} of {group[0]}:{group[1]}, and no run of this profile left it (another machine " + f"with a profile of this name, a key made by hand, or a group whose name gives the same scope)", + variable, + ), [] return "", [] if env_value: where = f"its key {label} is active at ctx" if held else f"ctx has no active key {label}" @@ -1213,16 +1280,31 @@ def _key_conflict( f"the key {key.get('id')} labelled {label} is a {key.get('tenant_role') or 'non-member'} key, not " f"one provision made; revoke it with api-key-delete" ), [] - foreign = [key for key in held if stopped is None or not _left_by(key, stopped)] - if foreign: + foreign = [key for key in held if not (ours and _left_by(key, stopped))] + if foreign and _of_group(made.get(str(foreign[0].get("id") or "")), group): return ( - f"ctx has an active key {label} of this group ({foreign[0].get('id')}) that the profile's .env does " - f"not hold, and no run of this profile left it (another machine with a profile of this name, or a " - f"line removed from the .env); --replace makes a new key for this group and deactivates that one" + f"ctx has an active key {label} of this group ({foreign[0].get('id')}) that this profile made and its " + f".env does not hold (a line removed from the .env); --replace makes a new key for this group and " + f"deactivates that one" + ), [] + if foreign: + return _by_hand( + f"ctx has an active key {label} ({foreign[0].get('id')}) that the profile's .env does not hold, and no " + f"run of this profile left it (another machine with a profile of this name, or a key made by hand)", + variable, ), [] return "", [str(key.get("id") or "") for key in held] +def _by_hand(what: str, variable: str) -> str: + """*what* with the way to check and replace that key by hand (nothing here ties it to the group).""" + return ( + f"{what}; check it at ctx (ctx manage api-key-list) and, if it is this group's key, deactivate it (ctx " + f"manage api-key-update with its id and active=false), remove {variable} from the profile's .env and run " + f"provision again without --replace" + ) + + def _full_name(scope: str) -> str: """A scope of the request as the answer names it, the slug left open (``*:<name>`` for a bare name).""" return scope if ":" in scope else f"*:{scope}" diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py new file mode 100644 index 000000000..8deb98d04 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py @@ -0,0 +1,168 @@ +"""``access provision --replace`` rotates the key of the same group only (PR review of the plugin layer). +What ctx stores of a key cannot tell its group: the label names server and profile, the home scope the +group's name with ``_`` as ``-`` (``a_b`` and ``a-b`` share both). So the profile home records, when +ctx answers a set, which platform, server and group (its name as given) the key was made for +(``ctx_state/access-provision.keys``), and a rotation goes ahead only for keys recorded for this group, +or explained by the note of this group's own stopped run. A key without such a record is refused, with +the way to check and replace it by hand.""" + +from __future__ import annotations + +import pytest +from fakes import access_host as ah + +_PKG = ah.load_plugin("ctx_checkpoint_access_seam_provision_identity") +cli = ah.plugin_module(_PKG, "memory.access_cli") + +ADMIN_KEY = "ctx_admin_MARKED_FAKE_KEY_identity" +LABEL = "hermes:discord:111:members" +VAR = "CTX_KEY_111_MEMBERS" + + +@pytest.fixture +def ctx(fake_ctx, monkeypatch, tmp_path): + fake_ctx.add_key(secret=ADMIN_KEY, tenant="t", home="t:main", role="admin") + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_ADMIN": ADMIN_KEY}) + monkeypatch.setenv("CTX_ADMIN", ADMIN_KEY) + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "process-home")) + return fake_ctx + + +def _home(root, profile="members"): + home = root / "profiles" / profile + home.mkdir(parents=True, exist_ok=True) + return home + + +def _provision(home, group, *extra, server="discord:111"): + argv = ["provision", "--server", server, "--profile", "members", "--group", group] + return cli.run_access([*argv, "--admin-key-env", "CTX_ADMIN", *extra], hermes_home=str(home)) + + +def _labelled(fake, label=LABEL): + return [key for key in fake.keys.values() if key.label == label] + + +def _active(fake, label=LABEL): + return [key for key in _labelled(fake, label) if key.active] + + +def _sets(fake): + return [r.body for r in fake.requests("/api/manage") if r.action == "keyset-provision"] + + +def _env(home): + return (home / ".env").read_text(encoding="utf-8") + + +def _stop_before_the_env_line(monkeypatch, home, group, *extra): + real = cli._write_env_line + + def broken(home, name, value): + raise OSError("disk full") + + monkeypatch.setattr(cli, "_write_env_line", broken) + assert _provision(home, group, *extra) == 1 + monkeypatch.setattr(cli, "_write_env_line", real) + + +# -- finding 4816373535: the group's name as given, not its scope, ties a key to it --------------- + + +@pytest.mark.parametrize("replace", [(), ("--replace",)]) +def test_a_group_whose_name_maps_to_another_group_s_scope_is_refused(ctx, tmp_path, capsys, replace): + """``a_b`` holds the key; ``a-b`` has the same scope and label. Neither a repeat nor ``--replace`` + may take ``a_b``'s key for ``a-b``'s.""" + home = _home(tmp_path) + assert _provision(home, "a_b") == 0 + (first,) = _active(ctx) + before = _env(home) + capsys.readouterr() + assert _provision(home, "a-b", *replace) == 1 + out = capsys.readouterr().out + assert "a_b" in out and "another name" in out and "Nothing was created" in out, out + assert first.active and len(_sets(ctx)) == 1 and _env(home) == before + + +def test_replace_of_a_key_this_home_has_no_record_of_is_refused_with_the_way_by_hand(ctx, tmp_path, capsys): + """Another machine with a profile of this name made the key: nothing here ties it to this group.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + assert _provision(host_b, "members") == 0 + (b_key,) = _active(ctx) + capsys.readouterr() + assert _provision(host_a, "members", "--replace") == 1 + out = capsys.readouterr().out + assert b_key.id in out and "no record" in out and "api-key-update" in out and "without --replace" in out, out + assert b_key.active and len(_sets(ctx)) == 1 and not (host_a / ".env").exists() + b_key.active = False # the way by hand: this group's key, deactivated at ctx, then a run without --replace + assert _provision(host_a, "members") == 0 + (a_key,) = _active(ctx) + assert _env(host_a) == f"{VAR}={a_key.secret}\n" + + +def test_the_same_group_rotates_and_its_record_follows_the_key(ctx, tmp_path): + home = _home(tmp_path) + assert _provision(home, "members") == 0 + (first,) = _active(ctx) + assert _provision(home, "members", "--replace") == 0 + (second,) = _active(ctx) + assert not first.active and _env(home) == f"{VAR}={second.secret}\n" + records = cli._made_keys(str(home)) + assert set(records) == {second.id} + assert {name: records[second.id][name] for name in ("platform", "server", "group", "label", "variable")} == { + "platform": "discord", + "server": "111", + "group": "members", + "label": LABEL, + "variable": VAR, + } + assert second.secret not in (home / "ctx_state" / cli.KEYS_FILE).read_text(encoding="utf-8") + + +def test_a_stopped_rotation_is_repeated_with_replace(ctx, tmp_path, monkeypatch): + """The rotation made its key and stopped before its line (the earlier key already inactive): the same + command again rotates the key the run recorded, and the .env ends with the one active key.""" + home = _home(tmp_path) + assert _provision(home, "members") == 0 + _stop_before_the_env_line(monkeypatch, home, "members", "--replace") + assert _provision(home, "members", "--replace") == 0 + (active,) = _active(ctx) + assert _env(home) == f"{VAR}={active.secret}\n" and len(_labelled(ctx)) == 3 + + +def test_a_stopped_run_of_another_group_of_the_scope_is_not_repeated_for_this_one(ctx, tmp_path, monkeypatch, capsys): + home = _home(tmp_path) + _stop_before_the_env_line(monkeypatch, home, "a_b") + (stopped,) = _active(ctx) + capsys.readouterr() + assert _provision(home, "a-b") == 1 + assert "a_b" in capsys.readouterr().out + assert stopped.active and len(_sets(ctx)) == 1 + assert _provision(home, "a_b") == 0 # its own group repeats it + assert not stopped.active and len(_active(ctx)) == 1 + + +@pytest.mark.parametrize("replace", [(), ("--replace",)]) +def test_a_lost_answer_of_another_group_of_the_scope_is_not_taken_for_this_one( + ctx, tmp_path, monkeypatch, capsys, replace +): + """ctx made ``a_b``'s key and its answer never came (no id, no record): only the note's group ties + the key to ``a_b``, so ``a-b`` neither retires nor rotates it.""" + home = _home(tmp_path) + real = cli._manage_once + + def lost(url, key, payload): + answer = real(url, key, payload) + if payload.get("action") == "keyset-provision": + raise cli._client.CtxApiError("connection error: reset by peer") + return answer + + monkeypatch.setattr(cli, "_manage_once", lost) + assert _provision(home, "a_b") == 1 + monkeypatch.setattr(cli, "_manage_once", real) + (stopped,) = _active(ctx) + capsys.readouterr() + assert _provision(home, "a-b", *replace) == 1 + assert "no run of this profile left it" in capsys.readouterr().out + assert stopped.active and len(_sets(ctx)) == 1 + assert _provision(home, "a_b") == 0 and not stopped.active # its own group repeats it diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py index 9b6379116..cf98f6854 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py @@ -147,7 +147,8 @@ def test_two_first_runs_on_two_machines_end_with_one_key_and_ctx_s_refusal(ctx, def test_a_key_of_this_group_that_another_machine_holds_is_not_replaced_without_replace(ctx, tmp_path, capsys): """ctx holds an active key of the label in the group's own scope and this profile's ``.env`` none, - but this home never sent a set for it: another machine's key, not a stopped run of this one.""" + but this home never sent a set for it: another machine's key, not a stopped run of this one. Nothing + here ties it to this group either, so ``--replace`` is refused as well (test_access_seam_provision_identity).""" host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") assert _provision(host_b, "members") == 0 (b_key,) = _labelled(ctx) @@ -157,8 +158,8 @@ def test_a_key_of_this_group_that_another_machine_holds_is_not_replaced_without_ assert "--replace" in out and LABEL in out, out assert b_key.active and len(_sent(ctx, "keyset-provision")) == 1 and not _sent(ctx, "api-key-update") assert not (host_a / ".env").exists() - assert _provision(host_a, "members", "--replace") == 0 # asked for: replaced - assert not b_key.active + assert _provision(host_a, "members", "--replace") == 1 # no record ties B's key to this group here + assert b_key.active and len(_sent(ctx, "keyset-provision")) == 1 def test_a_stopped_run_is_repeated_without_a_switch_and_retires_only_its_own_key(ctx, tmp_path, monkeypatch): diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py index 762fe4536..42bc3c083 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py @@ -1186,7 +1186,7 @@ def _stopped_by_a_lost_answer(world, monkeypatch, host, name: str) -> tuple[Path assert rc == 1 and "no clear answer from ctx" in out, out assert dropped and dropped[0][0] == 200, f"ctx committed the set: {dropped}" note = _pending(home).get(label) or {} - assert set(note) == {"sent"}, f"a run whose answer was lost notes only the time: {note}" + assert set(note) == {"sent", "group"}, f"a run whose answer was lost notes only the time and group: {note}" [orphan] = _label_keys(world, label) return home, label, orphan @@ -1219,7 +1219,7 @@ def test_a_run_that_lost_its_answer_is_repeated_by_its_note_and_ctxs_created_at( assert nar.evaluate(narrowed, plain, expect).ok -def test_a_note_older_than_the_slack_explains_no_key_and_replace_rotates_it(world, provisioning, monkeypatch): +def test_a_note_older_than_the_slack_explains_no_key_and_it_is_replaced_by_hand(world, provisioning, monkeypatch): home, label, orphan = _stopped_by_a_lost_answer(world, monkeypatch, provisioning, "stale") pending = _pending(home) sent = cli._instant(pending[label]["sent"]) @@ -1232,8 +1232,11 @@ def test_a_note_older_than_the_slack_explains_no_key_and_replace_rotates_it(worl sets = [row for row in fwd.seen if row[2] in ("keyset-provision", "api-key-update")] assert rc == 1 and "no run of this profile left it" in out and sets == [], (out, sets) _provision_via(provisioning, monkeypatch, URL) - rc, out = _provision(home, SERVER_A, "stale", "stale", "--replace") - assert rc == 0 and "an earlier key of this label is inactive now" in out, out + rc, out = _provision(home, SERVER_A, "stale", "stale", "--replace") # nothing here ties the key to the group + assert rc == 1 and "no record" in out and "api-key-update" in out and len(_label_keys(world, label)) == 1, out + must(manage(world["owner"], {"action": "api-key-update", "data": {"id": orphan["id"], "active": False}}), "by hand") + rc, out = _provision(home, SERVER_A, "stale", "stale") + assert rc == 0, out [active] = _label_keys(world, label) assert active["id"] != orphan["id"] new_key = _env_value(home, "CTX_KEY_111_STALE") From 1fc7d25b2aec02adfa30efa48876cfa52f27ae27 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:14:51 +0100 Subject: [PATCH 55/65] fix(ctx_checkpoint): provision does not overwrite a .env variable that holds another group's key, and --replace none it has no record of The key's variable CTX_KEY_<server id>_<PROFILE> names the server id, not the platform: discord:111 and slack:111 served by one profile share it, with different labels and scopes. --replace returned before the check of the occupied variable, so provisioning slack:111 overwrote the key of discord:111's group, whose binding then failed at its next build. Without --replace the refusal told the operator to use --replace. Now the key the variable holds is looked up in the profile's record of the keys it made (by the key's digest). A key recorded for another group is refused with and without --replace, naming that group; with --replace, a key without a record (set by hand) is refused with the way to replace it by hand. A key recorded for this group still rotates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 6 ++- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 4 +- .../ctx_checkpoint/memory/access_cli.py | 35 ++++++++++++- .../test_access_seam_provision_conflicts.py | 10 ++-- .../test_access_seam_provision_identity.py | 51 +++++++++++++++++++ 5 files changed, 99 insertions(+), 7 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 4819bc4a0..9120c09bc 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -668,7 +668,11 @@ a key for: give one of them another name); a group part longer than 9 characters is cut and ends in a 4-character hash. With `--per-community` (a tenant of this server alone): `k` and `<group>`. The key's label and variable name the server and the profile, not the group: one key per server and profile, so `provision` refuses a second group served by the same -profile on that server and names the key of the first. +profile on that server and names the key of the first. The variable names the server id, not the +platform: `discord:111` and `slack:111` served by one profile share `CTX_KEY_111_<PROFILE>`, so +`provision` never overwrites the variable while it holds the key the profile recorded for another +group (with or without `--replace`; it names that group), and `--replace` does not overwrite a key the +profile has no record of (set by hand: remove the line, then run without `--replace`). Warnings of `access check`: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index e93aedecd..23c7cab9a 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -62,7 +62,9 @@ older server a group binding is off and the profile's own connection works as be another key homes; the same group again needs `--replace` while its key is in the `.env`, and `--replace` rotates only keys the profile recorded making for this platform, server and group name (`ctx_state/access-provision.keys`; `a_b` and `a-b` share scope and label) or this group's own stopped - run left — any other key is refused with the way to replace it by hand. Only `--replace` sends `replace_label`, and + run left — any other key is refused with the way to replace it by hand; the `.env` variable (it names + the server id, not the platform) is not overwritten while it holds another group's recorded key or, + with `--replace`, a key without a record. Only `--replace` sends `replace_label`, and ctx's refusal of a set whose label an active key carries (409 with `labels`) is named with what to do: the repeat of a run that stopped before its `.env` line deactivates by id the key the run's note explains (the id ctx answered, or a key made within 5 minutes of the note), and a key diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index e5ee3a213..f02cf8885 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -1257,8 +1257,22 @@ def _key_conflict( f"{entry.get('platform')}:{entry.get('server')}, and the name {group[2]} gives the same scope " f"{target} (_ and - give the same scope name): give this group another name" ), [] + owner = _env_owner(made, variable, env_value) + if owner is not None and not _of_group(owner, group): + return ( + f"{variable} in the profile's .env holds the key of group {owner.get('group')} of " + f"{owner.get('platform')}:{owner.get('server')} ({owner.get('label')}): the variable names the server id " + f"and the profile, not the platform or the group, so give this group a profile of its own" + ), [] ours = stopped is not None and stopped.get("group") == group[2] # a stopped run of this very group if replace: + if env_value and owner is None: + return _by_hand( + f"{variable} in the profile's .env holds a key (digest {narrowing.key_digest(env_value)}) that this " + f"profile has no record of making for group {group[2]} of {group[0]}:{group[1]} (set by hand, or a " + f"key of another group)", + variable, + ), [] for key in held: if not (_of_group(made.get(str(key.get("id") or "")), group) or (ours and _left_by(key, stopped))): return _by_hand( @@ -1268,11 +1282,18 @@ def _key_conflict( variable, ), [] return "", [] + if env_value and owner is None: + return _by_hand( + f"{variable} in the profile's .env holds a key (digest {narrowing.key_digest(env_value)}) that this " + f"profile has no record of making for group {group[2]} of {group[0]}:{group[1]} (set by hand, or a key " + f"of another group)", + variable, + ), [] if env_value: where = f"its key {label} is active at ctx" if held else f"ctx has no active key {label}" return ( - f"{variable} in the profile's .env holds a key for this server and profile already ({where}); " - f"--replace makes a new key for this same group and deactivates the earlier one" + f"{variable} in the profile's .env holds this group's key already ({where}); --replace makes a new " + f"key for this same group and deactivates the earlier one" ), [] for key in held: # provision makes member keys only; ctx's replace_label spares every other key too if key.get("tenant_role") != "member": @@ -1296,6 +1317,16 @@ def _key_conflict( return "", [str(key.get("id") or "") for key in held] +def _env_owner(made: Mapping[str, Mapping[str, str]], variable: str, value: str) -> Mapping[str, str] | None: + """The record of the key *variable* holds in the ``.env`` (by the key's digest; ``None``: none, or no + value): which binding owns the variable.""" + if not value: + return None + digest = narrowing.key_digest(value) + found = [entry for entry in made.values() if entry.get("variable") == variable and entry.get("digest") == digest] + return found[0] if found else None + + def _by_hand(what: str, variable: str) -> str: """*what* with the way to check and replace that key by hand (nothing here ties it to the group).""" return ( diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py index 0cb0b6203..d5da28917 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py @@ -117,12 +117,16 @@ def test_the_same_group_again_needs_replace_while_its_key_is_in_the_env(ctx, tmp assert (home / ".env").read_text(encoding="utf-8") == f"CTX_KEY_111_MEMBERS={key.secret}\n" -def test_a_key_in_the_env_without_its_key_at_ctx_needs_replace(ctx, tmp_path, capsys): +def test_a_key_in_the_env_without_its_key_at_ctx_is_replaced_by_hand(ctx, tmp_path, capsys): + """A line this profile has no record of (set by hand): neither a run nor ``--replace`` overwrites it + (test_access_seam_provision_identity); removed by hand, the group is provisioned.""" home = _home(tmp_path, "members") (home / ".env").write_text("CTX_KEY_111_MEMBERS=ctx_key_nobody_holds_any_more\n", encoding="utf-8") assert _provision(home, "members", "members") == 1 - assert "--replace" in capsys.readouterr().out and _sets(ctx) == 0 - assert _provision(home, "members", "members", "--replace") == 0 + assert "without --replace" in capsys.readouterr().out and _sets(ctx) == 0 + assert _provision(home, "members", "members", "--replace") == 1 and _sets(ctx) == 0 + (home / ".env").write_text("", encoding="utf-8") + assert _provision(home, "members", "members") == 0 def test_a_run_that_stopped_before_its_env_line_repeats_without_replace(ctx, tmp_path, monkeypatch): diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py index 8deb98d04..80877adf2 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py @@ -166,3 +166,54 @@ def lost(url, key, payload): assert "no run of this profile left it" in capsys.readouterr().out assert stopped.active and len(_sets(ctx)) == 1 assert _provision(home, "a_b") == 0 and not stopped.active # its own group repeats it + + +# -- finding 4816377057: the variable belongs to one binding ------------------------------------- +# The variable names the server id and the profile, not the platform or the group: ``discord:111`` and +# ``slack:111`` served by one profile both name ``CTX_KEY_111_MEMBERS``. + + +@pytest.mark.parametrize("replace", [(), ("--replace",)]) +def test_the_variable_of_another_platform_s_group_is_not_overwritten(ctx, tmp_path, capsys, replace): + home = _home(tmp_path) + assert _provision(home, "members") == 0 + (discord,) = _active(ctx) + before = _env(home) + capsys.readouterr() + assert _provision(home, "mods", *replace, server="slack:111") == 1 + out = capsys.readouterr().out + assert VAR in out and "group members of discord:111" in out and "profile of its own" in out, out + assert _env(home) == before and discord.active + assert len(_sets(ctx)) == 1 and not _active(ctx, "hermes:slack:111:members") + + +def test_replace_of_a_variable_this_home_has_no_record_of_is_refused_with_the_way_by_hand(ctx, tmp_path, capsys): + """A key set by hand: nothing here says which group it belongs to.""" + home = _home(tmp_path) + (home / ".env").write_text(f"{VAR}=ctx_key_set_by_hand_0123456789\n", encoding="utf-8") + assert _provision(home, "members", "--replace") == 1 + out = capsys.readouterr().out + assert VAR in out and "no record" in out and "without --replace" in out, out + assert _sets(ctx) == [] and _env(home) == f"{VAR}=ctx_key_set_by_hand_0123456789\n" + (home / ".env").write_text("", encoding="utf-8") # the way by hand: the line removed + assert _provision(home, "members") == 0 + + +def test_a_variable_this_home_recorded_for_the_group_rotates(ctx, tmp_path): + home = _home(tmp_path) + assert _provision(home, "members") == 0 + assert _provision(home, "members", "--replace") == 0 + assert _provision(home, "members", "--replace") == 0 + (active,) = _active(ctx) + assert _env(home) == f"{VAR}={active.secret}\n" and set(cli._made_keys(str(home))) == {active.id} + + +def test_a_key_set_by_hand_over_this_group_s_line_is_not_taken_for_its_own(ctx, tmp_path, capsys): + """The record names this group for the variable, but the line holds another key now (by its digest).""" + home = _home(tmp_path) + assert _provision(home, "members") == 0 + (home / ".env").write_text(f"{VAR}=ctx_key_set_by_hand_0123456789\n", encoding="utf-8") + capsys.readouterr() + assert _provision(home, "members", "--replace") == 1 + assert "no record" in capsys.readouterr().out + assert len(_sets(ctx)) == 1 and _env(home) == f"{VAR}=ctx_key_set_by_hand_0123456789\n" From 906a1c20a46a927005c09fe54d8f54fb3ee4f3b9 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:19:25 +0100 Subject: [PATCH 56/65] fix(ctx_checkpoint): a repeated rotation deactivates no key it cannot tie to the group, and replace_label goes only with a key the check proved The README told the operator to run the same command again after a run without a clear answer or without its .env line, --replace included. With --replace the repeat skipped the stopped run's note and sent replace_label for the whole label, so a key another machine made since (the stopped key replaced there by hand, then a first run) was deactivated. With the record of the keys this profile made, a repeat with --replace rotates only keys recorded for the group or explained by its own stopped run; any other key is refused with the way to check it. A rotation now sends replace_label only when its check found this group's key: with none found, a key made by anyone after the check is ctx's 409, not deactivated, so two rotations of a label no active key carries end like two first runs. The 409 message no longer tells the operator to use --replace blindly. The README says what the repeat does and what it refuses. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 25 +++++----- .../plugin/ctx_checkpoint/memory/CHANGELOG.md | 10 ++-- .../ctx_checkpoint/memory/access_cli.py | 48 +++++++++++-------- .../tests/test_access_seam_provision_race.py | 46 ++++++++++++++++++ 4 files changed, 93 insertions(+), 36 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 9120c09bc..124d78742 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -625,27 +625,28 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co with and without it. A key without such a record (another machine, a key made by hand) is refused with the way to replace it by hand: check it with `ctx manage api-key-list`, deactivate it with `ctx manage api-key-update` and `active=false`, remove the line from the `.env`, and run `provision` again without - `--replace`. Only `--replace` sends `replace_label`, so a first run deactivates no key, - and ctx refuses its set while an active key carries the label (409 naming the labels; the command - then says to use `--replace` for the same group, or a profile of its own when another group or - machine holds the label). A key of the label that the `.env` does not hold is refused as well + `--replace`. Only `--replace` sends `replace_label`, and only when its check found this group's key, so + a first run deactivates no key, and ctx refuses a set without it while an active key carries the + label (409 naming the labels: a key made after the check; run the command again to see whose it is). + A key of the label that the `.env` does not hold is refused as well (another machine with a profile of this name), unless a run of this profile left it: the profile notes in `ctx_state/access-provision.pending` that it sent a set and, once ctx answered, the key's id, until the set's `.env` line is written. Nothing is written when ctx refuses (a 4xx answer; a reached `max_keys` or `max_scopes` answers 429). Without a clear answer (no answer in time, a 5xx or a proxy error) the set may have been created (with `--replace`, the earlier key of the label may - already be inactive): run the same command again — it deactivates by id the key the note explains - (the noted id, or without one a member key of the label in the group's scope that ctx made within - 5 minutes of the noted time, by ctx's and this computer's clocks), then asks for a new key, so one - key per label stays active and lands in the `.env`; a key it cannot place that way is refused like - another machine's. Runs in one profile home take turns under `ctx_state/access-provision.lock`, held + already be inactive): run the same command again — without `--replace` it deactivates by id the key + the note explains (the noted id, or without one a member key of the label in the group's scope that + ctx made within 5 minutes of the noted time, by ctx's and this computer's clocks), then asks for a new + key; with `--replace` it rotates only keys recorded for this group or explained by that note. Either + way one key per label stays active and lands in the `.env`, and a key it cannot place (one another + machine made since, or one replaced by hand) is refused with the way to check it, never deactivated. Runs in one profile home take turns under `ctx_state/access-provision.lock`, held from the check to the `.env` line: a second run sees what the first committed, and the `.env` ends with the key ctx committed last. A run that cannot have the lock within 5 s, or on a platform or file system without file locks, sends nothing. Two machines share no lock, but ctx decides the label under its tenant lock: of two first runs at the same moment one gets the key and the other the refusal. - Still open across machines: two rotations with `--replace` leave one machine with a deactivated key; - and a key of the label the other machine made within those 5 minutes of a run here whose answer was - lost is taken for that run's key when the run is repeated here. Sessions bound with an earlier + Two rotations of a label no active key carries send no `replace_label` and are decided the same + way. Still open across machines: a key of the label the other machine made within those 5 minutes of + a run here whose answer was lost is taken for that run's key when the run is repeated here. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id or group name no scope or variable name can hold, a `--profile` other than the profile the command diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 23c7cab9a..ed8cde0e8 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -64,15 +64,17 @@ older server a group binding is off and the profile's own connection works as be (`ctx_state/access-provision.keys`; `a_b` and `a-b` share scope and label) or this group's own stopped run left — any other key is refused with the way to replace it by hand; the `.env` variable (it names the server id, not the platform) is not overwritten while it holds another group's recorded key or, - with `--replace`, a key without a record. Only `--replace` sends `replace_label`, and - ctx's refusal of a set whose label an active key carries (409 with `labels`) is named with what to do: + with `--replace`, a key without a record. Only `--replace` sends `replace_label`, only when its check + found this group's key, and ctx's refusal of a set whose label an active key carries (409 with + `labels`) is named with what to do: the repeat of a run that stopped before its `.env` line deactivates by id the key the run's note explains (the id ctx answered, or a key made within 5 minutes of the note), and a key of the label no run of the profile left is refused. Runs in one profile home take turns under a lock that fails closed (`ctx_state/access-provision.lock`), from the check to the `.env` line, so the `.env` ends with the key ctx committed last; the line is written through Hermes' own `.env` writer - (`save_env_value`, under Hermes' `.env` lock), so a variable Hermes saves meanwhile is kept. `access check` reads the group's key from the - profile's `.env` and secret sources only, never from the shell's environment. + (`save_env_value`, under Hermes' `.env` lock), so a variable Hermes saves meanwhile is kept. `access + check` reads the group's key from the profile's `.env` and secret sources only, never from the shell's + environment. - Fixed before release: the state pruning (`state_retention_days`) deleted the markers after 30 days and a session whose root id was `access-mode` wrote its fact ledger over them (both kept now); a status write that failed could abort `initialize` (guarded); an id prefix of several blocks in diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index f02cf8885..1319e7a17 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -1025,7 +1025,7 @@ def _provision_locked( ) return 1 try: - conflict, stopped_keys = _key_conflict( + conflict, found = _key_conflict( url, admin_key, slug=slug, @@ -1048,6 +1048,9 @@ def _provision_locked( if conflict: print(f" ✗ {conflict}. Nothing was created") return 1 + # --replace: the keys the check proved this group's, which replace_label deactivates (none found: no + # replace_label, so a key made since by anyone is ctx's 409, not deactivated); else the stopped run's + replace_label, stopped_keys = (bool(found), []) if args.replace else (False, found) for key_id in stopped_keys: # the key a stopped run of this home made, by id (never the label's others) retire = {"action": "api-key-update", "data": {"id": key_id, "active": False}} try: @@ -1078,7 +1081,7 @@ def _provision_locked( "allowed_scopes": [knowledge, *extra], "write_scopes": [], "scope_narrowing": "required", - "replace_label": bool(args.replace), # a first run or a repeat deactivates no key of the label + "replace_label": replace_label, # a first run or a repeat deactivates no key of the label } ], }, @@ -1093,13 +1096,14 @@ def _provision_locked( if exc.status is not None and 400 <= exc.status < 500: with contextlib.suppress(OSError): # nothing was made: no stopped run to repeat _record_run(home, label, sent=False) - taken = exc.labels if isinstance(exc, _LabelsTaken) and not args.replace else [] + taken = exc.labels if isinstance(exc, _LabelsTaken) and not replace_label else [] if taken: # without replace_label: an active key of the tenant carries the label (ctx's lock decided) print( f" ✗ ctx refused the key set, nothing was created: an active key of the tenant already carries " - f"the label {', '.join(taken)}. For a new key of this same group run it again with --replace (the " - f"earlier key is deactivated); otherwise another group of this server and profile, or another " - f"machine with a profile of this name, holds the label: give this group a profile of its own" + f"the label {', '.join(taken)}, made after this run's check (another group of this server and " + f"profile, or another machine with a profile of this name). Run it again to see that key: a key " + f"this profile recorded for this group is rotated with --replace, any other is named with the way " + f"to replace it by hand (or give this group a profile of its own)" ) else: print(f" ✗ ctx refused the key set, nothing was created: {cause}") @@ -1107,7 +1111,8 @@ def _provision_locked( print( f" ✗ no clear answer from ctx ({cause}): whether the key set was created is unknown (with " "--replace, the earlier key of this label may be inactive now). Run the same command again: it " - "deactivates the key this run may have made, so one key stays active and lands in the .env" + "deactivates the key this run may have made and no key it cannot tie to this group, so one key " + "stays active and lands in the .env" ) return 1 keys = answer.get("keys") @@ -1146,7 +1151,7 @@ def _provision_locked( print(f" ctx scope {entry.get('scope')} ({'created' if entry.get('created') else 'there already'})") print( f" key: {variable} in {env_path} (label {label}, key digest {narrowing.key_digest(secret)})" - + ("; an earlier key of this label is inactive now" if args.replace else "") + + ("; an earlier key of this label is inactive now" if replace_label else "") ) print( f" sessions bound with an earlier key of this label lose ctx until their agent is rebuilt; " @@ -1209,17 +1214,20 @@ def _key_conflict( group: tuple[str, str, str], ) -> tuple[str, list[str]]: """Why this set would replace something it must not, from ctx's own list of the tenant's active keys - (``api-key-list`` with the tenant-admin key; ``""``: nothing), and the id of the key a stopped run - of this home left (to retire before the set). A key serves one group per server and profile: its - label names them, its home is the group's scope; which group (*group*: platform, server id, name as - given) only this home's records tell (*made*, :data:`KEYS_FILE`). Refused: (1) the label's key homed - in another group's scope; (2) the group's scope homing a key of another label (another server, profile - or group whose name maps to the same scope); (3) a key of the label recorded here for another group - (``a_b`` and ``a-b`` share scope and label); with *replace*, (4) a key of the label neither recorded - here for this group nor left by this group's stopped run — the way by hand is named; without - *replace*, (5) a key of this group in the ``.env`` already (rotation is asked for, not done by a - repeat), (6) a key of the label that is no member key, (7) a key of the label that the ``.env`` does - not hold and the note of this group's stopped run (*stopped*, see :func:`_left_by`) does not explain. + (``api-key-list`` with the tenant-admin key; ``""``: nothing), and the ids of the keys the set + replaces: with *replace* the label's keys proven this group's (``replace_label`` deactivates them; none, + no ``replace_label``), without it the key a stopped run of this home left (to retire before the set). + A key serves one group per server and profile: its label names them, its home is the group's scope; + which group (*group*: platform, server id, name as given) only this home's records tell (*made*, + :data:`KEYS_FILE`). Refused: (1) the label's key homed in another group's scope; (2) the group's scope + homing a key of another label (another server, profile or group whose name maps to the same scope); + (3) a key of the label recorded here for another group (``a_b`` and ``a-b`` share scope and label); + (4) a ``.env`` variable that holds a key recorded for another group (it names the server id, not the + platform); with *replace*, (5) a variable holding a key without a record, or a key of the label neither + recorded here for this group nor left by this group's stopped run — the way by hand is named; without + *replace*, (6) a key in the variable already (rotation is asked for, not done by a repeat), (7) a key + of the label that is no member key, (8) a key of the label that the ``.env`` does not hold and the + note of this group's stopped run (*stopped*, see :func:`_left_by`) does not explain. The key the note explains is the stopped run's: the repeat retires it by id, without ``replace_label`` (only *replace* sends it), so it never deactivates another group's key, and ctx takes the new set (a deactivated key does not hold the label).""" @@ -1281,7 +1289,7 @@ def _key_conflict( f"with a profile of this name, a key made by hand, or a group whose name gives the same scope)", variable, ), [] - return "", [] + return "", [str(key.get("id") or "") for key in held] if env_value and owner is None: return _by_hand( f"{variable} in the profile's .env holds a key (digest {narrowing.key_digest(env_value)}) that this " diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py index cf98f6854..85a83ae17 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py @@ -530,3 +530,49 @@ def test_without_a_file_lock_provision_sends_nothing(ctx, tmp_path, monkeypatch, assert _provision(home, "members") == 1 assert "no file lock" in capsys.readouterr().out assert ctx.count() == 0 and not (home / ".env").exists() + + +# -- finding 4816373581: a rotation's repeat deactivates no key it cannot place ------------------ + + +def test_a_rotation_s_repeat_does_not_deactivate_the_key_another_machine_made_since(ctx, tmp_path, monkeypatch, capsys): + """Machine A's rotation made key K and stopped before its line. On machine B the operator replaced + the group's key by hand since (K deactivated, a first run made K'). The same command again on A, + ``--replace`` included, must not deactivate K' by the label.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + assert _provision(host_a, "members") == 0 + real = cli._write_env_line + + def broken(home, name, value): + raise OSError("disk full") + + monkeypatch.setattr(cli, "_write_env_line", broken) + assert _provision(host_a, "members", "--replace") == 1 + monkeypatch.setattr(cli, "_write_env_line", real) + (stopped,) = [key for key in _labelled(ctx) if key.active] + stopped.active = False # by hand on machine B, then its first run + assert _provision(host_b, "members") == 0 + (b_key,) = [key for key in _labelled(ctx) if key.active] + capsys.readouterr() + assert _provision(host_a, "members", "--replace") == 1 + out = capsys.readouterr().out + assert b_key.id in out and "no record" in out, out + assert b_key.active and _env(host_b) == f"CTX_KEY_111_MEMBERS={b_key.secret}\n" + + +def test_two_rotations_of_a_label_no_key_carries_are_decided_by_ctx(ctx, tmp_path, monkeypatch, capsys): + """Two machines rotate a label whose key is gone (no active key, nothing to prove). Rotation A passed + its check and is about to send; rotation B runs whole meanwhile. A found no key to replace, so it sends + no ``replace_label``: ctx refuses it (the label is taken now) instead of deactivating B's key.""" + host_a, host_b = _home(tmp_path / "host-a"), _home(tmp_path / "host-b") + gate = _Gate(monkeypatch, "before") + result = gate.start(lambda: _provision(host_a, "members", "--replace")) + assert _provision(host_b, "members", "--replace") == 0 + capsys.readouterr() + gate.finish() + assert result == [1] + out = capsys.readouterr().out + assert "nothing was created" in out and LABEL in out and "made after this run's check" in out, out + (b_key,) = [key for key in _labelled(ctx) if key.active] + assert _env(host_b) == f"CTX_KEY_111_MEMBERS={b_key.secret}\n" and not (host_a / ".env").exists() + assert [call["data"]["keys"][0]["replace_label"] for call in _sent(ctx, "keyset-provision")] == [False, False] From d938a3f47573990db05a37bd29c0e533b91f3847 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:20:27 +0100 Subject: [PATCH 57/65] fix(ctx_checkpoint): a checkpoint writes through the chain writer it built for its own binding, reports that binding's write limit to that binding's entry, and no writer reports a limit older than the entry's _chain put a new writer in the shared self._chain_writer and returned whatever stood there after setting its write limit. A checkpoint that paused in between while the instance was built again and another group checkpointed got that group's writer back: its transcript went through the other group's current client into the other group's scope (the stale-client guard did not stop it). A re-initialization without a second checkpoint dropped the shared writer and the call crashed on None. The write limit came from the instance field and the server entry from _entry_key(), both the binding now, not the call's. _chain now works on the call's snapshot: it returns the writer it built (or the kept one when it belongs to the same client) and keeps it for later calls only while the snapshot's binding is current. The write limit comes from that binding (a group's write client proof stores it on the group; the profile connection's is in the snapshot) and the entry from the snapshot's base URL and key digest (_entry_key_of; the umbrella keys its MCP entry from the same snapshot). The recall's second query, the digests and the chain take their entry the same way. Separately, each writer reported the limit it held at every run, and the entry took the latest report: a writer that held an older answer (40) lifted the plan above a lower limit (10) another writer of the key had seen since. A limit now carries when ctx gave the answer (whoami_raw's answers keep the time of their request, also when remembered; the profile connection's whoami its own), and the entry ignores a report of an answer older than the one it holds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/__init__.py | 10 +- .../ctx_checkpoint/memory/checkpoint.py | 31 +++-- .../plugin/ctx_checkpoint/memory/narrowing.py | 27 ++++- .../plugin/ctx_checkpoint/memory/provider.py | 102 ++++++++++++---- .../tests/test_access_review_r3.py | 109 ++++++++++++++++++ 5 files changed, 238 insertions(+), 41 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index 7b6270a44..2746956f8 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -806,7 +806,7 @@ def _chain_writer_seams(self) -> dict[str, Any]: def _current_secrets(self) -> tuple[str, ...]: return (self._api_key, *self._profile_keys) - def _entry_key(self) -> tuple[str, ...]: + def _entry_key_of(self, lease: Any) -> tuple[str, ...]: """The MCP server entry the checkpoint writes to (GottZ/ctx#299): its name and a digest of what makes it one connection in Hermes — route and credentials, the fields Hermes compares before one profile adopts another profile's live connection of the same name @@ -815,9 +815,11 @@ def _entry_key(self) -> tuple[str, ...]: timeout) keeps the state; a changed route or key is another connection once Hermes reconnects. An OAuth entry is never adopted across profiles: it is keyed by the profile as well. Only compared, never logged; the digest is no copy of the key the entry carries. A - group binding writes over REST whatever the transport: its entry is the REST one.""" - if self.transport == "rest" or self._group is not None: - return super()._entry_key() + group binding writes over REST whatever the transport: its entry is the REST one. ``lease``: the + call's snapshot (None: the binding now).""" + group = lease.group if lease is not None else self._group + if self.transport == "rest" or group is not None: + return super()._entry_key_of(lease) name = self._server_name() entry = _configured_server(_effective_config(), name) canonical = json.dumps(_connection_identity_of(entry), sort_keys=True, ensure_ascii=False, default=str) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py index bf49dcd9d..59855c42c 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/checkpoint.py @@ -1013,17 +1013,26 @@ def __init__(self) -> None: self._recall_extra_off_until = 0.0 # The write limit the server last reported for the entry's key (whoami.rate_limit_write, # :meth:`report_write_limit`): ctx counts writes per key, so every window planned on the entry - # stays below it, also one a writer planned without knowing it. None: none reported. + # stays below it, also one a writer planned without knowing it. None: none reported. With it, + # when the server gave that answer (time.monotonic()). self._write_limit: int | None = None - - def report_write_limit(self, rate_limit_write: Any) -> None: - """The write limit the server reported for the key; the latest report holds (a tenant's - limit can go up as well as down, and 0 or less is none). A value that is not an int (None: the - writer knows none) is no report and changes nothing.""" + self._write_limit_at = float("-inf") + + def report_write_limit(self, rate_limit_write: Any, seen_at: float | None = None) -> None: + """The write limit the server reported for the key in an answer given at ``seen_at`` + (``time.monotonic()``; None: now). The latest answer holds, whichever writer reports it (a + tenant's limit can go up as well as down, and 0 or less is none): a report of an answer older + than the one the entry holds changes nothing, so a writer that keeps the limit of its own + older answer never lifts the plan above a lower limit another writer saw since. A value that + is not an int (None: the writer knows none) is no report and changes nothing.""" if isinstance(rate_limit_write, bool) or not isinstance(rate_limit_write, int): return + at = time.monotonic() if seen_at is None else float(seen_at) with self._cond: + if at < self._write_limit_at: + return self._write_limit = rate_limit_write + self._write_limit_at = at def capped(self, window_writes: int) -> int: """``window_writes`` below the write limit last reported for the key (unchanged without one).""" @@ -1681,6 +1690,9 @@ class ChainWriter: # the binding sets it, ``window_writes`` follows it; each run reports it to ``entry``, whose # other writers then plan below it too). None: the window of a server without it. rate_limit_write: int | None = None + # When the server gave the answer that reported it (time.monotonic(); None: now): the entry + # takes no report of an answer older than the one it holds (EntryState.report_write_limit). + rate_limit_seen_at: float | None = None _tool_evidence_warned: bool = field(default=False, init=False) def _notify(self, message: str) -> None: @@ -2200,10 +2212,11 @@ def new_run( entry that started before, so the plan holds the windows all of those need together. The caller ends the run with :meth:`_ChainRun.close` (``write`` does for its own run). - The writer's ``rate_limit_write`` is reported to the entry, and the run plans below the limit - last reported for the key, whichever writer of the key reported it.""" + The writer's ``rate_limit_write`` is reported to the entry with the time of its answer + (``rate_limit_seen_at``), and the run plans below the limit of the latest answer the key's + writers reported.""" entry = self.entry if self.entry is not None else EntryState() - entry.report_write_limit(self.rate_limit_write) + entry.report_write_limit(self.rate_limit_write, self.rate_limit_seen_at) window_writes = entry.capped(self._window_writes()) # budget_s in the run is the effective one (messages name what the chain really had). run = _ChainRun( diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py index d86b0898f..751ff7604 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py @@ -126,12 +126,31 @@ class _Proof: answer: Mapping[str, Any] | None = None failure: tuple[str, int | None, str] | None = None budget: float | None = None + answered_at: float = 0.0 # time.monotonic() when the server gave the answer def serves(self, now: float, left: float) -> bool: """Whether this proof answers a caller with ``left`` seconds of budget at ``now``.""" return self.expires > now and (self.budget is None or left <= self.budget) +class _Answer(dict): + """A raw ``whoami`` answer as :func:`whoami_raw` returns it: a plain mapping, which also knows when + the server gave it (``answered_at``, ``time.monotonic()``) — a remembered answer keeps the time of + its request (:func:`answered_at`).""" + + __slots__ = ("answered_at",) + + def __init__(self, answer: Mapping[str, Any], at: float) -> None: + super().__init__(answer) + self.answered_at = at + + +def answered_at(answer: Any) -> float | None: + """When the server gave a raw answer of :func:`whoami_raw` (``time.monotonic()``); None for any + other mapping.""" + return answer.answered_at if isinstance(answer, _Answer) else None + + _PROOFS: dict[tuple[str, str, str], _Proof] = {} _PROOFS_LOCK = threading.Lock() _next_prune = PROOF_PRUNE_MIN @@ -186,7 +205,7 @@ def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping if proof.failure is not None: message, status, code = proof.failure raise CtxApiError(message, status=status, code=code) - return copy.deepcopy(dict(proof.answer or {})) + return _Answer(copy.deepcopy(dict(proof.answer or {})), proof.answered_at) left = deadline - time.monotonic() if left <= 0 or not asking.wait(left): raise CtxApiError("connection error: timed out") # this caller's budget, not the server's answer @@ -215,8 +234,9 @@ def whoami_raw(client: CtxClient, *, narrowed: bool, budget_s: float) -> Mapping elif not exc.code: _remember(slot, _Proof(expires=expires, failure=failure, budget=budget)) raise - _remember(slot, _Proof(expires=time.monotonic() + PROOF_TTL_OK_S, answer=copy.deepcopy(dict(answer)))) - return copy.deepcopy(dict(answer)) + at = time.monotonic() + _remember(slot, _Proof(expires=at + PROOF_TTL_OK_S, answer=copy.deepcopy(dict(answer)), answered_at=at)) + return _Answer(copy.deepcopy(dict(answer)), at) finally: with _PROOFS_LOCK: _ASKING.pop(slot, None) @@ -391,6 +411,7 @@ def _other_key(narrowed: Mapping[str, Any], unnarrowed: Mapping[str, Any]) -> bo "Expect", "Narrowing", "VerifyResult", + "answered_at", "evaluate", "expected_label", "key_digest", diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index ba95e7ecb..7525fa158 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -213,6 +213,10 @@ class _GroupBinding: refused: dict[str, str] = field(default_factory=dict) refused_rules: dict[str, str] = field(default_factory=dict) # "<kind> client <rule>" -> expected value retry_at: dict[str, float] = field(default_factory=dict) + # The write limit its write client's proof read (``whoami.rate_limit_write``; None: none reported) + # and when the server gave that answer (time.monotonic()). + rate_limit_write: int | None = None + rate_limit_seen_at: float | None = None def clients(self) -> tuple[CtxClient, ...]: return tuple(c for c in (self.read_client, self.write_client, self.store_client) if c is not None) @@ -223,7 +227,10 @@ class _Lease: """One snapshot of the binding, taken under the binding lock by the gate (:meth:`_lease`): a call selects its group, clients and access context from it alone, never from what a re-initialization put in place meanwhile, and a group's clients refuse to send once it is stale. - ``generation`` counts the ``initialize`` calls; ``decided``: an access decision was taken.""" + ``generation`` counts the ``initialize`` calls; ``decided``: an access decision was taken; + ``key_digest``: the SHA-256 of the bound key (``""`` without one), which names the server entry; + ``rate_limit_write``/``rate_limit_seen_at``: the write limit the profile connection's ``whoami`` + reported and when (a group's is on the group, read by its write client's proof).""" generation: int group: _GroupBinding | None @@ -234,6 +241,9 @@ class _Lease: home_scope: str bound_turn: tuple[str, ...] | None decided: bool + key_digest: str = "" + rate_limit_write: int | None = None + rate_limit_seen_at: float | None = None def _plain(value: Any) -> Any: @@ -402,8 +412,9 @@ def __init__(self): self._access_lock = threading.RLock() self._binding_lock = threading.RLock() # The write limit per 60 s the ctx server reports for the writing key (whoami - # ``rate_limit_write``); the chain writer follows it (P-G). + # ``rate_limit_write``) and when it answered (time.monotonic()); the chain writer follows it (P-G). self._rate_limit_write: int | None = None + self._rate_limit_seen_at: float | None = None self._last_chain_receipt = None # Why the latest chain write failed (None after a success or when no chain ran); the # umbrella records it with the outcome of each checkpoint. @@ -537,6 +548,7 @@ def _drop_binding(self) -> None: self._home_scope = "" self._whoami_label = "" self._rate_limit_write = None + self._rate_limit_seen_at = None def _connect(self) -> None: """Bind credentials and the client; sets ``_active``/``_client``. Default: REST. The access @@ -573,6 +585,7 @@ def _connect(self) -> None: self._home_scope = str(info.get("home_scope") or "") self._whoami_label = str(info.get("label") or "") self._rate_limit_write = _write_limit(info) + self._rate_limit_seen_at = time.monotonic() logger.info( "CTX memory provider connected (scope=%s, label=%s, profile=%s)", self._home_scope or "?", @@ -792,12 +805,22 @@ def _binding_identity(self) -> tuple[str, ...]: access = (str(group.context.platform), str(group.context.scope_id), str(group.context.group), writer) return (self._hermes_home, self._base_url, key_digest, self._whoami_label, *access) + def _key_digest(self) -> str: + """The SHA-256 of the bound key, ``""`` without one (compared, never logged).""" + return hashlib.sha256(self._api_key.encode("utf-8")).hexdigest() if self._api_key else "" + def _entry_key(self) -> tuple[str, ...]: """The server entry the checkpoint writes to (``checkpoint.entry_state``, GottZ/ctx#299): on REST the base URL and the key's digest — ctx counts writes per key, so every binding of the - process to that key shares one window (the umbrella keys an MCP entry by profile and name).""" - key_digest = hashlib.sha256(self._api_key.encode("utf-8")).hexdigest() if self._api_key else "" - return ("rest", self._base_url, key_digest) + process to that key shares one window (the umbrella keys an MCP entry by profile and name). + The binding now; a call takes its snapshot's (:meth:`_entry_key_of`).""" + return self._entry_key_of(None) + + def _entry_key_of(self, lease: _Lease | None) -> tuple[str, ...]: + """:meth:`_entry_key` of the binding ``lease`` was taken from (None: the binding now).""" + if lease is None: + return ("rest", self._base_url, self._key_digest()) + return ("rest", lease.base_url, lease.key_digest) # -- Access groups (design 02 §4.2 to §4.6) --------------------------------------------- @@ -1056,7 +1079,7 @@ def left() -> float: if own is not None: # the client's own proof (``_client_proven``) is part of this one group.proven.add(own[0]) if own[0] == "write": - self._rate_limit_write = _write_limit(own[1]) + self._note_write_limit(group, own[1]) group.proven.add("group") self._client = group.read_client self._home_scope = group.write @@ -1199,9 +1222,16 @@ def _client_proven(self, kind: str, client: Any, group: Any = _CURRENT) -> bool: return False # turned off or re-initialized while the whoami was on its way group.proven.add(kind) if kind == "write": - self._rate_limit_write = _write_limit(raw) + self._note_write_limit(group, raw) return True + def _note_write_limit(self, group: _GroupBinding, raw: Mapping[str, Any]) -> None: + """The write limit the write client's proof read, and when ctx gave that answer (a remembered + answer keeps its own time), on the group (under the binding lock).""" + seen_at = _narrowing.answered_at(raw) + group.rate_limit_write = self._rate_limit_write = _write_limit(raw) + group.rate_limit_seen_at = self._rate_limit_seen_at = time.monotonic() if seen_at is None else seen_at + @staticmethod def _client_expect(kind: str, client: Any, group: _GroupBinding) -> Any: """What the write (``"write"``) or the store client's (``"store"``) narrowed ``whoami`` is judged @@ -1242,6 +1272,9 @@ def _snapshot(self) -> _Lease | None: home_scope=self._home_scope, bound_turn=self._bound_turn, decided=self._decision is not None, + key_digest=self._key_digest(), + rate_limit_write=self._rate_limit_write, + rate_limit_seen_at=self._rate_limit_seen_at, ) def _lease(self) -> _Lease | None: @@ -1556,7 +1589,7 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: client = lease.client if not lease.active or not self._config.get("auto_recall", True) or not client: return "" - entry = self._recall_entry() + entry = self._recall_entry(lease) q = (query or "").strip() if not q: return "" @@ -1618,7 +1651,7 @@ def queue_prefetch(self, query: str, *, session_id: str = "") -> None: if not self._recall_allowed(lease): return client = lease.client - entry = self._recall_entry() + entry = self._recall_entry(lease) def _warm() -> None: try: @@ -1705,10 +1738,10 @@ def _session_digest_recall_results(self) -> int: return 0 return int(self._config.get("prefetch_session_digest_results") or 0) - def _recall_entry(self) -> _cp.EntryState | None: - """The current binding's server entry for the recall's second query, taken with its client; - None while that query is off (no lookup of the entry then).""" - return _cp.entry_state(self._entry_key()) if self._session_digest_recall_results() > 0 else None + def _recall_entry(self, lease: _Lease | None) -> _cp.EntryState | None: + """The server entry of the binding ``lease`` was taken from, for the recall's second query, + taken with its client; None while that query is off (no lookup of the entry then).""" + return _cp.entry_state(self._entry_key_of(lease)) if self._session_digest_recall_results() > 0 else None def _session_digest_sources( self, @@ -2189,7 +2222,7 @@ def _pre_compress( # #299: the chain and the required facts after it write against the process-wide state of # this server entry (its error answers in a row, its booked writes of the window). chain = self._chain(client, lease) - entry = chain.entry = _cp.entry_state(self._entry_key()) + entry = chain.entry = _cp.entry_state(self._entry_key_of(lease)) # P4: select facts BEFORE the chain write so their dedupe keys ride in the head/ # manifest metadata (``fact_hashes``); keys already stored for this root are skipped. @@ -2343,19 +2376,24 @@ def _join_receipt(chain_text: str, facts_text: str) -> str: return f"{chain_text}\n\n{facts_text}" if facts_text else chain_text def _chain(self, client: Any = _CURRENT, lease: Any = _CURRENT) -> ChainWriter: - """The chain writer of ``client`` (default: the current write client, :meth:`_writer_client`), - with the tags and the ``ctx_plugin.access`` provenance of the access group of ``lease`` (the - call's snapshot; default: the binding now).""" + """The chain writer of ``client`` (default: the write client, :meth:`_writer_client`) for the + binding of ``lease`` (the call's snapshot; default: the binding now): the tags and the + ``ctx_plugin.access`` provenance of its access group and the write limit its key reported. The + writer is the call's own; the one kept for the next call is reused only for the same client and + replaced only while ``lease`` is the current binding.""" + if lease is _CURRENT: + lease = self._snapshot() if client is _CURRENT: - client = self._writer_client() - context = self._access_context() if lease is _CURRENT else (lease.context if lease is not None else None) - if self._chain_writer is None or self._chain_writer.client is not client: + client = self._writer_client(lease) + context = lease.context if lease is not None else None + writer = self._chain_writer + if writer is None or writer.client is not client: write_tags = self._write_tags def _tags(base: list[str]) -> list[str]: return write_tags(list(base), "checkpoint", context) - self._chain_writer = ChainWriter( + writer = ChainWriter( client=client, category=self._checkpoint_category(), sensitivity=str(self._config.get("checkpoint_sensitivity") or "personal"), @@ -2369,9 +2407,23 @@ def _tags(base: list[str]) -> list[str]: access=self._access_metadata(context), **self._chain_writer_seams(), ) - # The write limit the writing key's whoami reported (P-G follows it; None: not reported). - self._chain_writer.rate_limit_write = self._rate_limit_write - return self._chain_writer + with self._binding_lock: + if lease is None or self._lease_current(lease): + self._chain_writer = writer + # The write limit the writing key's whoami reported for this binding, and when (P-G follows it; + # None: not reported). + writer.rate_limit_seen_at, writer.rate_limit_write = self._write_limit_of(lease) + return writer + + @staticmethod + def _write_limit_of(lease: _Lease | None) -> tuple[float | None, int | None]: + """(when ctx gave it, the write limit) of the binding ``lease`` was taken from: its group's + (read by the write client's proof) or the profile connection's.""" + if lease is None: + return None, None + if lease.group is not None: + return lease.group.rate_limit_seen_at, lease.group.rate_limit_write + return lease.rate_limit_seen_at, lease.rate_limit_write def _checkpoint_notice(self, message: str) -> None: """A notice of the chain writer while it runs (a paced chain: the compaction waits for @@ -2776,7 +2828,7 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: client = self._writer_client(lease) group = lease.group if lease is not None else None context = lease.context if lease is not None else None - entry = _cp.entry_state(self._entry_key()) + entry = _cp.entry_state(self._entry_key_of(lease)) logger.info( "CTX %s digest scheduled (profile=%s, trigger=%s, root=%s, seg=%d, exchanges=%d)", hook, diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index b75064188..619971e23 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -588,6 +588,115 @@ def test_a_warm_up_queued_under_one_binding_never_queries_through_the_next(world assert provider._prefetch_cache is None +_cp = ah.plugin_module(pc._PKG, "memory.checkpoint") + + +def _writer_barrier(monkeypatch): + """Chain writers whose write limit, set by the provider after it built (and published) one, stops + the first such set on thread ``race-t1``. Returns (arrived, go).""" + import threading + + arrived, go = threading.Event(), threading.Event() + + class _StoppingWriter(_cp.ChainWriter): + @property + def rate_limit_write(self): + return self.__dict__.get("_limit") + + @rate_limit_write.setter + def rate_limit_write(self, value): + again = "_limit" in self.__dict__ # the dataclass __init__ sets it first + self.__dict__["_limit"] = value + if again and threading.current_thread().name == "race-t1" and not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + + monkeypatch.setattr(_prov, "ChainWriter", _StoppingWriter) + return arrived, go + + +def _mods_blocks_with(fake, text: str) -> list[str]: + return [b["title"] for b in fake.blocks.values() if b["scope"] == A_MODS and text in str(b["content"])] + + +def test_a_checkpoint_writes_only_through_the_chain_writer_it_built_for_its_binding(world, monkeypatch): + """The ops checkpoint builds its writer and stops before it returns it; the instance is built again + for group mods, whose checkpoint puts the mods writer in place. The ops transcript must not go + through the mods writer into the mods scope.""" + fake, host, home = world + _add_mods(fake, host) + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _ops(home) + arrived, go = _writer_barrier(monkeypatch) + t1, box = _run(lambda: provider.on_pre_compress(pc._messages(tag="o"), require_checkpoint=False)) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + assert provider.on_pre_compress(pc._messages(tag="m"), require_checkpoint=True), "mods checkpoints" + mods_writer = provider._chain_writer + go.set() + _joined(t1, box) + pc._settle(provider) + assert _mods_blocks_with(fake, "o line") == [], "the ops transcript went into the mods scope" + assert provider._chain_writer is mods_writer, "a stale call never puts its writer in place" + + +def _checkpoint(provider, tag): + return provider.on_pre_compress(pc._messages(tag=tag), require_checkpoint=False) + + +def test_a_checkpoint_reports_its_write_limit_to_its_own_server_entry_only(world, monkeypatch): + """The ops checkpoint (its key reported 40) stops after it built its writer; the instance is built + again for group mods (another key, which reported 10). The ops run must not report its limit to + the mods key's entry, whose windows would then plan 37 writes against a limit of 10.""" + fake, host, home = world + _add_mods(fake, host) + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _ops(home) + _reinit_mods(provider, home) + fake.rate_limit_write = 10 + assert _checkpoint(provider, "m"), "mods checkpoints" + mods_entry = _cp.entry_state(provider._entry_key()) + assert mods_entry.capped(97) == 7 + pc._settle(provider) + provider.initialize( + "s-1", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=pc.OPS_FIELDS), + ) + fake.rate_limit_write = 40 + _nar.reset_proofs() + arrived, go = _writer_barrier(monkeypatch) + t1, box = _run(lambda: _checkpoint(provider, "o")) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + go.set() + _joined(t1, box) + pc._settle(provider) + assert mods_entry.capped(97) == 7, "another key's limit was reported to the mods entry" + + +def test_a_writer_does_not_report_a_limit_older_than_the_one_its_entry_holds(world, monkeypatch): + """Two sessions of one group key: the first proved its write client while the key's limit was 40, + the second after it went down to 10. The first session's next checkpoint must not lift the entry's + plan back to 37 writes a window.""" + fake, _host, home = world + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + fake.rate_limit_write = 40 + first = _ops(home) + assert _checkpoint(first, "a") + entry = _cp.entry_state(first._entry_key()) + assert entry.capped(97) == 37 + fake.rate_limit_write = 10 + _nar.reset_proofs() + second = _ops(home) + assert _checkpoint(second, "b") + assert _cp.entry_state(second._entry_key()) is entry and entry.capped(97) == 7 + assert _checkpoint(first, "c") + assert entry.capped(97) == 7, "a writer reported the older limit 40 over the newer 10" + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From cbb927a3d0772448075fddc3add2f0c5b5fc97d1 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:31:03 +0100 Subject: [PATCH 58/65] fix(ctx_checkpoint): a checkpoint records its outcome and head under the home, session root and binding of the snapshot it ran on, with the receipt it wrote The umbrella took the binding before the checkpoint, but read the home, the session root and the receipt when it recorded the outcome: a re-initialization for another session (or profile home) while the checkpoint ended recorded its head under the new root or in the new home, where the lookup for its own root never finds it; a checkpoint of the next session that ran meanwhile left its receipt on the instance, and the first call recorded that one. Each checkpoint is now a _CheckpointCall: the engine keeps the call's snapshot, the receipt it wrote and its chain error there, and the umbrella records from it (home, root, pointer binding, receipt; without a snapshot the home and root at the call's start). The snapshot carries the session as initialize set it (home, root, session id, platform, agent context, the write gate), and the call takes its chain root and labels, its fact ledger, the receipt's read path and the digests' root and session from it instead of from the instance. Fact ledgers and digest states are kept per home and root. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/__init__.py | 61 +++++--- .../plugin/ctx_checkpoint/memory/provider.py | 143 +++++++++++++----- .../tests/test_access_binding_races.py | 4 +- .../tests/test_access_review_r3.py | 52 +++++++ 4 files changed, 192 insertions(+), 68 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index 2746956f8..59d058f38 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -60,7 +60,7 @@ umbrella_transport, ) from .memory.mcp_client import McpClient, colliding_servers, collision_text, mcp_tool_name -from .memory.provider import CtxMemoryProvider +from .memory.provider import CtxMemoryProvider, _CheckpointCall logger = logging.getLogger(__name__) @@ -968,26 +968,27 @@ def on_pre_compress( forget = getattr(self._client, "forget_host_refusal", None) if callable(forget): forget() - # The head this checkpoint records belongs to the binding it started under, even when the - # instance is built again before it ends: never named to the next binding. - binding = self._pointer_binding() + # The head this checkpoint records belongs to the snapshot it ran on (binding, home, session + # root) and is the one it wrote, even when the instance is built again before it ends. + call = _CheckpointCall(home=self._hermes_home, root=self._checkpoint_root()) try: - receipt_text = super().on_pre_compress( - messages, require_checkpoint=require_checkpoint, tool_evidence=tool_evidence, **kwargs + receipt_text = self._run_checkpoint( + call, messages, require_checkpoint=require_checkpoint, tool_evidence=tool_evidence, **kwargs ) except Exception as exc: - self._record_outcome(bool(require_checkpoint), exc, binding) + self._record_outcome(bool(require_checkpoint), exc, call) raise - self._record_outcome(bool(require_checkpoint), self._last_chain_error, binding) + self._record_outcome(bool(require_checkpoint), call.error, call) return receipt_text - def _record_outcome(self, required: bool, error: Exception | None, binding: str | None = None) -> None: + def _record_outcome(self, required: bool, error: Exception | None, call: Any = None) -> None: """Outcome file + user notice. Never raises: it must not turn a checkpoint into a failure, - nor replace the exception a failed one raises. ``binding``: the pointer binding the - checkpoint started under (default: the binding now).""" + nor replace the exception a failed one raises. ``call``: the checkpoint (its snapshot, the + receipt it wrote; default: what the instance holds now).""" try: - receipt = self._last_chain_receipt - skipped = "" if (error is not None or receipt is not None) else self._skip_reason() + lease = call.lease if call is not None else None + receipt = call.receipt if call is not None else self._last_chain_receipt + skipped = "" if (error is not None or receipt is not None) else self._skip_reason(lease) secrets = self._bound_secrets() if error is not None else () outcome = _st.checkpoint_outcome( required=required, @@ -999,12 +1000,18 @@ def _record_outcome(self, required: bool, error: Exception | None, binding: str ) # The chain's head is kept even when a later step of the same call failed (required # facts): it is durable in ctx and the read entry of this root session. + if lease is not None: + home, root = lease.home, lease.root + elif call is not None: + home, root = call.home, call.root + else: + home, root = self._hermes_home, self._checkpoint_root() _st.record_checkpoint( - self._hermes_home, + home, outcome, - root=self._checkpoint_root(), + root=root, head_id=str(receipt.head_id or "") if receipt is not None else "", - binding=binding if binding is not None else self._pointer_binding(), + binding=self._pointer_binding(lease), ) if outcome["error"]: self._notify_user(_st.failure_warning(outcome, self._server_name())) @@ -1015,8 +1022,10 @@ def _record_outcome(self, required: bool, error: Exception | None, binding: str except Exception: logger.debug("ctx_checkpoint: checkpoint outcome not recorded", exc_info=True) - def _skip_reason(self) -> str: - if not (self._active and self._client): + def _skip_reason(self, lease: Any = None) -> str: + """Why a checkpoint wrote no chain, for the binding of ``lease`` (the call's snapshot; None: + it had none).""" + if lease is None or not (lease.active and lease.client): return "the provider is not connected" if self.pre_compress_checkpoint_api_version < 2: return "checkpoint_mode: off" @@ -1075,17 +1084,19 @@ def system_prompt_block(self) -> str: # -- checkpoint read path (system prompt block, receipt) ----------------------- - def _pointer_binding(self) -> str: + def _pointer_binding(self, lease: Any = None) -> str: """What a recorded head belongs to: transport, ctx server (MCP entry name or REST base URL) and chain category, as a digest. A head written through another binding is not - named — its id would not resolve there, or the search would run in another category.""" - group = self._group + named — its id would not resolve there, or the search would run in another category. + ``lease``: the call's snapshot (None: the binding now).""" + group = lease.group if lease is not None else self._group rest = self.transport == "rest" or group is not None - server = self._base_url if rest else self._server_name() + base_url = lease.base_url if lease is not None else self._base_url + server = base_url if rest else self._server_name() raw = f"{'rest' if rest else self.transport}\0{server}\0{self._checkpoint_category()}" if group is not None: # a group's head is its own: key, platform, server and group context = group.context - key = hashlib.sha256(self._api_key.encode("utf-8")).hexdigest() + key = lease.key_digest if lease is not None else hashlib.sha256(self._api_key.encode("utf-8")).hexdigest() raw += f"\0{key}\0{context.platform}\0{context.scope_id}\0{context.group}" return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] @@ -1109,8 +1120,8 @@ def _read_tools(self) -> _cp.ReadTools: server = self._server_name() return _cp.mcp_read_tools(mcp_tool_name(server, "get"), mcp_tool_name(server, "search")) - def _receipt_read_path(self, head_id: str, root: str) -> str: - if not self._chain_readable(): + def _receipt_read_path(self, head_id: str, root: str, lease: Any = None) -> str: + if not self._chain_readable(lease): return "" return _cp.read_path(self._read_tools(), head_id=head_id, category=self._checkpoint_category()) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 7525fa158..22768d14d 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -244,6 +244,29 @@ class _Lease: key_digest: str = "" rate_limit_write: int | None = None rate_limit_seen_at: float | None = None + # The session the binding serves, as ``initialize`` (and a session switch) set it: the profile + # home, the session and its root, the platform and agent context, and whether facts and digests + # are written in that context. + home: str = "" + root: str = "" + session_id: str = "" + platform: str = "" + agent_context: str = "" + write_enabled: bool = True + + +@dataclass +class _CheckpointCall: + """One pre-compress checkpoint: the snapshot it ran on (None: no binding at its gate), the + receipt of the chain it wrote and why the chain failed, and the home and root at its start (for an + outcome without a snapshot). The outcome is recorded from these, never from what a later call or + a re-initialization left on the instance.""" + + home: str = "" + root: str = "" + lease: _Lease | None = None + receipt: Any = None + error: Exception | None = None def _plain(value: Any) -> Any: @@ -520,9 +543,9 @@ def _host_compaction_wait_s(self) -> float | None: The umbrella reads it through a module function its tests replace.""" return _cp.host_compaction_wait_s() - def _receipt_read_path(self, head_id: str, root: str) -> str: + def _receipt_read_path(self, head_id: str, root: str, lease: Any = None) -> str: """Last line of the chain receipt: how to read the checkpoint (the umbrella names the - tools of the session). Default: none.""" + tools of the session of ``lease``, the call's snapshot). Default: none.""" return "" def _checkpoint_category(self) -> str: @@ -1275,6 +1298,12 @@ def _snapshot(self) -> _Lease | None: key_digest=self._key_digest(), rate_limit_write=self._rate_limit_write, rate_limit_seen_at=self._rate_limit_seen_at, + home=self._hermes_home, + root=self._checkpoint_root(), + session_id=self._session_id, + platform=self._platform, + agent_context=self._agent_context, + write_enabled=self._write_enabled, ) def _lease(self) -> _Lease | None: @@ -2154,10 +2183,25 @@ def on_pre_compress( facts continue, or one for the facts alone) end with this call, whichever way it ends (GottZ/ctx#299): their planned writes never hold the entry's windows after it. """ + call = _CheckpointCall(home=self._hermes_home, root=self._checkpoint_root()) + return self._run_checkpoint( + call, messages, require_checkpoint=require_checkpoint, tool_evidence=tool_evidence, **kwargs + ) + + def _run_checkpoint( + self, + call: _CheckpointCall, + messages: list[dict[str, Any]], + *, + require_checkpoint: bool = False, + tool_evidence: list[dict[str, Any]] | None = None, + **kwargs, + ) -> str: + """:meth:`on_pre_compress` for ``call``, which holds its snapshot, receipt and chain error.""" runs: list[Any] = [] try: return self._pre_compress( - messages, runs, require_checkpoint=require_checkpoint, tool_evidence=tool_evidence, **kwargs + messages, runs, call=call, require_checkpoint=require_checkpoint, tool_evidence=tool_evidence, **kwargs ) finally: for run in runs: @@ -2168,11 +2212,14 @@ def _pre_compress( messages: list[dict[str, Any]], runs: list[Any], *, + call: _CheckpointCall | None = None, require_checkpoint: bool = False, tool_evidence: list[dict[str, Any]] | None = None, **kwargs, ) -> str: - """:meth:`on_pre_compress`; every run it registers at the entry is appended to ``runs``.""" + """:meth:`on_pre_compress`; every run it registers at the entry is appended to ``runs``. The + call works on one snapshot (its session, root and binding), kept in ``call`` with its outcome.""" + call = call if call is not None else _CheckpointCall(home=self._hermes_home, root=self._checkpoint_root()) # P5: the host calls on_session_end right after a compaction (commit_memory_session, # conversation_compression.py:3733) → that digest is the compaction segment digest. self._compaction_pending = True @@ -2194,14 +2241,15 @@ def _pre_compress( api_version = self.pre_compress_checkpoint_api_version # A group binding writes through its write client (``capture``), proven before its first # write; a session the access decision or the trip wire turned off writes nothing. - lease = self._lease() + lease = call.lease = self._lease() client = self._ready_writer(lease) if lease is not None else None connected = bool(lease is not None and lease.active and client) + write_enabled = lease.write_enabled if lease is not None else self._write_enabled # The chain archives evidence in every agent context (labelled, never dropped); # facts stay behind the cron/flush/subagent write gate. chain_set = bool(self._config.get("checkpoint_chain", True)) chain_on = connected and chain_set and api_version >= 2 - facts_on = connected and self._write_enabled and bool(self._config.get("auto_compress_extract", True)) + facts_on = connected and write_enabled and bool(self._config.get("auto_compress_extract", True)) if require_checkpoint and connected and not chain_set: # Facts are not a transcript checkpoint (#289): without the chain no word of the # conversation would be in ctx, so a required checkpoint must not pass on them. @@ -2213,7 +2261,7 @@ def _pre_compress( if not connected else ( "checkpoint_chain disabled and facts write-gated for this agent context" - if not self._write_enabled + if not write_enabled else "checkpoint_chain and auto_compress_extract disabled" ) ) @@ -2231,7 +2279,7 @@ def _pre_compress( new_keys: list[str] | None = None ledger = None if facts_on: - ledger = self._fact_ledger() + ledger = self._fact_ledger(lease) known_keys = ledger.keys() facts = extract_salient_facts( source, @@ -2257,9 +2305,10 @@ def _pre_compress( extra_writes=len(facts) if require_checkpoint else 0, runs=runs, chain=chain, + call=call, ) except CtxCheckpointError as exc: - self._last_chain_error = exc + self._last_chain_error = call.error = exc if require_checkpoint: logger.warning( "CTX checkpoint chain failed (profile=%s, required): %s", self._profile, self._error_text(exc) @@ -2271,7 +2320,7 @@ def _pre_compress( self._error_text(exc), ) except Exception as exc: # defensive: never let an unexpected bug escape best effort - self._last_chain_error = exc + self._last_chain_error = call.error = exc mode = "required" if require_checkpoint else "best_effort" logger.warning( "CTX checkpoint chain crashed (profile=%s, %s): %s", self._profile, mode, self._error_text(exc) @@ -2295,7 +2344,7 @@ def _pre_compress( return chain_text # P4: drop facts the server-side chain head already lists (ledger lost/other host) — except # those whose store failed after the head named them (pending in the ledger, #302). - receipt = self._last_chain_receipt if chain_text else None + receipt = call.receipt if chain_text else None server_known = set(getattr(receipt, "previous_fact_hashes", None) or []) - set(ledger.pending()) dropped_server = 0 if server_known: @@ -2429,12 +2478,14 @@ def _checkpoint_notice(self, message: str) -> None: """A notice of the chain writer while it runs (a paced chain: the compaction waits for it). Logged by the writer; the umbrella passes it on to the user.""" - def _fact_ledger(self) -> FactLedger: - root = self._root_session_id or self._session_id or "unknown" - ledger = self._fact_ledgers.get(root) + def _fact_ledger(self, lease: _Lease | None = None) -> FactLedger: + """The fact ledger of the session root of ``lease`` (the call's snapshot; default: now).""" + home = lease.home if lease is not None else self._hermes_home + root = lease.root if lease is not None else self._checkpoint_root() + ledger = self._fact_ledgers.get((home, root)) if ledger is None: - ledger = FactLedger(self._hermes_home or ".", root) - self._fact_ledgers[root] = ledger + ledger = FactLedger(home or ".", root) + self._fact_ledgers[(home, root)] = ledger return ledger def _write_chain( @@ -2449,19 +2500,22 @@ def _write_chain( extra_writes: int = 0, runs: list[Any] | None = None, chain: ChainWriter | None = None, + call: _CheckpointCall | None = None, ) -> str: """Synchronous chain write; raises ``CtxCheckpointError``. Returns the upstream receipt frame. - A run the chain leaves open for the required facts (``extra_writes``) goes to ``runs``.""" - root = self._checkpoint_root() + A run the chain leaves open for the required facts (``extra_writes``) goes to ``runs``. The + session, root and binding are those of ``call``'s snapshot (default: now), and so is its receipt.""" + lease = call.lease if call is not None else self._snapshot() + root = lease.root if lease is not None else self._checkpoint_root() host_api = self._probe_host_api() - receipt = (chain or self._chain()).write( + receipt = (chain or self._chain(lease=lease)).write( source, host_api=host_api, negotiated_api=self._negotiate(host_api), root_session_id=root, - session_id=self._session_id, - platform=self._platform, - agent_context=self._agent_context, + session_id=lease.session_id if lease is not None else self._session_id, + platform=lease.platform if lease is not None else self._platform, + agent_context=lease.agent_context if lease is not None else self._agent_context, budget_s=budget, deadline=deadline, tool_evidence=tool_evidence, @@ -2475,6 +2529,8 @@ def _write_chain( runs.append(receipt.run) self._last_manifest_by_root[root] = receipt.manifest_id self._last_chain_receipt = receipt + if call is not None: + call.receipt = receipt logger.info( "CTX checkpoint chain stored (profile=%s, root=%s): head=%s manifest=%s parent=%s parts=%d writes=%d " "reused=%d windows=%d sha=%s lookup=%s rate_limited=%d %.2fs", @@ -2492,7 +2548,7 @@ def _write_chain( receipt.rate_limited, receipt.duration_s, ) - return receipt.frame(self._receipt_read_path(receipt.head_id, root) if receipt.head_id else "") + return receipt.frame(self._receipt_read_path(receipt.head_id, root, lease) if receipt.head_id else "") def _checkpoint_facts_sync( self, @@ -2654,18 +2710,20 @@ def _digest_enabled(self, lease: Any = _CURRENT) -> bool: return bool( lease is not None and lease.active - and self._write_enabled + and lease.write_enabled and self._writer_client(lease) and self._config.get("auto_capture", True) and self._config.get("auto_session_digest", True) ) - def _digest_state(self, root: str) -> _dg.DigestState: + def _digest_state(self, root: str, home: str | None = None) -> _dg.DigestState: + """The digest state of ``root`` in ``home`` (default: the profile home now).""" + home = self._hermes_home if home is None else home with self._digest_states_lock: - state = self._digest_states.get(root) + state = self._digest_states.get((home, root)) if state is None: - state = _dg.DigestState(self._hermes_home or ".", root) - self._digest_states[root] = state + state = _dg.DigestState(home or ".", root) + self._digest_states[(home, root)] = state return state def on_session_end(self, messages: list[dict[str, Any]]) -> None: @@ -2691,8 +2749,8 @@ def on_session_end(self, messages: list[dict[str, Any]]) -> None: "CTX session_end digest skipped (profile=%s, trigger=%s): %s", self._profile, trigger, - "writes disabled for agent_context=%s" % (self._agent_context or "?") - if not self._write_enabled + "writes disabled for agent_context=%s" % (lease.agent_context or "?") + if not lease.write_enabled else "auto_capture/auto_session_digest off", ) return @@ -2721,8 +2779,7 @@ def sync_turn( if lease is None or not self._same_binding(first, lease) or not self._digest_enabled(lease) or messages is None: return try: - root = self._root_session_id or self._session_id or "unknown" - state = self._digest_state(root) + state = self._digest_state(lease.root, lease.home) pending = len(state.new_exchanges(messages)) every_n = int(self._config.get("digest_every_exchanges") or 0) every_h = float(self._config.get("digest_every_hours") or 0.0) @@ -2731,16 +2788,18 @@ def sync_turn( every_h > 0 and pending >= min_n and (time.time() - state.since_ts) >= every_h * 3600.0 ): self._digest(messages, "rolling", hook="digest_rolling", lease=lease) - self._arm_idle_timer(messages, lease.generation) + self._arm_idle_timer(messages, lease.generation, lease.root) except Exception as exc: # never break the host worker logger.debug("CTX sync_turn digest check failed: %s", _cp.redacted_traceback(exc, self._bound_secrets())) - def _arm_idle_timer(self, messages: list[dict[str, Any]], generation: int | None = None) -> None: + def _arm_idle_timer( + self, messages: list[dict[str, Any]], generation: int | None = None, root: str | None = None + ) -> None: minutes = float(self._config.get("idle_digest_minutes") or 0.0) if minutes <= 0: return snapshot = list(messages) - root = self._root_session_id or self._session_id or "unknown" + root = root or self._checkpoint_root() with self._idle_lock: if self._idle_timer is not None: self._idle_timer.cancel() @@ -2783,8 +2842,10 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: nothing and releases the exchanges. Returns True when a store was scheduled.""" if lease is _CURRENT: lease = self._snapshot() - root = self._root_session_id or self._session_id or "unknown" - state = self._digest_state(root) + if lease is None: + return False # off: nothing is digested, nothing is claimed + root = lease.root + state = self._digest_state(root, lease.home) min_n = int(self._config.get("digest_min_exchanges") or 4) with state.lock: new = state.new_exchanges(messages) @@ -2806,7 +2867,7 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: now = datetime.now(timezone.utc).strftime("%Y-%m-%d") manifest_id = self._last_manifest_by_root.get(root, "") if trigger == "compaction" else "" digest = ( - f"Session {self._session_id or '?'} · root {root} · segment {segment} · trigger {trigger} " + f"Session {lease.session_id or '?'} · root {root} · segment {segment} · trigger {trigger} " f"(digest {now}, {len(new)} exchanges)\n\n" f"Intent: {shorten(first_user, 400)}\n\n" f"Last request: {shorten(last_user, 400)}\n\n" @@ -2817,7 +2878,7 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: title = f"Session digest {root[-8:]} seg {segment:03d} {now}" metadata: dict[str, Any] = { "root_session_id": root, - "session_id": self._session_id or "", + "session_id": lease.session_id or "", "segment": segment, "trigger": trigger, "exchanges": len(new), @@ -2826,8 +2887,8 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: metadata["manifest_id"] = manifest_id sensitivity = self._config.get("sensitivity_default") client = self._writer_client(lease) - group = lease.group if lease is not None else None - context = lease.context if lease is not None else None + group = lease.group + context = lease.context entry = _cp.entry_state(self._entry_key_of(lease)) logger.info( "CTX %s digest scheduled (profile=%s, trigger=%s, root=%s, seg=%d, exchanges=%d)", diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py index 13309d8c8..ac1724b24 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py @@ -324,11 +324,11 @@ def test_an_idle_digest_writes_only_through_the_binding_it_was_armed_under(world arrived, go = threading.Event(), threading.Event() real = provider._digest_state - def digest_state(root): + def digest_state(root, *home): if not arrived.is_set(): arrived.set() assert go.wait(WAIT_S) - return real(root) + return real(root, *home) provider._digest_state = digest_state t1, box = _run(lambda: provider._on_idle(*timer.args)) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 619971e23..ca36b159f 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -697,6 +697,58 @@ def test_a_writer_does_not_report_a_limit_older_than_the_one_its_entry_holds(wor assert entry.capped(97) == 7, "a writer reported the older limit 40 over the newer 10" +_st = ah.plugin_module(pc._PKG, "memory.status") + + +def _outcome_barrier(monkeypatch): + """Stop the first outcome a checkpoint records, before it is written. Returns (arrived, go).""" + import threading + + arrived, go = threading.Event(), threading.Event() + real = _st.checkpoint_outcome + + def checkpoint_outcome(**kwargs): + if threading.current_thread().name == "race-t1" and not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + return real(**kwargs) + + monkeypatch.setattr(_st, "checkpoint_outcome", checkpoint_outcome) + return arrived, go + + +@pytest.mark.parametrize("change", ["root", "home"]) +def test_a_checkpoint_records_its_head_under_its_own_root_and_home(world, monkeypatch, tmp_path, change): + """The ops checkpoint of session s-1 has written its head and stops before it records it; the + instance is built again for session s-2 (``root``) or in another profile home (``home``), and that + session checkpoints too. The first head is recorded under s-1 in the first home, the receipt the + first call wrote, never the second call's.""" + _fake, _host, home = world + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _ops(home) + binding = provider._pointer_binding() + arrived, go = _outcome_barrier(monkeypatch) + t1, box = _run(lambda: provider.on_pre_compress(pc._messages(tag="o"), require_checkpoint=True)) + assert arrived.wait(WAIT_S) + other = home if change == "root" else tmp_path / "profiles" / "other" + other.mkdir(parents=True, exist_ok=True) + provider.initialize( + "s-2", + hermes_home=str(other), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=pc.OPS_FIELDS), + ) + assert provider._active, provider._access_off + second = provider.on_pre_compress(pc._messages(tag="n"), require_checkpoint=True).split("`")[1] + go.set() + first = _joined(t1, box).split("`")[1] + assert first != second + assert _st.known_head(str(home), "s-1", binding=binding) == first, _st.read_state(str(home)).get("heads") + heads = _st.read_state(str(other)).get("heads") or {} + assert {root: entry["head_id"] for root, entry in heads.items()}.get("s-2") == second, heads + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From f7f01aa9cba3071c014fa3066e96b2d208b3966e Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:35:14 +0100 Subject: [PATCH 59/65] fix(ctx_checkpoint): provision keeps a lost answer's proof through a failed repeat, and names what a fresh review found unclear A fresh review of the fixes above found five smaller gaps, each with a test that was red before: - A rotation whose answer was lost leaves its key proven by the note alone; a repeat whose set ctx then refused dropped the note, and the next repeat refused the key. A key only the note proved is now recorded for the group before the set is sent. - Hermes' .env writer can raise errors of its own (a home it cannot set up); after the key was made at ctx that ended in a traceback. It now ends like any failed line, with the note kept. - A group that follows a gone one in the same variable was told to give itself a profile of its own; the message now names the key and says to deactivate it and remove the line if that group is gone. - A key the record could not be written for is named, since a later --replace cannot tie it to the group. - An existing .env that others can read keeps its mode (Hermes' rule); the command now warns. The README names the window in which replace_label still deactivates a key made by hand on another machine. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 8 +-- .../ctx_checkpoint/memory/access_cli.py | 46 ++++++++++++---- .../tests/test_access_seam_provision_env.py | 19 ++++++- .../test_access_seam_provision_identity.py | 54 +++++++++++++++++++ 4 files changed, 112 insertions(+), 15 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 124d78742..1a6510652 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -601,8 +601,8 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co key as one line `CTX_KEY_<server>_<PROFILE>=…` into the profile's `.env` through Hermes' own `.env` writer (`save_env_value`: under Hermes' `.env` lock, so a variable Hermes saves meanwhile is neither lost nor overwrites the line; every other line kept; a new file gets mode 0600 outside a container, an - existing one keeps its mode; a variable that a later line sets again is named and the run counts as - stopped), sets `memory.ctx_checkpoint.ungoverned: local` (an `off` stays), and prints the `/policy field` + existing one keeps its mode and the command warns when others can read it; a variable that a later + line sets again is named and the run counts as stopped), sets `memory.ctx_checkpoint.ungoverned: local` (an `off` stays), and prints the `/policy field` line for an existing group and the `/policy group` line for a new one; `--emit-yaml` adds the whole group entry with its fields for `gateway.access_groups` (one write, so the group never exists without its fields). A `--read` scope must already be a scope of the tenant, named `<name>` or @@ -646,7 +646,9 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co its tenant lock: of two first runs at the same moment one gets the key and the other the refusal. Two rotations of a label no active key carries send no `replace_label` and are decided the same way. Still open across machines: a key of the label the other machine made within those 5 minutes of - a run here whose answer was lost is taken for that run's key when the run is repeated here. Sessions bound with an earlier + a run here whose answer was lost is taken for that run's key when the run is repeated here; and + `replace_label` deactivates every active key of the label when ctx commits, so a key made by hand on + another machine between a rotation's check and its set is deactivated as well. Sessions bound with an earlier key lose ctx until their agent is rebuilt; raising `ctx_checkpoint.base_rev` of the group rebuilds them at once. Refused before any request: a server id or group name no scope or variable name can hold, a `--profile` other than the profile the command diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 1319e7a17..57c8052b4 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -33,6 +33,7 @@ import json import os import re +import stat import time import urllib.error import urllib.request @@ -1051,6 +1052,13 @@ def _provision_locked( # --replace: the keys the check proved this group's, which replace_label deactivates (none found: no # replace_label, so a key made since by anyone is ctx's 409, not deactivated); else the stopped run's replace_label, stopped_keys = (bool(found), []) if args.replace else (False, found) + identity = {"label": label, "platform": platform, "server": scope_id, "group": group, "variable": variable} + if replace_label: # a key only the stopped run's note proved (its answer was lost): recorded before the set, + recorded = _made_keys(home) # so a set that fails now does not lose the proof with the note + for key_id in found: + if key_id not in recorded: + with contextlib.suppress(OSError): + _record_key(home, key_id, {**identity, "digest": ""}, last=False) for key_id in stopped_keys: # the key a stopped run of this home made, by id (never the label's others) retire = {"action": "api-key-update", "data": {"id": key_id, "active": False}} try: @@ -1128,14 +1136,13 @@ def _provision_locked( ) return 1 secret, _slug, scopes = made - record = {"label": label, "platform": platform, "server": scope_id, "group": group, "variable": variable} - record["digest"] = narrowing.key_digest(secret) + record = {**identity, "digest": narrowing.key_digest(secret)} if isinstance(key_id, str) and key_id: # before the line: a stopped run's key is tied to its group too with contextlib.suppress(OSError): _record_key(home, key_id, record, last=False) try: _write_env_line(home, variable, secret) - except (OSError, ValueError) as exc: + except Exception as exc: # Hermes' writer: OSError, ValueError, or its own (a home it cannot set up) cause = _status.redact_error(exc, (secret, admin_key)) print( f" ✗ the key was created at ctx but {env_path} could not be written ({type(exc).__name__}: {cause}); " @@ -1147,6 +1154,15 @@ def _provision_locked( if isinstance(key_id, str) and key_id: with contextlib.suppress(OSError): _record_key(home, key_id, record, last=True) + if not (isinstance(key_id, str) and key_id in _made_keys(home)): + print( + f" ⚠ {FACT_STATE_DIR}/{KEYS_FILE} does not record this key: a later --replace of this group cannot tie " + "it to the group and is refused (the way by hand still works)" + ) + with contextlib.suppress(OSError): + mode = stat.S_IMODE(env_path.stat().st_mode) + if mode & 0o077: + print(f" ⚠ {env_path} is readable beyond its owner (mode {mode:o}; Hermes keeps an existing file's mode)") for entry in scopes: print(f" ctx scope {entry.get('scope')} ({'created' if entry.get('created') else 'there already'})") print( @@ -1266,11 +1282,13 @@ def _key_conflict( f"{target} (_ and - give the same scope name): give this group another name" ), [] owner = _env_owner(made, variable, env_value) - if owner is not None and not _of_group(owner, group): + if owner is not None and not _of_group(owner[1], group): return ( - f"{variable} in the profile's .env holds the key of group {owner.get('group')} of " - f"{owner.get('platform')}:{owner.get('server')} ({owner.get('label')}): the variable names the server id " - f"and the profile, not the platform or the group, so give this group a profile of its own" + f"{variable} in the profile's .env holds the key {owner[0]} of group {owner[1].get('group')} of " + f"{owner[1].get('platform')}:{owner[1].get('server')} ({owner[1].get('label')}): the variable names the " + f"server id and the profile, not the platform or the group, so give this group a profile of its own; " + f"if group {owner[1].get('group')} is gone, deactivate that key (ctx manage api-key-update with its id " + f"and active=false) and remove {variable} from the profile's .env first" ), [] ours = stopped is not None and stopped.get("group") == group[2] # a stopped run of this very group if replace: @@ -1325,13 +1343,19 @@ def _key_conflict( return "", [str(key.get("id") or "") for key in held] -def _env_owner(made: Mapping[str, Mapping[str, str]], variable: str, value: str) -> Mapping[str, str] | None: - """The record of the key *variable* holds in the ``.env`` (by the key's digest; ``None``: none, or no - value): which binding owns the variable.""" +def _env_owner( + made: Mapping[str, Mapping[str, str]], variable: str, value: str +) -> tuple[str, Mapping[str, str]] | None: + """The id and record of the key *variable* holds in the ``.env`` (by the key's digest; ``None``: none, + or no value): which binding owns the variable.""" if not value: return None digest = narrowing.key_digest(value) - found = [entry for entry in made.values() if entry.get("variable") == variable and entry.get("digest") == digest] + found = [ + (key_id, entry) + for key_id, entry in made.items() + if entry.get("variable") == variable and entry.get("digest") == digest + ] return found[0] if found else None diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py index a1dae6b7d..8eeb21e77 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py @@ -104,7 +104,7 @@ def replace(*args, **kwargs): assert values.get(VAR) == key.secret and values.get("FIRST") == "1" -def test_a_new_env_is_0600_and_an_existing_one_keeps_its_lines_and_mode(ctx, tmp_path): +def test_a_new_env_is_0600_and_an_existing_one_keeps_its_lines_and_mode(ctx, tmp_path, capsys): home = _home(tmp_path) assert _provision(home) == 0 if not hermes_constants._container_or_chmod_skipped(): # Hermes' rule: no chmod inside a container @@ -119,6 +119,7 @@ def test_a_new_env_is_0600_and_an_existing_one_keeps_its_lines_and_mode(ctx, tmp text = (other / ".env").read_text(encoding="utf-8") assert text == f"FOO=bar\n# a comment\nexport OTHER='x y'\n{VAR}={key.secret}\n" assert stat.S_IMODE((other / ".env").stat().st_mode) == 0o640, "Hermes' writer keeps an existing file's mode" + assert "readable beyond its owner (mode 640" in capsys.readouterr().out def test_a_variable_set_twice_in_the_env_is_named_and_the_run_can_be_repeated(ctx, tmp_path, capsys): @@ -149,3 +150,19 @@ def pinned(key, action): out = capsys.readouterr().out assert rc == 1 and "managed by your administrator" in out and "nothing was sent" in out, out assert ctx.count() == 0 and not (home / ".env").exists() + + +def test_an_error_of_hermes_writer_of_its_own_counts_as_a_stopped_run(ctx, tmp_path, monkeypatch, capsys): + """Hermes' writer may raise its own errors (a home it cannot set up): the key exists at ctx, so the run + must end like any failed line, with its note, not with a traceback.""" + + def broken(name, value): + raise RuntimeError("the home cannot be set up") + + monkeypatch.setattr(hermes_config, "save_env_value", broken) + home = _home(tmp_path) + assert _provision(home) == 1 + out = capsys.readouterr().out + assert "RuntimeError" in out and "again" in out, out + (made,) = _active(ctx) + assert cli._stopped_runs(str(home))[LABEL].get("id") == made.id diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py index 80877adf2..726747872 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py @@ -217,3 +217,57 @@ def test_a_key_set_by_hand_over_this_group_s_line_is_not_taken_for_its_own(ctx, assert _provision(home, "members", "--replace") == 1 assert "no record" in capsys.readouterr().out assert len(_sets(ctx)) == 1 and _env(home) == f"{VAR}=ctx_key_set_by_hand_0123456789\n" + + +# -- a fresh review of the above ------------------------------------------------------------------ + + +def test_a_rotation_whose_answer_was_lost_and_whose_repeat_ctx_refused_is_repeated_again(ctx, tmp_path, monkeypatch): + """The rotation's key is proven by the note alone (its answer was lost); the repeat's set is refused + (nothing made, the note goes). The proof must survive for the next repeat.""" + home = _home(tmp_path) + assert _provision(home, "members") == 0 + real = cli._manage_once + + def lost(url, key, payload): + answer = real(url, key, payload) + if payload.get("action") == "keyset-provision": + raise cli._client.CtxApiError("connection error: reset by peer") + return answer + + def refused(url, key, payload): + if payload.get("action") == "keyset-provision": + raise cli._client.CtxApiError("HTTP 429: tenant key quota exceeded", status=429) + return real(url, key, payload) + + monkeypatch.setattr(cli, "_manage_once", lost) + assert _provision(home, "members", "--replace") == 1 + monkeypatch.setattr(cli, "_manage_once", refused) + assert _provision(home, "members", "--replace") == 1 + monkeypatch.setattr(cli, "_manage_once", real) + assert _provision(home, "members", "--replace") == 0 + (active,) = _active(ctx) + assert _env(home) == f"{VAR}={active.secret}\n" + + +def test_a_group_that_follows_a_gone_one_is_told_to_remove_its_line(ctx, tmp_path, capsys): + home = _home(tmp_path) + assert _provision(home, "members") == 0 + (gone,) = _active(ctx) + gone.active = False # the group is gone: its key deactivated by hand + capsys.readouterr() + assert _provision(home, "users", "--replace") == 1 + out = capsys.readouterr().out + assert "if group members is gone" in out and f"remove {VAR}" in out and gone.id in out, out + (home / ".env").write_text("", encoding="utf-8") + assert _provision(home, "users") == 0 + + +def test_a_key_the_record_misses_is_named(ctx, tmp_path, monkeypatch, capsys): + def unwritable(*args, **kwargs): + raise OSError("read-only file system") + + monkeypatch.setattr(cli, "_record_key", unwritable) + home = _home(tmp_path) + assert _provision(home, "members") == 0 + assert f"{cli.KEYS_FILE} does not record this key" in capsys.readouterr().out From 0b2d58aa4d335b1dcb38c0db7466df598ff07402 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:35:51 +0100 Subject: [PATCH 60/65] fix(ctx_checkpoint): the manifest cache and the tags of a tool store follow the binding of the call's snapshot Two more readings of the binding after the call's gate, found in a sweep of provider.py for the same form: - The process manifest cache bridges a missing server head on the same binding only. A chain that ended after a re-initialization for another binding put its manifest into the cache the new binding had just emptied, and the new binding's first chain, whose head search found none, took it as its parent. The cache is now kept and read only for a call whose snapshot's binding identity is the one the cache belongs to (_verified_binding, set under the binding lock). - ctx_store tagged its block with the access group of the binding now, not of the snapshot its client came from: a store through the profile connection that passed its gate before a re-initialization for a group carried that group's server:/group: tags. The provider now hands the tool its client together with the snapshot's access context (_tool_binding), and the store is tagged with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/provider.py | 61 ++++++++++++----- .../plugin/ctx_checkpoint/memory/tools.py | 37 +++++++---- .../tests/test_access_review_r3.py | 66 +++++++++++++++++++ 3 files changed, 132 insertions(+), 32 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 22768d14d..44b4c1c7b 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -253,6 +253,8 @@ class _Lease: platform: str = "" agent_context: str = "" write_enabled: bool = True + # The binding identity (``_binding_identity``) the manifest cache is kept and read for. + identity: tuple[str, ...] = () @dataclass @@ -805,11 +807,27 @@ def _note_verified_binding(self, previous_binding: tuple[str, ...] | None) -> No from another profile, backend, key or access group must never become a parent. Only verified bindings count: a failed re-init (inactive, no writes) keeps the cache for a later retry on the same binding.""" - if self._active: - binding = self._binding_identity() - if binding != previous_binding: - self._last_manifest_by_root = {} - self._verified_binding = binding + with self._binding_lock: # a call keeps or reads the cache only for its own binding + if self._active: + binding = self._binding_identity() + if binding != previous_binding: + self._last_manifest_by_root = {} + self._verified_binding = binding + + def _cached_manifest(self, lease: _Lease | None, root: str) -> str | None: + """The manifest this process last wrote for ``root``, for a call whose snapshot is of the binding + the cache belongs to (``_verified_binding``); None for any other (None: the binding now).""" + with self._binding_lock: + if lease is not None and lease.identity != self._verified_binding: + return None + return self._last_manifest_by_root.get(root) + + def _keep_manifest(self, lease: _Lease | None, root: str, manifest_id: str) -> None: + """Keep ``manifest_id`` for ``root`` while the call's binding is the one the cache belongs to: a + chain that ends after a re-initialization for another binding never becomes its parent.""" + with self._binding_lock: + if lease is None or lease.identity == self._verified_binding: + self._last_manifest_by_root[root] = manifest_id def _binding_identity(self) -> tuple[str, ...]: """Profile home, backend, credential, whoami identity and access group (platform, server, @@ -1304,6 +1322,7 @@ def _snapshot(self) -> _Lease | None: platform=self._platform, agent_context=self._agent_context, write_enabled=self._write_enabled, + identity=self._binding_identity(), ) def _lease(self) -> _Lease | None: @@ -1416,26 +1435,32 @@ def _no_writer_reason(self, lease: Any = _CURRENT) -> str: return f"{NO_BINDING} (the write client is not proven yet)" def _tool_client(self, tool_name: str) -> tuple[Any, str]: + """The client an agent tool goes through, or None and why not (:meth:`_tool_binding`).""" + client, refusal, _context = self._tool_binding(tool_name) + return client, refusal + + def _tool_binding(self, tool_name: str) -> tuple[Any, str, Any]: """The client an agent tool goes through, or None and why not (``""``: the provider is not - active), from the one snapshot the gate took: the profile's one client; a group's read client - for the read tools and its store client, once proven, for ``ctx_store`` (unrestricted groups - only). A group's client sends only while its binding is current.""" + active), and the access context its writes are tagged with, all from the one snapshot the + gate took: the profile's one client; a group's read client for the read tools and its store + client, once proven, for ``ctx_store`` (unrestricted groups only). A group's client sends only + while its binding is current.""" lease = self._lease() if lease is None: - return None, f"CTX is off for this session ({NO_BINDING})" + return None, f"CTX is off for this session ({NO_BINDING})", None if not lease.active: - return None, "" + return None, "", None group = lease.group if group is None: - return lease.client, "" + return lease.client, "", lease.context if tool_name == STORE_TOOL: client = group.store_client if client is not None and self._client_proven("store", client, group): - return client, "" - return None, f"CTX tool {STORE_TOOL} is not available for this access group" + return client, "", lease.context + return None, f"CTX tool {STORE_TOOL} is not available for this access group", None if tool_name in READ_TOOLS and lease.client is not None: - return lease.client, "" - return None, f"CTX tool {tool_name} is not available for this access group" + return lease.client, "", lease.context + return None, f"CTX tool {tool_name} is not available for this access group", None def _offered_tools(self, lease: Any = _CURRENT) -> tuple[str, ...] | None: """The agent tools a group binding offers (``None``: the profile's connection, all of them).""" @@ -2519,7 +2544,7 @@ def _write_chain( budget_s=budget, deadline=deadline, tool_evidence=tool_evidence, - cached_manifest_id=self._last_manifest_by_root.get(root), + cached_manifest_id=self._cached_manifest(lease, root), fact_hashes=fact_hashes, wait_limit=wait_limit, host_wait_s=host_wait_s, @@ -2527,7 +2552,7 @@ def _write_chain( ) if runs is not None and getattr(receipt, "run", None) is not None: runs.append(receipt.run) - self._last_manifest_by_root[root] = receipt.manifest_id + self._keep_manifest(lease, root, receipt.manifest_id) self._last_chain_receipt = receipt if call is not None: call.receipt = receipt @@ -2865,7 +2890,7 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: last_user = next((str(m["content"]) for m in reversed(new) if m.get("role") == "user"), "") last_assistant = next((str(m["content"]) for m in reversed(new) if m.get("role") == "assistant"), "") now = datetime.now(timezone.utc).strftime("%Y-%m-%d") - manifest_id = self._last_manifest_by_root.get(root, "") if trigger == "compaction" else "" + manifest_id = (self._cached_manifest(lease, root) or "") if trigger == "compaction" else "" digest = ( f"Session {lease.session_id or '?'} · root {root} · segment {segment} · trigger {trigger} " f"(digest {now}, {len(new)} exchanges)\n\n" diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/tools.py b/integrations/hermes/plugin/ctx_checkpoint/memory/tools.py index 05f9f4d81..688a9cfdc 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/tools.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/tools.py @@ -199,22 +199,31 @@ def _safe(provider, text: Any) -> str: return redact_error_text(text, _bound_secrets(provider)) -def _tool_client(provider, tool_name: str) -> tuple[Any, str]: - """The client the tool goes through and, without one, why not (``""``: not active). The - provider picks it (``_tool_client``: a group binding reads through its read client and stores - through its store client); a provider without that pick has its one client.""" - pick = getattr(provider, "_tool_client", None) +# A provider that names no access context for its tool client: its writes take the provider's tags now. +_TAGS_NOW: Any = object() + + +def _tool_client(provider, tool_name: str) -> tuple[Any, str, Any]: + """The client the tool goes through and, without one, why not (``""``: not active), and the access + context of the snapshot the client came from (its writes are tagged with it). The provider picks + them (``_tool_binding``: a group binding reads through its read client and stores through its store + client; ``_tool_client`` without a context); a provider without that pick has its one client.""" + pick = getattr(provider, "_tool_binding", None) if callable(pick): return pick(tool_name) - return (provider._client, "") if provider._active and provider._client else (None, "") + pick = getattr(provider, "_tool_client", None) + if callable(pick): + return (*pick(tool_name), _TAGS_NOW) + client = provider._client if provider._active and provider._client else None + return client, "", _TAGS_NOW -def _write_tags(provider, agent_tags: Any, hook: str) -> list[str]: - """The tags of a write: the provider's (with the access group's ``server:``/``group:``) or the - origin tags alone.""" +def _write_tags(provider, agent_tags: Any, hook: str, context: Any = _TAGS_NOW) -> list[str]: + """The tags of a write: the provider's (with the ``server:``/``group:`` of ``context``, the access + group of the call's snapshot) or the origin tags alone.""" tags_of = getattr(provider, "_write_tags", None) if callable(tags_of): - return tags_of(agent_tags, hook) + return tags_of(agent_tags, hook) if context is _TAGS_NOW else tags_of(agent_tags, hook, context) return merge_tags(agent_tags, getattr(provider, "_profile", "default"), hook) @@ -222,14 +231,14 @@ def handle_tool_call(provider, tool_name: str, args: dict[str, Any], **kwargs) - """Dispatch a tool call on behalf of the provider instance. Every error text in the result and in the log is redacted (:func:`_safe`); a DEBUG line carries the redacted traceback instead of ``exc_info``, whose rendering would chain the raw texts.""" - client, refusal = _tool_client(provider, tool_name) + client, refusal, context = _tool_client(provider, tool_name) if client is None: return tool_error(refusal or "CTX provider is not active (check CTX_BASE_URL/CTX_KEY and server reachability)") try: if tool_name == "ctx_query": return _tool_query(provider, client, args) if tool_name == "ctx_store": - return _tool_store(provider, client, args) + return _tool_store(provider, client, args, context) if tool_name == "ctx_search": return _tool_search(provider, client, args) if tool_name == "ctx_get": @@ -321,7 +330,7 @@ def _tool_query(provider, client, args: dict[str, Any]) -> str: return json.dumps(result, ensure_ascii=False) -def _tool_store(provider, client, args: dict[str, Any]) -> str: +def _tool_store(provider, client, args: dict[str, Any], context: Any = _TAGS_NOW) -> str: category = str(args.get("category") or "").strip() title = str(args.get("title") or "").strip() content = str(args.get("content") or "").strip() @@ -362,7 +371,7 @@ def _tool_store(provider, client, args: dict[str, Any]) -> str: title, content, sensitivity=sensitivity or provider._config.get("sensitivity_default"), - tags=_write_tags(provider, args.get("tags"), "tool"), + tags=_write_tags(provider, args.get("tags"), "tool", context), **extra, ) if not data.get("success"): diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index ca36b159f..83929af57 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -749,6 +749,72 @@ def test_a_checkpoint_records_its_head_under_its_own_root_and_home(world, monkey assert {root: entry["head_id"] for root, entry in heads.items()}.get("s-2") == second, heads +# -- the sweep: the manifest cache belongs to one binding ----------------------------------------- + + +def test_a_chain_written_under_one_binding_is_never_the_cached_parent_of_the_next(world, monkeypatch): + """The ops chain is written and stops before the instance keeps its manifest in the process cache; + the instance is built again for group mods in the same session (the cache is emptied: another + binding). The ops manifest must not land in the cache the mods binding then reads: the first mods + chain, whose head search finds none, would take it as its parent.""" + import threading + + fake, host, home = world + _add_mods(fake, host) + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _ops(home) + written, go = threading.Event(), threading.Event() + ops: list = [] + + class _PausingWriter(_cp.ChainWriter): + def write(self, *args, **kwargs): + receipt = super().write(*args, **kwargs) + if threading.current_thread().name == "race-t1" and not written.is_set(): + ops.append(receipt.manifest_id) + written.set() + assert go.wait(WAIT_S) + return receipt + + monkeypatch.setattr(_prov, "ChainWriter", _PausingWriter) + t1, box = _run(lambda: _checkpoint(provider, "o")) + assert written.wait(WAIT_S) + ops_manifest = ops[0] + _reinit_mods(provider, home, fields={**MODS_FIELDS, "read": [pc.B_K, A_MODS]}) + go.set() + _joined(t1, box) + assert ops_manifest not in provider._last_manifest_by_root.values(), provider._last_manifest_by_root + assert _checkpoint(provider, "m") + receipt = provider._last_chain_receipt + assert receipt.parent_manifest_id != ops_manifest and receipt.lookup != "cache", receipt + + +def test_a_tool_store_carries_the_tags_of_the_binding_its_client_came_from(world, monkeypatch): + """A ``ctx_store`` on the profile connection passes its gate; the instance is built again for + group ops. The profile client stores as 0.19.1 did, but the block must not carry the ops group's + ``server:``/``group:`` tags (the plugin's provenance of a group write).""" + fake, _host, home = world + provider = pc._provider(home, platform="cli", **ah.v5_kwargs()) + assert provider._decision.kind == "profile" and provider._group is None + arrived, go = _gate_barrier(monkeypatch) + args = {"category": "c", "title": "profile note", "content": "x"} + t1, box = _run(lambda: provider.handle_tool_call("ctx_store", args)) + assert arrived.wait(WAIT_S) + _ops(home) # warm the proof store: the instance below binds ops at once + provider.initialize( + "s-1", + hermes_home=str(home), + platform="discord", + agent_context="primary", + **ah.v5_kwargs(scope_id="111", group="ops", group_restricted=False, fields=pc.OPS_FIELDS), + ) + assert provider._active and provider._group is not None + go.set() + _joined(t1, box) + stored = [b for b in fake.blocks.values() if b["title"] == "profile note"] + assert stored and stored[0]["scope"] == "t:main", stored + assert not [t for t in stored[0]["tags"] if t.startswith(("server:", "group:"))], stored[0]["tags"] + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From d86632abfa685c6367b9c153254f97c4bdf36fa1 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:40:02 +0100 Subject: [PATCH 61/65] fix(ctx_checkpoint): a session end is a compaction segment only for the binding whose compaction ran on_pre_compress set an instance flag that the next on_session_end consumed to name its digest the compaction segment. A re-initialization in between handed the flag to the next binding: its own session end was stored as a compaction segment, with the trigger compaction. The flag now holds the binding generation the compaction ran under, and on_session_end names the digest a compaction segment only for its snapshot of that generation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../plugin/ctx_checkpoint/memory/provider.py | 10 ++++++---- .../tests/test_access_review_r3.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 44b4c1c7b..ac07204ed 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -449,7 +449,9 @@ def __init__(self): # P5 digests per segment (compaction / rolling / idle / end) self._digest_states: dict[str, _dg.DigestState] = {} self._digest_states_lock = threading.Lock() - self._compaction_pending = False + # The binding generation a compaction ran under, until the session end Hermes calls after it + # (None: none pending); a session end of another binding is no compaction segment. + self._compaction_pending: int | None = None self._idle_timer: threading.Timer | None = None self._idle_lock = threading.Lock() # Counted up by every initialize: an idle timer armed under one binding never digests through @@ -2247,7 +2249,7 @@ def _pre_compress( call = call if call is not None else _CheckpointCall(home=self._hermes_home, root=self._checkpoint_root()) # P5: the host calls on_session_end right after a compaction (commit_memory_session, # conversation_compression.py:3733) → that digest is the compaction segment digest. - self._compaction_pending = True + self._compaction_pending = self._binding_generation # Outcome of THIS call only: an early return below must not leave the previous receipt. self._last_chain_receipt = None self._last_chain_error = None @@ -2762,12 +2764,12 @@ def on_session_end(self, messages: list[dict[str, Any]]) -> None: Heuristic, not an LLM summary: /api/query synthesizes over stored blocks, it does not accept a document to summarize. """ - trigger = "compaction" if self._compaction_pending else "end" - self._compaction_pending = False + pending, self._compaction_pending = self._compaction_pending, None self._cancel_idle_timer() lease = self._lease() if lease is None: return + trigger = "compaction" if pending is not None and pending == lease.generation else "end" if not self._digest_enabled(lease): if lease.active: logger.info( diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 83929af57..302d904ba 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -815,6 +815,22 @@ def test_a_tool_store_carries_the_tags_of_the_binding_its_client_came_from(world assert not [t for t in stored[0]["tags"] if t.startswith(("server:", "group:"))], stored[0]["tags"] +def test_a_compaction_of_one_binding_never_names_the_next_bindings_session_end_a_compaction(world, monkeypatch): + """The ops session compacts; the instance is built again for group mods before Hermes ends that + session. The mods session's end digest is no compaction segment of the ops chain.""" + fake, host, home = world + _add_mods(fake, host) + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + provider = _ops(home) + assert _checkpoint(provider, "o") + _reinit_mods(provider, home, session="s-2") + provider.on_session_end(pc._messages(12, tag="mm")) + pc._settle(provider) + digests = [b for b in fake.blocks.values() if b["scope"] == A_MODS and "mm line" in str(b["content"])] + assert digests, "the mods session's end digest is stored" + assert [d["metadata"].get("trigger") for d in digests] == ["end"], [d["metadata"] for d in digests] + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From 89f72383fb3ab6415b349dc5bc0812e266feb970 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:40:44 +0100 Subject: [PATCH 62/65] docs(ctx_checkpoint): E2 names both whoami answers, and the write limit of the latest answer holds for every chain of the key README (rule E2, the write limit) and CHANGELOG (0.20.0, the write limit) for two fixes of this round: a restricted proof needs scope_narrowing required in the narrowed and the unnarrowed answer, and a writer that keeps the limit of an older whoami answer never lifts the plan of the key's entry above the limit of a newer one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- integrations/hermes/plugin/ctx_checkpoint/README.md | 9 ++++++--- .../hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index 29fcb7b76..e2dec57fc 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -434,7 +434,7 @@ What fails is named with the value it expected (`access status`, `access check`) | Rule | Holds when | For | |---|---|---| | E1 | the fields above are set and well formed; `write` not in `read`; `key` is `CTX_KEY_<server id>_…` | restricted | -| E2 | the key's tenant is `tenant`; it is no ctx server admin, its role is `member`, and it requires narrowing (`scope_narrowing: required`) | restricted (tenant: every group that sets it) | +| E2 | the key's tenant is `tenant`; it is no ctx server admin, its role is `member`, and it requires narrowing (`scope_narrowing: required`, in the narrowed and the unnarrowed answer) | restricted (tenant: every group that sets it) | | E3 | `write` is the key's home scope; the key writes exactly `write`, reads exactly `read` plus `write` (an incoming tenant grant fails this) and does not stage its writes (`confirm_writes`) | restricted; for an unrestricted group the write client checks the home scope before its first write, and ctx refuses a `read` outside the key | | E4 | the key's label is `hermes:<platform>:<server id>:<profile>` (a profile name that makes it longer than 100 characters is replaced by `#` and 16 hex digits of its SHA-256) | restricted | | E5 | the narrowed `whoami` reports exactly the narrowing sent, and every answer echoes it | every group | @@ -683,8 +683,11 @@ ok as well (`access_unreadable`). Without access groups the report is as before. checkpoint chain plans its writes per minute below the write limit its key's `whoami` reports (`rate_limit_write`, ctx 5.95.0 or later), keeping 3 writes of the window for other writes of the key: the window shrinks when the limit minus 3 is below what the chain plans (`max_parts` + 2, so below 85 -with the default 80); `0` is no limit, and a server without the field leaves the window as in 0.19.1. ctx keys that limit by the key's home scope: a group key gets a lower limit through a -settings write with a tenant-admin key of the group's home scope, or ctx's global setting. +with the default 80); `0` is no limit, and a server without the field leaves the window as in 0.19.1. +Every chain of the key in the process plans below the limit of the latest `whoami` answer any of them +saw (a session bound before a change keeps no older limit). ctx keys that limit by the key's home +scope: a group key gets a lower limit through a settings write with a tenant-admin key of the group's +home scope, or ctx's global setting. ### What this does not promise diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index df15fc4c3..a5299c1ab 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -51,7 +51,8 @@ older server a group binding is off and the profile's own connection works as be `base_cache_entries`); `base_rev` reloads. - **The chain follows the write limit** of its key (`whoami.rate_limit_write`, minus 3 writes for the key's other writes; `0` is no limit) for every chain of the key in the process, on REST connections - and group bindings (the MCP transport reads no `whoami`). + and group bindings (the MCP transport reads no `whoami`); the latest answer holds, an older one a + writer still keeps never lifts it. - **Operator tools and status** (`access_cli.py`, `status.py`): `hermes ctx_checkpoint access status | check | provision | reset-marker`; a status file per binding (`ctx_state/access/`) with the outcome of its base blocks and the write or store client ctx refused (`bound; write client off: …`); From 7c308dbbefbc1266d0ec30b6ee58c2c049e828b3 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:41:56 +0100 Subject: [PATCH 63/65] test(ctx_checkpoint): the ops run's own entry gets its limit, a remembered proof answer keeps its time, and a stale recall leaves the indicator alone Three tests that pin parts of the fixes before them, each killed by its mutant: the chain of a replaced binding reports its own key's limit to its own entry; a write client proof that takes the proof store's remembered answer reports the time of that answer, so it does not lift a newer, lower limit; a prefetch of a replaced binding does not reset the recall indicator of the current one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../tests/test_access_review_r3.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 302d904ba..202195daa 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -675,6 +675,8 @@ def test_a_checkpoint_reports_its_write_limit_to_its_own_server_entry_only(world _joined(t1, box) pc._settle(provider) assert mods_entry.capped(97) == 7, "another key's limit was reported to the mods entry" + ops_entry = _cp.entry_state(("rest", fake.url, _sha(pc.OPS_A_KEY))) + assert ops_entry is not mods_entry and ops_entry.capped(97) == 37, "the ops run reports the ops key's limit" def test_a_writer_does_not_report_a_limit_older_than_the_one_its_entry_holds(world, monkeypatch): @@ -831,6 +833,47 @@ def test_a_compaction_of_one_binding_never_names_the_next_bindings_session_end_a assert [d["metadata"].get("trigger") for d in digests] == ["end"], [d["metadata"] for d in digests] +def _sha(key: str) -> str: + import hashlib + + return hashlib.sha256(key.encode("utf-8")).hexdigest() + + +def test_a_remembered_proof_answer_keeps_the_time_of_its_request_for_the_write_limit(world, monkeypatch): + """A second session's write client proof takes the answer the proof store remembers from the + first session's (limit 40); another writer of the key has seen 10 since. The remembered answer is + older than that, so it must not lift the entry's plan.""" + import time + + fake, _host, home = world + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + fake.rate_limit_write = 40 + first = _ops(home) + assert _checkpoint(first, "a") + entry = _cp.entry_state(first._entry_key()) + assert entry.capped(97) == 37 + entry.report_write_limit(10, time.monotonic()) # another writer of the key saw 10 since + second = _ops(home) + assert _checkpoint(second, "b") + assert entry.capped(97) == 7, "the remembered answer of 40 counted as a new one" + + +def test_a_recall_of_a_replaced_binding_leaves_the_recall_indicator_of_the_current_one(world, monkeypatch): + fake, host, home = world + _add_mods(fake, host) + provider = _ops(home) + arrived, go = _gate_barrier(monkeypatch) + t1, box = _run(lambda: provider.prefetch("plans?")) + assert arrived.wait(WAIT_S) + _reinit_mods(provider, home) + assert "bravo knowledge" in provider.prefetch("plans?") + shown = provider.recall_status() + assert shown is not None and shown.count >= 1 + go.set() + assert _joined(t1, box) == "" + assert provider.recall_status() == shown, "the ops call reset the mods turn's recall indicator" + + def ah_home(): """The serving profile's home the base-block hook reads (``get_hermes_home``: the test's HERMES_HOME).""" import os From 687707d6648d9b76c0832dcd90638e4017ef328d Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 12:47:15 +0100 Subject: [PATCH 64/65] test(ctx_checkpoint): a profile checkpoint across a re-initialization keeps its writer and limit, and the outcome test stops before the outcome is recorded The profile connection's client writes on after a re-initialization (as in 0.19.1); a new test pins that its chain plans with its own key's limit on its own entry and that its writer never replaces the one the new binding keeps. The outcome test now stops the first checkpoint before _record_outcome reads anything, so it also covers the receipt the call wrote; the limit-order test paces on a fake clock instead of waiting a real rate window. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../tests/test_access_review_r3.py | 46 ++++++++++++++++--- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py index 202195daa..3ee8b04a3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -685,6 +685,13 @@ def test_a_writer_does_not_report_a_limit_older_than_the_one_its_entry_holds(wor plan back to 37 writes a window.""" fake, _host, home = world monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + clock = [1000.0] # the chains' pacing clock: a wait for the next rate window passes at once + + def sleep(seconds): + clock[0] += seconds + + monkeypatch.setattr(pc._PKG, "_monotonic", lambda: clock[0]) + monkeypatch.setattr(pc._PKG, "_sleep", sleep) fake.rate_limit_write = 40 first = _ops(home) assert _checkpoint(first, "a") @@ -702,20 +709,21 @@ def test_a_writer_does_not_report_a_limit_older_than_the_one_its_entry_holds(wor _st = ah.plugin_module(pc._PKG, "memory.status") -def _outcome_barrier(monkeypatch): - """Stop the first outcome a checkpoint records, before it is written. Returns (arrived, go).""" +def _outcome_barrier(provider): + """Stop thread ``race-t1``'s checkpoint after it ended and before it records its outcome (the + umbrella's ``_record_outcome``). Returns (arrived, go).""" import threading arrived, go = threading.Event(), threading.Event() - real = _st.checkpoint_outcome + real = provider._record_outcome - def checkpoint_outcome(**kwargs): + def record_outcome(*args, **kwargs): if threading.current_thread().name == "race-t1" and not arrived.is_set(): arrived.set() assert go.wait(WAIT_S) - return real(**kwargs) + return real(*args, **kwargs) - monkeypatch.setattr(_st, "checkpoint_outcome", checkpoint_outcome) + provider._record_outcome = record_outcome return arrived, go @@ -729,7 +737,7 @@ def test_a_checkpoint_records_its_head_under_its_own_root_and_home(world, monkey monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) provider = _ops(home) binding = provider._pointer_binding() - arrived, go = _outcome_barrier(monkeypatch) + arrived, go = _outcome_barrier(provider) t1, box = _run(lambda: provider.on_pre_compress(pc._messages(tag="o"), require_checkpoint=True)) assert arrived.wait(WAIT_S) other = home if change == "root" else tmp_path / "profiles" / "other" @@ -833,6 +841,30 @@ def test_a_compaction_of_one_binding_never_names_the_next_bindings_session_end_a assert [d["metadata"].get("trigger") for d in digests] == ["end"], [d["metadata"] for d in digests] +def test_a_checkpoint_of_a_replaced_profile_connection_keeps_its_own_writer_and_limit(world, monkeypatch): + """A checkpoint on the profile connection (its key reported 40) passes its gate; the instance is + built again for group mods, which checkpoints. The profile client writes on as in 0.19.1, with its + own key's limit on its own entry, and its writer never replaces the one the mods binding keeps.""" + fake, host, home = world + _add_mods(fake, host) + monkeypatch.setattr(pc._PKG, "_host_compaction_wait_s", lambda: None, raising=False) + fake.rate_limit_write = 40 + provider = pc._provider(home, platform="cli", **ah.v5_kwargs()) + assert provider._decision.kind == "profile" and provider._group is None + arrived, go = _gate_barrier(monkeypatch) + t1, box = _run(lambda: _checkpoint(provider, "p")) + assert arrived.wait(WAIT_S) + fake.rate_limit_write = 10 # what the mods key's write client proof reads + _reinit_mods(provider, home) + assert _checkpoint(provider, "m") + mods_writer = provider._chain_writer + go.set() + _joined(t1, box) + assert provider._chain_writer is mods_writer, "a call of the replaced binding put its writer in place" + profile_entry = _cp.entry_state(("rest", fake.url, _sha(pc.PROFILE_KEY))) + assert profile_entry.capped(97) == 37, "the profile chain planned without its key's limit" + + def _sha(key: str) -> str: import hashlib From 73dbbb6ba14b2288f85fafe58e15aba19233a7d9 Mon Sep 17 00:00:00 2001 From: Jan-Stefan Janetzky <git@gottz.de> Date: Sun, 6 Dec 2026 13:02:03 +0100 Subject: [PATCH 65/65] fix(ctx_checkpoint): access check leaves the key's home scope out of a group's implicit read set, and the cut-off note names the base-block cache window access check took the read set of a group without read as the key's read set without the group's write scope only; for a key homed in one scope and a group that names write: <another scope> it narrowed its proof to the home scope as well, unlike the provider since d2489e17. It now leaves out the home scope and the write scope, and a test pins the narrowed whoami of such a check. The cut-off note that access status and access provision print, and the README, no longer promise an immediate cut: a base-block text already rendered stays in the hook's cache until base_cache_s expires. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../hermes/plugin/ctx_checkpoint/README.md | 5 +++-- .../ctx_checkpoint/memory/access_cli.py | 9 ++++++--- .../tests/test_access_pe_rules.py | 20 +++++++++++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/integrations/hermes/plugin/ctx_checkpoint/README.md b/integrations/hermes/plugin/ctx_checkpoint/README.md index ecf1a1717..3c9dd9f3a 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -579,8 +579,9 @@ takes `-p`/`--profile` before the plugin sees it). The plugin never reads the co expected; tenant, read and write scopes, the key's digest (never the key), the time of the last change; per group whether the base-block hook delivered its text and, if not, why; the markers `restricted_seen` and `governed_seen`; messaging sessions without an access group that ran on the - profile's own connection; and the way to cut a group off at once (deactivate its key with `ctx manage - api-key-update` and `active=false`; ctx checks the key on every request, without a cache). A status + profile's own connection; and the way to cut a group off (deactivate its key with `ctx manage + api-key-update` and `active=false`; ctx checks the key on every request, without a cache; a base-block + text already rendered stays in the hook's cache until it expires, `base_cache_s`). A status file of a group you removed stays until you delete it. - - `access check --server <platform>:<id> --group <name> [--profile <p>] [--restricted | --unrestricted] --field <name>=<value> …` — proves a group's fields the way the provider binds them diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py index 57c8052b4..3e11420dc 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -105,8 +105,9 @@ _STANDARD_KEYS = ("CTX_KEY", "CTX_API_KEY") _BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz" _REVOKE = ( - "To cut a group off at once: deactivate its key (ctx manage api-key-update with active=false); ctx checks the " - "key on every request, without a cache." + "To cut a group off: deactivate its key (ctx manage api-key-update with active=false); ctx checks the key on " + "every request, without a cache. A base-block text already rendered stays in the hook's cache until it " + "expires (base_cache_s)." ) @@ -536,7 +537,9 @@ def _prove( home_scope = unnarrowed.get("home_scope") write = write or (home_scope if isinstance(home_scope, str) else "") known = unnarrowed.get("read_scopes") - read = read or tuple(str(s) for s in (known if isinstance(known, list) else ()) if s != write) + read = read or tuple( + str(s) for s in (known if isinstance(known, list) else ()) if s not in (home_scope, write) + ) if not read or len(read) > access.READ_MAX: print(f" ✗ read: expected 1 to {access.READ_MAX} scopes; the key reads {len(read)} besides {write}") return 1, {"unnarrowed": unnarrowed} diff --git a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py index edca3492a..1f3309906 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -429,6 +429,26 @@ def test_check_of_an_unrestricted_group_in_an_open_profile_warns_of_no_standard_ assert "⚠" not in capsys.readouterr().out +def test_check_of_a_group_without_read_never_narrows_to_the_keys_home_scope(fake_ctx, monkeypatch, tmp_path, capsys): + """The provider's rule (test_access_review_r3): a group without ``read`` reads the key's read set + without its home scope and without the group's write scope, also when ``write`` names another scope + than the home. ``check`` proves the same read set: its narrowed ``whoami`` names neither.""" + write = "t:d111-ops" + fake_ctx.add_key(secret=PROFILE_KEY, tenant="t", home="t:private", allowed=(write, A_K)) + ah.install(monkeypatch, v8=True, secrets={"CTX_BASE_URL": fake_ctx.url, "CTX_KEY_111_OPS": PROFILE_KEY}) + home = _home(tmp_path, "ops") + (home / ".env").write_text(f"CTX_KEY_111_OPS={PROFILE_KEY}\n", encoding="utf-8") + nar.reset_proofs() + argv = ["--server", "discord:111", "--profile", "ops", "--group", "ops", "--unrestricted"] + fields = ["--field", "key=CTX_KEY_111_OPS", "--field", f"write={write}", "--field", "capture=false"] + assert _run(home, "check", *argv, *fields) == 1 # E3: the write scope is not the key's home + narrowed = [row.read_header for row in fake_ctx.requests("/api/whoami") if row.read_header is not None] + assert narrowed == [A_K], narrowed + out = capsys.readouterr().out + assert "✗ E3: expected home scope t:d111-ops" in out, out + assert "✗ read" not in out and PROFILE_KEY not in out + + # -- access provision -------------------------------------------------------------------------------------