Repository navigation
feat(ctx_checkpoint): 0.20.0 — an access group reaches ctx only through its own, proven binding, and base blocks reach a group as its prompt #596
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: root
Are you sure you want to change the base?
Changes from all commits
e636103
e8df54f
4ee3407
a1b60e5
d6eea04
0e6d4e9
17a89c1
1245eed
6eb675a
987341e
0e2e384
0f165f2
7d04ccb
392a84e
5ae9ffe
61c0f61
d2b9406
51ee275
7cf8808
c2724c4
8627a10
3080ab1
ea4434d
0f89e7f
709a332
6463dca
7711460
5fc7db5
96a49ac
a76856f
b87a10f
c561a29
157e426
36eaa87
efefef3
fba2ac7
60943c4
69eb951
154e6a3
b9f2f13
da331a3
1e7a61d
b84fcb3
35ff2a3
d526ce6
caab3c2
0fe190d
5ebeb9f
236d10e
631f0e9
cd4d75e
071e62a
edab0bf
ff53a0a
099db02
9b31cfb
d2489e1
8d14048
db51146
124c4f4
9b6c462
e26bbeb
684d935
1fc7d25
906a1c2
d938a3f
cbb927a
f7f01aa
0b2d58a
d86632a
89f7238
7c308db
687707d
9f7e114
52369b5
73dbbb6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| 0.19.1 | ||
| 0.20.0 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -47,6 +47,8 @@ | |
| from typing import Any | ||
|
|
||
| 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 | ||
|
|
@@ -58,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__) | ||
|
|
||
|
|
@@ -804,17 +806,20 @@ 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 | ||
| (``tools/mcp_tool_registration.py`` ``_connection_identity``: then the two share one breaker | ||
| 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": | ||
| return super()._entry_key() | ||
| 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. ``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) | ||
|
|
@@ -829,8 +834,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() | ||
|
|
@@ -854,6 +863,11 @@ def _connect(self) -> None: | |
| "on" if self.memory_enabled else "off", | ||
| ) | ||
|
|
||
| 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 | ||
| and Hermes registered the tool (the entry's tool filter), else None.""" | ||
|
|
@@ -869,6 +883,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 | ||
|
|
||
|
|
@@ -951,22 +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 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) | ||
| self._record_outcome(bool(require_checkpoint), exc, call) | ||
| raise | ||
| self._record_outcome(bool(require_checkpoint), self._last_chain_error) | ||
| self._record_outcome(bool(require_checkpoint), call.error, call) | ||
| return receipt_text | ||
|
|
||
| def _record_outcome(self, required: bool, error: Exception | 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.""" | ||
| 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 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do not let an older checkpoint replace the latest known head. If A writes H1 and pauses before recording, B can write and record H2 for the same root and binding. When A resumes, its call-local receipt correctly supplies H1, but Keep the call-local receipt. Also carry head publication order into the status update and reject older head updates under the status lock. Preserve independent records for distinct roots.
|
||
| 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, | ||
|
|
@@ -978,12 +1000,18 @@ def _record_outcome(self, required: bool, error: Exception | None) -> None: | |
| ) | ||
| # 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=self._pointer_binding(), | ||
| binding=self._pointer_binding(lease), | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Record the category the checkpoint used. If a checkpoint writes to
|
||
| ) | ||
| if outcome["error"]: | ||
| self._notify_user(_st.failure_warning(outcome, self._server_name())) | ||
|
|
@@ -994,8 +1022,10 @@ def _record_outcome(self, required: bool, error: Exception | None) -> None: | |
| 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" | ||
|
|
@@ -1021,9 +1051,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 ------------------------------------------------------ | ||
|
|
||
|
|
@@ -1034,29 +1065,49 @@ 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.""" | ||
| 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() | ||
| 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) ----------------------- | ||
|
|
||
| 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.""" | ||
| server = self._base_url if self.transport == "rest" else self._server_name() | ||
| raw = f"{self.transport}\0{server}\0{self._checkpoint_category()}" | ||
| 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 | ||
| 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 = 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] | ||
|
|
||
| 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). ``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: | ||
| """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 | ||
|
|
@@ -1069,7 +1120,9 @@ 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: | ||
| 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()) | ||
|
|
||
| def _checkpoint_pointer(self) -> str: | ||
|
|
@@ -1369,9 +1422,26 @@ 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) | ||
| # 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: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This comment is about line 828, outside the diff; it is anchored on the nearest change, line 821.
Use the checkpoint's OAuth profile when selecting entry state.
If an OAuth MCP checkpoint takes a lease in profile A and then pauses before entry lookup, reinitialization for profile B changes
self._hermes_home. The checkpoint still holds A's client, but this return value selects B's entry when the profiles use the same named connection. A's calls can consume B's write slots or update B's error counters. Capture the MCP entry identity with the client, including the OAuth profile home, and use that identity when a lease is supplied.