Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GST-359 D: review fixes: refuse x-qm-audience, forget judges ownership first, get_write_request attestable by default, strict valid_from, fixture matches the server
garrytan4806c5c78366
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f015bf0b9d..bfe9a8e71a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,7 +31,7 @@ identifiers and attribution are available in the pre-removal Git revision| A trusted system that names the person (QM) | | a client-credentials client granted `gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]` sends `x-qm-actor: <canonical id>`; each attested operation runs as the member that id is linked to (`gbrain access member link <member> --qm <id>`, `unlink`, `links`), never reading private pages, and queued writes and jobs re-check the link and the operation list. `capture`, `extract_facts`, `forget`, `forget_fact`, take writes and `list_write_conflicts` are not attestable yet. Refusals carry `structuredContent.error` (`actor_not_attested`, `actor_unlinked`). Every MCP server's `serverInfo` now has a one-line `description` || A member saves a fact remotely (`remember` attested as a person, or from a credential bound to one member) | from a member-bound credential, went on the entity page as a fact every reader of the source recalled; an attested call could not run `remember` | goes on the member's own page `memory/members/<member>` (created with `readable_by: [member:<id>]`), private, with the entity kept as metadata; only that member recalls it, and it never dedups against, supersedes or contests another page's fact, never consolidates into a take and keeps its readers through a fence rebuild and relink. Two people's identical words make two facts. The page must name that member alone, or the fact is refused; remote `put_page`, `edit_page`, `delete_page` and every other remote page write under `memory/members/` are refused (`permission_denied`) unless the caller is that member. A member id a repo brain would store under another slug (`a--b`, `zed-`) holds no member facts (`invalid_params`) || One attest client serving several people | hot memory, `delta` cursors, write receipts and agent jobs were keyed by the client | each is keyed by the person too: Alice and Bob on one session id never share a hot-memory payload or a `delta` cursor, Bob and the bare client get `not_found` for Alice's receipt (`get_write_request`, `list_write_requests`, `cancel_write_request`) and agent job (`get_agent_job`, and the client's own `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job`), and Alice's `request_id` never replays for Bob. `remember`, `delta`, the receipt ops, `submit_agent` and `get_agent_job` are now attestable |-| QM's memory provider | | `memory_recall {query, max_chars?}` answers the attested person's own recent facts first, then the facts they may read ranked by the query, one plain line per fact cut within `max_chars` (200-12000, default 6000), keyword-only on a keyless brain; `memory_write {facts, idempotency_key}` saves 1-20 facts on that person's own page through `remember`'s writer, with request ids derived per person from the key so a replay returns the first receipt. Results ride `structuredContent`; an unlinked person gets an empty recall with `code: "actor_unlinked"`. Contract: `docs/contracts/qm-memory-provider/v1.json`; guide: `docs/guides/qm.md` |+| QM's memory provider | | `memory_recall {query, max_chars?}` answers the attested person's own recent facts first, then the facts they may read ranked by the query, one plain line per fact cut within `max_chars` (200-12000, default 6000), keyword-only on a keyless brain; `memory_write {facts, idempotency_key}` saves 1-20 facts on that person's own page through `remember`'s writer, with request ids derived per person from the key so a replay returns the first receipt. Results ride `structuredContent`, and every refusal carries `structuredContent.error`; an unlinked person gets an empty recall with `code: "actor_unlinked"`. `get_write_request` joins the default attested operations. A request carrying `x-qm-audience` is refused until channel audiences are served (`audience_not_supported`). `forget` from an attested person or a member-bound credential reaches only that member's own page. `remember` and `memory_write` take `valid_from` only as an ISO 8601 date or time in years 0001-9999. Contract: `docs/contracts/qm-memory-provider/v1.json`; guide: `docs/guides/qm.md` || An attested `forget` or `forget_fact` | refused (`op_not_attested`) | withdraws only a fact on the person's own member page, and only there: another member's copy of the same claim stays active and rememberable |### What to watch for after you upgradediff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 81cdcc418e..104ff79057 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -66,7 +66,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (off in all modes) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`s... (line truncated to 2000 chars)-- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and the managed drain, read with `git show` at the synced commit); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v282 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, `forget`, `forget_fact`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v283. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`), and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).+- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and the managed drain, read with `git show` at the synced commit); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v282 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, `forget`, `forget_fact`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v283. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`), and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).- `src/core/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (a `regen:all` artifact). Tests: `test/qm-memory-tools.test.ts` (both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).- `src/core/search/projection-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only, if none pending) or unknown; LIMIT 1 arms use the v161 pending index. Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.diff --git a/docs/contracts/qm-memory-provider/README.md b/docs/contracts/qm-memory-provider/README.mdindex 7b99cb219f..ac762541ca 100644--- a/docs/contracts/qm-memory-provider/README.md+++ b/docs/contracts/qm-memory-provider/README.md@@ -3,7 +3,8 @@`v1.json` is the contract between gbrain and QM's memory provider: the two tools(`memory_recall`, `memory_write`) with their argument schemas, output shapes andlimits, the `x-qm-actor` header and actor id pattern, every error code and-`actor_not_attested` reason with its fix, and the operations not attestable yet.+`actor_not_attested` reason with its fix, the operations not attestable yet, and+the `x-qm-audience` header, refused until wave 2.It is generated from the live operation registry by`bun scripts/build-qm-memory-contract.ts` (part of `bun run regen:all`), anddiff --git a/docs/contracts/qm-memory-provider/v1.json b/docs/contracts/qm-memory-provider/v1.jsonindex f5ef1b0139..3c1827dffd 100644--- a/docs/contracts/qm-memory-provider/v1.json+++ b/docs/contracts/qm-memory-provider/v1.json@@ -17,6 +17,7 @@},"system": "qm","default_attest_ops": [+ "get_write_request","memory_recall","memory_write"],@@ -45,8 +46,8 @@"description": "What the turn is about; ranks the facts."},"max_chars": {- "type": "number",- "description": "Text cap, 200-12000 (default 6000)."+ "type": "integer",+ "description": "Text cap in UTF-16 code units, 200-12000 (default 6000)."},"acting_user": {"type": "string",@@ -125,18 +126,21 @@"min": 200,"max": 12000,"default": 6000,- "whole_number": true+ "whole_number": true,+ "unit": "UTF-16 code units (JavaScript string length)"},"query_chars_ranked": 2000,"own_recent_window_hours": 24},+ "arguments_checked": "query and max_chars are checked before any read, also for an unlinked person (invalid_params)","content": {"line": "- <fact> (<YYYY-MM-DD>; <kind>)","truncated_tail": "… <N> more","never": ["page bodies","fence markers",- "heading markers"+ "heading markers",+ "line breaks or control characters inside a fact"],"bounded_by": "max_chars, cut at a line boundary"},@@ -186,8 +190,11 @@"commitment","belief","fact"- ]+ ],+ "provenance": "one line: no line breaks or control characters, and not starting with qm: (gbrain adds qm:<actor id> itself)",+ "valid_from": "YYYY-MM-DD or YYYY-MM-DDTHH:MM[:SS[.fraction]][Z|±HH:MM], a real calendar day in years 0001-9999"},+ "validation": "every fact is checked before any is saved: one bad fact refuses the whole call with invalid_params and the idempotency_key stays unused","saved_as": {"page": "memory/members/<member>","readers": [@@ -207,7 +214,8 @@"fact_ids": ["string"]- }+ },+ "fact_ids": "distinct; facts repeating one claim in a call share one id, and <N> counts distinct facts"},"pending": {"content": "Accepted <N> fact(s); <M> still publishing.",@@ -238,12 +246,13 @@}}},+ "applies_to": "every refusal of memory_recall and memory_write, including the transport's scope and unknown-tool refusals","codes": [{"code": "actor_not_attested","class": "host_only",- "summary": "A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header or comes without an attested header, or the id is not 1-256 visible ASCII characters; or a write that saves only as an attested person (memory_write) named none. Nothing was read or written.",- "suggestion": "Read reason: no_attest_right and op_not_attested are the brain operator's call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation, invalid_actor_id and actor_required are fixed in the calling harness.",+ "summary": "A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header or comes without an attested header, or the id is not 1-256 visible ASCII characters; or a write that saves only as an attested person (memory_write) named none; or the request carries x-qm-audience, a channel audience gbrain does not serve yet. Nothing was read or written.",+ "suggestion": "Read reason: no_attest_right and op_not_attested are the brain operator's call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation, invalid_actor_id, actor_required and audience_not_supported are fixed in the calling harness.","docs": "docs/guides/write-refusals.md#actor_not_attested","reasons": [{@@ -275,6 +284,11 @@"reason": "actor_required","fixed_by": "calling_harness","fix": "memory_write saves only as an attested person: send x-qm-actor from a credential holding the attest right."+ },+ {+ "reason": "audience_not_supported",+ "fixed_by": "calling_harness",+ "fix": "Send the call without x-qm-audience; channel turns are refused until wave 2 and nothing is read or written."}]},@@ -312,19 +326,48 @@"code": "insufficient_scope","class": "host_only","summary": "The connection lacks the OAuth scope the operation requires.",- "docs": "docs/guides/error-codes.md#insufficient_scope"+ "docs": "docs/guides/error-codes.md#insufficient_scope",+ "note": "The credential lacks the OAuth scope the tool needs (memory_write needs write); refused by the transport before the call runs."+ },+ {+ "code": "unknown_tool",+ "class": "caller",+ "summary": "The named tool does not exist or is not callable on this connection.",+ "docs": "docs/guides/error-codes.md#unknown_tool",+ "note": "The tool is not callable on this connection (its surface or bound-operation list leaves it out)."+ },+ {+ "code": "not_found",+ "class": "caller",+ "summary": "The requested resource does not exist or is not visible to this caller.",+ "docs": "docs/guides/error-codes.md#not_found",+ "note": "get_write_request for a receipt that is not this person's, or forget for a fact that is not on this person's own member page."},{- "code": "rate_limited",- "class": "retryable",- "summary": "The request was rate-limited; retry after the stated delay.",- "docs": "docs/guides/error-codes.md#rate_limited"+ "code": "fact_not_found",+ "class": "caller",+ "summary": "Fact not found.",+ "docs": "docs/guides/error-codes.md#fact_not_found",+ "note": "forget_fact for a fact that is not on this person's own member page."+ },+ {+ "code": "unavailable",+ "class": "unavailable",+ "summary": "A required dependency or capability cannot serve this request.",+ "docs": "docs/guides/error-codes.md#unavailable",+ "note": "memory_recall could not read the fact candidates (a database failure); retry the same call."}]},"wave_2": {"audience_header": "x-qm-audience","encoding": "base64url of a JSON array of canonical ids",- "status": "reserved; not honoured yet"+ "status": "refused until wave 2",+ "refusal": {+ "code": "actor_not_attested",+ "reason": "audience_not_supported",+ "tools_call": "errors.shape, with or without x-qm-actor",+ "other_methods": "JSON-RPC error -32600 whose data carries code and reason (tools/list, resources/list, resources/read)"+ }}}diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 6641994c04..21909f6df7 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -165,9 +165,9 @@ More: [docs/guides/write-refusals.md#access_rule_invalid](../../docs/guides/writ| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header or comes without an attested header, or the id is not 1-256 visible ASCII characters; or a write that saves only as an attested person (memory_write) named none. Nothing was read or written. | Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it. | Read reason: no_attest_right and op_not_attested are the brain operator's call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation, invalid_actor_id and actor_required are fixed in the calling harness. | user | `gbrain doctor --json` | 1 | no |+| A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header or comes without an attested header, or the id is not 1-256 visible ASCII characters; or a write that saves only as an attested person (memory_write) named none; or the request carries x-qm-audience, a channel audience gbrain does not serve yet. Nothing was read or written. | Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it. | Read reason: no_attest_right and op_not_attested are the brain operator's call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation, invalid_actor_id, actor_required and audience_not_supported are fixed in the calling harness. | user | `gbrain doctor --json` | 1 | no |-Reasons: `no_attest_right`, `op_not_attested`, `argument_mismatch`, `argument_without_attestation`, `invalid_actor_id`, `actor_required`.+Reasons: `no_attest_right`, `op_not_attested`, `argument_mismatch`, `argument_without_attestation`, `invalid_actor_id`, `actor_required`, `audience_not_supported`.More: [docs/guides/write-refusals.md#actor_not_attested](../../docs/guides/write-refusals.md#actor_not_attested)diff --git a/docs/guides/qm.md b/docs/guides/qm.mdindex 139f491d20..d436171006 100644--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@ -10,13 +10,14 @@ names in the `x-qm-actor` header. The wire contract QM vendors is```bashgbrain auth register-client qm --grant-types client_credentials --scopes "read write"-gbrain auth rescope --client <client_id> --attest-actor qm # attested ops default to memory_recall,memory_write+gbrain auth rescope --client <client_id> --attest-actor qm # attested ops default to get_write_request,memory_recall,memory_writegbrain access member add alice-examplegbrain access member link alice-example --qm U0ALICE # the canonical id QM sends, compared exactly```-Add `forget` with `--attest-ops forget,memory_recall,memory_write` if QM should-withdraw facts; an attested `forget` reaches only facts on the person's own page.+Add `forget` with `--attest-ops forget,get_write_request,memory_recall,memory_write` if QM+should withdraw facts; an attested `forget` reaches only facts on the person's own+page, and any other id is `not_found`.Links and the right are database state, so a repo-less brain works the same; wherea repo exists, saved facts go through the same git-first writer door as `remember`.@@ -26,14 +27,24 @@ a repo exists, saved facts go through the same git-first writer door as `remembe(`- <fact> (<date>; <kind>)`): the person's own facts from the last 24 hoursfirst, then the facts they may read ranked by `query`. Never page bodies. The textis cut at a line with a final `… N more` line and never exceeds `max_chars`- (200-12000, default 6000). Ranking is keyword-only on a keyless brain.+ (a whole number of UTF-16 code units, 200-12000, default 6000). Each fact is+ one line: line breaks and control characters in it become spaces. Ranking is+ keyword-only on a keyless brain.- `memory_write {facts, idempotency_key}` saves 1-20 facts on`memory/members/<member>`, readable by that member alone, with provenance- `qm:<id>; <provenance>`. The same key from the same person replays the first+ `qm:<id>; <provenance>`. `provenance` is one line that does not start with+ `qm:`; `valid_from` is `YYYY-MM-DD` or an ISO 8601 time in years 0001-9999.+ Every fact is checked before any is saved, so one bad fact refuses the call and+ leaves the key unused. Repeating a claim in one call saves it once, with one+ id in `fact_ids`. The same key from the same person replays the firstreceipt; from another person it is a separate write. A write still publishinganswers `status: "pending"` with a `request_id` for `get_write_request`.On success the result is in `structuredContent`, and `content` holds only the textfor the model. A person not yet linked gets an empty `memory_recall` with-`structuredContent.code: "actor_unlinked"`. Refusals are listed in+`structuredContent.code: "actor_unlinked"` (its arguments are still checked+first). Every refusal, including the transport's scope and unknown-tool ones,+carries `structuredContent.error`. A request carrying `x-qm-audience` (channel+turns, wave 2) is refused before any work with `actor_not_attested` reason+`audience_not_supported`, with or without `x-qm-actor`. Refusals are listed in[attested-actor refusals](write-refusals.md#attested-actor-refusals).diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 9004765102..37ef60eb28 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -984,7 +984,7 @@ Links and the right live in the database, so they are the same on a repo-less br| Code | What happened | What to do ||---|---|---|-| <a id="actor_not_attested"></a>`actor_not_attested` | The call named a person in a way gbrain does not honour. `reason` says which: `no_attest_right` (the credential holds no attest right, or the token of an attest client was issued before the upgrade or by another grant: the message then says to take a new client-credentials token), `op_not_attested` (the operation is not in the credential's attested operations, or is not attestable yet: `list_write_conflicts`, `capture`, `extract_facts` and `takes_add|update|resolve|supersede`; also when a queued write or agent job tool call runs after its operation was removed from the list), `argument_mismatch` (the `acting_user` argument differs from the header), `argument_without_attestation` (`acting_user` came without an attested header), `invalid_actor_id` (the header or argument is not 1-256 visible ASCII characters) or `actor_required` (`memory_write` named no attested person). Nothing was read or written. | `no_attest_right` and `op_not_attested` are the brain operator's call: `fix` carries `gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]`. The other four are fixed in the calling harness: send the canonical id unchanged in the header from the attest credential, and the same value or nothing in `acting_user`. |+| <a id="actor_not_attested"></a>`actor_not_attested` | The call named a person in a way gbrain does not honour. `reason` says which: `no_attest_right` (the credential holds no attest right, or the token of an attest client was issued before the upgrade or by another grant: the message then says to take a new client-credentials token), `op_not_attested` (the operation is not in the credential's attested operations, or is not attestable yet: `list_write_conflicts`, `capture`, `extract_facts` and `takes_add|update|resolve|supersede`; also when a queued write or agent job tool call runs after its operation was removed from the list), `argument_mismatch` (the `acting_user` argument differs from the header), `argument_without_attestation` (`acting_user` came without an attested header), `invalid_actor_id` (the header or argument is not 1-256 visible ASCII characters), `actor_required` (`memory_write` named no attested person) or `audience_not_supported` (the request carries `x-qm-audience`, QM's channel audience, which is refused on every call until wave 2). Nothing was read or written. | `no_attest_right` and `op_not_attested` are the brain operator's call: `fix` carries `gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]`. The other five are fixed in the calling harness: send the canonical id unchanged in the header from the attest credential, the same value or nothing in `acting_user`, and no `x-qm-audience`. || <a id="actor_unlinked"></a>`actor_unlinked` | The id is not linked to an enabled member: never linked, unlinked, or the member is disabled or removed. Ids compare exactly, with no case folding. Nothing was read or written. A queued write or agent job made for the person is refused the same way when its link is gone or now names another member. `memory_recall` answers it as an empty success instead (`structuredContent: {facts: [], truncated: false, code: "actor_unlinked"}`), so a person not yet linked reads nothing. | The brain operator links it: `gbrain access member link <member> --qm <id>` (or `gbrain access member enable <member>`). |## Relateddiff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex f9fcdced99..06e52b0151 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -246,7 +246,7 @@ what every named person may read.A trusted system that already knows who each person is (QM) instead holds theattest right: register a client-credentials client, grant it with `gbrain authrescope --client <id> --attest-actor qm [--attest-ops <op,...>]` (default-`memory_recall,memory_write`), and link each person's canonical id with `gbrain+`get_write_request,memory_recall,memory_write`), and link each person's canonical id with `gbrainaccess member link <member> --qm <id>` (`unlink`, `links`). Its `x-qm-actor`header then runs each attested operation as that member, never reading privatepages; see [attested-actor refusals](../guides/write-refusals.md#attested-actor-refusals).@@ -256,7 +256,8 @@ read back only by that member, written remotely by no one else), and `delta` curjobs (`submit_agent`, `get_agent_job`) belong to the person they were made for.QM's memory pair, `memory_recall` and `memory_write`, reads and saves thatperson's facts ([QM guide](../guides/qm.md)); `forget` and `forget_fact` withdraw-only a fact on the person's own page. Not attestable yet, because what they+only a fact on the person's own page (also for a credential bound to a member).+A request carrying `x-qm-audience` is refused (`audience_not_supported`). Not attestable yet, because what theyread or write is not yet kept to the person: `list_write_conflicts`, `capture`,`extract_facts` and `takes_add|update|resolve|supersede`.`gbrain access check --token <name>` shows thediff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.mdindex 0bb0e38fb0..2d132b1c7e 100644--- a/docs/tutorials/company-brain.md+++ b/docs/tutorials/company-brain.md@@ -163,7 +163,7 @@ A page is returned only when every audience entry may read it (`guest` reads no```bashgbrain auth register-client qm --grant-types client_credentials --scopes "read write"-gbrain auth rescope --client <client_id> --attest-actor qm # default ops: memory_recall,memory_write+gbrain auth rescope --client <client_id> --attest-actor qm # default ops: get_write_request,memory_recall,memory_writegbrain access member link alice-example --qm U0ALICE # --dry-run previews; unlink and links manage them```diff --git a/scripts/build-qm-memory-contract.ts b/scripts/build-qm-memory-contract.tsindex e4cf24d74e..6941fcef4e 100644--- a/scripts/build-qm-memory-contract.ts+++ b/scripts/build-qm-memory-contract.ts@@ -11,7 +11,7 @@ import { dirname, join } from 'node:path';import { operations } from '../src/core/operations.ts';import { paramDefToSchema } from '../src/mcp/tool-defs.ts';import { CODES } from '../src/core/error-registry.ts';-import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE } from '../src/core/access/actor-model.ts';+import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER } from '../src/core/access/actor-model.ts';import { IDEMPOTENCY_KEY_RE, MEMORY_RECALL_MAX_CHARS, MEMORY_RECALL_QUERY_CHARS, MEMORY_WRITE_KINDS, MEMORY_WRITE_MAX_FACTS, MEMORY_WRITE_PROVENANCE_MAX, OWN_RECENT_WINDOW_HOURS, QM_MEMORY_OPS, unlinkedRecallResult } from '../src/core/ops/qm-memory.ts';export const QM_CONTRACT_PATH = join(import.meta.dir, '..', 'docs', 'contracts', 'qm-memory-provider', 'v1.json');@@ -24,15 +24,21 @@ export const ACTOR_REASON_FIXES: Record<string, { fixed_by: 'brain_operator' | 'argument_without_attestation: { fixed_by: 'calling_harness', fix: 'Remove acting_user, or send the x-qm-actor header from a credential holding the attest right.' },invalid_actor_id: { fixed_by: 'calling_harness', fix: 'Send the canonical id unchanged: 1-256 visible ASCII characters, no spaces.' },actor_required: { fixed_by: 'calling_harness', fix: 'memory_write saves only as an attested person: send x-qm-actor from a credential holding the attest right.' },+ audience_not_supported: { fixed_by: 'calling_harness', fix: 'Send the call without x-qm-audience; channel turns are refused until wave 2 and nothing is read or written.' },};-const ERROR_CODES = ['actor_not_attested', 'actor_unlinked', 'on_behalf_of_invalid_audience', 'invalid_params', 'scope_denied', 'insufficient_scope', 'rate_limited'] as const;+const ERROR_CODES = ['actor_not_attested', 'actor_unlinked', 'on_behalf_of_invalid_audience', 'invalid_params', 'scope_denied', 'insufficient_scope', 'unknown_tool', 'not_found', 'fact_not_found', 'unavailable'] as const;const ERROR_NOTES: Partial<Record<typeof ERROR_CODES[number], string>> = {actor_unlinked: 'Refuses memory_write. memory_recall answers it as a success instead (unlinked_recall).',on_behalf_of_invalid_audience: 'Sent when x-qm-actor is combined with an on_behalf_of audience (X-Gbrain-On-Behalf-Of or request-level _meta.on_behalf_of). QM classifies it as a failed call.',invalid_params: 'Bad arguments, refused before anything is saved. A reused idempotency_key with different facts carries write_error idempotency_conflict; a claim the person forgot carries the fact_withdrawn message.',scope_denied: 'The write is not authorized, including a member page whose readers name anyone but its member (squatted or widened): nothing is saved.',+ insufficient_scope: 'The credential lacks the OAuth scope the tool needs (memory_write needs write); refused by the transport before the call runs.',+ unknown_tool: 'The tool is not callable on this connection (its surface or bound-operation list leaves it out).',+ not_found: 'get_write_request for a receipt that is not this person\'s, or forget for a fact that is not on this person\'s own member page.',+ fact_not_found: 'forget_fact for a fact that is not on this person\'s own member page.',+ unavailable: 'memory_recall could not read the fact candidates (a database failure); retry the same call.',};function toolEntry(name: string) {@@ -58,24 +64,29 @@ export function buildQmMemoryContract(): Record<string, unknown> {},tools: [...QM_MEMORY_OPS].sort().map(toolEntry),memory_recall: {- limits: { max_chars: { ...MEMORY_RECALL_MAX_CHARS, whole_number: true }, query_chars_ranked: MEMORY_RECALL_QUERY_CHARS, own_recent_window_hours: OWN_RECENT_WINDOW_HOURS },- content: { line: '- <fact> (<YYYY-MM-DD>; <kind>)', truncated_tail: '… <N> more', never: ['page bodies', 'fence markers', 'heading markers'], bounded_by: 'max_chars, cut at a line boundary' },+ limits: { max_chars: { ...MEMORY_RECALL_MAX_CHARS, whole_number: true, unit: 'UTF-16 code units (JavaScript string length)' }, query_chars_ranked: MEMORY_RECALL_QUERY_CHARS, own_recent_window_hours: OWN_RECENT_WINDOW_HOURS },+ arguments_checked: 'query and max_chars are checked before any read, also for an unlinked person (invalid_params)',+ content: { line: '- <fact> (<YYYY-MM-DD>; <kind>)', truncated_tail: '… <N> more', never: ['page bodies', 'fence markers', 'heading markers', 'line breaks or control characters inside a fact'], bounded_by: 'max_chars, cut at a line boundary' },order: ['own facts from the last ' + OWN_RECENT_WINDOW_HOURS + ' hours, newest first', 'facts the person may read, ranked by query'],ranking: 'keyword-only unless an embedding provider is configured (no embedding call on a keyless brain)',structured_content: { facts: [{ id: 'string', text: 'string', date: 'YYYY-MM-DD', kind: 'string' }], truncated: 'boolean', code: 'actor_unlinked (only on unlinked_recall)' },},unlinked_recall: { isError: false, content: unlinked.content, structuredContent: unlinked.structuredContent },memory_write: {- limits: { facts: { min: 1, max: MEMORY_WRITE_MAX_FACTS }, provenance_chars: MEMORY_WRITE_PROVENANCE_MAX, idempotency_key: IDEMPOTENCY_KEY_RE.source, kinds: [...MEMORY_WRITE_KINDS] },+ limits: { facts: { min: 1, max: MEMORY_WRITE_MAX_FACTS }, provenance_chars: MEMORY_WRITE_PROVENANCE_MAX, idempotency_key: IDEMPOTENCY_KEY_RE.source, kinds: [...MEMORY_WRITE_KINDS],+ provenance: 'one line: no line breaks or control characters, and not starting with qm: (gbrain adds qm:<actor id> itself)',+ valid_from: 'YYYY-MM-DD or YYYY-MM-DDTHH:MM[:SS[.fraction]][Z|±HH:MM], a real calendar day in years 0001-9999' },+ validation: 'every fact is checked before any is saved: one bad fact refuses the whole call with invalid_params and the idempotency_key stays unused',saved_as: { page: 'memory/members/<member>', readers: ['member:<member>'], visibility: 'private', provenance: 'qm:<actor id>; <caller provenance>' },request_id: 'uuidv5(uuidv5(namespace, "member:<member>"), idempotency_key) for the first fact; later facts derive from it',replay: 'the same idempotency_key from the same person returns the first receipt; from another person it is a separate write',retries: 'never retried server-side; a write still publishing answers pending',- committed: { content: 'Saved <N> fact(s).', structuredContent: { status: 'committed', request_id: 'uuid', fact_ids: ['string'] } },+ committed: { content: 'Saved <N> fact(s).', structuredContent: { status: 'committed', request_id: 'uuid', fact_ids: ['string'] }, fact_ids: 'distinct; facts repeating one claim in a call share one id, and <N> counts distinct facts' },pending: { content: 'Accepted <N> fact(s); <M> still publishing.', structuredContent: { status: 'pending', request_id: 'uuid', fact_ids: ['string'], pending_request_ids: ['uuid'] }, poll: 'get_write_request {request_id}' },},errors: {shape: { isError: true, content: 'one JSON text block with top-level code, message, suggestion and optional reason and fix', structuredContent: { error: { code: 'string', message: 'string', reason: 'string?', write_error: 'string?', fix: 'object?' } } },+ applies_to: 'every refusal of memory_recall and memory_write, including the transport\'s scope and unknown-tool refusals',codes: ERROR_CODES.map(code => {const entry: { class: string; summary: string; suggestion?: string; reasons?: readonly string[]; docs?: string } = CODES[code];return { code, class: entry.class, summary: entry.summary, ...(entry.suggestion ? { suggestion: entry.suggestion } : {}), docs: entry.docs ?? 'docs/guides/error-codes.md#' + code,@@ -83,7 +94,8 @@ export function buildQmMemoryContract(): Record<string, unknown> {...(ERROR_NOTES[code] ? { note: ERROR_NOTES[code] } : {}) };}),},- wave_2: { audience_header: 'x-qm-audience', encoding: 'base64url of a JSON array of canonical ids', status: 'reserved; not honoured yet' },+ wave_2: { audience_header: QM_AUDIENCE_HEADER, encoding: 'base64url of a JSON array of canonical ids', status: 'refused until wave 2',+ refusal: { code: 'actor_not_attested', reason: 'audience_not_supported', tools_call: 'errors.shape, with or without x-qm-actor', other_methods: 'JSON-RPC error -32600 whose data carries code and reason (tools/list, resources/list, resources/read)' } },};}diff --git a/src/cli/op-param-values.ts b/src/cli/op-param-values.tsindex 87613a3332..d588499334 100644--- a/src/cli/op-param-values.ts+++ b/src/cli/op-param-values.ts@@ -15,9 +15,9 @@ export function opParamValue(op: OperationMeta, key: string, def: ParamDef | undif (!def) return raw;const name = positional ? `<${key}>` : `--${key.replace(/_/g, '-')}`;const usage = `gbrain ${op.cliHints?.name ?? op.name}`;- if (def.type === 'number') {+ if (def.type === 'number' || def.type === 'integer') {const n = Number(raw);- if (raw.trim() !== '' && Number.isFinite(n)) return n;+ if (raw.trim() !== '' && (def.type === 'integer' ? Number.isInteger(n) : Number.isFinite(n))) return n;const example = typeof def.default === 'number' ? def.default : 10;throw usageError(`${name} must be a number; got '${inertText(raw, 40)}'.`,`Pass a number, e.g. ${usage} ${positional ? example : `${name} ${example}`}.`);diff --git a/src/commands/auth-binding.ts b/src/commands/auth-binding.tsindex 0efb6ed85c..c3c3e99fa8 100644--- a/src/commands/auth-binding.ts+++ b/src/commands/auth-binding.ts@@ -1,7 +1,7 @@/** GBRA-218: the member-binding flags shared by auth create, rescope and register-client. */import type { BrainEngine } from '../core/engine.ts';import { memberIdentity, parseMayActFor, parseMemberFlag, type BindingPatch, type BindingResult } from '../core/access/members.ts';-import { ATTEST_SYSTEMS, parseAttestOps } from '../core/access/actor.ts';+import { ATTEST_SYSTEMS, DEFAULT_ATTEST_OPS, parseAttestOps } from '../core/access/actor.ts';import { operationsByName } from '../core/operations.ts';import { opError } from '../core/ops/contract.ts';import { usageError } from '../cli/cli-error.ts';@@ -12,7 +12,7 @@ const NEEDS: Record<Flag, string> = {'--member': 'Pass a member id, or none to unbind (gbrain access member list).','--may-act-for': 'Pass a comma-separated list of member ids, group:<id>, guest or *, or none.','--attest-actor': 'Pass qm (the system whose x-qm-actor header this credential may send), or none.',- '--attest-ops': 'Pass a comma-separated list of operations an attested call may run (default memory_recall,memory_write).',+ '--attest-ops': 'Pass a comma-separated list of operations an attested call may run (default get_write_request,memory_recall,memory_write).',};function parseAttestActor(value: string): string | null {@@ -52,6 +52,6 @@ export async function checkBindingTarget(engine: BrainEngine, patch: BindingPatc}export function bindingLine(b: BindingResult, dryRun = false): string {- const attest = b.attest_actor ? `; attests actor: ${b.attest_actor} for ${(b.attest_ops ?? ['memory_recall', 'memory_write']).join(', ')}` : '';+ const attest = b.attest_actor ? `; attests actor: ${b.attest_actor} for ${(b.attest_ops ?? DEFAULT_ATTEST_OPS).join(', ')}` : '';return ` Member: ${b.member ?? 'none'}; may act for: ${b.may_act_for?.join(', ') ?? 'none'}${attest}${b.changed ? (dryRun ? ' (preview, not written)' : ' (updated)') : ''}`;}diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex a2d23da7ec..3579944cd8 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -1355,7 +1355,8 @@ Usage:(X-Gbrain-On-Behalf-Of or _meta.on_behalf_of)--attest-actor <qm|none> [--attest-ops <op,...>] A client-credentials client or member-less token may namethe person a QM call serves (x-qm-actor; linked with gbrain- access member link); ops default memory_recall,memory_write+ access member link); ops default get_write_request,+ memory_recall,memory_write--private-pages <granted-sources|none> Remote reads see visibility: private pages in thesources this grant names explicitly (never theno-grant floor, federation, a client's bound sourcediff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex f749b93f10..8fbfb508c4 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -9,7 +9,7 @@ import type { Express, Request, Response } from 'express';import { Server } from '@modelcontextprotocol/sdk/server/index.js';import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '@modelcontextprotocol/sdk/server/requestBody.js';-import { ListToolsRequestSchema, CallToolRequestSchema, ReadResourceRequestSchema, McpError, ErrorCode, type CallToolRequest } from '@modelcontextprotocol/sdk/types.js';+import { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, McpError, ErrorCode, type CallToolRequest } from '@modelcontextprotocol/sdk/types.js';import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';import { opAllowedForBoundClient } from '../core/operations.ts';import { authTransport } from '../core/ops/contract.ts';@@ -22,7 +22,7 @@ import { createSkillResources } from '../mcp/skill-resources.ts';import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';import { hasScope, operationScopesAllowed } from '../core/scope.ts';-import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, requestMetaSessionId, hotMemoryOffIn, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, grantBlockedNotices, admitNotices, type ToolResult } from '../mcp/dispatch.ts';+import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, requestMetaSessionId, hotMemoryOffIn, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, grantBlockedNotices, admitNotices, audienceRefusal, type ToolResult } from '../mcp/dispatch.ts';import { toAgentError } from '../core/agent-output.ts';import { STATUS_TOOL_NAME, statusModeOf, statusToolResult } from '../mcp/status-mode.ts';import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';@@ -42,7 +42,8 @@ import {} from '../mcp/surface.ts';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';-import { ACTOR_HEADER, EXTERNAL_ID_RE } from '../core/access/actor-model.ts';+import { ACTOR_HEADER, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER } from '../core/access/actor-model.ts';+import { qmMemoryToolResult } from '../core/ops/qm-memory.ts';import { attestableOp } from '../core/access/actor.ts';const actorResourceRefusal = () => new McpError(ErrorCode.InvalidRequest,@@ -72,6 +73,8 @@ interface McpRequestState {onBehalfOfHeader: string | undefined;/** GST-359 C1: the x-qm-actor header (a trusted system names the person); honoured in dispatch only for an attest credential. */actorHeader: string | undefined;+ /** GST-359 D: the x-qm-audience header (QM's channel audience, wave 2); any request carrying it is refused before any work. */+ audienceHeader: string | undefined;}export function mountMcp(app: Express, ctx: ServeHttpContext): void {@@ -183,7 +186,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {surface === 'full' && authInfo.allowedOperations == null ? undefined : new Set(mcpOperations.map(o => o.name));const thinClient = isGbrainThinClient(req.get(GBRAIN_CLIENT_HEADER));const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient,- onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), actorHeader: req.get(ACTOR_HEADER) };+ onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), actorHeader: req.get(ACTOR_HEADER), audienceHeader: req.get(QM_AUDIENCE_HEADER) };const server = createMcpRequestServer(ctx, state, writeback);await serveMcpRequest(server, req, res);}@@ -227,7 +230,7 @@ function createMcpRequestServer(installCapabilitiesResource(server, async () => {return { transport: authTransport(authInfo), client_id: authInfo.clientId,...await resolveAuthCapabilities(authInfo, engine, config), administration: mcpAdministrationGuidance(mcpResourceUrl.toString()) };- }, state.actorHeader != null ? undefined : createSkillResources(engine, async () => {+ }, state.actorHeader != null || state.audienceHeader !== undefined ? undefined : createSkillResources(engine, async () => {const sourceId = authInfo.sourceId ?? 'default';const { noGrantFederatedScope } = await import('../core/source-resolver.ts');return { remote: true, transport: 'http', sourceId, auth: authInfo, config,@@ -236,6 +239,16 @@ function createMcpRequestServer(}));// GST-359 C1: resources are never read as an attested person, so a request naming one reads none.if (state.actorHeader != null) server.setRequestHandler(ReadResourceRequestSchema, async () => { throw actorResourceRefusal(); });+ // GST-359 D: a request carrying x-qm-audience is refused before any work, on every method that reads or runs a tool.+ if (state.audienceHeader !== undefined) {+ const refusal = (op: string) => audienceRefusal(op, { auth: authInfo, transport: 'http' });+ const rpcRefusal = (method: string) => { const { rpc } = refusal(method); return new McpError(ErrorCode.InvalidRequest, rpc.message, rpc.data); };+ for (const [schema, method] of [[ListResourcesRequestSchema, 'resources/list'], [ReadResourceRequestSchema, 'resources/read'], [ListToolsRequestSchema, 'tools/list']] as const) {+ server.setRequestHandler(schema, async () => { throw rpcRefusal(method); });+ }+ server.setRequestHandler(CallToolRequestSchema, async (request) => refusal(request.params.name).result);+ return server;+ }server.setRequestHandler(ListToolsRequestSchema, async () => listMcpTools(ctx, state));server.setRequestHandler(CallToolRequestSchema, async (request) => callMcpTool(ctx, state, request));return server;@@ -322,7 +335,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requesif (statusMode && hasScope(authInfo.scopes, 'read')) return statusToolResult(statusMode, 'http');const op = mcpOperations.find(o => o.name === name);if (!op) {- return rejectUnknownMcpOperation(ctx, state, name, requestMetaSessionId(request.params));+ return qmMemoryToolResult(name, await rejectUnknownMcpOperation(ctx, state, name, requestMetaSessionId(request.params)));}// Scope enforcement (v0.28: hasScope replaces exact-string-match so@@ -338,7 +351,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques// denial first would tell the operator to widen the grant for nothing.const scopeSatisfied = op.cliOnly !== undefined || operationScopesAllowed(authInfo.scopes, op);if (!scopeSatisfied) {- return rejectInsufficientMcpScope(ctx, state, name, requiredScope, requestMetaSessionId(request.params));+ return qmMemoryToolResult(name, await rejectInsufficientMcpScope(ctx, state, name, requiredScope, requestMetaSessionId(request.params)));}// F8: redact request payload by default (declared keys only via the@@ -423,7 +436,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques...(sessionId ? { sessionId } : {}),...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),onBehalfOf: { header: state.onBehalfOfHeader, requestMeta: (request.params as { _meta?: unknown })._meta },- actor: { header: state.actorHeader },+ actor: { header: state.actorHeader, audience: state.audienceHeader },takesHoldersAllowList: tokenAllowList,sourceId: tokenSourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}),diff --git a/src/core/access/actor-model.ts b/src/core/access/actor-model.tsindex a590816fe6..6589d9ed3f 100644--- a/src/core/access/actor-model.ts+++ b/src/core/access/actor-model.ts@@ -5,10 +5,12 @@/** The header the trusted system sets on every HTTP request of a call (case-insensitive). */export const ACTOR_HEADER = 'x-qm-actor';+/** QM's channel-audience header (wave 2). Not served yet: any request carrying it is refused before any work. */+export const QM_AUDIENCE_HEADER = 'x-qm-audience';/** The tool argument the system also sends; equal to the header on an attested call, stripped before the handler. */export const ACTOR_ARGUMENT = 'acting_user';export const ATTEST_SYSTEMS: readonly string[] = ['qm'];-export const DEFAULT_ATTEST_OPS: readonly string[] = ['memory_recall', 'memory_write'];+export const DEFAULT_ATTEST_OPS: readonly string[] = ['get_write_request', 'memory_recall', 'memory_write'];/*** Operations no attested call may run yet: what they read or write is not keyed to the person, so one person could* change or see another's (a conflict list across writers) or write facts and takes every reader sees. GST-359 C2diff --git a/src/core/access/actor.ts b/src/core/access/actor.tsindex 39afa9372b..a16efa1779 100644--- a/src/core/access/actor.ts+++ b/src/core/access/actor.ts@@ -21,7 +21,7 @@ import { identityFor } from './principals.ts';import { isUndefinedColumnError, isUndefinedTableError } from '../utils.ts';import { memberIdentity } from './members.ts';import { folderAccessFor } from './caller.ts';-import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, attestRightFrom, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, type AttestedActor, type AttestRight } from './actor-model.ts';+import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, attestRightFrom, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER, type AttestedActor, type AttestRight } from './actor-model.ts';export * from './actor-model.ts';@@ -29,7 +29,7 @@ const ATTESTABLE_SCOPES = new Set(['read', 'write', 'agent']);-export type ActorReason = 'no_attest_right' | 'op_not_attested' | 'argument_mismatch' | 'argument_without_attestation' | 'invalid_actor_id' | 'actor_required';+export type ActorReason = 'no_attest_right' | 'op_not_attested' | 'argument_mismatch' | 'argument_without_attestation' | 'invalid_actor_id' | 'actor_required' | 'audience_not_supported';/** The operation metadata attestability reads (a subset of Operation, so this module never imports the registry). */export interface AttestableOpShape { scope?: string; requiredScopes?: readonly string[]; localOnly?: boolean; cliOnly?: unknown }@@ -132,6 +132,9 @@ export function actorNotAttested(reason: ActorReason, caller: ActorCaller, ctx:case 'actor_required':return opError('actor_not_attested', `${ctx.op} writes only as an attested person, and this call names none (no ${ACTOR_HEADER} header on a credential holding the attest right), so nothing was written.`,`Send ${ACTOR_HEADER} with the person's canonical id from a credential the brain operator granted the attest right (gbrain auth rescope --client <id> --attest-actor qm). To save a fact as yourself, call remember.`, { reason, docs });+ case 'audience_not_supported':+ return opError('actor_not_attested', `This request carries ${QM_AUDIENCE_HEADER} (a channel audience), which this brain does not serve yet, so nothing was read or written.`,+ `Send the call without ${QM_AUDIENCE_HEADER}. Channel turns are refused until wave 2; a call for one person sends ${ACTOR_HEADER} alone.`, { reason, docs });case 'invalid_actor_id':return opError('actor_not_attested', `The ${ACTOR_HEADER} header or the ${ACTOR_ARGUMENT} argument is not a canonical person id (1-256 visible ASCII characters), so nothing was read or written.`,'Fix the harness code that sets the header: send the canonical id unchanged, with no spaces or control characters.', { reason, docs });@@ -211,7 +214,8 @@ export async function attestedCallerAccess(engine: Pick<BrainEngine, 'executeRaw}/** The actor channel a transport read from the request: the header value, undefined when absent. Never tool arguments. */-export interface ActorChannels { header?: string | null }+/** The headers the HTTP transport read: x-qm-actor, and x-qm-audience (refused on every call while it is not served). */+export interface ActorChannels { header?: string | null; audience?: string | null }/*** The attested-actor decision for one remote call, made before any work. Null when the call names no actor (no header,@@ -225,8 +229,9 @@ export async function resolveAttestedActor(engine: Pick<BrainEngine, 'executeRaw}): Promise<{ actor: AttestedActor; access: Partial<CallerAccess>; params: Record<string, unknown> } | null> {const header = input.channels?.header ?? undefined;const hasArgument = !!input.params && Object.prototype.hasOwnProperty.call(input.params, ACTOR_ARGUMENT);- if (header === undefined && !hasArgument) return null;const caller: ActorCaller = { auth: input.auth };+ if (input.channels?.audience != null) throw actorNotAttested('audience_not_supported', caller, { op: input.op, transport: input.transport });+ if (header === undefined && !hasArgument) return null;const ctx = { op: input.op, transport: input.transport };const argument = hasArgument ? input.params![ACTOR_ARGUMENT] : undefined;if ((header !== undefined && !EXTERNAL_ID_RE.test(header)) || (hasArgument && (typeof argument !== 'string' || !EXTERNAL_ID_RE.test(argument)))) {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 256274e977..b6ee26c8b3 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1376,9 +1376,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', id: 'member_read_access_gbra218', text: 'A page whose frontmatter names readers (`readable_by: [alice-example, group:team-a]`) is now read remotely only by a token, OAuth client or stdio server bound to a listed member (`gbrain access member add`, `gbrain auth rescope --token <name> --member <id>`, config `mcp.stdio_member`). Every other remote caller gets the same `not_found` as for a missing page, including unbound credentials, a `--private-pages granted-sources` bot and both escape hatches (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), which relax only `visibility: private`. A malformed `readable_by` reads as nobody, and a page derived from a restricted page reads as nobody remotely. Pages that already named `readable_by` before this upgrade read as nobody remotely until `gbrain repair access` (preview, then `--apply`). The local CLI is unchanged; `--as <member>` previews one member\'s view.' },{ since: 'TBD', id: 'member_access_hatch_scope_gbra218', text: 'On a brain where any page names readers or any member exists, the escape hatches no longer turn the remote read filter off: remote reads still hide pages the caller\'s member is not listed on, and secondary surfaces that use the identity-free filter (proactive brief, retrieval reflex, entity resolution, known-as-of) hide every restricted page and keep hiding `visibility: private` pages under a hatch. A brain with no restriction keeps the old hatch behaviour exactly. A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).' },{ since: 'TBD', id: 'shared_agent_audience_gbra231', text: 'A shared agent can now read as the people a turn serves: its harness names the audience in the `X-Gbrain-On-Behalf-Of` header or request-level `_meta.on_behalf_of` (member ids, `group:<id>`, `guest`), and the call returns only pages every entry may read, within the agent\'s own source grant; a channel audience (more than one member, a group or a guest) never sees a `visibility: private` page. Each entry must be in the credential\'s `may_act_for` (`gbrain auth rescope --token <name> --may-act-for <list>`; for stdio, config `mcp.stdio_may_act_for`), which earlier releases stored without enforcing. An audience inside tool arguments is refused (`on_behalf_of_in_arguments`). Every remote MCP response now carries `_meta.access` (member, groups, audience, policy revisions, privacy relaxation), and `whoami` returns it as `access.applied`.' },- { since: 'TBD', id: 'qm_attested_actor_gst359', text: 'A trusted system can now name the person a call serves: a client-credentials client the brain host grants the attest right (`gbrain auth rescope --client <id> --attest-actor qm`) sends `x-qm-actor: <canonical id>`, and each attested operation runs as the member that id is linked to (`gbrain access member link <member> --qm <id>`), never reading `visibility: private` pages; `capture`, `extract_facts`, `forget`, `forget_fact`, take writes and `list_write_conflicts` are not attestable yet. A call that sends `x-qm-actor` or an `acting_user` argument without that right, for an operation outside the credential\'s `--attest-ops`, or with an id that is not 1-256 visible ASCII characters is refused (`actor_not_attested`); an id with no link to an enabled member is refused (`actor_unlinked`). Refusals carry their code in `structuredContent.error`. Every MCP server\'s `serverInfo` now includes a one-line `description`.' },+ { since: 'TBD', id: 'qm_attested_actor_gst359', text: 'A trusted system can now name the person a call serves: a client-credentials client the brain host grants the attest right (`gbrain auth rescope --client <id> --attest-actor qm`) sends `x-qm-actor: <canonical id>`, and each attested operation runs as the member that id is linked to (`gbrain access member link <member> --qm <id>`), never reading `visibility: private` pages; `capture`, `extract_facts`, take writes and `list_write_conflicts` are not attestable yet. A call that sends `x-qm-actor` or an `acting_user` argument without that right, for an operation outside the credential\'s `--attest-ops`, or with an id that is not 1-256 visible ASCII characters is refused (`actor_not_attested`); an id with no link to an enabled member is refused (`actor_unlinked`). Refusals carry their code in `structuredContent.error`. Every MCP server\'s `serverInfo` now includes a one-line `description`.' },{ since: 'TBD', id: 'member_facts_gst359', text: 'A fact a member saves remotely (`remember` attested as a person, or from a credential bound to one member) now goes on that member\'s own page `memory/members/<member>`, created with `readable_by: [member:<id>]`, as a `visibility: private` fact with the entity kept as metadata, instead of on the entity page where every reader of the source recalled it. Only that member recalls it; it never dedups against, supersedes or contests another page\'s fact, never consolidates into a take, and keeps its readers through a fence rebuild and relink. Under one attest client, hot memory, `delta` cursors, write receipts (`get_write_request`, `list_write_requests`, `cancel_write_request`, replays by `request_id`) and agent jobs (`get_agent_job`) are kept to the person they were made for: another person and the client\'s bare calls get `not_found`. `remember`, `delta`, the receipt operations, `submit_agent` and `get_agent_job` are now attestable.' },- { since: 'TBD', id: 'qm_memory_provider_gst359', text: 'QM can now keep per-person memory: `memory_recall` and `memory_write`, the default attested operations of an attest client (`gbrain auth rescope --client <id> --attest-actor qm`), read the person\'s own recent facts first and then the facts they may read, and save facts on that person\'s own page `memory/members/<member>`, readable by them alone. `memory_write` needs an attested person (`actor_not_attested` reason `actor_required` otherwise), and a reused `idempotency_key` returns the first receipt for the same person only. `forget` and `forget_fact` are now attestable: they withdraw only a fact on the person\'s own page, and only on that page. The contract QM vendors is `docs/contracts/qm-memory-provider/v1.json`.' },+ { since: 'TBD', id: 'qm_memory_provider_gst359', text: 'QM can now keep per-person memory: `memory_recall` and `memory_write`, the default attested operations of an attest client with `get_write_request` (`gbrain auth rescope --client <id> --attest-actor qm`), read the person\'s own recent facts first and then the facts they may read, and save facts on that person\'s own page `memory/members/<member>`, readable by them alone. `memory_write` needs an attested person (`actor_not_attested` reason `actor_required` otherwise), and a reused `idempotency_key` returns the first receipt for the same person only. `forget` and `forget_fact` are now attestable: for an attested person or a credential bound to a member they withdraw only a fact on that member\'s own page, and only on that page; any other fact is `not_found`. A request carrying `x-qm-audience` is refused (`actor_not_attested` reason `audience_not_supported`) until channel audiences are served. `remember` and `memory_write` accept `valid_from` only as an ISO 8601 date or time in years 0001-9999. The contract QM vendors is `docs/contracts/qm-memory-provider/v1.json`.' },{ since: 'TBD', id: 'folder_access_rules_gbra218', text: 'A source can now keep whole folders to named members with folder rules (`gbrain access rule add --prefix partners/alice-example/ --readers alice-example,group:team-a --source <id>`, preview then `--yes`). On a repo-less source the rules live in the database; on a git-backed source they live in `.gbrain/access.yml`, committed through `gbrain git commit-push` and applied on sync. A remote read of a page under a rule needs the caller\'s member to be listed on every rule covering it, on top of the page\'s own `readable_by`; no hatch, grant or `--as` relaxes it. Narrowing applies at once; a change that widens (removing a rule or a reader) is held until `gbrain access apply --source <id>` previews it and `--yes --expect <plan_hash>` approves it. While an apply is unfinished its prefixes read as nobody remotely (`access_policy_pending`, fixed by `gbrain access resume --source <id>`). `gbrain export` carries each source\'s applied rules under `.gbrain/`, and `gbrain import` installs them before any page (`--access-policy <source>` picks one source\'s rules from a multi-source export). Remote callers cannot write `.gbrain/` pages. Nothing changes on a source with no folder rule.' },];diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5ca209c01d..f6ce937506 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -68,7 +68,7 @@ export const CODES = {on_behalf_of_invalid_audience: { class: 'caller', summary: "A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read.", why: 'The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed.', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience', suggestion: 'Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent.' },on_behalf_of_unknown_member: { class: 'caller', summary: "A shared agent's audience names a member who is not enabled on this brain, or a group that does not exist, so nothing was read.", why: 'An unknown or disabled entry is refused rather than read as a guest, so a typo or a removed person never quietly changes what the agent reads.', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member', suggestion: 'Name enabled members and existing groups only (gbrain access member list --all, gbrain access group list on the brain host); a person who is not a member joins the audience as guest.' },on_behalf_of_not_permitted: { class: 'host_only', actor: 'user', summary: "A shared agent asserted an audience its credential's may_act_for does not list (for a stdio server, config mcp.stdio_may_act_for), so nothing was read.", why: 'A shared agent acts only for the people the brain operator approved for its credential; widening that list is the operator\'s decision, never the agent\'s.', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted', suggestion: 'The brain operator decides whether to approve the audience: gbrain auth rescope --token <name>|--client <id> --may-act-for <list> on the brain host. Until then, call without the audience.' },- actor_not_attested: { class: 'host_only', actor: 'user', reasons: ['no_attest_right', 'op_not_attested', 'argument_mismatch', 'argument_without_attestation', 'invalid_actor_id', 'actor_required'], summary: "A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header or comes without an attested header, or the id is not 1-256 visible ASCII characters; or a write that saves only as an attested person (memory_write) named none. Nothing was read or written.", why: 'Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it.', docs: 'docs/guides/write-refusals.md#actor_not_attested', suggestion: 'Read reason: no_attest_right and op_not_attested are the brain operator\'s call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation, invalid_actor_id and actor_required are fixed in the calling harness.' },+ actor_not_attested: { class: 'host_only', actor: 'user', reasons: ['no_attest_right', 'op_not_attested', 'argument_mismatch', 'argument_without_attestation', 'invalid_actor_id', 'actor_required', 'audience_not_supported'], summary: "A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header or comes without an attested header, or the id is not 1-256 visible ASCII characters; or a write that saves only as an attested person (memory_write) named none; or the request carries x-qm-audience, a channel audience gbrain does not serve yet. Nothing was read or written.", why: 'Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it.', docs: 'docs/guides/write-refusals.md#actor_not_attested', suggestion: 'Read reason: no_attest_right and op_not_attested are the brain operator\'s call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation, invalid_actor_id, actor_required and audience_not_supported are fixed in the calling harness.' },actor_unlinked: { class: 'host_only', actor: 'user', summary: 'An attested call named a person whose canonical id is not linked to an enabled member of this brain (never linked, unlinked, or the member is disabled or removed), so nothing was read or written.', why: 'An attested call reads and writes as exactly one member; an unknown person is refused rather than read as a guest, and unlinking or disabling takes effect on the next call.', docs: 'docs/guides/write-refusals.md#actor_unlinked', suggestion: 'The brain operator links the id to its member: gbrain access member link <member> --qm <id> (or enables the member).' },on_behalf_of_in_arguments: { class: 'caller', summary: 'A tool call carried on_behalf_of inside its arguments, where conversation text could set it, so it was refused and nothing was read.', why: 'Only harness code may name whose notes a shared agent reads: the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of, never tool arguments.', docs: 'docs/guides/write-refusals.md#on_behalf_of_in_arguments', suggestion: 'Remove on_behalf_of from the tool arguments. Harness code sends it as the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of; other stdio clients use a credential bound to one member or config mcp.stdio_member.' },access_policy_invalid: { class: 'host_only', actor: 'user', docs: 'docs/guides/write-refusals.md#access_policy_invalid', summary: "A source's folder-rule policy (the committed .gbrain/access.yml, or a file given to gbrain access rule import) does not validate, so it was not applied: the last applied rules stay in force and every prefix the bad file names reads as nobody (the whole source when its prefixes cannot be read).", why: 'A typo in an access file must never open a folder: an unreadable revision keeps the previous rules and hides what it touches until it is fixed.', suggestion: 'Show each problem with its line (gbrain access rule list --source <id>), fix the file, commit it with gbrain git commit-push and sync the source (gbrain sync --source <id> --no-pull).', fix: { argv: ['gbrain', 'access', 'rule', 'list', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the applied rules and each problem in the policy file with its line; changes nothing.' } },diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 0cc24aaafb..0c85e0295d 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -6126,8 +6126,8 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["description": "What the turn is about; ranks the facts."},"max_chars": {- "type": "number",- "description": "Text cap, 200-12000 (default 6000)."+ "type": "integer",+ "description": "Text cap in UTF-16 code units, 200-12000 (default 6000)."},"acting_user": {"type": "string",diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 915c16f3b6..68ed1e234f 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -254,7 +254,7 @@ export function verbError(}export interface ParamDef {- type: 'string' | 'number' | 'boolean' | 'object' | 'array';+ type: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array';required?: boolean;description?: string;default?: unknown;diff --git a/src/core/ops/op-fix.ts b/src/core/ops/op-fix.tsindex 806737a203..ff291096a4 100644--- a/src/core/ops/op-fix.ts+++ b/src/core/ops/op-fix.ts@@ -87,7 +87,7 @@ function exampleValue(def: ParamDef | undefined, choices: readonly string[] | unif (choices?.length) return choices[0];if (def?.default !== undefined) return def.default;switch (def?.type) {- case 'number': return 10;+ case 'number': case 'integer': return 10;case 'boolean': return true;case 'array': return [];case 'object': return {};diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.tsindex 244eb0c098..9d629b7662 100644--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@ -24,6 +24,7 @@ import { currentCallerAccess, resolveExcludePrivatePages } from '../search/privaimport { callerMember, memberPageSlug } from '../access/member-facts.ts';import { ACTOR_ARGUMENT, ACTOR_HEADER } from '../access/actor-model.ts';import { uuidV5 } from '../persistence/preconditions.ts';+import { isStrictIsoDateTime } from '../utils.ts';export const QM_MEMORY_OPS: ReadonlySet<string> = new Set(['memory_recall', 'memory_write']);export const MEMORY_RECALL_MAX_CHARS = { min: 200, max: 12_000, default: 6_000 } as const;@@ -39,6 +40,7 @@ export const IDEMPOTENCY_KEY_RE = /^[\x21-\x7e]{1,128}$/;/** remember's input kinds (MEMORY_VERBS v1, frozen); a stored `idea` can still come back from memory_recall. */export const MEMORY_WRITE_KINDS = ['event', 'preference', 'commitment', 'belief', 'fact'] as const;const FACT_KEYS = new Set(['fact', 'provenance', 'kind', 'valid_from']);+const CONTROL_RE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;/** Namespace of the per-member request-id namespaces. Changing it orphans every journaled memory_write receipt. */export const QM_MEMORY_REQUEST_NAMESPACE = '6b3e9f2a-41c7-4d58-9a0e-2f7c5d1b8e63';@@ -46,12 +48,14 @@ const actorParam: ParamDef = { type: 'string', description: `Set by the trustedexport interface RecallFact { id: string; text: string; date: string; kind: string }-/** Fact text as one plain line: fence and heading markers and rules removed, whitespace collapsed. */+/** Fact text as one plain line: fence and heading markers and rules removed, every line break and control character a space. */export function plainFactText(text: string): string {return text+ .replace(/[\r\v\f\u0085\u2028\u2029]/g, '\n').replace(/^[ \t]{0,3}#{1,6}(?=\s|$)/gm, '').replace(/^[ \t]*(?:-{3,}|\*{3,}|_{3,}|={3,})[ \t]*$/gm, '').replace(/`{3,}|~{3,}/g, '')+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').replace(/\s+/g, ' ').trim();}@@ -72,10 +76,15 @@ export function boundFactLines(lines: readonly string[], maxChars: number): { kereturn { kept, text: kept ? `${lines.slice(0, kept).join('\n')}\n${tail}` : tail };}-const isoDate = (value: Date | string | null | undefined): string => {- const t = value instanceof Date ? value : value ? new Date(value) : null;- return t && Number.isFinite(t.getTime()) ? t.toISOString().slice(0, 10) : 'undated';-};+/** YYYY-MM-DD of a stored time, read from its own fields: a database text value keeps its date as written (a non-ISO+ * parse reads year 50 as 1950), a Date its UTC year, month and day; 'undated' outside years 0001-9999. */+export function isoDate(value: Date | string | null | undefined): string {+ const written = typeof value === 'string' ? /^(\d{4})-(\d{2})-(\d{2})(?![\d])/.exec(value.trim()) : null;+ if (written) return written[1] === '0000' ? 'undated' : written.slice(1).join('-');+ const t = value instanceof Date ? value : null;+ if (!t || !Number.isFinite(t.getTime()) || t.getUTCFullYear() < 1 || t.getUTCFullYear() > 9999) return 'undated';+ return [String(t.getUTCFullYear()).padStart(4, '0'), String(t.getUTCMonth() + 1).padStart(2, '0'), String(t.getUTCDate()).padStart(2, '0')].join('-');+}const invalid = (message: string, suggestion: string): OperationError => opError('invalid_params', message, suggestion);@@ -88,6 +97,12 @@ function parseMaxChars(raw: unknown): number {return raw;}+/** memory_recall's arguments, checked before any read (and before an unlinked person's empty answer): query and max_chars. */+export function recallArguments(p: Record<string, unknown> | undefined): { query: string; maxChars: number } {+ if (typeof p?.query !== 'string') throw invalid('query is required and must be a string.', 'Pass what the turn is about as query.');+ return { query: p.query.trim().slice(0, MEMORY_RECALL_QUERY_CHARS), maxChars: parseMaxChars(p.max_chars) };+}+type ReadPolicy = { excludePrivate: boolean; eligibility: Awaited<ReturnType<typeof resolveReadEligibility>> };/** The caller's own facts written in the last 24 hours on its member page, newest first; none outside a member caller. */@@ -110,14 +125,13 @@ const memory_recall: Operation = {description: 'Facts for the person this call serves, one per line: their own recent facts first, then facts matching query. Never page bodies. For QM; agents use recall.',params: {query: { type: 'string', required: true, description: 'What the turn is about; ranks the facts.' },- max_chars: { type: 'number', description: `Text cap, ${MEMORY_RECALL_MAX_CHARS.min}-${MEMORY_RECALL_MAX_CHARS.max} (default ${MEMORY_RECALL_MAX_CHARS.default}).` },+ max_chars: { type: 'integer', description: `Text cap in UTF-16 code units, ${MEMORY_RECALL_MAX_CHARS.min}-${MEMORY_RECALL_MAX_CHARS.max} (default ${MEMORY_RECALL_MAX_CHARS.default}).` },[ACTOR_ARGUMENT]: actorParam,},scope: 'read',annotations: { title: 'memory_recall (QM memory read)', readOnlyHint: true },handler: async (ctx, p) => {- const maxChars = parseMaxChars(p.max_chars);- const query = typeof p.query === 'string' ? p.query.trim().slice(0, MEMORY_RECALL_QUERY_CHARS) : '';+ const { query, maxChars } = recallArguments(p);const scope = federatedSearchScope(ctx, undefined);const sources = [...new Set(scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? ctx.sourceId ?? 'default'])];const read: ReadPolicy = { excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote), eligibility: await resolveReadEligibility(ctx, {}) };@@ -129,7 +143,10 @@ const memory_recall: Operation = {})).rows : [];const seen = new Set<number>();const rows = [...own, ...ranked].filter(r => !seen.has(r.id) && !!seen.add(r.id));- const plain = rows.map(r => ({ id: String(r.id), text: plainFactText(r.fact), date: isoDate(r.valid_from ?? r.created_at), kind: String(r.kind) }));+ // The date as the database writes it: a driver's timestamp parse reads years 1-99 as 19xx.+ const written = new Map(rows.length ? (await ctx.engine.executeRaw<{ id: number | string; d: string }>(+ `SELECT id, to_char(COALESCE(valid_from, created_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS d FROM facts WHERE id = ANY($1::bigint[])`, [rows.map(r => r.id)])).map(r => [Number(r.id), r.d]) : []);+ const plain = rows.map(r => ({ id: String(r.id), text: plainFactText(r.fact), date: isoDate(written.get(Number(r.id)) ?? r.valid_from ?? r.created_at), kind: String(r.kind) }));const { redactRetrievalOutput } = await import('../search/output-redaction.ts');const facts: RecallFact[] = (ctx.remote === false ? plain : redactRetrievalOutput(plain, {}, { uncapped: true }).results).filter(f => f.text);const { kept, text } = boundFactLines(facts.map(f => `- ${f.text} (${f.date}; ${f.kind})`), maxChars);@@ -161,11 +178,14 @@ function parseFacts(raw: unknown, actorId: string): Array<Record<string, unknownif (!provenance || provenance.length > MEMORY_WRITE_PROVENANCE_MAX) {throw invalid(`${at}.provenance must be 1 to ${MEMORY_WRITE_PROVENANCE_MAX} characters.`, 'Pass where the fact came from, for example "slack:C0123/p1700000000".');}+ if (CONTROL_RE.test(f.provenance as string) || /^qm:/i.test(provenance)) {+ throw invalid(`${at}.provenance must be one line of text that does not start with qm:.`, 'gbrain adds qm:<actor id> itself; pass only where the fact came from, without line breaks or control characters.');+ }if (f.kind !== undefined && !(MEMORY_WRITE_KINDS as readonly unknown[]).includes(f.kind)) {throw invalid(`${at}.kind is not a fact kind.`, `Use one of: ${MEMORY_WRITE_KINDS.join(', ')}, or omit it (fact).`);}- if (f.valid_from !== undefined && (typeof f.valid_from !== 'string' || !Number.isFinite(Date.parse(f.valid_from)))) {- throw invalid(`${at}.valid_from must be an ISO 8601 date or time.`, 'Pass when the fact became true, for example "2026-10-30", or omit it.');+ if (f.valid_from !== undefined && !isStrictIsoDateTime(f.valid_from)) {+ throw invalid(`${at}.valid_from must be an ISO 8601 date or time in years 0001-9999.`, 'Pass when the fact became true as YYYY-MM-DD or YYYY-MM-DDTHH:MM[:SS][Z|±HH:MM], for example "2026-10-30", or omit it.');}return { fact, provenance: `qm:${actorId}; ${provenance}`, ...(f.kind !== undefined ? { kind: f.kind } : {}), ...(f.valid_from !== undefined ? { valid_from: f.valid_from } : {}) };});@@ -224,12 +244,13 @@ const memory_write: Operation = {}}const pending = saved.filter(s => s.pending).map(s => s.request_id);+ const factIds = [...new Set(saved.flatMap(s => s.fact_id ? [s.fact_id] : []))];return {status: pending.length ? 'pending' : 'committed',request_id: pending[0] ?? items[0]!.request_id,- fact_ids: saved.flatMap(s => s.fact_id ? [s.fact_id] : []),+ fact_ids: factIds,...(pending.length ? { pending_request_ids: pending } : {}),- text: pending.length ? `Accepted ${items.length} fact(s); ${pending.length} still publishing.` : `Saved ${items.length} fact(s).`,+ text: pending.length ? `Accepted ${factIds.length + pending.length} fact(s); ${pending.length} still publishing.` : `Saved ${factIds.length} fact(s).`,};},};diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 720a903bca..60ed34db2a 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -28,9 +28,9 @@ import { requestAttribution } from './attribution.ts';import { isTerminal, type WriteRequest } from './model.ts';import { prepareMemoryMutation } from './memory-prepare.ts';import { retryWriteAdmission } from './admission-retry.ts';-import { currentCallerAccess, privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';+import { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { markBeliefCommits } from '../belief/append.ts';-import { memberFactAdmitSql, memberFactPage, memberPageIsOwn, memberPageNotOwned, memberPageSlug } from '../access/member-facts.ts';+import { callerMember, memberFactAdmitSql, memberFactPage, memberPageIsOwn, memberPageNotOwned, memberPageSlug } from '../access/member-facts.ts';export { prepareMemoryMutation } from './memory-prepare.ts';/** Only semantic appends without an explicit caller revision can be recomputed. */@@ -331,12 +331,17 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foif (!Number.isSafeInteger(id) || id <= 0) throw verbError(operation === 'forget' ? 'not_found' : 'fact_not_found',`No fact with id "${rawId}".`, 'Pass the fact id returned by remember or recall.');const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);- // GST-359 D: an attested person withdraws only facts on their own member page, and only there (the page is the- // withdrawal's subject), so another member's copy of the same claim stays active and rememberable.- const actor = ctx.remote !== false ? currentCallerAccess().actor : undefined;- const ownPage = actor ? memberPageSlug(actor.member) : null;+ // GST-359 D: a remote caller that is one member (an attested person or a member-bound credential) withdraws only facts+ // on its own member page, and only there (the page is the withdrawal's subject), so another member's copy of the same+ // claim stays active and rememberable. Ownership is judged first: any other fact is not_found before a trust check,+ // so no owner proposal is filed and its tier is never disclosed.+ const member = ctx.remote !== false ? callerMember() : null;+ const ownPage = member ? memberPageSlug(member) : null;+ const notFound = () => verbError(operation === 'forget' ? 'not_found' : 'fact_not_found',+ `No fact with id "${rawId}".`, 'Ids come from remember/recall. Recall the entity first to find the right fact.');+ if (ownPage && !(await ctx.engine.executeRaw(`SELECT 1 FROM facts WHERE id=$1 AND source_id=$2 AND ${memberFactAdmitSql('facts')}`, [id, sourceId])).length) throw notFound();// #5575 I3: a remote caller cannot forget a fact more trusted than its own writes; the owner is asked instead.- if (ctx.remote !== false && Number.isSafeInteger(id) && id > 0) await guardRemoteForget(ctx.engine, { sourceId, factId: id, principal, reason, excludePrivate });+ if (ctx.remote !== false) await guardRemoteForget(ctx.engine, { sourceId, factId: id, principal, reason, excludePrivate });// Retry the whole withdrawal, so source/principal guards and the connection// are released before backoff. Admission must not retry a nested savepoint.let withdrawn: WithdrawalCommit['pages'] = [];@@ -362,8 +367,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foWHERE id=$1 AND source_id=$2 AND ${ownPage ? memberFactAdmitSql('facts'): `($3::boolean=false OR visibility='world')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`} FOR UPDATE`,ownPage ? [id, sourceId] : [id, sourceId, ctx.remote !== false]);- if (!fact) throw verbError(operation === 'forget' ? 'not_found' : 'fact_not_found',- `No fact with id "${rawId}".`, 'Ids come from remember/recall. Recall the entity first to find the right fact.');+ if (!fact) throw notFound();if (ctx.remote !== false && supersessionGuarded('agent_written', fact.trust_tier)) throw remoteForgetRaced(id);if (!ownPage) await refuseForgetReachingOtherCopies(tx, sourceId, fact, ctx.remote !== false, excludePrivate);const slug = fact.source_markdown_slug ?? fact.entity_slug ?? 'memory/unattributed';diff --git a/src/core/utils.ts b/src/core/utils.tsindex 9c6f7bbfeb..841e46a05c 100644--- a/src/core/utils.ts+++ b/src/core/utils.ts@@ -690,3 +690,18 @@ export function staleTakeRowToRow(row: Record<string, unknown>): StaleTakeRow {export function bigintToStringReplacer(_key: string, value: unknown): unknown {return typeof value === 'bigint' ? value.toString() : value;}++/**+ * A strict ISO 8601 date or time in years 0001-9999: YYYY-MM-DD, or that with THH:MM[:SS[.fraction]] and an optional+ * Z or ±HH:MM offset, naming a real calendar day and time. Date.parse alone admits '2026-02-30', 'March 3' and year+ * 10000, which the database refuses or moves.+ */+export function isStrictIsoDateTime(value: unknown): value is string {+ if (typeof value !== 'string') return false;+ const m = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(?:Z|[+-](\d{2}):(\d{2}))?)?$/.exec(value);+ if (!m) return false;+ const [year, month, day] = [Number(m[1]), Number(m[2]), Number(m[3])];+ const days = [31, year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];+ if (year < 1 || month < 1 || month > 12 || day < 1 || day > days[month - 1]!) return false;+ return Number(m[4] ?? 0) <= 23 && Number(m[5] ?? 0) <= 59 && Number(m[6] ?? 0) <= 59 && Number(m[7] ?? 0) <= 23 && Number(m[8] ?? 0) <= 59;+}diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 0a734a5c6c..c1c4c0a968 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -29,6 +29,7 @@ import { recordFunnelEvent, recordRememberOutcome } from './funnel.ts';import type { Operation } from './operations.ts';import { WRITE_RECEIPT_SCHEMA, WRITE_REQUEST_PARAM, AGENT_CONTENT_PARAMS, CONTENT_ORIGIN_PARAM } from './persistence/params.ts';import { WRITE_ERROR_CODES } from './persistence/types.ts';+import { isStrictIsoDateTime } from './utils.ts';/** Frozen protocol version for the MEMORY_VERBS v1 verb set. Single source of truth. */export const MEMORY_VERBS_VERSION = 1;@@ -168,11 +169,11 @@ const remember: Operation = {'Use "world" (default — agents can recall it) or "private" (local CLI reads only).',);}- if (p.valid_from !== undefined && (typeof p.valid_from !== 'string' || !Number.isFinite(Date.parse(p.valid_from)))) {+ if (p.valid_from !== undefined && !isStrictIsoDateTime(p.valid_from)) {throw verbError('invalid_params',- 'valid_from must be an ISO 8601 date or time.',- 'Pass when the fact was said or became true, e.g. valid_from: "2026-03-01", or omit it.',+ 'valid_from must be an ISO 8601 date or time in years 0001-9999.',+ 'Pass when the fact was said or became true as YYYY-MM-DD or YYYY-MM-DDTHH:MM[:SS][Z|±HH:MM], e.g. valid_from: "2026-03-01", or omit it.',);}if (p.content_origin !== undefined && !CONTENT_ORIGIN_PARAM.enum!.includes(p.content_origin as string)) {diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex b42304f320..d79c654683 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -17,8 +17,8 @@ import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../coreimport { withCallerAccess } from '../core/search/private-visibility.ts';import { appliedAccessSummary, remoteCallerAccess } from '../core/access/caller.ts';import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';-import { ACTOR_ARGUMENT, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';-import { qmMemoryToolResult, unlinkedRecallResult } from '../core/ops/qm-memory.ts';+import { ACTOR_ARGUMENT, actorNotAttested, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';+import { qmMemoryToolResult, recallArguments, unlinkedRecallResult } from '../core/ops/qm-memory.ts';import { resolveBrainId } from '../core/brain-resolver.ts';import { getCliOptions } from '../core/cli-options.ts';import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';@@ -923,7 +923,7 @@ export async function dispatchToolCall(let attested: Awaited<ReturnType<typeof resolveAttestedActor>> = null;let access: Awaited<ReturnType<typeof remoteCallerAccess>>;const header = opts.actor?.header ?? undefined;- const actorNamed = header !== undefined || (!!params && Object.prototype.hasOwnProperty.call(params, ACTOR_ARGUMENT));+ const actorNamed = header !== undefined || opts.actor?.audience != null || (!!params && Object.prototype.hasOwnProperty.call(params, ACTOR_ARGUMENT));const assertion = (outcome: AudienceAuditEvent['outcome'], reason?: string) => logAudienceAssertion({ outcome, op: name,audience: [...(attested?.access.audience ?? audience ?? [])], transport: opts.transport ?? 'unknown',principal: opts.auth?.principal ? `${opts.auth.principal.kind}:${opts.auth.principal.id}` : opts.transport === 'stdio' ? 'local_stdio' : 'unknown',@@ -937,7 +937,7 @@ export async function dispatchToolCall(} catch (e) {if (!(e instanceof OperationError) || !/^(on_behalf_of_|actor_)/.test(String(e.code))) throw e;assertion(e.code as AudienceAuditEvent['outcome'], e.reason);- return actorNamed ? actorRefusal(e, opts, name, header) : errorResult(e, opts, { op: name });+ return qmMemoryToolResult(name, actorNamed ? actorRefusal(e, opts, name, header, params) : errorResult(e, opts, { op: name }));}if (audience || attested) assertion('accepted');const callParams = attested ? attested.params : params;@@ -960,8 +960,9 @@ export async function dispatchToolCall(* actor_unlinked as a success instead (GST-359 D): empty content and structuredContent {facts: [], truncated: false,* code: 'actor_unlinked'}, the code also in `_meta.access`, so a person not yet linked reads nothing and QM's turn goes on.*/-function actorRefusal(e: OperationError, opts: DispatchOpts, op: string, header: string | undefined): ToolResult {+function actorRefusal(e: OperationError, opts: DispatchOpts, op: string, header: string | undefined, params: Record<string, unknown> | undefined): ToolResult {if (op === 'memory_recall' && e.code === 'actor_unlinked') {+ try { recallArguments(params); } catch (invalid) { if (invalid instanceof OperationError) return actorRefusal(invalid, opts, op, header, params); throw invalid; }return { ...unlinkedRecallResult(), _meta: { access: { code: 'actor_unlinked', member: null, groups: [], audience: null, actor: { system: 'qm', external_id: header } } } };}const out = errorResult(e, opts, { op });@@ -972,6 +973,17 @@ function actorRefusal(e: OperationError, opts: DispatchOpts, op: string, header:return out;}+/**+ * GST-359 D: the refusal both HTTP transports give a request carrying x-qm-audience (a channel audience gbrain does+ * not serve yet), before any work: the tools/call result (with structuredContent.error) and the JSON-RPC error for+ * every other method that would read (tools/list, resources).+ */+export function audienceRefusal(op: string, opts: Pick<DispatchOpts, 'auth' | 'transport'>): { result: ToolResult; rpc: { code: number; message: string; data: Record<string, unknown> } } {+ const e = actorNotAttested('audience_not_supported', { auth: opts.auth }, { op, transport: opts.transport });+ return { result: actorRefusal(e, { remote: true, ...opts }, op, undefined, undefined),+ rpc: { code: -32600, message: `actor_not_attested: ${e.message}`, data: { code: 'actor_not_attested', reason: 'audience_not_supported', message: e.message } } };+}+/** The response-meta hook's keys, or its failure message; never rejects (a hook failure degrades to no keys). */async function runMetaHook(hook: NonNullable<DispatchOpts['metaHook']>, name: string, ctx: OperationContext): Promise<{ meta?: Record<string, unknown>; failure?: string }> {try { return { meta: await hook(name, ctx) }; }diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 12554dbd51..6fcfd79823 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -38,11 +38,12 @@ import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writebackimport { operations, operationsByName, opAllowedForBoundClient } from '../core/operations.ts';import { scopeDeniedError } from '../core/ops/op-fix.ts';import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';-import { ACTOR_HEADER, withAttestRight } from '../core/access/actor-model.ts';+import { ACTOR_HEADER, QM_AUDIENCE_HEADER, withAttestRight } from '../core/access/actor-model.ts';+import { qmMemoryToolResult } from '../core/ops/qm-memory.ts';import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import type { AuthInfo } from '../core/operations.ts';import { VERSION } from '../version.ts';-import { dispatchToolCall, requestLogStatusForResult, errorResult } from './dispatch.ts';+import { audienceRefusal, dispatchToolCall, requestLogStatusForResult, errorResult } from './dispatch.ts';import { GBRAIN_CLIENT_HEADER, isGbrainThinClient, resolveResultRowsMode, resultRowsForRequest } from './result-rows.ts';import { parseStrictParamsMode } from './validate-params.ts';import { filterOpsForSurface, clampSurface, advertisedOps, resolveAdvertisedSurface, type McpSurface } from './surface.ts';@@ -191,6 +192,18 @@ function authFailureBody(code: AuthResult['code']): Record<string, string> {: { error: 'invalid_token', message: 'Bearer token required. Create one: gbrain auth create <name>' };}+/**+ * GST-359 D: a request carrying x-qm-audience (QM's channel audience, not served yet) is refused before any work on+ * every method that reads or runs a tool: tools/call gets the refusal result, the others a JSON-RPC error. Null otherwise.+ */+function qmAudienceRefusal(req: Request, body: { method?: string; params?: any; id?: any }, auth: AuthInfo): { log: string; body: Record<string, unknown> } | null {+ const { method, params, id } = body;+ if (req.headers.get(QM_AUDIENCE_HEADER) === null || !['tools/list', 'tools/call', 'resources/list', 'resources/read'].includes(method ?? '')) return null;+ const op = method === 'tools/call' ? String(params?.name ?? 'unknown') : method!;+ const refused = audienceRefusal(op, { auth, transport: 'http' });+ return method === 'tools/call' ? { log: `tools/call:${op}`, body: { jsonrpc: '2.0', id, result: refused.result } } : { log: op, body: { jsonrpc: '2.0', id, error: refused.rpc } };+}+export async function startHttpTransport(opts: HttpTransportOptions) {const { port, engine } = opts;@@ -437,7 +450,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {}const { method, params, id } = body;-+ const audienceRefused = qmAudienceRefusal(req, body, auth.auth!); if (audienceRefused) { logRequest(auth.tokenName!, audienceRefused.log, 'error', Date.now() - startedMs); return Response.json(audienceRefused.body, { headers: corsHeaders(origin) }); }// initializeif (method === 'initialize') {logRequest(auth.tokenName!, 'initialize', 'success', Date.now() - startedMs);@@ -529,7 +542,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// Frozen v1 pair: `error: permission_denied` stays; `code: insufficient_scope`.const denial = scopeDeniedError({ op: toolName, required: [op.scope ?? 'read', ...(op.requiredScopes ?? [])], auth: auth.auth,transport: 'http', message: `Tool requires ${op.scope ?? 'read'} scope`, legacy_error: 'permission_denied' });- return Response.json({ jsonrpc: '2.0', id, result: errorResult(denial, { remote: true, transport: 'http', auth: auth.auth }, { op: toolName }) },+ return Response.json({ jsonrpc: '2.0', id, result: qmMemoryToolResult(toolName, errorResult(denial, { remote: true, transport: 'http', auth: auth.auth }, { op: toolName })) },{ headers: corsHeaders(origin) });}// v0.28: thread per-token takes-holder allow-list so takes_list /@@ -555,7 +568,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {takesHoldersAllowList: auth.takesHoldersAllowList,sourceId: auth.sourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta },- actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined }, // #1336: thread the token's federated_read grant so read ops scope+ actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined, audience: req.headers.get(QM_AUDIENCE_HEADER) ?? undefined }, // #1336: thread the token's federated_read grant so read ops scope// to the operator-granted sources via sourceScopeOpts.auth: auth.auth,// MEMORY_VERBS v1 [c1/c2]: fail-closed surface enforcement here too.diff --git a/src/mcp/validate-params.ts b/src/mcp/validate-params.tsindex c9476899d3..43c5157463 100644--- a/src/mcp/validate-params.ts+++ b/src/mcp/validate-params.ts@@ -35,6 +35,7 @@ export function findInvalidParam(op: Operation, params: Record<string, unknown>)const expected = def.type;if (expected === 'string' && typeof val !== 'string') return fail(`Parameter "${key}" must be a string`);if (expected === 'number' && typeof val !== 'number') return fail(`Parameter "${key}" must be a number`);+ if (expected === 'integer' && !Number.isInteger(val)) return fail(`Parameter "${key}" must be a whole number`);if (expected === 'boolean' && typeof val !== 'boolean') return fail(`Parameter "${key}" must be a boolean`);if (expected === 'object' && (typeof val !== 'object' || Array.isArray(val))) return fail(`Parameter "${key}" must be an object`);if (expected === 'array' && !Array.isArray(val)) return fail(`Parameter "${key}" must be an array`);@@ -86,7 +87,7 @@ function retryWithValidParam(op: Operation, failure: ParamValidationFailure, parconst def = op.params[failure.param];if (!def || params[failure.param] === undefined || params[failure.param] === null) return undefined;const value = def.enum?.length ? (def.default !== undefined && def.enum.includes(String(def.default)) ? def.default : def.enum[0])- : def.type === 'number' ? (typeof def.default === 'number' ? def.default : 10)+ : def.type === 'number' || def.type === 'integer' ? (typeof def.default === 'number' ? def.default : 10): def.type === 'boolean' ? (typeof def.default === 'boolean' ? def.default : true): undefined;if (value === undefined) return undefined;diff --git a/test/e2e/serve-http-qm-memory.test.ts b/test/e2e/serve-http-qm-memory.test.tsindex 31a3c13604..1718d0c374 100644--- a/test/e2e/serve-http-qm-memory.test.ts+++ b/test/e2e/serve-http-qm-memory.test.ts@@ -35,7 +35,7 @@ const KEYLESS: Record<string, string> = Object.fromEntries(Object.entries(procesdescribeE2E('/mcp memory_recall and memory_write over keyless serve --http', () => {let serverProcess: ReturnType<typeof import('child_process').spawn> | null = null;let engine: PostgresEngine;- const tokens: Record<'qm' | 'plain', string> = { qm: '', plain: '' };+ const tokens: Record<'qm' | 'plain' | 'readonly', string> = { qm: '', plain: '', readonly: '' };const cli = (...args: string[]) => execFileSync('bun', ['run', 'src/cli.ts', ...args], { cwd: process.cwd(), env: KEYLESS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });beforeAll(async () => {@@ -44,7 +44,9 @@ describeE2E('/mcp memory_recall and memory_write over keyless serve --http', ()const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });const qm = await provider.registerClientManual('qm-mem-e2e-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], 'default');const plain = await provider.registerClientManual('qm-mem-e2e-plain-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], 'default');- expect(cli('auth', 'rescope', '--client', qm.clientId, '--attest-actor', 'qm')).toContain('attests actor: qm for memory_recall, memory_write');+ const readonly = await provider.registerClientManual('qm-mem-e2e-ro-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], 'default');+ expect(cli('auth', 'rescope', '--client', readonly.clientId, '--attest-actor', 'qm')).toContain('attests actor: qm');+ expect(cli('auth', 'rescope', '--client', qm.clientId, '--attest-actor', 'qm')).toContain('attests actor: qm for get_write_request, memory_recall, memory_write');expect(cli('auth', 'rescope', '--client', qm.clientId, '--attest-actor', 'qm', '--attest-ops', 'forget,memory_recall,memory_write')).toContain('forget, memory_recall, memory_write');expect(cli('access', 'member', 'link', 'alice-example', '--qm', ALICE_ID)).toContain('Linked qm:' + ALICE_ID);expect(cli('access', 'member', 'link', 'bob-example', '--qm', BOB_ID)).toContain('-> bob-example');@@ -60,7 +62,7 @@ describeE2E('/mcp memory_recall and memory_write over keyless serve --http', ()if (!up) await new Promise(r => setTimeout(r, 500));}if (!up) throw new Error('Server failed to start within 15s.\nstderr: ' + stderr.slice(-500));- for (const [key, c] of [['qm', qm], ['plain', plain]] as const) {+ for (const [key, c] of [['qm', qm], ['plain', plain], ['readonly', readonly]] as const) {const res = await fetch(BASE + '/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body: new URLSearchParams({ grant_type: 'client_credentials', client_id: c.clientId, client_secret: c.clientSecret! }) });expect(res.status).toBe(200);@@ -77,18 +79,21 @@ describeE2E('/mcp memory_recall and memory_write over keyless serve --http', ()await teardownDB();}, 30_000);- async function tool(who: 'qm' | 'plain', name: string, args: Record<string, unknown>, actor?: string) {+ async function rpc(who: 'qm' | 'plain' | 'readonly', body: Record<string, unknown>, headers: Record<string, string> = {}) {const res = await fetch(BASE + '/mcp', {method: 'POST',- headers: { Authorization: 'Bearer ' + tokens[who], 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream',- ...(actor !== undefined ? { 'x-qm-actor': actor } : {}) },- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),+ headers: { Authorization: 'Bearer ' + tokens[who], 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', ...headers },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, ...body }),});expect(res.status).toBe(200);expect(res.headers.get('mcp-session-id')).toBeNull();const text = (await res.text()).trim();- const parsed = JSON.parse(text.startsWith('{') ? text : text.split('\n').filter(l => l.startsWith('data:')).pop()!.slice(5).trim()) as { result: Record<string, any> };- const r = parsed.result;+ return JSON.parse(text.startsWith('{') ? text : text.split('\n').filter(l => l.startsWith('data:')).pop()!.slice(5).trim()) as { result?: Record<string, any>; error?: { code: number; message: string; data?: Record<string, unknown> } };+ }++ async function tool(who: 'qm' | 'plain' | 'readonly', name: string, args: Record<string, unknown>, actor?: string, headers: Record<string, string> = {}) {+ const parsed = await rpc(who, { method: 'tools/call', params: { name, arguments: args } }, { ...(actor !== undefined ? { 'x-qm-actor': actor } : {}), ...headers });+ const r = parsed.result!;const body = (r.content as Array<{ text: string }>).map(c => c.text).join('\n');let json: Record<string, any> = {};try { json = JSON.parse(body); } catch { /* plain text */ }@@ -127,6 +132,30 @@ describeE2E('/mcp memory_recall and memory_write over keyless serve --http', ()expect(await engine.executeRaw("SELECT 1 FROM facts WHERE fact LIKE '%canarye2erefused%'")).toHaveLength(0);}, 60_000);+ test('x-qm-audience is refused before any work, with or without x-qm-actor, on tools/call, tools/list and resources', async () => {+ for (const actor of [ALICE_ID, undefined]) {+ for (const [name, args] of [['memory_recall', { query: 'harbor ledger' }], ['memory_write', { facts: [{ fact: 'x canarye2eaudience', provenance: 'y' }], idempotency_key: randomUUID() }]] as const) {+ const out = await tool('qm', name, args, actor, { 'x-qm-audience': 'WyJVMEJPQiJd' });+ expect({ isError: out.isError, code: out.json.code, reason: out.json.reason }).toEqual({ isError: true, code: 'actor_not_attested', reason: 'audience_not_supported' });+ expect(out.structured?.error).toMatchObject({ code: 'actor_not_attested', reason: 'audience_not_supported' });+ expect(out.text).not.toContain('canarye2e');+ }+ const headers = { 'x-qm-audience': 'WyJVMEJPQiJd', ...(actor ? { 'x-qm-actor': actor } : {}) };+ for (const [method, params] of [['tools/list', {}], ['resources/list', {}], ['resources/read', { uri: 'gbrain://capabilities' }]] as const) {+ const out = await rpc('qm', { method, params }, headers);+ expect(out.result).toBeUndefined();+ expect(out.error!.data).toMatchObject({ code: 'actor_not_attested', reason: 'audience_not_supported' });+ }+ }+ expect(await engine.executeRaw("SELECT 1 FROM facts WHERE fact LIKE '%canarye2eaudience%'")).toHaveLength(0);+ }, 60_000);++ test('a scope refusal of a memory tool carries structuredContent.error like every other refusal', async () => {+ const out = await tool('readonly', 'memory_write', { facts: [{ fact: 'x canarye2ereadonly', provenance: 'y' }], idempotency_key: randomUUID() }, ALICE_ID);+ expect(out.isError).toBe(true);+ expect(out.structured?.error).toMatchObject({ code: 'insufficient_scope', message: out.json.message });+ }, 60_000);+test('forget withdraws only the person\'s own fact', async () => {const [row] = await engine.executeRaw<{ id: number }>("SELECT id FROM facts WHERE fact LIKE '%canarye2ealice%'");const bobTry = await tool('qm', 'forget', { id: String(row!.id) }, BOB_ID);diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 574440e5f5..c217697263 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 267537,- "stdoutSha256": "a8833d13e72c68b0bbae9ab86c55ab9ab2d870e31fa28dc835bef295152005e9",+ "stdoutBytes": 267560,+ "stdoutSha256": "25f870be62f4c5b6726a56665a8c684939ac62aa6cbf6daed7ebfc97d6bbf413","toolNames": ["remember","entity",@@ -7099,7 +7099,7 @@"name": "memory_recall","parameters": {"acting_user": "string?",- "max_chars": "number?",+ "max_chars": "integer?","query": "string"},"required_scopes": [],@@ -7110,8 +7110,8 @@"type": "string"},"max_chars": {- "description": "Text cap, 200-12000 (default 6000).",- "type": "number"+ "description": "Text cap in UTF-16 code units, 200-12000 (default 6000).",+ "type": "integer"},"query": {"description": "What the turn is about; ranks the facts.",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 848e8d4a02..33e6afe670 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6544,7 +6544,7 @@"items?: ParamDef | undefined","properties?: Record<string, ParamDef> | undefined","required?: boolean | undefined",- "type: \"string\" | \"number\" | \"boolean\" | \"object\" | \"array\""+ "type: \"string\" | \"number\" | \"boolean\" | \"object\" | \"integer\" | \"array\""],"name": "ParamDef"},diff --git a/test/mcp-tool-defs.test.ts b/test/mcp-tool-defs.test.tsindex e9863ae8de..82855ffd77 100644--- a/test/mcp-tool-defs.test.ts+++ b/test/mcp-tool-defs.test.ts@@ -28,7 +28,7 @@ import type { Operation, ParamDef } from '../src/core/operations.ts';// every existing operation, but new ops that add a default get it on the// wire automatically.type ParamDefLike = {- type: 'string' | 'number' | 'boolean' | 'object' | 'array';+ type: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array';description?: string;enum?: string[];default?: unknown;diff --git a/test/qm-memory-contract.test.ts b/test/qm-memory-contract.test.tsindex 71fcfcf440..8f80628ae1 100644--- a/test/qm-memory-contract.test.ts+++ b/test/qm-memory-contract.test.ts@@ -29,7 +29,13 @@ describe('QM memory-provider contract v1', () => {expect(fixture.transport).toMatchObject({ session: 'stateless', success_codes_in: 'structuredContent' });expect(fixture.unlinked_recall).toEqual({ isError: false, ...unlinkedRecallResult() });expect(fixture.unlinked_recall.structuredContent).toEqual({ facts: [], truncated: false, code: 'actor_unlinked' });- expect(fixture.memory_recall.limits.max_chars).toEqual({ min: 200, max: 12000, default: 6000, whole_number: true });+ expect(fixture.memory_recall.limits.max_chars).toEqual({ min: 200, max: 12000, default: 6000, whole_number: true, unit: 'UTF-16 code units (JavaScript string length)' });+ expect(fixture.tools.find((t: { name: string }) => t.name === 'memory_recall').input_schema.properties.max_chars.type).toBe('integer');+ expect(fixture.wave_2).toMatchObject({ audience_header: 'x-qm-audience', status: 'refused until wave 2', refusal: { code: 'actor_not_attested', reason: 'audience_not_supported' } });+ expect(fixture.actor.default_attest_ops).toEqual(['get_write_request', 'memory_recall', 'memory_write']);+ const codes = fixture.errors.codes.map((c: { code: string }) => c.code);+ expect(codes).not.toContain('rate_limited');+ for (const code of ['unavailable', 'unknown_tool', 'not_found', 'fact_not_found']) expect(codes).toContain(code);expect(fixture.memory_write.limits.facts).toEqual({ min: 1, max: 20 });expect(fixture.actor.deferred_ops).not.toContain('forget');expect(fixture.actor.deferred_ops).not.toContain('forget_fact');diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.tsindex 6503aa27b0..57d3908b9f 100644--- a/test/qm-memory-tools.test.ts+++ b/test/qm-memory-tools.test.ts@@ -32,7 +32,12 @@ import { __resetHotMemoryCacheForTests, getBrainHotMemoryMeta } from '../src/corimport { addMember, bindCredential } from '../src/core/access/members.ts';import { attestRightOf, linkedMember, linkMember } from '../src/core/access/actor.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { boundFactLines, memoryWriteRequestId, plainFactText, MEMORY_RECALL_MAX_CHARS } from '../src/core/ops/qm-memory.ts';+import { boundFactLines, isoDate, memoryWriteRequestId, plainFactText, MEMORY_RECALL_MAX_CHARS } from '../src/core/ops/qm-memory.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { startHttpTransport } from '../src/mcp/http-transport.ts';+import { RateLimiter } from '../src/mcp/rate-limit.ts';+import { BEHAVIOR_CHANGES } from '../src/core/behavior-change-notice.ts';+import { withTrustPromotion } from '../src/core/persistence/context.ts';import type { AuthInfo } from '../src/core/ops/contract.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -82,6 +87,33 @@ describe('memory_recall text bounds (pure)', () => {expect(plainFactText('#1 priority is the harbor')).toBe('#1 priority is the harbor');});+ test('every Unicode line break and control character becomes a space, so one fact is always one line', () => {+ const breaks = ['\u0085', '\u2028', '\u2029', '\u001b[31m', '\u0007', '\u009b', '\r', '\u000b', '\u000c', '\u007f', '\u0000'];+ for (const b of breaks) {+ const out = plainFactText('harbor' + b + '## ledger' + b + 'notes');+ expect(out).not.toMatch(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/);+ expect(out.startsWith('harbor ')).toBe(true);+ expect(out.endsWith('notes')).toBe(true);+ }+ expect(plainFactText('a\u2028## heading\u0085---\u0085b')).toBe('a heading b');+ });++ test('dates render from their own year, month and day: years 1-99 are never read as 19xx or 20xx', () => {+ expect(isoDate('0050-03-01 00:00:00+00')).toBe('0050-03-01');+ expect(isoDate('0005-06-07 12:00:00+00')).toBe('0005-06-07');+ const early = new Date(Date.UTC(2000, 0, 1));+ early.setUTCFullYear(50, 2, 1);+ expect(isoDate(early)).toBe('0050-03-01');+ expect(isoDate(new Date(Date.UTC(2026, 9, 30, 23, 59)))).toBe('2026-10-30');+ expect(isoDate(null)).toBe('undated');+ expect(isoDate('not a date')).toBe('undated');+ });++ test('the C1 behavior-change row no longer says forget and forget_fact are not attestable; the D row discloses the audience refusal', () => {+ expect(String(BEHAVIOR_CHANGES.find(r => r.id === 'qm_attested_actor_gst359')!.text)).not.toMatch(/forget/);+ expect(String(BEHAVIOR_CHANGES.find(r => r.id === 'qm_memory_provider_gst359')!.text)).toContain('audience_not_supported');+ });+test('a database failure while re-resolving a stored actor is rethrown, never read as unlinked or as no attest right', async () => {const failing = (code: string, message: string) => ({ executeRaw: async () => { throw Object.assign(new Error(message), { code }); } }) as never;const principal = { principal: { kind: 'oauth_client', id: 'c1' } } as never;@@ -117,7 +149,7 @@ for (const kind of testBackends()) {const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });const tokens: Record<string, string> = {};const verify = async (bearer: string) => await provider().verifyAccessToken(bearer) as unknown as AuthInfo;- type Who = { token: string; actor?: string };+ type Who = { token: string; actor?: string; audience?: string };const alice: Who = { token: 'qm', actor: ALICE_ID };const bob: Who = { token: 'qm', actor: BOB_ID };const carol: Who = { token: 'qm', actor: CAROL_ID };@@ -125,7 +157,7 @@ for (const kind of testBackends()) {async function call(as: Who, op: string, params: Record<string, unknown>, extra: { writeWaitMs?: number } = {}) {const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {remote: true, transport: 'http', auth: await verify(tokens[as.token]!), sourceId: SRC, takesHoldersAllowList: ['world'],- ...(as.actor !== undefined ? { actor: { header: as.actor } } : {}), ...extra,+ ...(as.actor !== undefined || as.audience !== undefined ? { actor: { header: as.actor, ...(as.audience !== undefined ? { audience: as.audience } : {}) } } : {}), ...extra,metaHook: (name, ctx) => getBrainHotMemoryMeta(name, ctx),});const text = out.content.map(c => c.text).join('\n');@@ -158,7 +190,15 @@ for (const kind of testBackends()) {const bobKey = await register('bob');await bindCredential(engine, { kind: 'client', id: bobKey.id }, { member: 'bob-example' });const plain = await register('plain');- for (const [name, c] of [['qm', qm], ['bob', bobKey], ['plain', plain]] as const) tokens[name] = (await provider().exchangeClientCredentials(c.id, c.secret)).access_token;+ const qmDefault = await register('qmdefault');+ await bindCredential(engine, { kind: 'client', id: qmDefault.id }, { attestActor: 'qm' });+ for (const [name, c] of [['qm', qm], ['bob', bobKey], ['plain', plain], ['qmdefault', qmDefault]] as const) tokens[name] = (await provider().exchangeClientCredentials(c.id, c.secret)).access_token;+ const legacy = await mintLegacyToken(engine, { name: 'qm-mem-legacy-' + randomUUID().slice(0, 8), scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC] });+ await bindCredential(engine, { kind: 'token', id: legacy.id }, { attestActor: 'qm', attestOps: ATTEST_OPS });+ tokens.legacy = legacy.token;+ const legacyRead = await mintLegacyToken(engine, { name: 'qm-mem-legacy-ro-' + randomUUID().slice(0, 8), scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });+ await bindCredential(engine, { kind: 'token', id: legacyRead.id }, { attestActor: 'qm', attestOps: ATTEST_OPS });+ tokens.legacyRead = legacyRead.token;await linkMember(engine, 'alice-example', 'qm', ALICE_ID);await linkMember(engine, 'bob-example', 'qm', BOB_ID);await linkMember(engine, 'carol-example', 'qm', CAROL_ID);@@ -387,6 +427,143 @@ for (const kind of testBackends()) {expect(await active(second.structured!.fact_ids[0])).toBe(false);}, 120_000);+ test('a request carrying x-qm-audience is refused before any work, with or without the actor header (wave 2 is not served yet)', async () => {+ const before = await factRows('canaryaudience');+ for (const as of [{ ...alice, audience: 'WyJVMEJPQiJd' }, { token: 'qm', audience: 'WyJVMEJPQiJd' }, { token: 'bob', audience: '' }, { token: 'plain', audience: 'x' }] as Who[]) {+ for (const [op, args] of [['memory_recall', { query: 'budget ledger' }], ['memory_write', { facts: [{ fact: 'Audience write canaryaudience', provenance: 'turn 1' }], idempotency_key: randomUUID() }],+ ['get_page', { slug: ACME }], ['forget', { id: '1' }]] as const) {+ const out = await call(as, op, args);+ expect({ op, isError: out.isError, code: out.json.code, reason: out.json.reason }).toEqual({ op, isError: true, code: 'actor_not_attested', reason: 'audience_not_supported' });+ expect(out.structured?.error).toMatchObject({ code: 'actor_not_attested', reason: 'audience_not_supported' });+ expect(out.all).not.toContain('canary');+ }+ }+ expect(await factRows('canaryaudience')).toEqual(before);+ }, 60_000);++ test('the legacy bearer transport refuses x-qm-audience on every method before any work, and its scope refusal of a memory tool carries structuredContent.error', async () => {+ const server = await startHttpTransport({ port: 0, engine, surface: 'full', limiters: {+ ip: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),+ token: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),+ } });+ try {+ const post = async (token: string, headers: Record<string, string>, body: Record<string, unknown>) => {+ const res = await fetch('http://127.0.0.1:' + server.port + '/mcp', {+ method: 'POST', headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json', ...headers },+ body: JSON.stringify({ jsonrpc: '2.0', id: 7, ...body }),+ });+ return await res.json() as { result?: Record<string, any>; error?: { code: number; message: string; data?: Record<string, unknown> } };+ };+ const recallCall = { method: 'tools/call', params: { name: 'memory_recall', arguments: { query: 'budget ledger' } } };+ for (const headers of [{ 'x-qm-actor': ALICE_ID, 'x-qm-audience': 'WyJVMEJPQiJd' }, { 'X-QM-Audience': 'WyJVMEJPQiJd' }] as Array<Record<string, string>>) {+ const called = await post(tokens.legacy!, headers, recallCall);+ expect(called.result!.isError).toBe(true);+ expect(called.result!.structuredContent.error).toMatchObject({ code: 'actor_not_attested', reason: 'audience_not_supported' });+ expect(JSON.stringify(called)).not.toContain('canary');+ for (const method of ['tools/list', 'resources/list', 'resources/read']) {+ const out = await post(tokens.legacy!, headers, { method, params: method === 'resources/read' ? { uri: 'gbrain://capabilities' } : {} });+ expect(out.result).toBeUndefined();+ expect(out.error!.data).toMatchObject({ code: 'actor_not_attested', reason: 'audience_not_supported' });+ }+ }+ expect(JSON.stringify(await post(tokens.legacy!, { 'x-qm-actor': ALICE_ID }, recallCall))).toContain('canary');+ const denied = await post(tokens.legacyRead!, { 'x-qm-actor': ALICE_ID }, { method: 'tools/call', params: { name: 'memory_write', arguments: { facts: [{ fact: 'x', provenance: 'y' }], idempotency_key: randomUUID() } } });+ expect(denied.result!.isError).toBe(true);+ expect(denied.result!.structuredContent.error).toMatchObject({ code: 'insufficient_scope' });+ } finally {+ server.stop(true);+ }+ }, 60_000);++ test('attested and member-bound forget judge ownership first: a fact off the caller\'s own member page is not_found and files no owner proposal', async () => {+ await engine.insertFact({ fact: 'Acme harbor charter is confirmed canaryconfirmed', kind: 'fact', entity_slug: ACME, source: 'test', visibility: 'world' }, { source_id: SRC });+ const [confirmed] = await factRows('canaryconfirmed');+ await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw("UPDATE facts SET trust_tier = 'user_confirmed' WHERE id = $1", [confirmed!.id])));+ const proposals = async () => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM trust_proposals'))[0]!.n);+ const start = await proposals();+ const a = await write(alice, [{ fact: 'Alice tends the harbor lamps canaryownforget', provenance: 'turn 20' }]);+ const bobOwn = await call({ token: 'bob' }, 'remember', { fact: 'Bob tends the harbor bell canarybobforget', provenance: 'turn 20' });+ expect(bobOwn.isError).toBe(false);+ const [bobRow] = await factRows('canarybobforget');+ expect(bobRow).toMatchObject({ visibility: 'private', source_markdown_slug: 'memory/members/bob-example' });+ for (const as of [alice, { token: 'bob' }] as Who[]) {+ for (const [op, id] of [['forget', String(confirmed!.id)], ['forget_fact', Number(confirmed!.id)]] as const) {+ const out = await call(as, op, { id });+ expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code: op === 'forget' ? 'not_found' : 'fact_not_found' });+ }+ }+ expect(await proposals()).toBe(start);+ const crossed = await call({ token: 'bob' }, 'forget', { id: a.structured!.fact_ids[0] });+ expect(crossed.json.code).toBe('not_found');+ const own = await call({ token: 'bob' }, 'forget', { id: String(bobRow!.id) });+ expect(own.isError).toBe(false);+ const active = async (id: unknown) => (await engine.executeRaw<{ expired_at: unknown }>('SELECT expired_at FROM facts WHERE id = $1', [Number(id)]))[0]?.expired_at === null;+ expect(await active(bobRow!.id)).toBe(false);+ expect(await active(a.structured!.fact_ids[0])).toBe(true);+ expect(await active(confirmed!.id)).toBe(true);+ }, 120_000);++ test('the default attested operations read the person\'s own write receipt; another person and the bare client get not_found', async () => {+ const qmd = (actor?: string): Who => ({ token: 'qmdefault', ...(actor ? { actor } : {}) });+ const out = await write(qmd(ALICE_ID), [{ fact: 'Alice books the night ferry canarydefaultreceipt', provenance: 'turn 21' }], randomUUID(), { writeWaitMs: 0 });+ expect(out.structured!.status).toBe('pending');+ const id = out.structured!.request_id;+ const own = await call(qmd(ALICE_ID), 'get_write_request', { request_id: id });+ expect(own.isError).toBe(false);+ expect(own.all).toContain(id);+ for (const as of [qmd(BOB_ID), qmd()]) {+ const other = await call(as, 'get_write_request', { request_id: id });+ expect({ isError: other.isError, code: other.json.code }).toEqual({ isError: true, code: 'not_found' });+ }+ }, 60_000);++ test('valid_from is a strict ISO date or time in years 0001-9999, checked for the whole batch before any write, so the key is never poisoned', async () => {+ const key = 'qm-poison-' + randomUUID();+ const good = { fact: 'Alice signs the harbor lease canarypoisongood', provenance: 'turn 22' };+ for (const valid_from of ['10000-01-01', '2026-02-30', 'March 3, 2026', '2026-10-30T25:00:00Z', '0000-01-01', '+010000-01-01T00:00:00Z', '2026-10-30 10:00', '20261030']) {+ const out = await write(alice, [good, { fact: 'Alice leaves canarypoisonbad', provenance: 'turn 22', valid_from }], key);+ expect({ valid_from, isError: out.isError, code: out.json.code }).toEqual({ valid_from, isError: true, code: 'invalid_params' });+ const viaRemember = await call({ token: 'bob' }, 'remember', { fact: 'Bob note canarypoisonremember', provenance: 'turn 22', valid_from });+ expect({ valid_from, code: viaRemember.json.code, message: viaRemember.json.message }).toEqual({ valid_from, code: 'invalid_params', message: expect.stringContaining('valid_from') });+ }+ expect(await factRows('canarypoison')).toHaveLength(0);+ const saved = await write(alice, [good], key);+ expect(saved.structured!.status).toBe('committed');+ for (const valid_from of ['0001-01-01', '9999-12-31', '2026-10-30T10:00:00Z', '2026-10-30T10:00:00.123+05:30', '2024-02-29']) {+ const ok = await write(alice, [{ fact: 'Valid date ' + valid_from + ' canaryvalidfrom', provenance: 'turn 23', valid_from }]);+ expect({ valid_from, status: ok.structured?.status ?? ok.text }).toEqual({ valid_from, status: 'committed' });+ }+ await write(alice, [{ fact: 'Alice found the old harbor stone canaryyearfifty', provenance: 'turn 24', valid_from: '0050-03-01' }]);+ const line = (await recall(alice, 'old harbor stone')).text.split('\n').find(l => l.includes('canaryyearfifty'));+ expect(line).toMatch(/\(0050-03-01; fact\)$/);+ }, 120_000);++ test('caller provenance with control characters or its own qm: prefix is refused, and duplicate facts in one call are one fact in the reply', async () => {+ for (const provenance of ['qm:U0EVE; turn 1', 'QM:U0EVE', ' qm:spoof', 'turn\u0000one', 'turn\u001b[2Jone', 'turn\u0085one', 'turn\u2028one', 'turn\none']) {+ const out = await write(alice, [{ fact: 'Provenance check canaryprov', provenance }]);+ expect({ provenance, code: out.json.code }).toEqual({ provenance, code: 'invalid_params' });+ }+ expect(await factRows('canaryprov')).toHaveLength(0);+ const dup = await write(alice, [{ fact: 'Alice repeats herself canarydup', provenance: 'turn 25' }, { fact: 'Alice repeats herself canarydup', provenance: 'turn 26' }]);+ expect(dup.structured!.status).toBe('committed');+ expect(dup.structured!.fact_ids).toHaveLength(1);+ expect(dup.out.content).toEqual([{ type: 'text', text: 'Saved 1 fact(s).' }]);+ expect(await factRows('canarydup')).toHaveLength(1);+ }, 60_000);++ test('an unlinked person\'s recall still validates its arguments first, and a surface-hidden memory tool refuses with structuredContent.error', async () => {+ const nobody: Who = { token: 'qm', actor: 'U0NOBODY' };+ for (const args of [{ query: 'harbor', max_chars: 5 }, { query: 'harbor', max_chars: 200.5 }, { max_chars: 400 }, { query: 7 }]) {+ const out = await call(nobody, 'memory_recall', args);+ expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code: 'invalid_params' });+ expect(out.structured?.error).toMatchObject({ code: 'invalid_params' });+ }+ const hidden: ToolResult = await dispatchToolCall(engine, 'memory_recall', { query: 'harbor' }, {+ remote: true, transport: 'http', auth: await verify(tokens.qm!), sourceId: SRC, actor: { header: ALICE_ID }, allowedOps: new Set(['get_page']) });+ expect(hidden.isError).toBe(true);+ expect((hidden.structuredContent as { error: { code: string } }).error.code).toBe('unknown_tool');+ }, 60_000);+test('a keyless brain ranks by keyword and makes no embedding call', async () => {let embedCalls = 0;try {