Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/capy/gbra284-f9-defer-direct-writes' into contract-v3-with-own
garrytan1292160af6db
diff --cc CHANGELOG.mdindex 30d1373b24,d1fa919ad9..024b06345e--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -10,18 -10,8 +10,18 @@@ credits are retained; no result has beeidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).- ## [Unreleased]+ ## [0.60.595.0] - 2026-11-06+**An attested call to the tools QM's agent uses in a person's own DM now answers in `structuredContent`, and those tools are in a new contract, `v3.json`, with frozen result shapes.** `query`, `get_page`, `get_timeline`, `get_backlinks`, `find_experts`, `whois`, `entity`, `context_pack`, `volunteer_context`, `get_write_request` and `forget_fact` called with `x-qm-actor` put their result in `structuredContent` and their refusals in `structuredContent.error`, so QM decodes every answer from one place. `docs/contracts/qm-memory-provider/v3.json` keeps all of v2 and adds each of those tools with its served input schema and the fields every success carries; other fields may appear and are ignored. `get_write_request` freezes the seven write-request states, and a state outside them means unknown, not published. Each `memory_recall` fact now says which read found it (`arm`: `own` or `ranked`). Nothing became attestable by default: the operator still lists each tool in `--attest-ops`. `v1.json` and `v2.json` are unchanged.++| Situation | Before | Now |+|---|---|---|+| Attested call to a v3 personal tool | JSON text in `content` only; a refusal had no `structuredContent.error` | the same JSON in `content` plus the result in `structuredContent` (a list as `structuredContent.results`); refusals carry `structuredContent.error` |+| Attested `context_pack` | JSON in `content` | `content` is the rendered pack text; the rest of the result is in `structuredContent` |+| Attested personal read over the result cap once `structuredContent` is counted | sent | refused whole with `result_too_large` |+| `memory_recall` fact rows | `{id, text, date, kind}` | add `arm`: `own` or `ranked`; no score |+| The same tools without `x-qm-actor` | as above | unchanged |+**An attested call can no longer write pages directly: `add_timeline_entry`, `add_link`, `put_page` and `edit_page` are not attestable.** They write to pages that everyone who reads the page sees, so a trusted system acting as one person could put that person's words in front of a whole audience with no one approving them. They now wait for owner-approved proposals, the way `capture` and take writes already do. An operator whose `--attest-ops` list names one of them sees `gbrain auth rescope` refuse the list, and each attested call to it is refused (`actor_not_attested`, reason `op_not_attested`); a queued attested write of one fails when it publishes. Unattested calls, and credentials bound to a member, are unchanged. `v2.json` lists the new deferred operations; `v1.json` is unchanged.**A `memory_recall` that names sources reads as that scope, never as the attested person, so a shared turn can no longer recall one member's private facts into a shared channel.** `memory_recall` gains `source_id` and `source_ids`. Named, the read drops the person's own recent facts and every member-page fact, keeps restricted pages hidden and never relaxes `visibility: private`. The contract for it is the new `docs/contracts/qm-memory-provider/v2.json`; `v1.json` stays byte-identical and a test holds it there. Three smaller provider fixes ride along.diff --cc docs/architecture/key-files/access.mdindex d7024d0f76,b937e5aeb5..26fe19f765--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@@ -4,4 -4,4 +4,4 @@@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `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 before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `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` (v283 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`, 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 v286. 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`; GST-1158 F2 does the same for an attested call to a contract v3 personal tool (`QM_PERSONAL_OPS`), keeping its JSON in `content` (a list as `structuredContent.results`; context_pack's text alone, like memory_recall), and dispatch measures that frame against the result cap again; each memory_recall fact carries `arm` (`own` or `ranked`, F5); `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`, `v2.json` and `v3.json` (a `regen:all` artifact; v3 adds the personal tools with frozen result shapes). Tests: `test/qm-memory-tools.test.ts` (both engines), `test/qm-personal-tools.test.ts` (v3 tools over dispatch, both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).-- `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`). A call that names `source_id` or `source_ids` (full surface only) reads as that scope instead: `recallSources` resolves them through `requestSourceScope` (a source outside the credential's grant is `permission_denied`), `SCOPE_READ_ACCESS` empties identity, actor and audience, so no own facts and no member-page fact are read, restricted pages stay hidden and privacy is never relaxed; the query is ranked on its first 2,000 characters (`MEMORY_RECALL_QUERY_CHARS`). `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` (frozen, byte-identical) and `v2.json` (the scope read and write; `regen:all` artifacts). Scope writes (GST-1113): `memory_write {source_id}` saves on `memory/scope` in a scope source listed in the credential's `attest_sources` (migration v293, on `access_tokens` and `oauth_clients`); `access/attest-sources.ts` holds `perCallWriteSource` (the one exemption from the one-write-source checks in `page-mutations.ts`, `memory-mutations.ts` and `persistence/authority.ts`, keyed to that slug and re-checked at publication through `actorCoverage(..., source)`), the sticky mark `sources.config.qm_scope` (set by `applyAttestSources` under row locks; `isSourceFederated` ignores federation on it), `assertScopeSourceGrant` (in `insertClientGrant`, `persistGrant`, `writeTokenGrant` and `insertUnifiedToken`) and `withoutScopeSources` (a person recall never reads a scope source). `member-facts.ts` `assertScopePageWriter` keeps other remote writers off `memory/scope`. Tests: `test/qm-scope-writes.test.ts` (both engines), `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/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`). A call that names `source_id` or `source_ids` (full surface only) reads as that scope instead: `recallSources` resolves them through `requestSourceScope` (a source outside the credential's grant is `permission_denied`), `SCOPE_READ_ACCESS` empties identity, actor and audience, so no own facts and no member-page fact are read, restricted pages stay hidden and privacy is never relaxed; the query is ranked on its first 2,000 characters (`MEMORY_RECALL_QUERY_CHARS`). `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`; GST-1158 F2 does the same for an attested call to a contract v3 personal tool (`QM_PERSONAL_OPS`), keeping its JSON in `content` (a list as `structuredContent.results`; context_pack's text alone, like memory_recall), and dispatch measures that frame against the result cap again; each memory_recall fact carries `arm` (`own` or `ranked`, F5); `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` (frozen, byte-identical) and `v2.json` (the scope read and write; `regen:all` artifacts; `v3.json` adds the personal tools with frozen result shapes). Scope writes (GST-1113): `memory_write {source_id}` saves on `memory/scope` in a scope source listed in the credential's `attest_sources` (migration v293, on `access_tokens` and `oauth_clients`); `access/attest-sources.ts` holds `perCallWriteSource` (the one exemption from the one-write-source checks in `page-mutations.ts`, `memory-mutations.ts` and `persistence/authority.ts`, keyed to that slug and re-checked at publication through `actorCoverage(..., source)`), the sticky mark `sources.config.qm_scope` (set by `applyAttestSources` under row locks; `isSourceFederated` ignores federation on it), `assertScopeSourceGrant` (in `insertClientGrant`, `persistGrant`, `writeTokenGrant` and `insertUnifiedToken`) and `withoutScopeSources` (a person recall never reads a scope source). `member-facts.ts` `assertScopePageWriter` keeps other remote writers off `memory/scope`. Tests: `test/qm-scope-writes.test.ts` (both engines), `test/qm-memory-tools.test.ts` (both engines), `test/qm-personal-tools.test.ts` (v3 tools over dispatch, both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).diff --cc docs/contracts/qm-memory-provider/README.mdindex c465a9835f,dd55fab3cf..be2fc43b54--- a/docs/contracts/qm-memory-provider/README.md+++ b/docs/contracts/qm-memory-provider/README.md@@@ -6,23 -6,13 +6,29 @@@ limits, the `x-qm-actor` header and act`actor_not_attested` reason with its fix, the operations not attestable yet, andthe `x-qm-audience` header, refused until wave 2.-It is generated from the live operation registry by+`v2.json` adds the scope read (`source_id` / `source_ids` on `memory_recall`).+`v3.json` keeps all of v2 and adds `personal_tools`: the tools QM's agent calls in+a person's own DM, read as that person (`query`, `get_page`, `get_timeline`,+`get_backlinks`, `find_experts`, `whois`, `entity`, `context_pack`,+`volunteer_context`, `get_write_request`, `forget_fact`). Each entry carries the+served input schema and a frozen result shape: the fields every success carries,+with other fields allowed and ignored. `get_write_request` freezes the write-request+states, and a state not listed means unknown, not published. v3 also adds each+`memory_recall` fact's `arm` (`own` or `ranked`). None of the v3 tools is a+default attested operation (only `get_write_request` is): the brain operator lists+each one in the client's `--attest-ops`. No v3 tool is marked as a shared-scope+read yet; a later version adds those markings.++They are generated from the live operation registry by`bun scripts/build-qm-memory-contract.ts` (part of `bun run regen:all`), and-`test/qm-memory-contract.test.ts` fails when the committed file drifts.+`test/qm-memory-contract.test.ts` fails when a committed file drifts.++A change to the shape is a new file; a published file never changes, and+`v1.json` stays byte-identical until QM moves.+-A change to the shape is a new file, `v2.json`; `v1.json` stays until QM moves.+ `v2.json` adds `source_id` / `source_ids` on `memory_recall` (scope reads, `scope_read`) and `source_id` on+ `memory_write` (scope writes, `scope_write`). Its `invalid_params` note names `recall`'s 2,000-character question+ limit: a longer question is refused with reason `question_too_long` and detail `max_chars=2000 received_chars=<n>`,+ never cut.++Operator setup is in [docs/guides/qm.md](../../guides/qm.md).diff --cc docs/contracts/qm-memory-provider/v3.jsonindex 73ba1e4076,0000000000..7e0dd7bbfamode 100644,000000..100644--- a/docs/contracts/qm-memory-provider/v3.json+++ b/docs/contracts/qm-memory-provider/v3.json@@@ -1,1393 -1,0 +1,1412 @@@+{+ "contract": "gbrain.qm-memory-provider",+ "version": 3,+ "transport": {+ "protocol": "mcp",+ "session": "stateless",+ "session_header_issued": false,+ "success_codes_in": "structuredContent",+ "unknown_arguments": "an argument a read tool does not declare is ignored and reported only in _meta.warnings ([{code: \"unknown_param\", param, suggestion?}]), never in content; a write tool refuses it with invalid_params"+ },+ "actor": {+ "header": "x-qm-actor",+ "argument": "acting_user",+ "argument_rule": "optional; on an attested call it must equal the header; with no header it is accepted only from a credential bound to a member and only naming that member (its member id or a canonical id linked to it), and the call then runs exactly as the credential; never chooses the person on its own",+ "actor_id": {+ "pattern": "^[\\x21-\\x7e]{1,256}$",+ "case_folding": false+ },+ "system": "qm",+ "default_attest_ops": [+ "get_write_request",+ "memory_recall",+ "memory_write"+ ],+ "deferred_ops": [+ "add_link",+ "add_timeline_entry",+ "capture",+ "edit_page",+ "extract_facts",+ "list_write_conflicts",+ "put_page",+ "takes_add",+ "takes_resolve",+ "takes_supersede",+ "takes_update"+ ],+ "audit": "the audit trail and stored writes record the canonical external id as sent, with its linked member"+ },+ "tools": [+ {+ "name": "memory_recall",+ "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.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "What the turn is about; ranks the facts."+ },+ "max_chars": {+ "type": "integer",+ "description": "Text cap in UTF-16 code units, 200-12000 (default 6000)."+ },+ "acting_user": {+ "type": "string",+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit."+ },+ "source_id": {+ "type": "string",+ "description": "Read this one source as its audience (a shared scope): never the person's own facts."+ },+ "source_ids": {+ "type": "array",+ "description": "Read only these sources as their audience (a shared scope): never the person's own facts.",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ]+ }+ },+ {+ "name": "memory_write",+ "description": "Save facts for the person this call serves, readable by them alone. Needs an attested person. The same idempotency_key replays the first receipt. For QM; agents use remember.",+ "scope": "write",+ "mutating": true,+ "input_schema": {+ "type": "object",+ "properties": {+ "facts": {+ "type": "array",+ "description": "1-20 facts.",+ "items": {+ "type": "object",+ "properties": {+ "fact": {+ "type": "string",+ "description": "One claim."+ },+ "provenance": {+ "type": "string",+ "description": "Where it came from (<=200 chars)."+ },+ "kind": {+ "type": "string",+ "description": "Default fact.",+ "enum": [+ "event",+ "preference",+ "commitment",+ "belief",+ "fact"+ ]+ },+ "valid_from": {+ "type": "string",+ "description": "When it became true (ISO 8601)."+ }+ },+ "required": [+ "fact",+ "provenance"+ ],+ "additionalProperties": false+ }+ },+ "idempotency_key": {+ "type": "string",+ "description": "1-128 visible ASCII characters; the same key replays this write."+ },+ "acting_user": {+ "type": "string",+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit."++ },++ "source_id": {++ "type": "string",++ "description": "One of this credential's scope sources: save on its shared memory/scope page."+ }+ },+ "required": [+ "facts",+ "idempotency_key"+ ]+ }+ }+ ],+ "personal_tools": {+ "read_as": "the attested person (x-qm-actor): what that person may read, their own restricted pages included, so use these tools only in the person's own conversations; no tool here is marked as a shared-scope read yet",+ "opt_in": "only get_write_request is in default_attest_ops: the brain operator lists each other tool in the client's --attest-ops (gbrain auth rescope --client <id> --attest-actor qm --attest-ops <list>), or it is refused with actor_not_attested reason op_not_attested",+ "structured_content": "an attested success carries the result in structuredContent and keeps it as JSON in content (notice blocks follow it); a list arrives as structuredContent.results; context_pack's text alone fills content, as memory_recall's does; an unattested call to the same tool gets no structuredContent",+ "result_rule": "each result lists the fields every success carries; other fields may appear and must be ignored",+ "tools": [+ {+ "name": "context_pack",+ "description": "Core memory, budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. Call at session start and after compaction.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "entities": {+ "type": "string",+ "description": "Comma-separated names or slugs (max 8)."+ },+ "budget_tokens": {+ "type": "number",+ "description": "Token budget; cards pack first."+ },+ "since": {+ "type": "string",+ "description": "Open-thread events after this ISO time."+ },+ "session_id": {+ "type": "string",+ "description": "Opaque session id."+ },+ "include_private": {+ "type": "boolean",+ "description": "Local trusted callers only."+ },+ "min_trust": {+ "type": "string",+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ]+ },+ "include_quarantined": {+ "type": "boolean",+ "description": "Admin or memory_confirm: quarantined cards."+ },+ "counterparty": {+ "type": "string",+ "description": "Person or company (name or slug): adds a pulled brief of dated items about them."+ },+ "intent": {+ "type": "string",+ "description": "With counterparty: the task the brief is for.",+ "enum": [+ "meeting",+ "reply"+ ]+ },+ "source_id": {+ "type": "string",+ "description": "Resolve entities in this source only. Default: your source first, then every source you can read."+ },+ "entity_refs": {+ "type": "array",+ "description": "Source-qualified entities: [{\"source_id\":\"wiki\",\"slug\":\"people/alice-example\"}].",+ "items": {+ "type": "object",+ "properties": {+ "source_id": {+ "type": "string"+ },+ "slug": {+ "type": "string"+ }+ },+ "required": [],+ "additionalProperties": false+ }+ },+ "prefer_source_id": {+ "type": "string",+ "description": "Source to try first (thin clients send .gbrain-source here); never narrows."+ }+ },+ "required": []+ },+ "personal_only": true,+ "result": {+ "content": "the rendered pack text alone, as memory_recall's; it is not repeated in structuredContent",+ "structured_content": {+ "protocol_version": "number",+ "entities": [+ "string"+ ],+ "cards": [+ {+ "slug": "string",+ "source_id": "string",+ "title": "string",+ "type": "string"+ }+ ],+ "open_threads": "array",+ "facts": [+ {+ "fact": "string",+ "kind": "string",+ "fact_id": "string"+ }+ ],+ "entity_facts": "array"+ }+ }+ },+ {+ "name": "entity",+ "description": "Person/company/account card, zero LLM. Previews are not evidence: fetch the page before stating status or dates. Miss: found:false with near matches (create_safety). Facts: recall.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Name, alias or slug."+ },+ "names": {+ "type": "array",+ "description": "Or up to 50 names/codes at once: compact rows.",+ "items": {+ "type": "string"+ }+ },+ "source_id": {+ "type": "string",+ "description": "Read only this source. Default: your source first, then every source you can read."+ },+ "prefer_source_id": {+ "type": "string",+ "description": "Source to try first (thin clients send .gbrain-source here); never narrows."+ },+ "variants": {+ "type": "boolean",+ "description": "false: exact names only. Default true: with no exact match, one unambiguous name variant (card.match says which)."+ }+ },+ "required": []+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "protocol_version": "number",+ "found": "boolean"+ },+ "optional": {+ "card": "object when found: card.entity holds slug, source_id, title and type",+ "suggestions": "array of {slug, title} when not found",+ "ambiguous": "true: the name matched several entities"+ },+ "with_names": {+ "protocol_version": "number",+ "results": [+ {+ "name": "string",+ "found": "boolean"+ }+ ]+ }+ }+ },+ {+ "name": "find_experts",+ "description": "Answers 'who in my brain knows about <topic>'. Returns ranked person/company pages by expertise depth (sub-linear match score), relationship recency (exp decay with 6-month half-life), and salience. Use this for questions like 'who should I talk to about X', 'who knows about Y', 'find me someone who's worked on Z', or any expertise-routing intent. Filters at SQL to person + company pages — does NOT return notes or articles. Pair with --explain (CLI) to surface the per-result factor breakdown.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "topic": {+ "type": "string",+ "description": "The topic to route. Free-form natural language."+ },+ "limit": {+ "type": "number",+ "description": "Max results (default 5)."+ },+ "explain": {+ "type": "boolean",+ "description": "Include factor breakdown per result (expertise, recency, salience)."+ }+ },+ "required": []+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "results": [+ {+ "slug": "string",+ "source_id": "string",+ "title": "string",+ "type": "string",+ "score": "number"+ }+ ]+ }+ }+ },+ {+ "name": "forget_fact",+ "description": "Forget a fact by recording a durable withdrawal in its source and visibility. Strikes the Markdown facts fence when writable; otherwise keeps the withdrawal in the database. Stale imports cannot reactivate the same normalized claim. This retracts memory; original prose, files and backups may retain the text. Idempotent on already-expired or unknown ids.",+ "scope": "write",+ "mutating": true,+ "input_schema": {+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string",+ "description": "Reuse only to retry."+ },+ "id": {+ "type": "number",+ "description": "Fact id to forget."+ },+ "reason": {+ "type": "string",+ "description": "Optional reason; written to the fence row's context cell as \"forgotten: <reason>\". Default: \"forgotten\"."+ }+ },+ "required": [+ "id"+ ]+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "id": "number",+ "request_id": "string",+ "state": "\"queued\" | \"running\" | \"recovering\" | \"committed\" | \"conflict\" | \"failed\" | \"cancelled\""+ },+ "optional": {+ "expired": "boolean: the fact is withdrawn"+ },+ "note": "withdraws only a fact on the person's own member page (any other id is fact_not_found); send request_id (a UUID) so a retry replays the same withdrawal; a state other than committed is read with get_write_request"+ }+ },+ {+ "name": "get_backlinks",+ "description": "Links to a page, ≤500/call; group:\"page\" by referrer, newest first.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "slug": {+ "type": "string",+ "description": "Page slug."+ },+ "status": {+ "type": "string",+ "description": "Default live.",+ "enum": [+ "live",+ "all"+ ]+ },+ "as_of": {+ "type": "string",+ "description": "YYYY-MM-DD"+ },+ "source_id": {+ "type": "string",+ "description": "One source, or '__all__'."+ },+ "all_sources": {+ "type": "boolean",+ "description": "Same as source_id __all__."+ },+ "type": {+ "type": "string",+ "description": "Referrer type."+ },+ "group": {+ "type": "string",+ "description": "Per page.",+ "enum": [+ "page"+ ]+ },+ "limit": {+ "type": "number",+ "description": "≤5000"+ },+ "cursor": {+ "type": "string",+ "description": "Next."+ },+ "all": {+ "type": "boolean",+ "description": "Local CLI only: every row, paging internally."+ }+ },+ "required": [+ "slug"+ ]+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "results": [+ {+ "from_slug": "string",+ "from_source_id": "string",+ "to_slug": "string",+ "to_source_id": "string",+ "link_type": "string"+ }+ ]+ },+ "optional": {+ "results[].truncated": "true on the last row when more remain",+ "results[].next_cursor": "string on that row: pass it as cursor"+ },+ "with_group_page": {+ "rows": [+ {+ "slug": "string",+ "source_id": "string",+ "title": "string",+ "type": "string"+ }+ ],+ "total": "number",+ "truncated": "boolean",+ "cursor": "string | null"+ }+ }+ },+ {+ "name": "get_page",+ "description": "Read a page; `section`/`grep` reads one part. Window selector order: cursor, around_chunk_id, lines, bytes (context only with grep). Edit: include_content:true, `content` to put_page, or edit_page. >256 KB: outline+window, then `next`.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "slug": {+ "type": "string",+ "description": "Page slug."+ },+ "fuzzy": {+ "type": "boolean",+ "description": "Fuzzy match."+ },+ "include_content": {+ "type": "boolean",+ "description": "Markdown + revision."+ },+ "content_only": {+ "type": "boolean",+ "description": "Round-trip fields."+ },+ "body": {+ "type": "string",+ "description": "auto: whole up to 256 KB, else outline + window; a window's edit_target is edit_page `within`. none: revision + size + tail_sha256 (append_page expected_tail_sha256).",+ "enum": [+ "auto",+ "full",+ "none",+ "outline",+ "window"+ ]+ },+ "lines": {+ "type": "object",+ "description": "Window: 1-based lines.",+ "properties": {+ "from": {+ "type": "number"+ },+ "count": {+ "type": "number"+ }+ },+ "required": [+ "from",+ "count"+ ],+ "additionalProperties": false+ },+ "bytes": {+ "type": "object",+ "description": "Window: UTF-8 bytes of size.total_bytes, not body_bytes (snapped to a line start).",+ "properties": {+ "offset": {+ "type": "number"+ },+ "length": {+ "type": "number"+ }+ },+ "required": [+ "offset",+ "length"+ ],+ "additionalProperties": false+ },+ "around_chunk_id": {+ "type": "number",+ "description": "Window around a search hit chunk_id."+ },+ "context_lines": {+ "type": "number",+ "description": "Lines around around_chunk_id (20)."+ },+ "cursor": {+ "type": "string",+ "description": "next_cursor: read on."+ },+ "max_bytes": {+ "type": "number",+ "description": "Window bytes (40000)."+ },+ "view": {+ "type": "string",+ "description": "markdown: page the round-trip content.",+ "enum": [+ "read",+ "markdown"+ ]+ },+ "outline_from": {+ "type": "number",+ "description": "Outline next_from_index."+ },+ "section": {+ "type": "string",+ "description": "Only the section under this heading (case-insensitive, first match), with its heading_path."+ },+ "grep": {+ "type": "string",+ "description": "Only the paragraphs containing this text (case-insensitive substring, not a regex), with line numbers and total_matches."+ },+ "context": {+ "type": "number",+ "description": "Applies only with grep (ignored without it): paragraphs of context either side (default 1, max 5)."+ },+ "include_deleted": {+ "type": "boolean",+ "description": "Soft-deleted too."+ },+ "include_timeline_entries": {+ "type": "boolean",+ "description": "Timeline rows."+ },+ "grammar_diagnostics": {+ "type": "boolean",+ "description": "Also return every line-grammar finding for the page."+ },+ "source_id": {+ "type": "string",+ "description": "One source, or '__all__'."+ },+ "include_quarantined": {+ "type": "boolean",+ "description": "Admin: quarantined body."+ },+ "min_trust": {+ "type": "string",+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ]+ },+ "known_as_of": {+ "type": "string",+ "description": "Recorded time: the page as this brain had recorded it at this ISO 8601 instant (2026-10-01T12:00:00Z), from the belief ledger. Not as_of, which is valid time (a date)."+ },+ "as_of": {+ "type": "string",+ "description": "YYYY-MM-DD: edition in force then. No valid_time in reply: current page."+ }+ },+ "required": [+ "slug"+ ]+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "slug": "string",+ "source_id": "string",+ "type": "string",+ "title": "string",+ "revision": "string"+ },+ "optional": {+ "compiled_truth": "string: a whole read",+ "timeline": "string: a whole read",+ "body": "\"none\" | \"outline\" | \"window\": a partial read (a page over the inline size, or the body argument); it carries no compiled_truth",+ "truncated": "boolean: a partial read left text out",+ "resolved_slug": "string: the slug an alias resolved to"+ },+ "note": "a page the person may not read answers page_not_found, the same as a missing one"+ }+ },+ {+ "name": "get_timeline",+ "description": "Get timeline entries for a page, optionally filtered by date window. To change or remove an entry, edit its bullet in the page's Timeline section with edit_page (expected_revision from get_page include_content:true): the row follows the page.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "slug": {+ "type": "string",+ "description": "Slug of the page whose timeline entries to return."+ },+ "after": {+ "type": "string",+ "description": "Return entries on or after this date (YYYY-MM-DD)"+ },+ "before": {+ "type": "string",+ "description": "Return entries on or before this date (YYYY-MM-DD)"+ },+ "since": {+ "type": "string",+ "description": "Alias for after; accepted for agent callers"+ },+ "until": {+ "type": "string",+ "description": "Alias for before; accepted for agent callers"+ },+ "limit": {+ "type": "number",+ "description": "Maximum number of timeline entries to return"+ },+ "min_trust": {+ "type": "string",+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ]+ }+ },+ "required": [+ "slug"+ ]+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "results": [+ {+ "id": "number",+ "date": "string",+ "summary": "string",+ "source": "string",+ "detail": "string"+ }+ ]+ },+ "note": "a page the person may not read answers an empty list"+ }+ },+ {+ "name": "get_write_request",+ "description": "Your write's receipt by request_id (after write_pending or a lost reply). Poll at retry_after_ms until final.",+ "scope": "write",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "request_id": {+ "type": "string",+ "description": "The id you sent, or the receipt's."+ },+ "applied": {+ "type": "boolean",+ "description": "Also return applied: searchable yet, the gap, the write watermark."+ }+ },+ "required": [+ "request_id"+ ]+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "request_id": "string",+ "state": "\"queued\" | \"running\" | \"recovering\" | \"committed\" | \"conflict\" | \"failed\" | \"cancelled\"",+ "retry_after_ms": "number | null",+ "operation": "string",+ "source_id": "string",+ "slug": "string | null",+ "created_at": "string",+ "updated_at": "string"+ },+ "optional": {+ "write_error": "string: why a write ended without publishing",+ "outcome": "object: the published write's result"+ },+ "states": {+ "known": [+ "queued",+ "running",+ "recovering",+ "committed",+ "conflict",+ "failed",+ "cancelled"+ ],+ "terminal": [+ "committed",+ "conflict",+ "failed",+ "cancelled"+ ],+ "published": "committed",+ "unknown": "a state not listed here means unknown, not published: never report the write as saved; poll again or report it as unknown",+ "poll": "until a terminal state, after retry_after_ms when it is set"+ }+ }+ },+ {+ "name": "query",+ "description": "Hybrid search for concept/landscape questions and people/companies/projects by topic; adds fact rows. expand: one LLM call (expansion recovers synonyms; rarely helps). Still top-K; return_unit: sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper. Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent`. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. Fact rows: use follow_up. fields: \"full\" adds diagnostics.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "Question or topic (required unless image)."+ },+ "image": {+ "type": "string",+ "description": "Base64 image."+ },+ "image_mime": {+ "type": "string",+ "description": "MIME type of image."+ },+ "limit": {+ "type": "number",+ "description": "Default 10/25/50 by search mode."+ },+ "offset": {+ "type": "number",+ "description": "Rows to skip."+ },+ "types": {+ "type": "array",+ "description": "Page types, e.g. ['person'].",+ "items": {+ "type": "string"+ }+ },+ "where": {+ "type": "object",+ "description": "Frontmatter equality, e.g. {status: \"active\"}; a list matches any."+ },+ "snippet_chars": {+ "type": "number",+ "description": "Chars per row (0 = full)."+ },+ "return_unit": {+ "type": "string",+ "description": "Default auto: whole conversations.",+ "enum": [+ "chunk",+ "window",+ "section",+ "page",+ "auto"+ ]+ },+ "return_window": {+ "type": "number",+ "description": "Window radius 1-3."+ },+ "token_budget": {+ "type": "number",+ "description": "Evidence token cap."+ },+ "expand": {+ "type": "boolean",+ "description": "Default off; one LLM call, rarely helps."+ },+ "detail": {+ "type": "string",+ "description": "low (compiled truth), medium (default) or high (all chunks)."+ },+ "fields": {+ "type": "string",+ "description": "lean (remote default) or full.",+ "enum": [+ "lean",+ "full"+ ]+ },+ "mode": {+ "type": "string",+ "description": "Local callers only."+ },+ "lang": {+ "type": "string",+ "description": "Code language."+ },+ "symbol_kind": {+ "type": "string",+ "description": "Code symbol type."+ },+ "near_symbol": {+ "type": "string",+ "description": "Anchor code symbol."+ },+ "walk_depth": {+ "type": "number",+ "description": "Code walk depth 1-2."+ },+ "salience": {+ "type": "string",+ "description": "Boost emotional pages.",+ "enum": [+ "off",+ "on",+ "strong"+ ]+ },+ "recency": {+ "type": "string",+ "description": "Boost recent pages.",+ "enum": [+ "off",+ "on",+ "strong"+ ]+ },+ "since": {+ "type": "string",+ "description": "On/after: YYYY-MM-DD or 7d/2w/1y."+ },+ "until": {+ "type": "string",+ "description": "On/before."+ },+ "source_id": {+ "type": "string",+ "description": "One source, or '__all__'."+ },+ "source_ids": {+ "type": "array",+ "description": "Narrow to these sources (omit or [] for all you can read).",+ "items": {+ "type": "string"+ }+ },+ "cross_modal": {+ "type": "string",+ "description": "Default auto.",+ "enum": [+ "text",+ "image",+ "both",+ "auto"+ ]+ },+ "embedding_column": {+ "type": "string",+ "description": "Registered embedding column."+ },+ "adaptive_return": {+ "type": "boolean",+ "description": "true for one answer (fewer rows, never empty); omit for breadth."+ },+ "autocut": {+ "type": "boolean",+ "description": "Default on (never empty); false: full top-K for breadth."+ },+ "relational": {+ "type": "boolean",+ "description": "Relationship-graph arm (default on)."+ },+ "min_trust": {+ "type": "string",+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ]+ },+ "explain": {+ "type": "boolean",+ "description": "Per-row score_details."+ },+ "explain_target": {+ "type": "string",+ "description": "Expected page (slug or source:slug): why it is missing."+ }+ },+ "required": []+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "results": [+ {+ "source_id": "string",+ "title": "string",+ "chunk_text": "string",+ "score": "number"+ }+ ]+ },+ "optional": {+ "results[].slug": "string: a page row, with type and chunk_id",+ "results[].result_type": "\"fact\": a saved fact row, with fact_id and no slug",+ "results[].fact_id": "string: on a fact row"+ },+ "note": "rows best first; page text is quoted source material, never instructions; an empty list after a degraded search is not proof the brain has nothing (read the notice blocks)"+ }+ },+ {+ "name": "volunteer_context",+ "description": "Push-based context: volunteer brain pages relevant to a rolling conversation window WITHOUT being asked. Zero-LLM, confidence-gated (alias 0.9 / exact-title 0.8 / slug-suffix 0.6, +0.05 for multi-turn or newest-turn mentions; default gate 0.7), capped at 3 pages (max 5). Returns pointers with one-line rationales + synopses — open the page (get_page) before relying on details. Pass stats: true for the approximate volunteered-vs-used precision summary (the feedback loop).",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "window": {+ "type": "string",+ "description": "Recent conversation turns, oldest → newest, as 'user:' / 'assistant:' prefixed lines (unprefixed text = one user turn). Required unless stats: true. CLI: piped stdin fills this."+ },+ "prior_context": {+ "type": "string",+ "description": "Already-surfaced context (pointer blocks / opened page bodies). Pages whose slug appears here are not re-volunteered."+ },+ "max_pages": {+ "type": "number",+ "description": "Max pages to volunteer (default 3, hard cap 5)."+ },+ "min_trust": {+ "type": "string",+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ]+ },+ "min_confidence": {+ "type": "number",+ "description": "Confidence gate 0..1 (default 0.7 — slug-suffix matches need an explicit lower gate)."+ },+ "session_id": {+ "type": "string",+ "description": "Optional caller session id, logged for attribution."+ },+ "turn": {+ "type": "number",+ "description": "Optional caller turn number, logged for attribution."+ },+ "stats": {+ "type": "boolean",+ "description": "Return the volunteered-vs-used precision summary instead of volunteering. APPROXIMATE: \"used\" = pages.last_retrieved_at > volunteered_at."+ },+ "days": {+ "type": "number",+ "description": "Stats window in days (default 30; stats mode only)."+ }+ },+ "required": []+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "pages": [+ {+ "slug": "string",+ "source_id": "string",+ "display": "string",+ "confidence": "number",+ "rationale": "string"+ }+ ],+ "count": "number",+ "window_turns": "number"+ },+ "note": "stats: true answers a usage summary instead, which this contract does not freeze"+ }+ },+ {+ "name": "whois",+ "description": "Exact identity lookup: entity pages whose email, title or declared alias equals an email address or name, ignoring case, accents and quotes. Never fuzzy: empty matches means no exact match; ambiguous means several.",+ "scope": "read",+ "mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "Email address or name, e.g. '[email protected]'."+ },+ "types": {+ "type": "array",+ "description": "Page types; default: the schema pack's entity types.",+ "items": {+ "type": "string"+ }+ },+ "source_id": {+ "type": "string",+ "description": "One source; '__all__' spans your sources."+ }+ },+ "required": [+ "query"+ ]+ },+ "personal_only": true,+ "result": {+ "structured_content": {+ "query": "string",+ "query_kind": "\"email\" | \"name\"",+ "matches": [+ {+ "slug": "string",+ "source_id": "string",+ "title": "string",+ "type": "string",+ "match": "string"+ }+ ],+ "ambiguous": "boolean"+ },+ "optional": {+ "truncated": "true: more candidates share the key than were returned",+ "note": "string"+ },+ "note": "exact, never fuzzy: no matches means no exact match; ambiguous: true means several, so ask which one and never take the first"+ }+ }+ ]+ },+ "memory_recall": {+ "limits": {+ "max_chars": {+ "min": 200,+ "max": 12000,+ "default": 6000,+ "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)",++ "arguments_checked": "query and max_chars are checked before any read, also for an unlinked person (invalid_params); a longer query is ranked on its first 2000 characters and never refused (recall's question is refused over 2000: invalid_params reason question_too_long)",+ "content": {+ "line": "- <fact> (<YYYY-MM-DD>; <kind>)",+ "never": [+ "page bodies",+ "fence markers",+ "heading markers",+ "line breaks or control characters inside a fact"+ ],+ "bounded_by": "max_chars: as many whole lines as fit; facts left out set structuredContent.truncated, with no marker line, because every line is one fact"+ },+ "order": [+ "own facts from the last 24 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",+ "arm": "\"own\" | \"ranked\""+ }+ ],+ "truncated": "boolean",+ "code": "actor_unlinked (only on unlinked_recall)"+ },+ "arm": "own: the person's own fact from the last 24 hours; ranked: matched by query (a fact found both ways is own); a call that names sources answers ranked rows only",+ "scope_read": {+ "arguments": [+ "source_id",+ "source_ids"+ ],+ "rule": "a call that names sources is read as their audience, never as the person: no own facts first and no member-page fact; a page restricted to named readers stays hidden; privacy is never relaxed",+ "sources": "narrowed inside the credential's read grant like recall's source_ids; a source outside it is permission_denied; source_id and source_ids together read their intersection, and an empty intersection reads nothing",+ "without_sources": "the person read above (own recent facts, then what the person may read across the read grant): use it only for the person's own conversations"+ }+ },+ "unlinked_recall": {+ "isError": false,+ "content": [+ {+ "type": "text",+ "text": ""+ }+ ],+ "structuredContent": {+ "facts": [],+ "truncated": false,+ "code": "actor_unlinked"+ }+ },+ "memory_write": {+ "limits": {+ "facts": {+ "min": 1,+ "max": 20+ },+ "provenance_chars": 200,+ "idempotency_key": {+ "pattern": "^[\\x21-\\x7e]{1,128}$"+ },+ "kinds": [+ "event",+ "preference",+ "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": [+ "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"+ ]+ },+ "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}"++ },++ "scope_write": {++ "argument": "source_id",++ "rule": "names one of the credential's scope sources (attest_sources, which the brain operator sets on the host); checked on the call and again when the write publishes, so a source the operator drops refuses queued writes; omit it to save for the person alone, exactly as without it",++ "saved_as": {++ "page": "memory/scope",++ "readers": "none: whoever holds read on the scope source, which only scope credentials may",++ "visibility": "world",++ "provenance": "qm:<actor id>; <caller provenance>"++ },++ "request_id": "uuidv5(uuidv5(namespace, \"member:<member>#source:<source_id>\"), idempotency_key) for the first fact; later facts derive from it; without source_id the member derivation above is unchanged",++ "replay": "per person and source: the same idempotency_key in another source is a separate write",++ "pending": "a scope source with a repository publishes git-first through its writer and answers pending until it commits; a source without one commits to the database",++ "recall": "read it with memory_recall source_id (read as the scope); a memory_recall without sources never reads a scope source",++ "withdrawal": "forget and forget_fact reach only the person's own member page, so a scope fact is not_found remotely"+ }+ },+ "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, and of a personal tool called with x-qm-actor, 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, names anyone but a member-bound credential's own member, or comes without an attested header from a credential bound to no member, 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": [+ {+ "reason": "no_attest_right",+ "fixed_by": "brain_operator",+ "fix": "gbrain auth rescope --client <id> --attest-actor qm on the brain host; a client that already holds the right takes a new token with grant_type=client_credentials."+ },+ {+ "reason": "op_not_attested",+ "fixed_by": "brain_operator",+ "fix": "gbrain auth rescope --client <id> --attest-actor qm --attest-ops <list>; a deferred operation cannot be attested yet."+ },+ {+ "reason": "argument_mismatch",+ "fixed_by": "calling_harness",+ "fix": "Send acting_user equal to the x-qm-actor header (with no header, on a credential bound to a member: that member id or a canonical id linked to it), or omit it."+ },+ {+ "reason": "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; a credential bound to no member never sends acting_user alone."++ "fix": "Remove acting_user, or send the x-qm-actor header from a credential holding the attest right; a credential bound to no member never sends acting_user alone. detail missing=<attest_right|x-qm-actor, comma-separated> names what this call lacked."+ },+ {+ "reason": "invalid_actor_id",+ "fixed_by": "calling_harness",+ "fix": "Send the canonical id unchanged: 1-256 visible ASCII characters, no spaces."+ },+ {+ "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."+ }+ ],+ "note": "With no x-qm-actor header, acting_user is accepted only from a credential bound to a member and only naming that member (its member id or a canonical id linked to it); the call then runs exactly as the credential."+ },+ {+ "code": "actor_unlinked",+ "class": "host_only",+ "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.",+ "suggestion": "The brain operator links the id to its member: gbrain access member link <member> --qm <id> (or enables the member).",+ "docs": "docs/guides/write-refusals.md#actor_unlinked",+ "note": "Refuses memory_write. memory_recall answers it as a success instead (unlinked_recall)."+ },+ {+ "code": "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.",+ "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.",+ "docs": "docs/guides/write-refusals.md#on_behalf_of_invalid_audience",+ "note": "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."+ },+ {+ "code": "invalid_params",+ "class": "caller",+ "summary": "A parameter is missing, has the wrong type, or has an invalid value.",+ "docs": "docs/guides/error-codes.md#invalid_params",- "note": "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."++ "note": "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. A memory_write whose source_id is the credential's own source carries reason source_is_member_source (omit source_id instead). recall refuses a question over 2000 UTF-16 code units with reason question_too_long and detail max_chars=2000 received_chars=<n>; nothing is read and the question is never cut, so shorten it and retry."+ },+ {+ "code": "scope_denied",+ "class": "host_only",+ "summary": "The connection lacks the scope this memory verb requires.",+ "docs": "docs/guides/error-codes.md#scope_denied",+ "note": "The write is not authorized, including a member page whose readers name anyone but its member (squatted or widened): nothing is saved."+ },+ {+ "code": "insufficient_scope",+ "class": "host_only",+ "summary": "The connection lacks the OAuth scope the operation requires.",+ "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": "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."+ },+ {+ "code": "permission_denied",+ "class": "host_only",+ "summary": "This caller is not authorized for the operation.",+ "docs": "docs/guides/error-codes.md#permission_denied",- "note": "memory_recall named a source (source_id or source_ids) outside the credential's read grant; nothing was read."++ "note": "memory_recall named a source (source_id or source_ids) outside the credential's read grant; nothing was read. memory_write named a source_id that is not one of the credential's scope sources (reason source_not_attested, also at publication after the operator drops it), or the scope page names readers (reason scope_page_not_shared); nothing was saved."+ },+ {+ "code": "page_not_found",+ "class": "caller",+ "summary": "No page with that slug exists in the selected source.",+ "docs": "docs/guides/error-codes.md#page_not_found",+ "note": "get_page for a page that does not exist or that the person may not read; one answer for both."+ },+ {+ "code": "result_too_large",+ "class": "caller",+ "summary": "The tool's result is larger than this connection can carry in one response, so it was replaced by this error; nothing was cut.",+ "suggestion": "Ask for less in one call: a window (get_page body: 'window'), a page of rows (limit / from_index), or metadata only (get_versions include_body: false).",+ "docs": "docs/guides/windowed-reads.md#result_too_large",+ "note": "A personal read whose answer, with structuredContent, is over the connection's result cap; nothing was returned. Ask for less: get_page body: \"outline\" or \"window\", or a smaller limit."+ }+ ]+ },+ "wave_2": {+ "audience_header": "x-qm-audience",+ "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 --cc docs/guides/qm.mdindex fa7a71f9df,77ba99d571..17381eb609--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@@ -4,8 -4,7 +4,7 @@@ QM, a trusted system that already knowmemory in a brain through two MCP tools: `memory_recall` reads what the person mayread, and `memory_write` saves facts only they read back. Both run as the person QMnames in the `x-qm-actor` header. The wire contract QM vendors is- [`docs/contracts/qm-memory-provider/v1.json`](../contracts/qm-memory-provider/README.md);- `v2.json` adds the scope read and `v3.json` the personal tools for the person's own DM.-[`docs/contracts/qm-memory-provider/v1.json`](../contracts/qm-memory-provider/README.md); `v2.json` adds scope reads and writes.++[`docs/contracts/qm-memory-provider/v1.json`](../contracts/qm-memory-provider/README.md); `v2.json` adds scope reads and writes, and `v3.json` the personal tools for the person's own DM.## Set up on the brain host@@@ -67,16 -61,40 +69,47 @@@ person's private facts to a whole roomid 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`.+ - `memory_write {facts, idempotency_key, source_id}` (contract v2) saves the facts on a shared+ scope's page `memory/scope` in that scope source instead, `visibility: world`, readable by every+ credential that reads the source. The source must be in the credential's `--attest-sources`; any other+ source is `permission_denied` reason `source_not_attested`, and the credential's own write source is+ `invalid_params` reason `source_is_member_source` (leave `source_id` out for the person's own page).+ The person is still attested and named in the provenance. A key replays per source.++ ## Shared scopes (projects, channels, teams)++ Give each scope its own source and list it on the QM credential:++ ```bash+ gbrain sources add scope-acme-example --path <dir> # on a repo brain: git-first, like member pages+ gbrain sources add scope-acme-example # on a repo-less brain+ gbrain auth rescope --client <client_id> --attest-sources scope-acme-example --federated-read <home>,scope-acme-example+ ```++ Listing a source marks it a scope source for good (`sources.config.qm_scope`): revoking or rotating the+ credential leaves the mark. A scope source is never federated (`sources federate` refuses, `sources restore`+ leaves it unfederated, a federated flag on it is ignored), and no other client, token or registration may+ add it to a read grant, so its memory is read only by naming it in `memory_recall` from the scope+ credential. A person read (no sources named) never reads a scope source. A source others already read,+ `default`, a federated source and the credential's own write source cannot be listed; a credential with+ scope sources keeps its attested ops within `forget,forget_fact,get_write_request,memory_recall,memory_write` and cannot+ hold `--private-pages granted-sources`. A leaked scope credential secret reads and writes every listed scope:+ restrict it with `--operations` to the memory tools. Remote writes to `memory/scope` other than a scope+ `memory_write` are refused, and a `memory/scope` page that names readers, is private or sits under a folder+ rule takes no scope fact (`scope_page_not_shared`). On a repo-backed scope source, anyone who can push to its+ repository can also author `memory/scope.md`, because git is the parent; its history keeps every actor's id+ through provenance. Each repo-backed scope source is one more writer claim, so its writes may answer `pending`+ until a writer publishes them.On success the result is in `structuredContent`, and `content` holds only the text-for the model. A person not yet linked gets an empty `memory_recall` with+for the model. Each fact in `structuredContent.facts` carries `arm`: `own` (the+person's own recent fact) or `ranked` (matched by `query`); a recall that names+sources has only `ranked` rows. An attested call to a v3 personal tool also gets its+result in `structuredContent` (a list as `structuredContent.results`), while+`content` keeps the JSON; `context_pack`'s `content` is its rendered text alone. The+same tools called without `x-qm-actor` answer as before, with no `structuredContent`.+A personal read whose answer, counted with `structuredContent`, is over the+connection's result cap is refused whole (`result_too_large`). A person not yet linked gets an empty `memory_recall` with`structuredContent.code: "actor_unlinked"` (its arguments are still checkedfirst). Every refusal, including the transport's scope and unknown-tool ones,carries `structuredContent.error`. A request carrying `x-qm-audience` (channeldiff --cc scripts/build-qm-memory-contract.tsindex e36def120c,8a07a74b01..5dbe93db9e--- a/scripts/build-qm-memory-contract.ts+++ b/scripts/build-qm-memory-contract.ts@@@ -15,11 -13,11 +15,13 @@@ import { operations } from '../src/coreimport { 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, QM_AUDIENCE_HEADER } from '../src/core/access/actor-model.ts';+ import { SCOPE_PAGE_SLUG } from '../src/core/access/principals.ts';+ import { QUESTION_MAX_CHARS } from '../src/core/facts/question-recall.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';+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, QM_PERSONAL_OPS, unlinkedRecallResult } from '../src/core/ops/qm-memory.ts';+import { WRITE_REQUEST_STATES } from '../src/core/persistence/types.ts';+import { TERMINAL_STATES } from '../src/core/persistence/model.ts';-export type QmContractVersion = 1 | 2;+export type QmContractVersion = 1 | 2 | 3;export const QM_CONTRACT_PATHS: Record<QmContractVersion, string> = {1: join(import.meta.dir, '..', 'docs', 'contracts', 'qm-memory-provider', 'v1.json'),2: join(import.meta.dir, '..', 'docs', 'contracts', 'qm-memory-provider', 'v2.json'),@@@ -151,11 -77,11 +153,12 @@@ function toolEntry(name: string, versioexport function buildQmMemoryContract(version: QmContractVersion): Record<string, unknown> {const unlinked = unlinkedRecallResult();const v2 = version > 1;- const codes = v2 ? [...ERROR_CODES, 'permission_denied' as const] : ERROR_CODES;+ const v3 = version > 2;+ const codes: readonly (keyof typeof CODES)[] = v3 ? [...ERROR_CODES, 'permission_denied', 'page_not_found', 'result_too_large'] : v2 ? [...ERROR_CODES, 'permission_denied'] : ERROR_CODES;const notes: Record<string, string | undefined> = v2 ? { ...ERROR_NOTES,actor_not_attested: 'With no x-qm-actor header, acting_user is accepted only from a credential bound to a member and only naming that member (its member id or a canonical id linked to it); the call then runs exactly as the credential.',- permission_denied: 'memory_recall named a source (source_id or source_ids) outside the credential\'s read grant; nothing was read.', ...(v3 ? V3_ERROR_NOTES : {}) } : ERROR_NOTES;+ invalid_params: `${ERROR_NOTES.invalid_params} A memory_write whose source_id is the credential's own source carries reason source_is_member_source (omit source_id instead). recall refuses a question over ${QUESTION_MAX_CHARS} UTF-16 code units with reason question_too_long and detail max_chars=${QUESTION_MAX_CHARS} received_chars=<n>; nothing is read and the question is never cut, so shorten it and retry.`,- permission_denied: 'memory_recall named a source (source_id or source_ids) outside the credential\'s read grant; nothing was read. memory_write named a source_id that is not one of the credential\'s scope sources (reason source_not_attested, also at publication after the operator drops it), or the scope page names readers (reason scope_page_not_shared); nothing was saved.' } : ERROR_NOTES;++ permission_denied: 'memory_recall named a source (source_id or source_ids) outside the credential\'s read grant; nothing was read. memory_write named a source_id that is not one of the credential\'s scope sources (reason source_not_attested, also at publication after the operator drops it), or the scope page names readers (reason scope_page_not_shared); nothing was saved.', ...(v3 ? V3_ERROR_NOTES : {}) } : ERROR_NOTES;return {contract: 'gbrain.qm-memory-provider', version,transport: { protocol: 'mcp', session: 'stateless', session_header_issued: false, success_codes_in: 'structuredContent',@@@ -169,16 -95,11 +172,18 @@@audit: 'the audit trail and stored writes record the canonical external id as sent, with its linked member',},tools: [...QM_MEMORY_OPS].sort().map(name => toolEntry(name, version)),+ ...(v3 ? { personal_tools: {+ read_as: 'the attested person (x-qm-actor): what that person may read, their own restricted pages included, so use these tools only in the person\'s own conversations; no tool here is marked as a shared-scope read yet',+ opt_in: 'only get_write_request is in default_attest_ops: the brain operator lists each other tool in the client\'s --attest-ops (gbrain auth rescope --client <id> --attest-actor qm --attest-ops <list>), or it is refused with actor_not_attested reason op_not_attested',+ structured_content: 'an attested success carries the result in structuredContent and keeps it as JSON in content (notice blocks follow it); a list arrives as structuredContent.results; context_pack\'s text alone fills content, as memory_recall\'s does; an unattested call to the same tool gets no structuredContent',+ result_rule: 'each result lists the fields every success carries; other fields may appear and must be ignored',+ tools: [...QM_PERSONAL_OPS].sort().map(name => ({ ...toolEntry(name, version), personal_only: true, result: PERSONAL_RESULTS[name] })),+ } } : {}),memory_recall: {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)',+ arguments_checked: v2+ ? `query and max_chars are checked before any read, also for an unlinked person (invalid_params); a longer query is ranked on its first ${MEMORY_RECALL_QUERY_CHARS} characters and never refused (recall's question is refused over ${QUESTION_MAX_CHARS}: invalid_params reason question_too_long)`+ : 'query and max_chars are checked before any read, also for an unlinked person (invalid_params)',content: { line: '- <fact> (<YYYY-MM-DD>; <kind>)', never: ['page bodies', 'fence markers', 'heading markers', 'line breaks or control characters inside a fact'], bounded_by: 'max_chars: as many whole lines as fit; facts left out set structuredContent.truncated, with no marker line, because every line is one fact' },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)',diff --cc scripts/module-size-limits.tsvindex 4d5f6375cf,7beb0fe08d..92a6a0a13a--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -47,4 -47,4 +47,4 @@@ src/commands/doctor/checks/extraction-ssrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)- src/core/behavior-change-notice.ts 1655 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 GST-1094/GST-900: the memory_recall scope-read, member-bound acting_user, recall max_chars and unknown_param _meta-only rows (since TBD until the merge slot); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot)-src/core/behavior-change-notice.ts 1668 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot)++src/core/behavior-change-notice.ts 1669 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot)diff --cc src/core/behavior-change-notice.tsindex 184b62b8b6,355ee1daa5..cdfc0a4eb5--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -1450,13 -1450,26 +1450,27 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.577.0', id: 'refresh_fence_refusal_gst1387', text: 'A write refused because `gbrain sources refresh` is fast-forwarding its checkout (`worktree_refreshing`) is now a registered retryable refusal whose fix is `next: wait` with `retry_after_ms`, instead of class server with `fix: gbrain doctor`; the memory verbs keep `unavailable` and add `canonical: worktree_refreshing`. An interactive CLI or MCP write waits out the fence for up to 10 s before that refusal; a background write is refused at once as before. `remember` with `items` whose every item failed is now refused with the first item\'s error (CLI exit 1, MCP isError) instead of a success envelope with `failed`, and a batch with any failed item adds `status: "error"` and the first failed `code`, so the CLI exits 1 and MCP returns isError with every item\'s receipt.' },{ since: '0.60.583.0', id: 'sync_write_through_off_writeback_7084', text: 'With `sync.write_through` off, a managed `gbrain sync` no longer writes its canonical correction of a file (the frontmatter, title or tags the page keeps when an upstream edit drops them) back into the checkout (#7084, #8118). The page keeps the correction in the database only, as on a read-only mirror source, and `git status` stays clean. With `sync.write_through` on, nothing changes. Files already rewritten by earlier versions are not touched; restore them with `git checkout -- <paths>` or commit them.' },{ since: '0.60.583.0', id: 'managed_sync_dry_run_counts_7087', text: 'A managed `gbrain sync --dry-run` now reports the files the run would add, modify, soft-delete and rename, and prints them as one line (#7087). It used to report the cursor\'s committed counts: zero before a run, or the previous run\'s counts when nothing had changed.' },+ // Convergence PR A (GST-1500, evidence-based baseline). since is stamped at the merge slot.+ { since: '0.60.592.0', id: 'conversion_content_evidence_pr_a', text: '`gbrain sources canonical <id> --to git` now decides a page with no import record by content evidence instead of calling it database-ahead: an older version equal to the committed file adopts it, a page equal to an older committed blob lets Git win (`git_wins.by.file_moved`), and a page where both moved or nothing is shared is a new discard (`no_record_both_moved`, `no_record_no_evidence`) until the owner decides it. `--list-out <file>` writes the review list, `--decisions <file>` applies the decisions (bound into the hash), and `--approval-out` / `--approved` apply an approval across time: only items unchanged since the approval apply, and the rest returns as `git_conversion_delta` with counts. These files are written 0600 and refused inside a source checkout. A page that changes during the apply is held instead of overwritten, and a failed apply reports `recovery` (mode, commits, push, writes, rollback). See docs/guides/git-canonical.md#review-list-and-decisions.' },+ { since: '0.60.592.0', id: 'git_gap_live_pages_pr_a', text: '`gbrain sources git-gap` and doctor `db_ahead_of_git` now report each source\'s live pages (`live_pages`) beside the pages read, and a scan the time budget stopped reads `PARTIAL, <read> of <live> live page(s) read` instead of a bare count. `sources git-gap` also reports `direction_evidence` for pages with no import record. `gbrain repair rows-behind` never re-imports a row with no import record whose older version equals its committed file (the database moved since), even with `--include-ambiguous`: it is listed `excluded:database_moved`. Nor one whose page and file both moved since the last state they shared: it is listed `excluded:both_moved`, and `gbrain repair file-drift` decides it.' },{ since: '0.60.583.0', id: 'frontmatter_missing_source_dir_7889', text: 'A registered source whose directory does not exist is no longer reported frontmatter-clean (#7889). The frontmatter audit marks it `missing` (and lists it under `missing_sources`), and doctor `frontmatter_integrity` and `frontmatter_repairable` warn with the path and ask you to restore it or run `gbrain sources set-path <id> <path>`; they no longer call it clean or blame a timeout.' },- { since: 'TBD', id: 'memory_recall_scope_read_gst1094', text: '`memory_recall` now takes `source_id` and `source_ids`. A call that names sources reads as their audience, never as the attested person: no own recent facts first and no fact from any member page; a page restricted to named readers stays hidden and `visibility: private` is never relaxed. A source outside the credential\'s read grant is refused (`permission_denied`) and `__all__` is refused (`invalid_params`). Without sources, `memory_recall` is unchanged. The contract is `docs/contracts/qm-memory-provider/v2.json`; `v1.json` is unchanged.' },- { since: 'TBD', id: 'member_bound_acting_user_gst900', text: 'A credential bound to a member may now send `acting_user` with no `x-qm-actor` header: its own member id, or a canonical id linked to that member, is dropped and the call runs exactly as the credential; any other value is refused (`actor_not_attested` reason `argument_mismatch`). A credential bound to no member is still refused (`argument_without_attestation`).' },- { since: 'TBD', id: 'recall_max_chars_harn15', text: '`recall` now takes `max_chars` (a whole number from 200 to 12000, as `memory_recall`): it keeps the whole facts, then results, whose text fits, adds no marker and returns `truncated`; without it `recall` is unchanged.' },+ { since: '0.60.595.0', id: 'memory_recall_scope_read_gst1094', text: '`memory_recall` now takes `source_id` and `source_ids`. A call that names sources reads as their audience, never as the attested person: no own recent facts first and no fact from any member page; a page restricted to named readers stays hidden and `visibility: private` is never relaxed. A source outside the credential\'s read grant is refused (`permission_denied`) and `__all__` is refused (`invalid_params`). Without sources, `memory_recall` is unchanged. The contract is `docs/contracts/qm-memory-provider/v2.json`; `v1.json` is unchanged.' },+ { since: '0.60.595.0', id: 'member_bound_acting_user_gst900', text: 'A credential bound to a member may now send `acting_user` with no `x-qm-actor` header: its own member id, or a canonical id linked to that member, is dropped and the call runs exactly as the credential; any other value is refused (`actor_not_attested` reason `argument_mismatch`). A credential bound to no member is still refused (`argument_without_attestation`).' },+ { since: '0.60.595.0', id: 'qm_scope_writes_gst1113', text: '`memory_write` now takes `source_id`: a credential that lists the source in `gbrain auth rescope --attest-sources` saves the facts on that scope source\'s `memory/scope` page (`visibility: world`, attested to the person); any other source is refused (`permission_denied` reason `source_not_attested`, or `invalid_params` reason `source_is_member_source` for its own write source). Listing a source marks it a QM scope source for good: it is never federated (`sources federate` refuses, `sources restore` leaves it unfederated) and no other grant, token or registration may read it. Remote writes to `memory/scope` other than a scope `memory_write` are refused, and `memory_recall` without sources never reads a scope source.' },+ { since: '0.60.595.0', id: 'recall_question_terms_gst1304', text: '`recall` with a `question` over 12 content words (a provider\'s instruction preamble ahead of the turn) is now searched on its last 24 content words and scored on the 12 of those the fewest candidate facts hold, instead of on its first 12, so a keyword-only brain no longer returns no facts because the preamble filled the 12. Shorter questions rank as before. A response whose candidates all fell under the admission floor carries `facts_below_floor: <n>`, and a question over 2,000 characters is refused with reason `question_too_long` and detail `max_chars=2000 received_chars=<n>`. `actor_not_attested` reason `argument_without_attestation` now names what the call lacked, in its message and in detail `missing=attest_right`, `missing=x-qm-actor` or both; QM tools also carry `detail` in `structuredContent.error`.' },+ { since: '0.60.595.0', id: 'recall_max_chars_harn15', text: '`recall` now takes `max_chars` (a whole number from 200 to 12000, as `memory_recall`): it keeps the whole facts, then results, whose text fits, adds no marker and returns `truncated`; without it `recall` is unchanged.' },+ { since: '0.60.595.0', id: 'unknown_param_meta_only_harn15', text: 'A read that ignores a parameter the tool does not declare (`mcp.strict_params` `warn`, the default) no longer adds a `[gbrain notice unknown_param kind=info]` text block to the result: the warning is only in `_meta.warnings` (`{code: \'unknown_param\', param, suggestion?}`), so a harness that stores tool output in its turns never stores it. Writes still refuse unknown parameters, and `reject` mode is unchanged.' },+ // PR B (convergence lane L4): commit ledger, foreign_writers, owner-path guard. since is stamped at the merge slot.+ { since: '0.60.594.0', id: 'commit_ledger_prb', text: 'Every commit gbrain makes is now recorded as one line in `<git common dir>/gbrain/commit-ledger.jsonl` (inside `.git`, never tracked, rotated at 4 MiB to `commit-ledger.1.jsonl`). A failed append never fails the commit; it is logged once.' },+ { since: '0.60.594.0', id: 'doctor_foreign_writers_prb', text: 'New doctor check `foreign_writers`: in every source checkout on this host, managed worktrees included, a commit gbrain\'s commit ledger does not name fails the check with the newest such commit and a fix that asks who makes it; an unconfirmed commit (a crash between `git commit` and the ledger line) and page files left uncommitted for over 30 minutes warn. Commits before the ledger started are reported as uncovered, not foreign. A repo-less brain reports not_applicable.' },+ { since: '0.60.594.0', id: 'sources_guard_prb', text: 'New `gbrain sources guard <source> --install|--uninstall|--status [--mode enforce]`: the commit guard on a managed source\'s worktree, from its owner host only, installed in a hooks directory private to that worktree. `--mode enforce` also refuses cherry-pick, revert, rebase and sequencer commits. `gbrain git guard` is unchanged.' },+ { since: '0.60.594.0', id: 'refresh_barrier_prb', text: 'New setting `persistence.refresh_barrier` (off by default): with it on, a single page write (`put_page`, `remember` and the other single-page verbs) that reaches a checkout while `gbrain sources refresh` drains or merges it is journaled and answered `pending` at once (MCP `isError: false`, CLI exit 10) instead of refused `worktree_refreshing`. It commits after the refresh, or ends `revision_conflict` when the refresh changed its file, or `refresh_barrier_expired` after `persistence.refresh_barrier_max_wait_ms` (15 minutes). Syncs, jobs and batches keep the refusal. `gbrain upgrade --check-downgrade` exits 3 `downgrade_blocked_deferred_writes` while such writes wait.' },+ { since: '0.60.594.0', id: 'commit_push_base_prb', text: '`gbrain git commit-push` takes `--base <path>=<blob>|absent` (repeatable, each path one the command commits): it refuses `commit_base_moved`, committing nothing, when the file at HEAD is no longer the blob the caller read. Without `--base` nothing changes.' },+ { since: '0.60.594.0', id: 'file_drift_held_needs_prefer_8615', text: '`gbrain repair file-drift` with `--held`, `--side`, `--state`, `--cursor` or `--provenance` and no `--prefer` now refuses with the usage line (`invalid_params`, and `file_drift_state_required` for a deleted side without `--state`) instead of silently running the all-drifted survey, which counted a different set of pages (#8615).' },+ { since: '0.60.594.0', id: 'refresh_source_changed_retry_8617', text: 'A `gbrain sources refresh` run refused `refresh_source_changed` because the checkout HEAD moved (a writer committing) or work reached the checkout after the drain check now retries once from a fresh precheck in the same run, so the tick is not lost (#8617). When the retry is refused too, the run returns the first `refresh_source_changed` refusal with the retry\'s cause appended; ownership or source-membership changes are not retried.' },+ { since: '0.60.594.0', id: 'commit_push_checkout_not_a_source_8662', text: '`gbrain git commit-push` now refuses `checkout_not_a_source` before staging anything when this brain home records its source checkouts (a managed brain) and the checkout it resolved from the working directory (no `--path`) is none of them and has no `gbrain.sourceRoot`, for example a wrapper that changed into another repository (#8662). The refusal names the resolved path and the brain\'s checkouts; pass `--path` with the absolute brain checkout. Hosts whose brain records no source checkout behave as before.' },{ since: 'TBD', id: 'attest_direct_page_writes_deferred_gst1158', text: 'An attested call (`x-qm-actor`) may no longer run `add_timeline_entry`, `add_link`, `put_page` or `edit_page`: they write pages every reader of the page sees, so they wait for owner-approved proposals. `gbrain auth rescope --attest-ops` refuses a list that names one, a credential whose list already names one is refused for it on every attested call (`actor_not_attested`, reason `op_not_attested`), and a queued attested write of one fails when it publishes. Unattested calls and member-bound credentials are unchanged.' },+ { since: 'TBD', id: 'qm_personal_structured_gst1158', text: 'An attested call (`x-qm-actor`) to `query`, `get_page`, `get_timeline`, `get_backlinks`, `find_experts`, `whois`, `entity`, `context_pack`, `volunteer_context`, `get_write_request` or `forget_fact` now also answers with its result in `structuredContent` (a list as `structuredContent.results`) and its refusals with `structuredContent.error`; `content` keeps the JSON, except `context_pack`, whose `content` is now its rendered text alone. A personal read whose answer, counted with `structuredContent`, is over the result cap is refused whole (`result_too_large`). Each `memory_recall` fact in `structuredContent.facts` gains `arm` (`own` or `ranked`). The same tools without `x-qm-actor` are unchanged, and none of them joined the default attested operations.' },- { since: 'TBD', id: 'unknown_param_meta_only_harn15', text: 'A read that ignores a parameter the tool does not declare (`mcp.strict_params` `warn`, the default) no longer adds a `[gbrain notice unknown_param kind=info]` text block to the result: the warning is only in `_meta.warnings` (`{code: \'unknown_param\', param, suggestion?}`), so a harness that stores tool output in its turns never stores it. Writes still refuse unknown parameters, and `reject` mode is unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/ops/qm-memory.tsindex c083a9c5eb,21e46fef0e..05a83e8bb2--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@@ -316,24 -322,19 +330,24 @@@ const memory_write: Operation =/*** A successful memory_recall or memory_write result as QM reads it: the model's text alone in `content` (notices stay* in `_meta.gbrain_notices`, so memory_recall's text stays within max_chars) and the result in `structuredContent`.- * A refusal keeps its JSON text block and gains `structuredContent.error` (code, message, reason, fix), as the actor+ * A refusal keeps its JSON text block and gains `structuredContent.error` (code, message, reason, detail, fix), as the actor* refusals carry it, so QM classifies every error from structuredContent. Dry runs and every other tool pass through.+ * GST-1158 F2: a personal tool (QM_PERSONAL_OPS) is rewritten the same way only for an attested person (`personal`):+ * `content` keeps its JSON and notice blocks, an array result arrives as `structuredContent.results`, and+ * context_pack's text fills `content` as memory_recall's does.*/-export function qmMemoryToolResult<T extends { content: Array<{ type: 'text'; text: string }>; isError?: boolean; structuredContent?: Record<string, unknown> }>(name: string, out: T): T {- if (!QM_MEMORY_OPS.has(name)) return out;+export function qmMemoryToolResult<T extends { content: Array<{ type: 'text'; text: string }>; isError?: boolean; structuredContent?: Record<string, unknown> }>(name: string, out: T, personal = false): T {+ if (!QM_MEMORY_OPS.has(name) && !(personal && QM_PERSONAL_OPS.has(name))) return out;let result: unknown;try { result = JSON.parse(out.content[0]?.text ?? ''); } catch { return out; }if (out.isError) {if (out.structuredContent || !result || typeof result !== 'object') return out;const env = result as Record<string, unknown>;- return { ...out, structuredContent: { error: { code: env.code, message: env.message, ...(env.reason ? { reason: env.reason } : {}), ...(env.write_error ? { write_error: env.write_error } : {}), ...(env.fix ? { fix: env.fix } : {}) } } };+ return { ...out, structuredContent: { error: { code: env.code, message: env.message, ...(env.reason ? { reason: env.reason } : {}), ...(env.detail ? { detail: env.detail } : {}), ...(env.write_error ? { write_error: env.write_error } : {}), ...(env.fix ? { fix: env.fix } : {}) } } };}if (!result || typeof result !== 'object' || 'dry_run' in result) return out;+ if (Array.isArray(result)) return { ...out, structuredContent: { results: result } };+ if (!TEXT_RESULT_OPS.has(name)) return { ...out, structuredContent: result as Record<string, unknown> };const { text, ...structured } = result as Record<string, unknown>;return { ...out, content: [{ type: 'text', text: typeof text === 'string' ? text : '' }], structuredContent: structured };}diff --cc test/qm-memory-contract.test.tsindex 8e62de780d,fe6ff7f4c9..14685aeec9--- a/test/qm-memory-contract.test.ts+++ b/test/qm-memory-contract.test.ts@@@ -100,91 -104,20 +106,105 @@@ describe('QM memory-provider contract vexpect(fixture.errors.codes.map((c: { code: string }) => c.code)).toContain('permission_denied');const v1 = JSON.parse(readFileSync(QM_CONTRACT_PATH, 'utf8'));expect(fixture.wave_2).toEqual(v1.wave_2);- expect(fixture.memory_write).toEqual(v1.memory_write);+ const { scope_write: scopeWrite, ...memoryWrite } = fixture.memory_write;+ expect(memoryWrite).toEqual(v1.memory_write);+ const write = fixture.tools.find((t: { name: string }) => t.name === 'memory_write');+ expect(write.input_schema.properties.source_id.type).toBe('string');+ expect(write.input_schema.required).toEqual(v1.tools.find((t: { name: string }) => t.name === 'memory_write').input_schema.required);+ expect(scopeWrite.saved_as).toMatchObject({ page: 'memory/scope', visibility: 'world' });+ expect(scopeWrite.rule).toContain('attest_sources');+ });++ test('it says what an over-long query, an over-long recall question and an unattested acting_user get (GST-1304)', () => {+ expect(fixture.memory_recall.arguments_checked).toContain('a longer query is ranked on its first 2000 characters and never refused');+ const notes = Object.fromEntries(fixture.errors.codes.map((c: { code: string; note?: string }) => [c.code, c.note]));+ expect(notes.invalid_params).toContain('question_too_long');+ const reasons = fixture.errors.codes.find((c: { code: string }) => c.code === 'actor_not_attested').reasons;+ expect(reasons.find((r: { reason: string }) => r.reason === 'argument_without_attestation').fix).toContain('detail missing=');});});++describe('QM memory-provider contract v3 (GST-1158 F1: personal tools, frozen result shapes, forget_fact)', () => {+ const fixture = JSON.parse(readFileSync(QM_CONTRACT_PATHS[3], 'utf8'));+ const v2 = JSON.parse(readFileSync(QM_CONTRACT_PATHS[2], 'utf8'));+ const personal = (name: string) => fixture.personal_tools.tools.find((t: { name: string }) => t.name === name);++ test('the committed fixture matches the live registry (regenerate with bun scripts/build-qm-memory-contract.ts)', () => {+ expect(readFileSync(QM_CONTRACT_PATHS[3], 'utf8')).toBe(renderQmMemoryContract(3));+ });++ test('it keeps everything v2 has; only the version, recall\'s fact rows and the error list grow', () => {+ expect(fixture.version).toBe(3);+ for (const key of Object.keys(v2)) {+ if (key === 'version' || key === 'memory_recall' || key === 'errors') continue;+ expect(fixture[key]).toEqual(v2[key]);+ }+ const { structured_content: recallShape, arm: _arm, ...recallRest } = fixture.memory_recall;+ const { structured_content: v2Shape, ...v2Rest } = v2.memory_recall;+ expect(recallRest).toEqual(v2Rest);+ expect({ ...recallShape, facts: [{ ...recallShape.facts[0], arm: undefined }] }).toEqual({ ...v2Shape, facts: [{ ...v2Shape.facts[0], arm: undefined }] });+ expect(fixture.errors.shape).toEqual(v2.errors.shape);+ for (const code of v2.errors.codes) expect(fixture.errors.codes.find((c: { code: string }) => c.code === code.code)).toBeDefined();+ expect(v2.personal_tools).toBeUndefined();+ expect(v2.memory_recall.structured_content.facts[0].arm).toBeUndefined();+ });++ test('memory_recall fact rows carry their arm, own or ranked, and no score', () => {+ expect(fixture.memory_recall.structured_content.facts[0]).toEqual({ id: 'string', text: 'string', date: 'YYYY-MM-DD', kind: 'string', arm: '"own" | "ranked"' });+ expect(fixture.memory_recall.arm).toContain('ranked rows only');+ expect(JSON.stringify(fixture.memory_recall)).not.toContain('score');+ });++ test('it lists every personal tool, personal-only and opt-in, with the schema MCP serves', () => {+ const names = fixture.personal_tools.tools.map((t: { name: string }) => t.name);+ expect(names).toEqual([...QM_PERSONAL_OPS].sort());+ expect(names).toEqual(['context_pack', 'entity', 'find_experts', 'forget_fact', 'get_backlinks', 'get_page', 'get_timeline', 'get_write_request', 'query', 'volunteer_context', 'whois']);+ const served = buildToolDefs(operations.filter(o => QM_PERSONAL_OPS.has(o.name)));+ for (const tool of fixture.personal_tools.tools) {+ const def = served.find(d => d.name === tool.name)!;+ expect({ description: tool.description, ...tool.input_schema }).toEqual({ description: def.description, ...def.inputSchema });+ expect(tool.personal_only).toBe(true);+ expect(tool.result.structured_content).toBeDefined();+ }+ expect(fixture.actor.default_attest_ops).toEqual([...DEFAULT_ATTEST_OPS]);+ expect(fixture.actor.default_attest_ops).toEqual(['get_write_request', 'memory_recall', 'memory_write']);+ expect(fixture.personal_tools.opt_in).toContain('--attest-ops');+ expect(fixture.personal_tools.result_rule).toContain('must be ignored');+ for (const name of names) expect(fixture.actor.deferred_ops).not.toContain(name);+ });++ test('the frozen fields are present: every result names the fields QM decodes', () => {+ const fields = (name: string) => Object.keys(personal(name).result.structured_content);+ expect(fields('query')).toEqual(['results']);+ expect(Object.keys(personal('query').result.structured_content.results[0])).toEqual(['source_id', 'title', 'chunk_text', 'score']);+ expect(fields('get_page')).toEqual(['slug', 'source_id', 'type', 'title', 'revision']);+ expect(Object.keys(personal('get_timeline').result.structured_content.results[0])).toEqual(['id', 'date', 'summary', 'source', 'detail']);+ expect(Object.keys(personal('get_backlinks').result.structured_content.results[0])).toEqual(['from_slug', 'from_source_id', 'to_slug', 'to_source_id', 'link_type']);+ expect(Object.keys(personal('find_experts').result.structured_content.results[0])).toEqual(['slug', 'source_id', 'title', 'type', 'score']);+ expect(fields('whois')).toEqual(['query', 'query_kind', 'matches', 'ambiguous']);+ expect(fields('entity')).toEqual(['protocol_version', 'found']);+ expect(fields('context_pack')).toEqual(['protocol_version', 'entities', 'cards', 'open_threads', 'facts', 'entity_facts']);+ expect(personal('context_pack').result.content).toContain('text');+ expect(fields('volunteer_context')).toEqual(['pages', 'count', 'window_turns']);+ expect(fields('get_write_request')).toEqual(['request_id', 'state', 'retry_after_ms', 'operation', 'source_id', 'slug', 'created_at', 'updated_at']);+ expect(fields('forget_fact')).toEqual(['id', 'request_id', 'state']);+ });++ test('get_write_request freezes the write-request states, and an unknown state means unknown, not published', () => {+ const states = personal('get_write_request').result.states;+ expect(states.known).toEqual([...WRITE_REQUEST_STATES]);+ expect(states.known).toEqual(['queued', 'running', 'recovering', 'committed', 'conflict', 'failed', 'cancelled']);+ expect(states.terminal).toEqual(['committed', 'conflict', 'failed', 'cancelled']);+ expect(states.published).toBe('committed');+ expect(states.unknown).toContain('unknown, not published');+ expect(personal('get_write_request').result.structured_content.state).toBe(WRITE_REQUEST_STATES.map(s => '"' + s + '"').join(' | '));+ expect(personal('forget_fact').result.structured_content.state).toBe(personal('get_write_request').result.structured_content.state);+ });++ test('the personal tools add the refusal codes they answer with, each registered', () => {+ const codes = fixture.errors.codes.map((c: { code: string }) => c.code);+ for (const code of ['page_not_found', 'result_too_large']) expect(codes).toContain(code);+ for (const c of fixture.errors.codes) expect(CODES[c.code as keyof typeof CODES]).toBeDefined();+ expect(fixture.errors.applies_to).toContain('personal');+ });+});diff --cc test/qm-memory-tools.test.tsindex c162544988,281b976e5f..aac4a26a2d--- a/test/qm-memory-tools.test.ts+++ b/test/qm-memory-tools.test.ts@@@ -432,25 -433,30 +433,49 @@@ for (const kind of testBackends())expect(unlinked.structured).toEqual({ facts: [], truncated: false, code: 'actor_unlinked' });}, 120_000);+ test('each recalled fact names its arm: own for the person\'s recent facts, ranked for query matches, ranked only under a scope read (GST-1158 F5)', async () => {+ for (const [fact, provenance] of [['Alice charts the harbor tide canaryarmown', 'turn 50'], ['Alice charted the harbor tide last year canaryarmold', 'turn 49']]) {+ expect((await write(alice, [{ fact, provenance }])).structured?.status).toBe('committed');+ }+ await engine.executeRaw("UPDATE facts SET created_at = now() - interval '3 days', valid_from = now() - interval '3 days' WHERE source_id = $1 AND fact LIKE '%canaryarmold%'", [SRC]);+ await engine.insertFact({ fact: 'Acme harbor tide tables canaryarmranked', kind: 'fact', entity_slug: ACME, source: 'test', visibility: 'world' }, { source_id: SRC });+ const out = await recall(alice, 'harbor tide', { max_chars: 12_000 });+ expect(out.isError).toBe(false);+ const arm = (needle: string) => out.structured!.facts.find((f: { text: string }) => f.text.includes(needle))?.arm;+ expect({ own: arm('canaryarmown'), old: arm('canaryarmold'), world: arm('canaryarmranked') }).toEqual({ own: 'own', old: 'ranked', world: 'ranked' });+ for (const f of out.structured!.facts) expect(Object.keys(f).sort()).toEqual(['arm', 'date', 'id', 'kind', 'text']);+ const firstRanked = out.structured!.facts.findIndex((f: { arm: string }) => f.arm === 'ranked');+ expect(out.structured!.facts.slice(firstRanked).every((f: { arm: string }) => f.arm === 'ranked')).toBe(true);+ const asScope = await recall(alice, 'harbor tide', { max_chars: 12_000, source_id: SRC });+ expect(asScope.structured!.facts.length).toBeGreaterThan(0);+ expect(asScope.structured!.facts.every((f: { arm: string }) => f.arm === 'ranked')).toBe(true);+ expect(asScope.all).not.toContain('canaryarmown');+ }, 120_000);++ test('a recall that names sources keeps folder fail-closed coverage: facts under a pending prefix stay hidden', async () => {+ expect(tokens.scoped).toBeDefined();+ const aliceScoped: Who = { token: 'scoped', actor: ALICE_ID };+ const held = 'pending-hr/scope-note';+ await importFromContent(engine, held, '---\ntype: note\ntitle: Held note\n---\n# Held note\n', { sourceId: SRC });+ await engine.insertFact({ fact: 'Payroll budget ledger draft canaryscopepending', kind: 'fact', entity_slug: ACME, source: 'test', visibility: 'world' }, { source_id: SRC });+ await engine.executeRaw('UPDATE facts SET source_markdown_slug = $1 WHERE fact LIKE $2', [held, '%canaryscopepending%']);+ __resetPrivateVisibilityCacheForTests();+ expect((await recall(aliceScoped, 'payroll budget ledger', { max_chars: 12_000, source_id: SRC })).text).toContain('canaryscopepending');+ await engine.executeRaw('INSERT INTO access_policy_state (source_id) VALUES ($1) ON CONFLICT (source_id) DO NOTHING', [SRC]);+ await engine.executeRaw("INSERT INTO access_pending_coverage (source_id, prefix, reason) VALUES ($1, 'pending-hr/', 'invalid')", [SRC]);+ try {+ __resetPrivateVisibilityCacheForTests();+ for (const args of [{ source_id: SRC }, { source_ids: [SRC] }]) {+ const asScope = await recall(aliceScoped, 'payroll budget ledger', { max_chars: 12_000, ...args });+ expect(asScope.isError).toBe(false);+ expect(asScope.all).not.toContain('canaryscopepending');+ }+ } finally {+ await engine.executeRaw("DELETE FROM access_pending_coverage WHERE source_id = $1 AND prefix = 'pending-hr/'", [SRC]);+ __resetPrivateVisibilityCacheForTests();+ }+ }, 120_000);+test('generic recall takes max_chars: whole facts in order, no marker, structured truncated, invalid values refused; without it recall is unchanged (HARN-15)', async () => {const ENTITY = 'companies/harn-recall-example';for (let i = 0; i < 12; i++) {