diff --git a/README.md b/README.md index 53c93776..01dc7be8 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 526a92e3..b0267a4f 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 7bccde4a..3c9dd9f3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/README.md +++ b/integrations/hermes/plugin/ctx_checkpoint/README.md @@ -21,7 +21,9 @@ Compaction checkpoint head ← 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:`, `hook:` | — | +| Provenance | every write is tagged `source:hermes`, `profile:`, `hook:`; a session of an access group adds `server::` and `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,378 @@ 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 ctx_checkpoint.=`) 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__<…>` 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 (`:`, 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 (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; 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` | + +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::` and `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__…` | 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`, 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:::` (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.` 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, 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. A session of a governed group +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. + +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) +### +<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. 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, 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 + 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`, 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 (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 + (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 + 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` 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 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 + `<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. `--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 + 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). 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`, 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 — 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. + 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; 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 + 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 (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` get the same scope name (refused within one command, and across +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 +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`: + +- `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`), 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 +ok as well (`access_unreadable`). Without access groups the report is as before. + +**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. +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 + +- **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, 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 + 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. +- **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 +913,13 @@ 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` (`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 extracted facts, the digests and what the model stores explicitly. Tool @@ -587,8 +967,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 +984,19 @@ 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/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), + `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. - **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 +1004,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 +1057,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 41915c79..5a03fb73 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/__init__.py b/integrations/hermes/plugin/ctx_checkpoint/__init__.py index b5c638dc..59d058f3 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/__init__.py +++ b/integrations/hermes/plugin/ctx_checkpoint/__init__.py @@ -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,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 @@ -812,9 +814,12 @@ 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": - 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 + 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), ) 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: diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md index 0fecb6cc..a4db2424 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/CHANGELOG.md @@ -6,6 +6,122 @@ 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`. 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 + 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 + 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, on REST connections + 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: …`); + `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, 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`, 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; 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`, 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. +- 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 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** 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 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), 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. 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 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 653ded35..16622bc4 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/access.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py new file mode 100644 index 00000000..52364620 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access.py @@ -0,0 +1,1197 @@ +"""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 +(``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, +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 + +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 FACT_STATE_DIR, MARKERS_FILE_NAME, 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" + +# 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). +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( + { + "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": 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 + } +) +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]: + 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_<server id>_<...>. 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 (<slug>:<name>, 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``). ``""``/``()`` 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 + 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 (``<home>/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 (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 + context: AccessContext | None = None + fields: GroupFields | None = None + 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`` 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: + """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``.""" + 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 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 + ``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`` 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 (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`` 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; a file that + cannot be read, does not parse, or holds anything but ``false`` for a marker counts as that + marker set.""" + 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, + ) + + +_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 False, None + except OSError: + return True, _UNREADABLE + try: + return True, json.loads(raw.decode("utf-8")) if len(raw) <= _MARKERS_MAX_BYTES else None + except (UnicodeDecodeError, ValueError): + return True, None + + +@contextmanager +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 (``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: + 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 + finally: + _PROCESS_MARKERS_LOCK.release() + + +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, 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; 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``). 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) + _write_markers( + path, + Markers( + restricted_seen=current.restricted_seen or "restricted_seen" in wanted, + governed_seen=current.governed_seen or "governed_seen" in wanted, + ), + ) + except Exception: + 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``, 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) + 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: + """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 + 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 seen_markers(init_kwargs: Mapping[str, Any], decision: Decision) -> dict[str, bool]: + """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.""" + 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 + 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 + + +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( + 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, no + 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``). + + 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", + "GroupFields", + "Markers", + "access_supported", + "context_from_init", + "current_access", + "decide", + "e7_inputs", + "fork_parent_platform", + "is_strict", + "load_settings", + "markers_held", + "markers_on_disk", + "parse_fields", + "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/memory/access_cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py new file mode 100644 index 00000000..3e11420d --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/access_cli.py @@ -0,0 +1,1508 @@ +"""``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, 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`` — 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 +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 (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: ``_`` +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 stat +import time +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 + +from . import access, narrowing +from . import client as _client +from . import config as _config +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. +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_]+)$") +# 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. 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 +# 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, "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 +# 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 = ( + "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)." +) + + +# -- 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.""" + 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*: ``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") + 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") + 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 (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 _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): + raise _Usage(f"{option} takes numeric ids, comma-separated") + return items + + +def _secret(name: str) -> str: + """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: + value = "" + 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: + 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": "✗"}.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 = [ + 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)}") + 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) + 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) + 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}") + 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.""" + 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 = 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, {} + 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 = secrets.get(fields.key, "").strip() + if not key: + 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) + 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 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} + 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 _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: + 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): + """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 _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).""" + 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(), "group": note.get("group") or group} + runs[label]["id"] = key_id + elif sent: + 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): + 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]: + """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 = _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: + 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) + _own_profile_only(args, home, "provision") + 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 + 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 + 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 " + "groups is within reach of its tools; keep it in the shell's environment for this command only" + ) + 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 + 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 + 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: + 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, found = _key_conflict( + url, + admin_key, + slug=slug, + label=label, + own=own, + variable=variable, + 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") + 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 + # --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: + 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") + 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, 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") + 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": replace_label, # a first run or a repeat deactivates no key of the label + } + ], + }, + } + 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: + 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) + 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)}, 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}") + 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 " + "--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 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") + 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( + 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 + 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 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}); " + "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 + _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) + 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( + f" key: {variable} in {env_path} (label {label}, key digest {narrowing.key_digest(secret)})" + + ("; 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; " + f"/policy field {group} server={scope_id} {access.NAMESPACE}.base_rev=<n+1> rebuilds them at once" + ) + rc = _ungoverned_local(home) + print(f" {_REVOKE}") + _print_fields(platform, scope_id, profile, group, fields, roles, users, emit_yaml=args.emit_yaml) + 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 _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, + 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 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).""" + 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" + ), [] + 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" + ), [] + owner = _env_owner(made, variable, env_value) + if owner is not None and not _of_group(owner[1], group): + return ( + 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: + 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( + 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 "", [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 " + 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 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": + 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 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 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 _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 = [ + (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 + + +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}" + + +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: 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" + 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" + 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)] + + +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") + _own_profile_only(args, home, "reset-marker") + _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", + "add_arguments", + "key_env_name", + "run_access", + "run_parsed", + "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 00000000..f7077838 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/base_blocks.py @@ -0,0 +1,864 @@ +"""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, 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 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``); 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 + 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 + +import asyncio +import concurrent.futures +import contextvars +import hashlib +import itertools +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 . 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 + +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 (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. +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 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", "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 + + +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 + + +@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 + restricted: bool | None = None # the group's restriction as the core told it (None: not told) + + +@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, 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, 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 +# 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 +# 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 +# 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] = {} + + +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, 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, number) + _CACHE.move_to_end(plan.key) + while len(_CACHE) > _CACHE_LIMIT: + _CACHE.popitem(last=False) + return True + + +def reset_state() -> None: + """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() + _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, *, 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, 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) -> 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 _not_delivered(request: _Request, reason: str) -> None: + _report(request, {"state": f"not delivered: {reason}"}) + + +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"): + # 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 ""), + 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: 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) + 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", + context.group, + context.platform, + context.scope_id, + parsed.field, + parsed.reason, + ) + 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)") + return None + return _Request( + context.platform, context.scope_id, context.group, str(profile or ""), strict, parsed, context.restricted + ) + + +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: 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 = {} + config = config if isinstance(config, Mapping) else {} + try: + return _config.profile_base_url(home, umbrella_section(dict(config)), config.get("mcp_servers")) + except Exception: + raise BaseBlocksUnavailable("the serving profile's secrets cannot be read in this scope") from None + + +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: 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 + + +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 _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``. 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 + 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: + 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: + 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.""" + 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, + ) + _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, ...] = () + 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, + ) + _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 + 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, + ) + _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))) + 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,)), + ) + 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), + 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), + ) + _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 "") + 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, 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: + 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. + 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)}) + else: + _report(request, {"state": "not delivered: none of the base blocks could be had", "skipped": skipped}) + 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. 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 + 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() + number = next(_FETCHES) + _INFLIGHT[plan.key] = (own, deadline, number) + if joined is not None: + return joined + try: + text = _fetch(plan, deadline, request, number) + 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, + 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"]``). 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 + try: + 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"}, 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 + + +# -- rendering ------------------------------------------------------------------------------------------------- + + +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__ = [ + "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 07c38b0f..59855c42 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" @@ -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. @@ -102,6 +106,29 @@ # 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, 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 # looks at its deadline again (EntryState.admit: the answer in flight decides whether it may go). ENTRY_WAIT_POLL_S = 0.05 @@ -559,8 +586,10 @@ 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). +# ``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. @@ -982,6 +1011,37 @@ 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. With it, + # when the server gave that answer (time.monotonic()). + self._write_limit: int | None = None + 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).""" + 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 @@ -1099,6 +1159,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)) @@ -1211,6 +1272,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) @@ -1593,8 +1655,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 @@ -1616,9 +1679,20 @@ 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) + # 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; 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: @@ -1628,8 +1702,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 -- @@ -2135,9 +2210,14 @@ 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 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, 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( deadline=deadline, @@ -2357,6 +2437,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/cli.py b/integrations/hermes/plugin/ctx_checkpoint/memory/cli.py index 76c02a17..74ba1bdd 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/client.py b/integrations/hermes/plugin/ctx_checkpoint/memory/client.py index 450ef0cd..ba6e0efc 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 @@ -33,13 +39,17 @@ import urllib.error import urllib.parse import urllib.request +from collections.abc import Callable, Mapping, Sequence from typing import Any +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", @@ -47,6 +57,9 @@ "invalid_sensitivity", "invalid_encoding", "scope_denied", + "scope_narrowing_invalid", + "scope_narrowing_route", + "scope_narrowing_required", "size_cap", "unknown_type", "reserved_type", @@ -77,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): @@ -261,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]``. @@ -360,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 "" @@ -378,7 +426,12 @@ def __init__( api_key: str, 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. @@ -393,9 +446,39 @@ def __init__( self._key = api_key self._timeout = timeout self._synthesis_timeout = synthesis_timeout + # 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 + self._before_send = before_send # 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: @@ -426,16 +509,29 @@ 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; 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) + 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 @@ -447,8 +543,19 @@ 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: 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) @@ -509,8 +616,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, @@ -632,3 +741,57 @@ 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, 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/config.py b/integrations/hermes/plugin/ctx_checkpoint/memory/config.py index 780fe36b..e12f85b8 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__) @@ -125,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. @@ -342,6 +350,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 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 {} + 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 + 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): @@ -379,8 +411,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 @@ -808,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 9b599bb0..e54db852 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/memory/narrowing.py b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py new file mode 100644 index 00000000..751ff760 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/narrowing.py @@ -0,0 +1,420 @@ +"""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 (BP-21). +""" + +from __future__ import annotations + +import copy +import hashlib +import threading +import time +from collections.abc import Iterable, 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 +# 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) +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. 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). + ``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 + 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 +# 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* (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. 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: + 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) + 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() + break + if fresh: + if proof.failure is not None: + message, status, code = proof.failure + raise CtxApiError(message, status=status, code=code) + 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 + try: + 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, 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: + # 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 + 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) + asking.set() + + +def reset_proofs() -> 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`` 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 + 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") + # 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: + 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__ = [ + "HEADER_NARROWED", + "HEADER_READ_SCOPES", + "HEADER_WRITE_SCOPE", + "LABEL_MAX", + "PROOF_TTL_FAILED_S", + "PROOF_TTL_OK_S", + "Expect", + "Narrowing", + "VerifyResult", + "answered_at", + "evaluate", + "expected_label", + "key_digest", + "reset_proofs", + "whoami_raw", +] diff --git a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py index 492fa261..ac07204e 100644 --- a/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py +++ b/integrations/hermes/plugin/ctx_checkpoint/memory/provider.py @@ -21,21 +21,28 @@ 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 config as _cfg 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 +137,193 @@ 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" +# 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; 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") + + 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 +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) + 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) + + +@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; + ``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 + client: Any + context: Any + active: bool + base_url: str + 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 + # 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 + # The binding identity (``_binding_identity``) the manifest cache is kept and read for. + identity: tuple[str, ...] = () + + +@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: + """``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. 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 + + +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) 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) else None + class _PacedFactStore: """The client the required facts are stored through (GottZ/ctx#299, point 5): each store goes @@ -210,7 +404,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 @@ -226,7 +421,25 @@ 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 = "" + # ``_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._binding_lock = threading.RLock() + # The write limit per 60 s the ctx server reports for the writing key (whoami + # ``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. @@ -236,9 +449,14 @@ 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 + # 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 -------------------------------------------- @@ -329,9 +547,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: @@ -343,19 +561,36 @@ def _checkpoint_root(self) -> str: session switch of a compaction).""" return self._root_session_id or self._session_id or "unknown" + 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.""" + 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 + self._rate_limit_seen_at = None + def _connect(self) -> None: - """Bind credentials and the client; sets ``_active``/``_client``. Default: REST.""" + """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._remember_secrets() - self._active = False - self._client = None - self._chain_writer = None - self._api_key = "" - self._base_url = "" - self._home_scope = "" - self._whoami_label = "" + 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 +611,8 @@ 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) + self._rate_limit_seen_at = time.monotonic() logger.info( "CTX memory provider connected (scope=%s, label=%s, profile=%s)", self._home_scope or "?", @@ -391,7 +628,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 @@ -436,7 +692,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: @@ -451,9 +726,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) @@ -474,13 +749,22 @@ 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 ------------------------------------------------------------ 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. + 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() # 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,35 +798,711 @@ 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. - 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. + 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.""" + 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, + 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 _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) --------------------------------------------- + + 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.fork_parent_platform(init), + settings, + markers, + _access.access_supported(), + ) + 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, 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, busy lock or" + " unreadable ctx_state)", + 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) + self._access_settings = settings + self._decision = decision + if decision.context is None: # display only (``access status``, ``access check``) + 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 = "" + 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, 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`` + 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, group: _GroupBinding) -> Any: + """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, 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 + 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 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) + 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 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 + group.store = "" if group.strict else (group.fields_store or write) + 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), group) if group.capture else None + ) + group.store_client = ( + self._group_client(_narrowing.Narrowing(read=(group.store,), write=group.store), group) + 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 (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) + + def left() -> float: + return max(0.0, deadline - self._now()) + + 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 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 + ) + 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 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: + 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, 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._note_write_limit(group, own[1]) + 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.""" + 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, + 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) + 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 + :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 _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 + + @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 + 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; 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 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 + 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 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( + "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]) + 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, 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()}) + 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 + 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._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 + 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>`` + (``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 _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, + 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, + identity=self._binding_identity(), + ) + + 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) != 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", lease) + return None + return lease + + 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. ``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 or (lease is not None and not self._lease_current(lease)): + 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, lease: Any = _CURRENT) -> bool: + """Recall before a turn: always on the profile's connection, a group only with ``recall``.""" + 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, 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 = lease.group + if group is None: + return lease.client + if "group" not in group.proven or "write" in group.refused: + return None + return group.write_client + + 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.""" + 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, 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).""" + 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: + 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 (: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), 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})", None + if not lease.active: + return None, "", None + group = lease.group + if group is None: + 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, "", 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, "", 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).""" + 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 () + 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, 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 (``context``: of the call's snapshot, default the binding now), + ``server:<platform>:<server>`` and ``group:<group>``.""" + tags = merge_tags(agent_tags, self._profile, hook) + 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, context: Any = _CURRENT) -> dict[str, str] | None: + """``ctx_plugin.access`` of the chain: where it was written from (provenance, no rights).""" + if context is _CURRENT: + 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._lease() def _invalidate_prefetch(self) -> None: """Drop the pre-warmed recall and orphan warm-ups still in flight.""" @@ -607,9 +1567,17 @@ 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() + lease = self._lease() + if lease is None: + return [] + offered = self._offered_tools(lease) + schemas = _schemas() + 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 @@ -619,11 +1587,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: + lease = self._lease() + if lease is None or not lease.active: return "" + offered = self._offered_tools(lease) + if offered is not None: + 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.", @@ -631,6 +1604,30 @@ def system_prompt_block(self) -> str: ] return "\n".join(lines) + 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 = lease.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(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) + ".", + ] + 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: @@ -639,29 +1636,46 @@ 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 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() + self._note_recall(0, 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() + entry = self._recall_entry(lease) q = (query or "").strip() if not q: 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: @@ -669,30 +1683,40 @@ 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).""" - if not self._active or not self._config.get("auto_recall", True) or not self._client: + """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`).""" + first = self._lease() + if first is None: return + self._retry_group_proof() 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: + # ``_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 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 - entry = self._recall_entry() + client = lease.client + entry = self._recall_entry(lease) 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)) @@ -770,10 +1794,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, @@ -955,10 +1979,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( @@ -974,6 +2007,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. @@ -988,7 +2022,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, access_context) extra: dict[str, Any] = {} if metadata: extra["metadata"] = metadata @@ -1107,13 +2141,18 @@ 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. """ + lease = self._lease() + if lease is None: + return + 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) - or not self._client + or not client ): return content = (content or "").strip() @@ -1122,13 +2161,22 @@ 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, 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) @@ -1162,10 +2210,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: @@ -1176,14 +2239,17 @@ 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 + 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 @@ -1200,12 +2266,17 @@ 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. + 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. @@ -1213,20 +2284,20 @@ def _pre_compress( if not (chain_on or facts_on): if require_checkpoint: reason = ( - "inactive" + self._no_writer_reason(lease) 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" ) ) 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()) + chain = self._chain(client, lease) + 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. @@ -1235,7 +2306,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, @@ -1260,9 +2331,11 @@ 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, + 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) @@ -1274,7 +2347,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) @@ -1298,7 +2371,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: @@ -1332,7 +2405,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, @@ -1342,20 +2415,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) @@ -1377,38 +2451,68 @@ 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: - if self._chain_writer is None or self._chain_writer.client is not self._client: - profile = self._profile + def _chain(self, client: Any = _CURRENT, lease: Any = _CURRENT) -> ChainWriter: + """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(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 merge_tags(list(base), profile, "checkpoint") + return write_tags(list(base), "checkpoint", context) - self._chain_writer = ChainWriter( - client=self._client, + writer = ChainWriter( + 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(context), **self._chain_writer_seams(), ) - 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 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( @@ -1422,23 +2526,27 @@ def _write_chain( host_wait_s: float = 0.0, 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 = 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, - 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, @@ -1446,8 +2554,10 @@ 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 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", @@ -1465,7 +2575,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, @@ -1477,6 +2587,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. @@ -1539,6 +2650,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, "") @@ -1583,6 +2695,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`).""" @@ -1598,6 +2711,7 @@ def _store_facts( sensitivity, block_type=SESSION_DIGEST_TYPE, entry=entry, + access_context=access_context, ): stored += 1 else: @@ -1616,21 +2730,27 @@ 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 - and self._write_enabled - and self._client + lease is not None + and lease.active + 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: @@ -1644,21 +2764,24 @@ 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() - if not self._digest_enabled(): - if self._active: + 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( "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 - self._digest(messages, trigger, hook="session_end") + self._digest(messages, trigger, hook="session_end", lease=lease) def sync_turn( self, @@ -1671,12 +2794,19 @@ 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.""" - if not self._digest_enabled() or messages is None: + 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`).""" + 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._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) @@ -1684,21 +2814,27 @@ 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, 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]]) -> 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() - 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 if generation is None else generation), + ) timer.daemon = True timer.name = "ctx-idle-digest" self._idle_timer = timer @@ -1710,21 +2846,33 @@ 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``): 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 root != (self._root_session_id or self._session_id or "unknown") or not self._digest_enabled(): + 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(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.""" - root = self._root_session_id or self._session_id or "unknown" - state = self._digest_state(root) + 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() + 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) @@ -1744,9 +2892,9 @@ 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 {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" @@ -1757,7 +2905,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), @@ -1765,8 +2913,10 @@ 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 - entry = _cp.entry_state(self._entry_key()) + client = self._writer_client(lease) + 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)", hook, @@ -1778,6 +2928,10 @@ def _digest(self, messages: list[dict[str, Any]] | None, trigger: str, *, hook: ) def _run() -> None: + # 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) ok, _bid = ( self._auto_store_result( @@ -1790,6 +2944,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/status.py b/integrations/hermes/plugin/ctx_checkpoint/memory/status.py index 34a7dae2..a030daf2 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 @@ -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: @@ -749,3 +750,405 @@ def mcp_report(hermes_home: str) -> dict[str, Any]: secrets=profile_ctx_keys(name), servers=servers if isinstance(servers, dict) else {}, ) + + +# -- access groups ------------------------------------------------------------------------------ +# One small file per binding under <home>/ctx_state/access/<platform>-<scope_id>-<profile>.json, +# 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 +# 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}$") +_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. 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) + + 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)) + 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) + + +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): 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 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); *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(group, str) or not group: + return + 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 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()} + 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 + (: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 = sorted(path for path in folder.iterdir() if path.suffix == ".json" and path.is_file()) + except OSError: + 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")) + 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, unreadable + + +def access_class(row: Mapping[str, Any]) -> str: + """``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" 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())) + 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')}" + + +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, unreadable = _scan_access(hermes_home) + except Exception: + return status + 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 + 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]): + 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 and not unreadable: + 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 89f6e72c..ac4cbdbc 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/memory/tests/test_host_contract.py b/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_host_contract.py index fa9ab182..d71c3dfa 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/memory/tests/test_key_redaction.py b/integrations/hermes/plugin/ctx_checkpoint/memory/tests/test_key_redaction.py index 9f2895b5..0f8d34a8 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 561f97fe..688a9cfd 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,50 @@ def _safe(provider, text: Any) -> str: return redact_error_text(text, _bound_secrets(provider)) +# 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) + 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, 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) if context is _TAGS_NOW else tags_of(agent_tags, hook, context) + 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, 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, args) + return _tool_query(provider, client, args) if tool_name == "ctx_store": - return _tool_store(provider, args) + return _tool_store(provider, client, args, context) 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 +297,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 +330,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], 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() @@ -323,15 +357,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", context), **extra, ) if not data.get("success"): @@ -367,7 +407,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 +417,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 +440,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/plugin.yaml b/integrations/hermes/plugin/ctx_checkpoint/plugin.yaml index c33027aa..019bcc15 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 64466e7e..1cb17951 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/conftest.py b/integrations/hermes/plugin/ctx_checkpoint/tests/conftest.py index b1728fcd..9c12acde 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 00000000..441862ec --- /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 00000000..2c0999f3 --- /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 00000000..3512bc4a --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/ctx_server.py @@ -0,0 +1,789 @@ +"""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 +(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`` 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 +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 (go:narrowing.go:158-163). +NARROWED_ROUTES = frozenset( + { + ("POST", "/api/query"), + ("POST", "/api/search"), + ("POST", "/api/store"), + ("GET", "/api/whoami"), + ("POST", "/api/manage"), + } +) +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", "api-key-update"}) +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 +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 + created_at: str = NOW # keyset-provision stamps the time it made the key + + @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, *sorted(self.grants)): + if scope not in out: + out.append(scope) + return out + + @property + def writable(self) -> list[str]: + """``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 +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 created by keyset-provision or add_scope (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 = 100 # ctx's default (query.rate_limit_write) + 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 + + # -- set-up ------------------------------------------------------------------------------ + + def add_key(self, **kwargs: Any) -> FakeKey: + key = FakeKey(**kwargs) + 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] = { + "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)), + "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: + 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 = _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 [] + 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 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() + 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: + # 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, _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 + 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"): + return self._store(key, body, narrowed, echo) + if (method, path) == ("POST", "/api/manage"): + 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) + 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), + "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 + out.update( + { + "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, + "rate_limit_write": self.rate_limit_write, + "scope_narrowing": key.scope_narrowing, + } + ) + 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" + 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 [ + _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": + 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 + 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": target.created_at, + } + 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, + 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": key.created_at, + } + 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]: + 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} + 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]) + 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. 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"]) + ] + 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" + ) + 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)) + 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 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=tenant, + home=spec["home_scope"], + allowed=tuple(spec["allowed_scopes"]), + 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( + { + "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} + + +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 _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]: + 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/pd_extra.py b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/pd_extra.py new file mode 100644 index 00000000..c9bc2ee6 --- /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 new file mode 100644 index 00000000..ae543bc1 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/fakes/s1_pending.py @@ -0,0 +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). Every cluster of +axis 02 is built: the set is empty, and the shield marks nothing.""" + +S1_PENDING: frozenset[str] = frozenset() 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 00000000..b3d1d1b8 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/s3_core_child.py @@ -0,0 +1,903 @@ +"""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 +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>" + + +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, + 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 + + 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"]], + } + } + 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: + 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": 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``). + 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 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: + 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") + 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( + 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", 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}), + "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 = [] + 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 + + 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``, 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, *, 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"), + ): + 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}") + 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 + + +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 + + +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, {}), + "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, {}), + "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}), +} + + +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_access_binding_races.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py new file mode 100644 index 00000000..ac1724b2 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_binding_races.py @@ -0,0 +1,574 @@ +"""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?") + + +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.""" + 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 + 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): + """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, *home): + if not arrived.is_set(): + arrived.set() + assert go.wait(WAIT_S) + return real(root, *home) + + 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()) + + +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() + # 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() + + +# -- 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] 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 00000000..82fe79fe --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pa_client.py @@ -0,0 +1,685 @@ +"""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) + + +# -- 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, + "_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,))) + 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) 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 00000000..0336898b --- /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_pb_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pb_rules.py new file mode 100644 index 00000000..08ee061b --- /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 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 00000000..6e1cd9a1 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pc_binding.py @@ -0,0 +1,836 @@ +"""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 + # 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?") + 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} + _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() + assert provider.prefetch("rules?") == "" and fake.count() == 0 + + +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" + 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:"))] + + +# -- 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 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 00000000..dd7757e6 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_base_blocks.py @@ -0,0 +1,375 @@ +"""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 errno +import inspect +import os +import threading +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" +# 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" + ) + 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 + 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")) + 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 + + +# -- 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 only reads the markers back (no lock, no write).""" + _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_access_pd_rules.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pd_rules.py new file mode 100644 index 00000000..3ee41e0a --- /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 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 00000000..1f330990 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_rules.py @@ -0,0 +1,688 @@ +"""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 time + +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) + # 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 + 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() + 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) + + +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(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 + 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 ------------------------------------------------------------------------------------- + + +@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_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=\nexport OTHER='x y'\n" + (home / ".env").write_text(before, encoding="utf-8") + 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) == 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._write_env_line + + def broken(home, name, value): + raise OSError("disk full") + + 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, "_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 + 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 + 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"} + (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 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"]) + + +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, "--replace") == 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) + + +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 + + +# -- 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) + 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) + 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_pe_tools.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py new file mode 100644 index 00000000..fa0138ed --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pe_tools.py @@ -0,0 +1,112 @@ +"""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, "--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"] + # 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 + 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 00000000..efb6f86c --- /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 00000000..3c4b395e --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_pg_window.py @@ -0,0 +1,347 @@ +"""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 datetime as _dt +import json +import threading + +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 + + +# -- 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(*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 (the checkpoint passes its snapshot's client). + writer = chain(*args, **kwargs) + 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 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 00000000..3ee8b04a --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_review_r3.py @@ -0,0 +1,914 @@ +"""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" + + +# -- 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() + + +# -- 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() + + +# -- 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() + + +# -- 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() + + +# -- 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() + + +# -- 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" + + +# -- 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"] + + +# -- 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 + + +_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" + 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): + """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) + 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") + 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" + + +_st = ah.plugin_module(pc._PKG, "memory.status") + + +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 = provider._record_outcome + + 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(*args, **kwargs) + + provider._record_outcome = record_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(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" + 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 + + +# -- 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 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 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 + + 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 pathlib import Path + + return Path(os.environ["HERMES_HOME"]) 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 00000000..15faddbb --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_status.py @@ -0,0 +1,171 @@ +"""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:"), 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): + 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" + + +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 new file mode 100644 index 00000000..ad5f48cd --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_base_workers.py @@ -0,0 +1,57 @@ +"""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. 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 + (tmp_path / "config.yaml").write_text("memory:\n ctx_checkpoint: {}\n", encoding="utf-8") + assert acc.load_settings(str(tmp_path))["base_workers"] == 32 + + +@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_check_profile_keys.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_check_profile_keys.py new file mode 100644 index 00000000..ff0cbddd --- /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 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 00000000..ba0aa705 --- /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_access_seam_client_status.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_client_status.py new file mode 100644 index 00000000..0c279dd9 --- /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" 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 00000000..3bfcb2cb --- /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) 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 00000000..cfc22f13 --- /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"] 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 00000000..8de2c6ba --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_profile_url.py @@ -0,0 +1,116 @@ +"""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( + "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"), +] + + +@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" 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 00000000..d5da2891 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_conflicts.py @@ -0,0 +1,170 @@ +"""``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, 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 + +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_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 "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): + home = _home(tmp_path, "members") + real = cli._write_env_line + + def broken(home, name, value): + raise OSError("disk full") + + monkeypatch.setattr(cli, "_write_env_line", broken) + assert _provision(home, "members", "members") == 1 + monkeypatch.setattr(cli, "_write_env_line", 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 + + +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 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 00000000..8eeb21e7 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_env.py @@ -0,0 +1,168 @@ +"""``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, capsys): + 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" + 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): + """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() + + +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_fields.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py new file mode 100644 index 00000000..cc532545 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_fields.py @@ -0,0 +1,125 @@ +"""``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 + + +# -- 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 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 00000000..72674787 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_identity.py @@ -0,0 +1,273 @@ +"""``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 + + +# -- 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" + + +# -- 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 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 00000000..85a83ae1 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_provision_race.py @@ -0,0 +1,578 @@ +"""``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``. 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 +``.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 +from datetime import datetime, timedelta, timezone + +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._write_env_line + + def broken(home, name, value): + raise OSError("disk full") + + monkeypatch.setattr(cli, "_write_env_line", broken) + assert _provision(home, group) == 1 + monkeypatch.setattr(cli, "_write_env_line", 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_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 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 == [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): + """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. 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) + 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") == 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): + 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_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``.""" + 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 + + +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. + +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._write_env_line + + 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(home, name, value) + + 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 + 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() + + +# -- 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] 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 00000000..9ba0b501 --- /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_access_seam_session_platform.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_session_platform.py new file mode 100644 index 00000000..63e98e1b --- /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_access_seam_write_limit.py b/integrations/hermes/plugin/ctx_checkpoint/tests/test_access_seam_write_limit.py new file mode 100644 index 00000000..d5ec8086 --- /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 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 09996d10..965db0d8 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): 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 00000000..fcb4606d --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_fake_ctx_wire.py @@ -0,0 +1,269 @@ +"""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", "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, 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" + 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. 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(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 + 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 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 00000000..7f1cedc5 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_core_contract.py @@ -0,0 +1,322 @@ +"""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); 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 + +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" + + +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 (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): + 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 + + +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"] + + +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), 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): + """``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} + + +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) + 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): + """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 new file mode 100644 index 00000000..42bc3c08 --- /dev/null +++ b/integrations/hermes/plugin/ctx_checkpoint/tests/test_s3_real_ctxd.py @@ -0,0 +1,1411 @@ +"""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 time +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 +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": []} + + +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 = "" + 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"): + 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, 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 +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", "--replace") + 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.") + # 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, + "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' " + "(docs/api.md names the home scope's overlay since the server's 6f5c0574); " + "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 + # 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 = CtxClient.store + + 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(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 + 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) + + +# -- 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", "group"}, f"a run whose answer was lost notes only the time and group: {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_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"]) + 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") # 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") + 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. + +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)