Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(qm): R51 round-1 fixes — batch idempotency, structured actor errors, member-page dedup exclusion, delta cursor key

garrytan126d658d409c
diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.md
index 3804e69239..9b6d84eef0 100644
--- a/docs/architecture/key-files/access.md
+++ b/docs/architecture/key-files/access.md
@@ -3,4 +3,5 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
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`, `forget`, `forget_fact`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration 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/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`; `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (a `regen:all` artifact). Tests: `test/qm-memory-tools.test.ts` (both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 1f24f47f5f..d3c5778504 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -66,7 +66,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (off in all modes) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.
- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`source_markdown_slug`) is private; the fact-list reads in `engine-sql/facts.ts` (by entity, since, keyset, session, supersessions, trajectory) apply it behind `FactListOpts.excludePrivate` / `TrajectoryOpts.excludePrivate`, which every remote fact surface resolves with `resolveExcludePrivatePages` (`test/remote-fact-list-private-provenance.test.ts`, both engines). Remote fact writes apply the same predicate behind an `excludePrivate` option: `forget` (`guardRemoteForget`, the row lock in `persistence/memory-mutations.ts`, `recordFactWithdrawal`, `similarActiveAfterForget`) and `remember` (`decideSingleFact`'s exact and cosine arms, `decideReplacement`), so a fact remote reads hide is `not_found` to a remote write and never matched as its duplicate (`test/remote-fact-write-private-provenance.test.ts`, both engines). Legacy slug-set helpers only enumerate names; they never authorize another row's data. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.
-- `src/core/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (a `regen:all` artifact). Tests: `test/qm-memory-tools.test.ts` (both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).
- `src/core/search/projection-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only, if none pending) or unknown; LIMIT 1 arms use the v161 pending index. Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 7b13ea6e6b..2d9f18b6ac 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -81,6 +81,7 @@ const VETTED_BUILDERS: Record<string, string> = {
readersAllowedSql: 'src/core/search/private-visibility.ts: GBRA-218 readers predicate over a caller alias; splices only identities that pass validIdentity (member:/group: plus [a-z0-9._-]), else none',
callerReadersAllowedSql: 'src/core/search/private-visibility.ts: GBRA-231 readersAllowedSql for the current caller, one conjunct per audience identity; each identity passes validIdentity',
privacyForCaller: 'src/core/search/private-visibility.ts: the caller privacy arm (TRUE, or the given predicate ORed with private-readable source ids checked by isValidSourceId); callers pass a constant alias and a vetted predicate builder',
+ factVisibilitySql: 'src/core/access/member-facts.ts: visibility values filtered to the constant set world/private; widened only by memberFactAdmitSql, whose member id passed ACCESS_ID_RE (no quote) and whose page test is privatePagesFilterForCaller; no values',
privateProvenanceFilterUnderPolicy: 'src/core/search/private-visibility.ts: constant fact-provenance predicate (readers part with no identity, privacy part dropped only under an operator relaxation); no values',
stagingNeedsTextSql: 'src/core/page-body/schema.ts: constant live-staging text-reference EXISTS predicate over a caller text alias; no values (Wave B purge)',
atomRetirementPurgeHold: 'src/core/persistence/atom-retirement-hold.ts: constant #7013 restorable-atom purge-hold predicate over a caller pages alias; no values',
diff --git a/src/core/access/actor.ts b/src/core/access/actor.ts
index a2fe302039..ebb2fe6ec9 100644
--- a/src/core/access/actor.ts
+++ b/src/core/access/actor.ts
@@ -18,7 +18,7 @@ import { hostOnlyError } from '../ops/op-fix.ts';
import { catalogueError, ERROR_CATALOGUE } from '../error-catalogue.ts';
import type { CallerAccess } from '../search/private-visibility.ts';
import { identityFor } from './principals.ts';
-import { isUndefinedColumnError, isUndefinedTableError } from '../utils.ts';
+import { isMissingSchemaObject } from '../utils.ts';
import { memberIdentity } from './members.ts';
import { folderAccessFor } from './caller.ts';
import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, attestRightFrom, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER, type AttestedActor, type AttestRight } from './actor-model.ts';
@@ -59,7 +59,7 @@ export async function attestRightOf(engine: Pick<BrainEngine, 'executeRaw'>, cal
} catch (e) {
// A schema before the attest columns has no right. Any other failure (a lock timeout, an aborted transaction) is
// rethrown: read as "no right" it would refuse a stored write for good instead of letting it retry.
- if (!isUndefinedTableError(e) && !isUndefinedColumnError(e, 'attest_')) throw e;
+ if (!isMissingSchemaObject(e, 'column', ['attest_actor', 'attest_ops', 'member_id'])) throw e;
}
return null;
}
@@ -131,7 +131,7 @@ export function actorNotAttested(reason: ActorReason, caller: ActorCaller, ctx:
`Remove ${ACTOR_ARGUMENT} from the arguments. A trusted system names the person in the ${ACTOR_HEADER} header from a credential holding the attest right (gbrain auth rescope ... --attest-actor qm on the brain host).`, { reason, docs });
case 'actor_required':
return opError('actor_not_attested', `${ctx.op} writes only as an attested person, and this call names none (no ${ACTOR_HEADER} header on a credential holding the attest right), so nothing was written.`,
- `Send ${ACTOR_HEADER} with the person's canonical id from a credential the brain operator granted the attest right (gbrain auth rescope --client <id> --attest-actor qm). To save a fact as yourself, call remember.`, { reason, docs });
+ `Send ${ACTOR_HEADER} with the person's canonical id from a credential the brain operator granted the attest right (${rescope(['--attest-actor', 'qm']).join(' ')}). To save a fact as yourself, call remember.`, { reason, docs });
case 'audience_not_supported':
return opError('actor_not_attested', `This request carries ${QM_AUDIENCE_HEADER} (a channel audience), which this brain does not serve yet, so nothing was read or written.`,
`Send the call without ${QM_AUDIENCE_HEADER}. Channel turns are refused until wave 2; a call for one person sends ${ACTOR_HEADER} alone.`, { reason, docs });
@@ -164,7 +164,7 @@ export async function linkedMember(engine: Pick<BrainEngine, 'executeRaw'>, syst
} catch (e) {
// GST-359 D: only a schema before the link tables reads as unlinked. A database failure (an aborted transaction under
// a concurrent publication, a lock timeout) is rethrown, so a stored write retries instead of failing as actor_unlinked.
- if (!isUndefinedTableError(e)) throw e;
+ if (!isMissingSchemaObject(e, 'table', ['access_member_links', 'access_members', 'access_group_members'])) throw e;
return null;
}
}
diff --git a/src/core/access/member-facts.ts b/src/core/access/member-facts.ts
index 3e1c62a5bd..83d7e76bd2 100644
--- a/src/core/access/member-facts.ts
+++ b/src/core/access/member-facts.ts
@@ -140,10 +140,15 @@ export function callerIdentityKey(): string {
return createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 16);
}
-/** A per-session state key (the delta cursor, context_pack's session) for the current caller: `base` plus the identity key. */
+/**
+ * A per-session state key (the delta cursor) for the current caller: `base` for a credential reading as itself, so a
+ * change to its member's groups or the upgrade keeps its cursor; otherwise `base` plus the person the call serves (the
+ * attested member, or the asserted audience entries), never the group-derived identity.
+ */
export function callerSessionKey(base: string | null): string | null {
- const key = callerIdentityKey();
- return key ? `${base ?? 'remote'}#id:${key}` : base;
+ const access = currentCallerAccess();
+ const person = access.actor ? { actor: [access.actor.system, access.actor.member] } : access.audience ? { audience: [...access.audience].sort() } : null;
+ return person ? `${base ?? 'remote'}#id:${createHash('sha256').update(JSON.stringify(person)).digest('hex').slice(0, 16)}` : base;
}
/** Whether a stored write's actor is the current caller's: both unattested, or the same system and member. */
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index a3f9856e6b..8e625fb690 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -190,8 +190,7 @@ export async function runPhaseConsolidate(
AND entity_slug IS NOT NULL
AND (attributed_to IS NULL OR attributed_to = 'user')
AND ($2::boolean=false OR visibility='world')
- AND ($1::text IS NULL OR source_id=$1)
- AND NOT ${readersSourcedFactSql('facts')}
+ AND ($1::text IS NULL OR source_id=$1) AND NOT ${readersSourcedFactSql('facts')}
GROUP BY source_id, entity_slug
HAVING COUNT(*) >= $3
`, [opts.sourceId ?? null, managed, minPerBucket]);
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index a39907dd89..2e4d858348 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -64,6 +64,7 @@ import { readTaintInputs, derivedWriteTrust, recordTaintEdges } from '../trust/t
import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, mergeGateTally, type GateTally } from '../trust/derived-gate.ts';
import { decideFactWrite } from '../write-gate-store.ts';
import { commitExtractionPlan, planExtraction, readPageWatermark, type InputTruncated } from '../extraction-watermark.ts';
+import { onMemberPageSql } from '../access/member-facts.ts';
// The notability-filter vocabulary lives in notability-filter.ts; re-exported for existing importers.
export { NOTABILITY_FILTERS, coerceNotabilityFilter, type FactNotabilityFilter } from './notability-filter.ts';
@@ -746,6 +747,14 @@ async function derivedFactWriter(ctx: FactsBackstopCtx, input: PipelineInput, de
return { insertDerivedFact, gateGroup, write_gate };
}
+/** GST-359: dedup candidates on a member page. Such a fact is that member's alone, never another write's duplicate. */
+async function memberPageFactIds(engine: BrainEngine, sourceId: string, ids: number[]): Promise<Set<number>> {
+ if (!ids.length) return new Set();
+ const rows = await engine.executeRaw<{ id: number | string }>(
+ `SELECT id FROM facts WHERE source_id = $1 AND id = ANY($2::bigint[]) AND ${onMemberPageSql('facts')}`, [sourceId, ids]);
+ return new Set(rows.map(r => Number(r.id)));
+}
+
/** The actual pipeline body — always runs inside a BudgetTracker scope (#4210). */
async function runPipelineBodyInner(
input: PipelineInput,
@@ -876,15 +885,12 @@ async function runPipelineBodyInner(
const exact = await decideSingleFact(ctx.engine, ctx.sourceId, { entity_slug: resolvedSlug, fact: f.fact, kind: f.kind ?? 'fact', visibility, attributed_to: f.attributed_to ?? null }, null);
let matchedExistingId: number | null = exact?.candidate?.id ?? null;
if (matchedExistingId === null && resolvedSlug && f.embedding && !f.entity_inferred) {
- const candidates = await ctx.engine.findCandidateDuplicates(
- ctx.sourceId,
- resolvedSlug,
- f.fact,
- { embedding: f.embedding, embeddingModel: f.embedding_model, k: DEDUP_CANDIDATE_LIMIT, attributedTo: f.attributed_to ?? null },
- );
+ const candidates = await ctx.engine.findCandidateDuplicates(ctx.sourceId, resolvedSlug, f.fact,
+ { embedding: f.embedding, embeddingModel: f.embedding_model, k: DEDUP_CANDIDATE_LIMIT, attributedTo: f.attributed_to ?? null });
+ const memberOwned = await memberPageFactIds(ctx.engine, ctx.sourceId, candidates.map(c => c.id));
let top: { row: typeof candidates[number]; score: number } | null = null;
for (const c of candidates) {
- if (!c.embedding) continue;
+ if (!c.embedding || memberOwned.has(Number(c.id))) continue;
const s = cosineSimilarity(f.embedding, c.embedding);
if (!top || s > top.score) top = { row: c, score: s };
}
diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.ts
index 989307d61f..e754b9f9fc 100644
--- a/src/core/facts/capture-dedup.ts
+++ b/src/core/facts/capture-dedup.ts
@@ -35,6 +35,7 @@ import { corpusFileSessionId } from '../context/corpus-segments.ts';
import { writeHeartbeat } from '../context/hook-heartbeat.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
import { cosineSimilarity } from './classify.ts';
+import { onMemberPageSql } from '../access/member-facts.ts';
export const CAPTURE_LANES = ['hook:writeback', 'sweep:corpus', 'hook:compact'] as const;
export const CAPTURE_DEDUP_WINDOW_MS = 15 * 60 * 1000;
@@ -175,6 +176,7 @@ export async function findCaptureDuplicate(scope: CaptureScope, candidate: Captu
AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3) AND expired_at IS NULL AND (valid_until IS NULL OR valid_until>now())
AND ($4::text IS NULL OR attributed_to IS NULL OR attributed_to=$4)
AND ($5::text IS NULL OR source_markdown_slug IS DISTINCT FROM $5 OR source NOT LIKE 'cli:extract-conversation-facts%')
+ AND NOT ${onMemberPageSql('facts')}
ORDER BY created_at DESC, id DESC LIMIT ${CAPTURE_DEDUP_SCAN_LIMIT}`,
[scope.sourceId, visibilities, candidate.fact, candidate.attributedTo ?? null, scope.replacingPage ?? null]);
const conversation = canonicalConversationKey(scope.sessionId);
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index fbc792f018..4b6f24f2ab 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -1029,8 +1029,7 @@ const delta: Operation = {
// for the trusted CLI/hook lane, gated on STRICT ctx.remote === false —
// anything else (true, undefined via cast bypass) is remote. Remote callers
// use their auth client id; an auth-LESS or blank-id remote (stdio MCP)
- // gets the shared 'remote' sentinel — never collapsed into 'local'.
- // GST-359 C2: plus the caller's identity, so two people behind one credential and one session id never share a cursor.
+ // gets the shared 'remote' sentinel — never collapsed into 'local'. GST-359: plus the person an attested or audience call serves.
const clientId = ctx.remote === false ? null : callerSessionKey(ctx.auth?.clientId?.trim() || 'remote');
const includePrivate = p.include_private === true && ctx.remote === false;
const budgetTokens =
diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.ts
index 0fe2d209f0..a05264c781 100644
--- a/src/core/ops/qm-memory.ts
+++ b/src/core/ops/qm-memory.ts
@@ -16,6 +16,7 @@
* QM reads success codes only from `structuredContent`. An unlinked actor on memory_recall is answered by dispatch
* (actorRefusal) with empty content and `{facts: [], truncated: false, code: 'actor_unlinked'}` (unlinkedRecallResult).
*/
+import { createHash } from 'node:crypto';
import type { Operation, OperationContext, ParamDef } from './contract.ts';
import { opError, OperationError } from './contract.ts';
import { federatedSearchScope } from './context.ts';
@@ -220,7 +221,11 @@ const memory_write: Operation = {
throw invalid('idempotency_key must be 1 to 128 visible ASCII characters (no spaces).', 'Send a stable key per write, for example a UUID; the same key replays the same write.');
}
const key = p.idempotency_key;
- const items = await Promise.all(parseFacts(p.facts, actor.external_id).map(async (f, i) => ({ ...f, request_id: await memoryWriteRequestId(actor.member, key, i) })));
+ const parsed = parseFacts(p.facts, actor.external_id);
+ // Every fact's replay intent carries the whole batch, so a key reused with more, fewer or other facts is an
+ // idempotency_conflict at its first fact, before anything new is written.
+ const qm_batch = createHash('sha256').update(JSON.stringify(parsed)).digest('hex');
+ const items = await Promise.all(parsed.map(async (f, i) => ({ ...f, qm_batch, request_id: await memoryWriteRequestId(actor.member, key, i) })));
const { verbOperations } = await import('../verbs.ts');
const remember = verbOperations.find(op => op.name === 'remember')!;
for (const [index, item] of items.entries()) {
diff --git a/src/core/schema-migrations/v286-qm-actor-links.ts b/src/core/schema-migrations/v286-qm-actor-links.ts
index f5a4d7984a..a5dafc8561 100644
--- a/src/core/schema-migrations/v286-qm-actor-links.ts
+++ b/src/core/schema-migrations/v286-qm-actor-links.ts
@@ -16,7 +16,7 @@ import type { Migration } from './types.ts';
// tokens issued before this migration: never attested). Database only, so a
// repo-less brain gets it unchanged. Nothing is rewritten on upgrade.
// No schema.sql mirror: like v282 and v283, these exist only through
-// migrations. Provisional number (C1 placeholder): renumbered at the merge slot.
+// migrations. Numbered at the train C merge after train M (v282-v285).
export const v286: Migration = {
version: 286,
name: 'qm_actor_links',
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 975b454c94..5c665220d7 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -935,7 +935,12 @@ export async function dispatchToolCall(
auth: opts.auth, transport: opts.transport, audienceAsserted: audience !== null });
access = attested ? attested.access : await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience);
} catch (e) {
- if (!(e instanceof OperationError) || !/^(on_behalf_of_|actor_)/.test(String(e.code))) throw e;
+ // GST-359: a call that names a person gets every failure here (a lock timeout reading its link included) in the
+ // envelope QM reads, never a thrown call; anything else keeps the caller's own error path.
+ if (!(e instanceof OperationError) || !/^(on_behalf_of_|actor_)/.test(String(e.code))) {
+ if (!actorNamed) throw e;
+ return withStructuredError(errorResult(e, opts, { op: name }));
+ }
assertion(e.code as AudienceAuditEvent['outcome'], e.reason);
return qmMemoryToolResult(name, actorNamed ? actorRefusal(e, opts, name, header, params) : errorResult(e, opts, { op: name }));
}
@@ -965,7 +970,11 @@ function actorRefusal(e: OperationError, opts: DispatchOpts, op: string, header:
try { recallArguments(params); } catch (invalid) { if (invalid instanceof OperationError) return actorRefusal(invalid, opts, op, header, params); throw invalid; }
return { ...unlinkedRecallResult(), _meta: { access: { code: 'actor_unlinked', member: null, groups: [], audience: null, actor: { system: 'qm', external_id: header } } } };
}
- const out = errorResult(e, opts, { op });
+ return withStructuredError(errorResult(e, opts, { op }));
+}
+
+/** An error result with its JSON envelope's code, message, reason and fix also in `structuredContent.error`, which QM reads. */
+function withStructuredError(out: ToolResult): ToolResult {
try {
const env = JSON.parse(out.content[0]!.text) as Record<string, unknown>;
out.structuredContent = { error: { code: env.code, message: env.message, ...(env.reason ? { reason: env.reason } : {}), ...(env.fix ? { fix: env.fix } : {}) } };
diff --git a/test/access-member-facts-dedup.test.ts b/test/access-member-facts-dedup.test.ts
new file mode 100644
index 0000000000..a16bce5292
--- /dev/null
+++ b/test/access-member-facts-dedup.test.ts
@@ -0,0 +1,87 @@
+/**
+ * GST-359 train C: writers that dedup by similarity never match a fact on a member page.
+ *
+ * 1. Protects: a member's fact lives on memory/members/<member>, readable by that member alone, with the entity kept as
+ * metadata. extract_facts' cosine dedup and the capture lanes' exact dedup read candidates by entity, so without a
+ * member-page exclusion another caller's world fact is dropped as a "duplicate" of a fact it may not read, and the
+ * reply hands it that fact's id (an existence oracle on a page its read filter hides).
+ * 2. Fails when: bob-example's extract_facts reports alice-example's member fact id as its duplicate and inserts nothing,
+ * or findCaptureDuplicate matches the member fact.
+ * 3. Existing coverage: test/access-member-facts.test.ts pins decideSingleFact (remember) and supersession on member pages.
+ * 4. Real seams: member-bound OAuth client-credentials tokens through MCP dispatch on a repo-less PGLite brain; chat and
+ * embeddings stubbed (one constant vector, so every candidate is a cosine match), a calibrated threshold set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { findCaptureDuplicate } from '../src/core/facts/capture-dedup.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+
+const DIMS = 1536;
+const VEC = (() => { const v = new Array<number>(DIMS).fill(0); v[7] = 1; return v; })();
+const SRC = 'member-dedup';
+const ACME = 'companies/acme-example';
+const CLAIM = 'Acme Example is quietly preparing a sale to a larger harbor firm';
+
+describe('similarity dedup never matches a member-page fact (pglite, repo-less)', () => {
+ let engine: BrainEngine;
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const tokens: Record<string, string> = {};
+ let aliceFactId = '';
+ const call = async (who: string, op: string, params: Record<string, unknown>) => {
+ const auth = await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo;
+ const out = await dispatchToolCall(engine, op, params, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'] });
+ const text = out.content.map(c => c.text).join('\n');
+ let json: Record<string, any> = {};
+ try { json = JSON.parse(text); } catch { /* prose */ }
+ return { isError: out.isError === true, text, json };
+ };
+
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, chat_model: 'openai:gpt-4o-mini', env: { OPENAI_API_KEY: 'test' } } as never);
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => VEC) })) as never);
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: JSON.stringify({ facts: [{ fact: CLAIM, kind: 'fact', entity: ACME, confidence: 1.0, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' }) as never);
+ engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
+ for (const id of ['alice-example', 'bob-example']) await addMember(engine, id);
+ await engine.setConfig('facts.supersession_thresholds', JSON.stringify({ 'openai:text-embedding-3-small@1536': 0.95 }));
+ await importFromContent(engine, ACME, '---\ntype: company\ntitle: Acme Example\n---\n# Acme Example\n\nAcme example builds harbor ledgers.', { sourceId: SRC });
+ for (const who of ['alice', 'bob']) {
+ const c = await provider().registerClientManual('dedup-' + who + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);
+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { member: who + '-example' });
+ tokens[who] = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;
+ }
+ const saved = await call('alice', 'remember', { fact: CLAIM, entity: ACME, provenance: 'alice dm' });
+ expect(saved.isError).toBe(false);
+ const [row] = await engine.executeRaw<{ id: number | string }>('SELECT id FROM facts WHERE source_id = $1 AND source_markdown_slug = $2', [SRC, 'memory/members/alice-example']);
+ aliceFactId = String(row!.id);
+ }, 120_000);
+
+ afterAll(async () => { __setEmbedTransportForTests(null); __setChatTransportForTests(null); resetGateway(); await engine.disconnect(); });
+
+ test('extract_facts saves its own world fact instead of reporting another member\'s private fact as its duplicate', async () => {
+ const out = await call('bob', 'extract_facts', { turn_text: 'In our call today: ' + CLAIM + '. Worth remembering for the deal review next week.', visibility: 'world', entity_hints: [ACME] });
+ expect(out.isError).toBe(false);
+ expect((out.json.fact_ids ?? []).map(String)).not.toContain(aliceFactId);
+ expect(out.text).not.toContain('"duplicate":1');
+ const world = await engine.executeRaw('SELECT id FROM facts WHERE source_id = $1 AND visibility = $2 AND entity_slug = $3', [SRC, 'world', ACME]);
+ expect(world.length).toBe(1);
+ }, 60_000);
+
+ test('the capture lanes\' exact dedup never matches a member-page fact', async () => {
+ for (const visibility of ['private', 'world'] as const) {
+ const match = await findCaptureDuplicate({ engine, sourceId: SRC, lane: 'cli:extract-conversation-facts', sessionId: null, anchor: null }, { fact: CLAIM, entitySlug: ACME, visibility });
+ expect(match?.id === undefined ? null : String(match.id)).not.toBe(aliceFactId);
+ }
+ }, 60_000);
+});
diff --git a/test/access-member-facts.test.ts b/test/access-member-facts.test.ts
index 8d010245c6..ebe587f384 100644
--- a/test/access-member-facts.test.ts
+++ b/test/access-member-facts.test.ts
@@ -28,7 +28,7 @@ import { sqlQueryForEngine } from '../src/core/sql-query.ts';
import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';
import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
import { __resetHotMemoryCacheForTests, getBrainHotMemoryMeta } from '../src/core/facts/meta-hook.ts';
-import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { addGroup, addMember, bindCredential } from '../src/core/access/members.ts';
import { linkMember } from '../src/core/access/actor.ts';
import { memberPageSlug } from '../src/core/access/member-facts.ts';
import { decideSingleFact, type SingleFactIntent } from '../src/core/facts/single-prepare.ts';
@@ -156,7 +156,7 @@ for (const kind of testBackends()) {
expect((await call(who.alice(), 'recall', { query: 'harbor' })).all).toContain(CANARY.alice);
for (const marker of [{ visibility: 'private' }, { derived_from: 'notes/private-origin-example' }]) {
if ('derived_from' in marker) await importFromContent(engine, 'notes/private-origin-example', '---\ntype: note\nvisibility: private\n---\n# Private origin\n', { sourceId: SRC });
- await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter || $3::jsonb WHERE source_id = $1 AND slug = $2', [SRC, page, JSON.stringify(marker)]);
+ await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter || jsonb_build_object($3::text, $4::text) WHERE source_id = $1 AND slug = $2', [SRC, page, ...Object.entries(marker)[0]!]);
try {
__resetPrivateVisibilityCacheForTests();
__resetHotMemoryCacheForTests();
@@ -167,17 +167,17 @@ for (const kind of testBackends()) {
expect((await call(who.alice(), 'context_pack', { query: 'harbor oolong', entities: [ACME] })).all).not.toContain(CANARY.alice);
const [bobFact] = await engine.executeRaw<{ id: number | string }>('SELECT id FROM facts WHERE fact LIKE $1 AND expired_at IS NULL', ['%' + CANARY.bob + '%']);
const bobPage = 'memory/members/bob-example';
- await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter || $3::jsonb WHERE source_id = $1 AND slug = $2', [SRC, bobPage, JSON.stringify(marker)]);
+ await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter || jsonb_build_object($3::text, $4::text) WHERE source_id = $1 AND slug = $2', [SRC, bobPage, ...Object.entries(marker)[0]!]);
try {
const forgot = await call(who.bobToken(), 'forget_fact', { id: Number(bobFact!.id) });
expect({ isError: forgot.isError, code: forgot.json.code }).toEqual({ isError: true, code: 'fact_not_found' });
const [still] = await engine.executeRaw<{ expired_at: unknown }>('SELECT expired_at FROM facts WHERE id = $1', [bobFact!.id]);
expect(still!.expired_at).toBeNull();
} finally {
- await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter - $3 WHERE source_id = $1 AND slug = $2', [SRC, bobPage, Object.keys(marker)[0]]);
+ await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter - $3::text WHERE source_id = $1 AND slug = $2', [SRC, bobPage, Object.keys(marker)[0]]);
}
} finally {
- await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter - $3 WHERE source_id = $1 AND slug = $2', [SRC, page, Object.keys(marker)[0]]);
+ await engine.executeRaw('UPDATE pages SET frontmatter = frontmatter - $3::text WHERE source_id = $1 AND slug = $2', [SRC, page, Object.keys(marker)[0]]);
__resetPrivateVisibilityCacheForTests();
__resetHotMemoryCacheForTests();
}
@@ -277,6 +277,19 @@ for (const kind of testBackends()) {
}
}, 60_000);
+ test('delta: a member\'s cursor survives a change to the member\'s groups, and the bound credential keeps its pre-upgrade key', async () => {
+ const session = 'delta-groups-' + randomUUID().slice(0, 6);
+ expect((await call(who.bobToken(), 'delta', { session_id: session })).all).toContain('started this session');
+ const [row] = await engine.executeRaw<{ client_id: string | null }>('SELECT client_id FROM session_context_state WHERE source_id = $1 AND position($2 in session_id) > 0', [SRC, session]);
+ expect(row?.client_id).toBe((await verify(tokens.bob!)).clientId);
+ await new Promise(r => setTimeout(r, 30));
+ await importFromContent(engine, 'notes/delta-groups-example', '---\ntype: note\n---\n# Delta groups\n\ncanarydeltagroups harbor note.', { sourceId: SRC });
+ await addGroup(engine, 'delta-team-example', ['bob-example']);
+ const later = await call(who.bobToken(), 'delta', { session_id: session });
+ expect(later.isError).toBe(false);
+ expect(later.all).toContain('notes/delta-groups-example');
+ }, 60_000);
+
test('receipts: Alice\'s write receipt is invisible to Bob and the bare client, and her request_id never replays for Bob', async () => {
const requestId = 'c2-receipt-' + randomUUID().slice(0, 6);
const written = await remember(who.alice(), 'Alice signs the harbor charter ' + CANARY.alice + 'r', { request_id: requestId });
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 05a2ab1929..3d8b84b351 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -444,6 +444,7 @@ test/purge-global-marker.test.ts
test/purge-missing-cache-6911.test.ts
test/purge-read-surfaces.test.ts
test/purge-sync-tombstone-hold-7130.test.ts
+test/qm-memory-tools.test.ts
test/read-meta-diag.test.ts
test/recall-page-fill.test.ts
test/receipt-compaction-newest-sync-gbra130.test.ts
diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.ts
index f0cd0cc506..19a4d22a9a 100644
--- a/test/qm-memory-tools.test.ts
+++ b/test/qm-memory-tools.test.ts
@@ -237,6 +237,12 @@ for (const kind of testBackends()) {
expect(changed.isError).toBe(true);
expect({ code: changed.json.code, write_error: changed.json.write_error }).toEqual({ code: 'invalid_params', write_error: 'idempotency_conflict' });
expect(await factRows('canaryreplay three')).toHaveLength(0);
+ const longer = await write(alice, [...facts, { fact: 'Alice adds a third canaryreplay extra', provenance: 'turn 1' }], key);
+ expect({ isError: longer.isError, write_error: longer.json.write_error }).toEqual({ isError: true, write_error: 'idempotency_conflict' });
+ expect(await factRows('canaryreplay extra')).toHaveLength(0);
+ const shorter = await write(alice, [facts[0]!], key);
+ expect({ isError: shorter.isError, write_error: shorter.json.write_error }).toEqual({ isError: true, write_error: 'idempotency_conflict' });
+ expect(await factRows('canaryreplay')).toHaveLength(2);
}, 60_000);
test('the same key from two members is two writes, each on its own page', async () => {
@@ -383,6 +389,28 @@ for (const kind of testBackends()) {
expect({ isError: named.isError, code: named.json.code, reason: named.json.reason }).toEqual({ isError: true, code: 'actor_not_attested', reason: 'no_attest_right' });
}, 60_000);
+ test('a database failure while resolving the person comes back as a structured error, never a thrown call', async () => {
+ const target = engine as { executeRaw: typeof engine.executeRaw };
+ const own = Object.prototype.hasOwnProperty.call(target, 'executeRaw');
+ const real = target.executeRaw;
+ target.executeRaw = (async function (this: BrainEngine, ...args: Parameters<typeof engine.executeRaw>) {
+ if (typeof args[0] === 'string' && args[0].includes('access_member_links')) throw Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' });
+ return real.apply(this, args);
+ }) as typeof engine.executeRaw;
+ try {
+ for (const [op, args] of [['memory_recall', { query: 'budget ledger' }], ['memory_write', { facts: [{ fact: 'Lock timeout canarylocktimeout', provenance: 'turn 1' }], idempotency_key: randomUUID() }]] as const) {
+ const out = await call(alice, op, args as Record<string, unknown>);
+ expect(out.isError).toBe(true);
+ expect(typeof out.json.code).toBe('string');
+ expect(out.structured?.error?.code).toBe(out.json.code);
+ }
+ } finally {
+ if (own) target.executeRaw = real;
+ else delete (target as Partial<typeof target>).executeRaw;
+ }
+ expect(await factRows('canarylocktimeout')).toHaveLength(0);
+ }, 60_000);
+
test('fact text arrives without fence or heading markers', async () => {
await write(alice, [{ fact: '## Harbor rules\n' + TICKS + '\nkeep the ledger canaryfence\n' + TICKS, provenance: 'turn 4' }]);
const out = await recall(alice, 'harbor ledger rules');