Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(mcp): attested actor via x-qm-actor, re-resolved for writes and jobs (GST-359 C1)
garrytan8860fbd0a398
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 3a39dcfa74..b12f91df49 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -15,7 +15,7 @@ import { opAllowedForBoundClient } from '../core/operations.ts';import { authTransport } from '../core/ops/contract.ts';import type { AuthInfo, Operation } from '../core/operations.ts';import { disabledOpsForPublishGates } from '../mcp/publish-gates.ts';-import { installInstructionsResolver, readInstructionContent, resolveMcpInstructions } from '../mcp/instructions.ts';+import { installInstructionsResolver, MCP_SERVER_DESCRIPTION, readInstructionContent, resolveMcpInstructions } from '../mcp/instructions.ts';import { httpInstructionTools } from '../mcp/initialize-context.ts';import { installCapabilitiesResource, mcpAdministrationGuidance } from '../mcp/capabilities.ts';import { createSkillResources } from '../mcp/skill-resources.ts';@@ -42,6 +42,7 @@ import {} from '../mcp/surface.ts';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';+import { ACTOR_HEADER } from '../core/access/actor-model.ts';import { serializeError } from '../core/errors.ts';import { VERSION } from '../version.ts';import { executeRawJsonb } from '../core/sql-query.ts';@@ -64,6 +65,8 @@ interface McpRequestState {thinClient: boolean;/** GBRA-231: the X-Gbrain-On-Behalf-Of header (a shared agent's audience); bounded by the credential's may_act_for in dispatch. */onBehalfOfHeader: string | undefined;+ /** GST-359 C1: the x-qm-actor header (a trusted system names the person); honoured in dispatch only for an attest credential. */+ actorHeader: string | undefined;}export function mountMcp(app: Express, ctx: ServeHttpContext): void {@@ -175,7 +178,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {surface === 'full' && authInfo.allowedOperations == null ? undefined : new Set(mcpOperations.map(o => o.name));const thinClient = isGbrainThinClient(req.get(GBRAIN_CLIENT_HEADER));const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient,- onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER) };+ onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), actorHeader: req.get(ACTOR_HEADER) };const server = createMcpRequestServer(ctx, state, writeback);await serveMcpRequest(server, req, res);}@@ -203,7 +206,7 @@ function createMcpRequestServer(});}const server = new Server(- { name: 'gbrain', version: VERSION },+ { name: 'gbrain', version: VERSION, description: MCP_SERVER_DESCRIPTION },{capabilities: { tools: {}, resources: {} },// #4748: contract (+ opt-in writeback section) + deployment identity.@@ -411,6 +414,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques...(sessionId ? { sessionId } : {}),...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),onBehalfOf: { header: state.onBehalfOfHeader, requestMeta: (request.params as { _meta?: unknown })._meta },+ actor: { header: state.actorHeader },takesHoldersAllowList: tokenAllowList,sourceId: tokenSourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}),diff --git a/src/core/access/actor-model.ts b/src/core/access/actor-model.tsnew file mode 100644index 0000000000..2f6dc29a9f--- /dev/null+++ b/src/core/access/actor-model.ts@@ -0,0 +1,42 @@+/**+ * GST-359 C1: the dependency-free part of the attested actor (access/actor.ts): the constants, the stored-actor shape and+ * the attest right a credential row carries. Verifiers and stored-authority parsers import this module alone.+ */++/** The header the trusted system sets on every HTTP request of a call (case-insensitive). */+export const ACTOR_HEADER = 'x-qm-actor';+/** The tool argument the system also sends; equal to the header on an attested call, stripped before the handler. */+export const ACTOR_ARGUMENT = 'acting_user';+export const ATTEST_SYSTEMS: readonly string[] = ['qm'];+export const DEFAULT_ATTEST_OPS: readonly string[] = ['memory_recall', 'memory_write'];+/** Canonical person ids: 1-256 visible ASCII characters (QM's credential broker rule), no case folding. */+export const EXTERNAL_ID_RE = /^[\x21-\x7e]{1,256}$/;++export interface AttestRight { system: string; ops: string[] }+export interface AttestedActor { system: string; external_id: string; member: string }++/**+ * The attest right a credential row carries, given the grant that issued the token (`legacy` for a legacy token,+ * else the OAuth grant type) and its member binding. Null unless the system is known, the credential is bound to no+ * member, and the token is a legacy token or a client-credentials token.+ */+export function attestRightFrom(row: Record<string, unknown> | undefined, grant: unknown, member: unknown): AttestRight | null {+ const system = row?.attest_actor;+ if (typeof system !== 'string' || !ATTEST_SYSTEMS.includes(system) || member != null) return null;+ if (grant !== 'legacy' && grant !== 'client_credentials') return null;+ const ops = Array.isArray(row!.attest_ops) ? (row!.attest_ops as unknown[]).filter((v): v is string => typeof v === 'string') : [...DEFAULT_ATTEST_OPS];+ return { system, ops };+}++/** The verify join plus the live attest right, for AuthInfo (a verifier spreads the result). */+export function withAttestRight<T extends { member: unknown }>(binding: T, row: Record<string, unknown>, grant: unknown): T & { attest: AttestRight | null } {+ return { ...binding, attest: attestRightFrom(row, grant, binding.member) };+}++/** A stored actor value (WriteAuthority.actingFor, a job grant's actor), or null when it is not one. */+export function parseStoredActor(value: unknown): AttestedActor | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const v = value as Record<string, unknown>;+ return typeof v.system === 'string' && ATTEST_SYSTEMS.includes(v.system) && typeof v.external_id === 'string' && EXTERNAL_ID_RE.test(v.external_id)+ && typeof v.member === 'string' ? { system: v.system, external_id: v.external_id, member: v.member } : null;+}diff --git a/src/core/access/actor.ts b/src/core/access/actor.tsnew file mode 100644index 0000000000..89c8ef51c4--- /dev/null+++ b/src/core/access/actor.ts@@ -0,0 +1,266 @@+/**+ * GST-359 C1 (GBRA-218): the attested actor. A trusted system's credential (only `qm` today) names the person a call+ * serves in the `x-qm-actor` header: an opaque canonical id (a Slack id, an email principal, `oidc:<hash>:<subject>`),+ * 1-256 visible ASCII characters, compared exactly. gbrain maps it through `access_member_links` to one enabled member+ * and reads and writes as that member, never relaxing privacy.+ *+ * Two facts must both hold, re-read on every call and at every later publication or job tool call (actorCoverage):+ * - the credential holds the attest right for the system: `attest_actor` on a legacy token bound to no member, or on+ * an OAuth client bound to no member whose token came from the client-credentials grant (the verifier checks the+ * grant that issued the token; a stored principal checks the client's registration);+ * - the id is linked to an enabled member.+ * Everything lives in the database, so a repo-less brain gets it unchanged.+ */+import type { BrainEngine } from '../engine.ts';+import type { AuthInfo } from '../ops/contract.ts';+import { opError, type OperationError } from '../ops/contract.ts';+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 { memberIdentity } from './members.ts';+import { folderAccessFor } from './caller.ts';+import { ACTOR_ARGUMENT, ACTOR_HEADER, attestRightFrom, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, type AttestedActor, type AttestRight } from './actor-model.ts';++export * from './actor-model.ts';++const ATTESTABLE_SCOPES = new Set(['read', 'write', 'agent']);++export type ActorReason = 'no_attest_right' | 'op_not_attested' | 'argument_mismatch' | 'argument_without_attestation' | 'invalid_actor_id';+/** The operation metadata attestability reads (a subset of Operation, so this module never imports the registry). */+export interface AttestableOpShape { scope?: string; requiredScopes?: readonly string[]; localOnly?: boolean; cliOnly?: unknown }++type Principal = { kind: string; id: string };+export interface ActorCaller {+ auth?: Pick<AuthInfo, 'attest' | 'member' | 'clientName'> & { principal?: Principal };+ principal?: Principal;+}++/** The caller's live attest right: the verifier's on a live call, else a row lookup from the stored principal. */+export async function attestRightOf(engine: Pick<BrainEngine, 'executeRaw'>, caller: ActorCaller): Promise<AttestRight | null> {+ if (caller.auth?.attest !== undefined) return caller.auth.attest ?? null;+ const principal = caller.auth?.principal ?? caller.principal;+ try {+ if (principal?.kind === 'legacy_token') {+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT attest_actor, attest_ops, member_id FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL', [principal.id]);+ return attestRightFrom(row, 'legacy', row?.member_id);+ }+ if (principal?.kind === 'oauth_client') {+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ `SELECT attest_actor, attest_ops, member_id, grant_types, client_secret_hash IS NOT NULL AS confidential FROM oauth_clients+ WHERE client_id = $1 AND (to_jsonb(oauth_clients)->>'deleted_at') IS NULL`, [principal.id]);+ const cc = Array.isArray(row?.grant_types) && (row!.grant_types as unknown[]).includes('client_credentials') && row!.confidential === true;+ return attestRightFrom(row, cc ? 'client_credentials' : null, row?.member_id);+ }+ } catch { /* unreadable (a schema before the attest columns): no right */ }+ return null;+}++/** Whether an operation may ever run under an attested actor: the reserved memory pair or a read, write or agent op. */+export function attestableOp(name: string, op: AttestableOpShape | undefined): boolean {+ if (DEFAULT_ATTEST_OPS.includes(name)) return true;+ if (!op || op.localOnly || op.cliOnly) return false;+ return ATTESTABLE_SCOPES.has(op.scope ?? 'read') && !(op.requiredScopes ?? []).some(s => !ATTESTABLE_SCOPES.has(s));+}++/** A `--attest-ops` value: distinct operation names, each attestable; admin and membership ops are refused. */+export function parseAttestOps(raw: string, lookup: (name: string) => AttestableOpShape | undefined): string[] {+ const ops = [...new Set(raw.split(',').map(s => s.trim()).filter(Boolean))];+ if (!ops.length) throw opError('invalid_params', '--attest-ops needs at least one operation.', `Pass a comma-separated list, for example ${DEFAULT_ATTEST_OPS.join(',')}.`);+ const refused = ops.filter(op => !/^[a-z][a-z0-9_]{0,63}$/.test(op) || !attestableOp(op, lookup(op)));+ if (refused.length) {+ throw opError('invalid_params', `--attest-ops names ${refused.join(', ')}, which an attested actor can never run.`,+ `Name read, write or agent operations (gbrain --tools-json lists them) or the memory pair ${DEFAULT_ATTEST_OPS.join(',')}; admin, membership and local-only operations are never attestable.`,+ { why: 'An attested call runs as a person the trusted system names; it never carries operator authority.' });+ }+ return ops.sort();+}++function credentialArgv(caller: ActorCaller): string[] {+ const principal = caller.auth?.principal ?? caller.principal;+ if (principal?.kind === 'oauth_client') return ['--client', principal.id];+ return caller.auth?.clientName ? ['--token', caller.auth.clientName] : ['--id', principal?.id ?? '<token id>'];+}++const transportOf = (transport?: string) => ({ remote: true, transport: transport === 'stdio' ? 'stdio' as const : 'http' as const });++/** actor_not_attested with its reason, remedy and (where the operator can fix it) the rescope command. */+export function actorNotAttested(reason: ActorReason, caller: ActorCaller, ctx: { op: string; transport?: string; right?: AttestRight | null }): OperationError {+ const docs = ERROR_CATALOGUE.actor_not_attested.docs;+ const rescope = (extra: string[]) => ['gbrain', 'auth', 'rescope', ...credentialArgv(caller), ...extra];+ const hostOnly = (message: string, argv: string[], why: string, suggestion: string) =>+ Object.assign(hostOnlyError(transportOf(ctx.transport), 'actor_not_attested', message, argv, why, { reason, suggestion }), { docs });+ switch (reason) {+ case 'no_attest_right':+ return hostOnly(`This connection may not name the person it acts for (${ACTOR_HEADER}), so nothing was read or written.`, rescope(['--attest-actor', 'qm']),+ 'Grants this client-credentials client (or member-less legacy token) the right to name the person a QM call serves. Trusting a system to name people is the brain operator\'s decision.',+ 'Only a credential the brain operator granted the attest right may send the actor header. Call without it, or ask the operator to run the command in fix.');+ case 'op_not_attested':+ return hostOnly(`${ctx.op} is not in this connection's attested operations, so nothing was read or written.`,+ rescope(['--attest-actor', 'qm', '--attest-ops', [...new Set([...(ctx.right?.ops ?? DEFAULT_ATTEST_OPS), ctx.op])].sort().join(',')]),+ 'Lets an attested call run this operation as the person it names. Widening what a trusted system may do as a person is the brain operator\'s decision.',+ `An attested call runs only the operations the operator listed (default ${DEFAULT_ATTEST_OPS.join(', ')}); admin and membership operations never.`);+ case 'argument_mismatch':+ return opError('actor_not_attested', `The ${ACTOR_ARGUMENT} argument names someone other than the ${ACTOR_HEADER} header, so nothing was read or written.`,+ `The header decides whom the call serves; send ${ACTOR_ARGUMENT} equal to it, or leave it out. Text in a conversation never chooses whose notes are read.`, { reason, docs });+ case 'argument_without_attestation':+ return opError('actor_not_attested', `The ${ACTOR_ARGUMENT} argument is accepted only on an attested call, so nothing was read or written.`,+ `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 'invalid_actor_id':+ return opError('actor_not_attested', `The ${ACTOR_HEADER} header or the ${ACTOR_ARGUMENT} argument is not a canonical person id (1-256 visible ASCII characters), so nothing was read or written.`,+ 'Fix the harness code that sets the header: send the canonical id unchanged, with no spaces or control characters.', { reason, docs });+ }+}++/** actor_unlinked: the operator links the id to a member. dispatch's actorRefusal is the one place a recall tool may turn it into an empty result. */+export function actorUnlinked(externalId: string, transport?: string): OperationError {+ return Object.assign(hostOnlyError(transportOf(transport), 'actor_unlinked',+ 'The person this call names is not linked to an enabled member of this brain, so nothing was read or written.',+ ['gbrain', 'access', 'member', 'link', '<member>', '--qm', externalId],+ 'Links the canonical id to the member it belongs to; an unlinked id, or one linked to a disabled member, reads nothing. Who a person is on this brain is the operator\'s decision.',+ { suggestion: 'Ask the brain operator to link this person to their member (gbrain access member link <member> --qm <id>), or to enable the member if it is disabled.' }),+ { docs: ERROR_CATALOGUE.actor_unlinked.docs });+}++/** The enabled member linked to (system, external_id), with its identity; null when unlinked, disabled or unreadable. */+export async function linkedMember(engine: Pick<BrainEngine, 'executeRaw'>, system: string, externalId: string): Promise<{ member: string; groups: string[]; identity: string[] } | null> {+ try {+ const [row] = await engine.executeRaw<{ id: string; groups: string[] | null }>(+ `SELECT m.id, COALESCE(array_agg(g.group_id ORDER BY g.group_id) FILTER (WHERE g.group_id IS NOT NULL), '{}') AS groups+ FROM access_member_links l JOIN access_members m ON m.id = l.member_id LEFT JOIN access_group_members g ON g.member_id = m.id+ WHERE l.system = $1 AND l.external_id = $2 AND m.disabled_at IS NULL AND m.tombstoned_at IS NULL GROUP BY m.id`, [system, externalId]);+ if (!row) return null;+ const groups = row.groups ?? [];+ return { member: row.id, groups, identity: identityFor(row.id, groups) };+ } catch {+ return null;+ }+}++/**+ * The one coverage test for an attested actor, used by dispatch, write publication and job tool calls: the caller's+ * live attest right for the system, and a live link from the id to an enabled member. Returns that member's identity;+ * throws actor_not_attested (no_attest_right) or actor_unlinked.+ */+export async function actorCoverage(engine: Pick<BrainEngine, 'executeRaw'>, caller: ActorCaller, actor: { system: string; external_id: string }, transport?: string):+ Promise<{ member: string; groups: string[]; identity: string[] }> {+ const right = await attestRightOf(engine, caller);+ if (!right || right.system !== actor.system) throw actorNotAttested('no_attest_right', caller, { op: 'stored', transport });+ const linked = EXTERNAL_ID_RE.test(actor.external_id) ? await linkedMember(engine, actor.system, actor.external_id) : null;+ if (!linked) throw actorUnlinked(actor.external_id, transport);+ return linked;+}++/** A stored attested authority (a queued write, an agent job) re-resolved through actorCoverage: the same member must still be covered. */+export async function storedActorIdentity(engine: Pick<BrainEngine, 'executeRaw'>, principal: Principal, actor: AttestedActor): Promise<string[]> {+ const covered = await actorCoverage(engine, { principal }, actor);+ if (covered.member !== actor.member) throw actorUnlinked(actor.external_id);+ return covered.identity;+}++/**+ * The caller-access record of an attested call: a one-member audience of the linked member with privacy never relaxed+ * (no granted_sources, no operator hatch), whatever the attest credential's own grants say. An explicit mode, not B's+ * may_act_for path, which relaxes privacy for a one-member audience.+ */+export async function attestedCallerAccess(engine: Pick<BrainEngine, 'executeRaw'>, actor: AttestedActor, identity: string[]): Promise<Partial<CallerAccess>> {+ return {+ identity,+ audience: [`member:${actor.member}`],+ audienceIdentities: [],+ actor: { ...actor },+ ...await folderAccessFor(engine, identity),+ privateReadableSources: [],+ hidePrivate: true,+ applyRemoteReadPolicy: false,+ restricted: true,+ };+}++/** The actor channel a transport read from the request: the header value, undefined when absent. Never tool arguments. */+export interface ActorChannels { header?: string | null }++/**+ * The attested-actor decision for one remote call, made before any work. Null when the call names no actor (no header,+ * no argument): the caller's own identity or B's audience applies. Otherwise the access record and the arguments with+ * `acting_user` stripped, or a refusal: actor_not_attested with its reason, actor_unlinked, or B's+ * on_behalf_of_invalid_audience when an on_behalf_of audience is asserted too.+ */+export async function resolveAttestedActor(engine: Pick<BrainEngine, 'executeRaw'>, input: {+ channels?: ActorChannels; params: Record<string, unknown> | undefined; op: string; opShape: AttestableOpShape | undefined;+ auth?: ActorCaller['auth']; transport?: string; audienceAsserted: boolean;+}): Promise<{ actor: AttestedActor; access: Partial<CallerAccess>; params: Record<string, unknown> } | null> {+ const header = input.channels?.header ?? undefined;+ const hasArgument = !!input.params && Object.prototype.hasOwnProperty.call(input.params, ACTOR_ARGUMENT);+ if (header === undefined && !hasArgument) return null;+ const caller: ActorCaller = { auth: input.auth };+ const ctx = { op: input.op, transport: input.transport };+ const argument = hasArgument ? input.params![ACTOR_ARGUMENT] : undefined;+ if ((header !== undefined && !EXTERNAL_ID_RE.test(header)) || (hasArgument && (typeof argument !== 'string' || !EXTERNAL_ID_RE.test(argument)))) {+ throw actorNotAttested('invalid_actor_id', caller, ctx);+ }+ if (header === undefined) throw actorNotAttested('argument_without_attestation', caller, ctx);+ if (input.audienceAsserted) {+ throw catalogueError('on_behalf_of_invalid_audience', `The call names its person twice (${ACTOR_HEADER} and an on_behalf_of audience). Nothing was read.`,+ `Send one: ${ACTOR_HEADER} from an attest credential, or X-Gbrain-On-Behalf-Of / request-level _meta.on_behalf_of from a shared agent.`);+ }+ const right = input.transport === 'stdio' ? null : await attestRightOf(engine, caller);+ if (!right || right.system !== 'qm') throw actorNotAttested(hasArgument ? 'argument_without_attestation' : 'no_attest_right', caller, ctx);+ if (!right.ops.includes(input.op) || !attestableOp(input.op, input.opShape)) throw actorNotAttested('op_not_attested', caller, { ...ctx, right });+ if (hasArgument && argument !== header) throw actorNotAttested('argument_mismatch', caller, ctx);+ const covered = await actorCoverage(engine, caller, { system: right.system, external_id: header }, input.transport);+ const actor: AttestedActor = { system: right.system, external_id: header, member: covered.member };+ const { [ACTOR_ARGUMENT]: _stripped, ...params } = input.params ?? {};+ return { actor, access: await attestedCallerAccess(engine, actor, covered.identity), params };+}++export interface MemberLink { system: string; external_id: string; member_id: string; created_at: string | null }++function linkInvalid(message: string, reason: string, suggestion: string): OperationError {+ return opError('access_member_invalid', message, suggestion, { reason, why: 'A link decides whose notes a trusted system reads for a person, so it is matched exactly and never guessed.' });+}++function assertExternalId(raw: unknown): string {+ if (typeof raw === 'string' && EXTERNAL_ID_RE.test(raw)) return raw;+ throw linkInvalid('The --qm id is not a canonical person id.', 'invalid_external_id',+ 'Pass the id exactly as QM sends it in x-qm-actor: 1-256 visible ASCII characters, no spaces (for example U0ALICE or oidc:3f2a:alice-example).');+}++const iso = (v: unknown) => v == null ? null : v instanceof Date ? v.toISOString() : String(v);+const toLink = (r: Record<string, unknown>): MemberLink => ({ system: String(r.system), external_id: String(r.external_id), member_id: String(r.member_id), created_at: iso(r.created_at) });++async function linkRow(engine: Pick<BrainEngine, 'executeRaw'>, system: string, externalId: string): Promise<MemberLink | null> {+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT system, external_id, member_id, created_at FROM access_member_links WHERE system = $1 AND external_id = $2', [system, externalId]);+ return row ? toLink(row) : null;+}++/** Links a canonical id to an enabled member; refuses an invalid id, a member that is not enabled and an id already linked. */+export async function linkMember(engine: BrainEngine, rawMember: unknown, system: string, rawId: unknown, opts: { dryRun?: boolean } = {}): Promise<{ link: MemberLink; applied: boolean }> {+ const externalId = assertExternalId(rawId);+ const { member } = await memberIdentity(engine, rawMember);+ const existing = await linkRow(engine, system, externalId);+ if (existing) {+ throw linkInvalid(`That ${system} id is already linked to member "${existing.member_id}".`, 'link_exists',+ existing.member_id === member ? 'Nothing to do: the link exists.' : `Unlink it first (gbrain access member unlink --${system} <id>), then link it to ${member}.`);+ }+ if (opts.dryRun) return { link: { system, external_id: externalId, member_id: member, created_at: null }, applied: false };+ await engine.executeRaw('INSERT INTO access_member_links (system, external_id, member_id) VALUES ($1, $2, $3)', [system, externalId, member]);+ return { link: (await linkRow(engine, system, externalId))!, applied: true };+}++/** Removes one link; the next attested call naming the id is refused (actor_unlinked). */+export async function unlinkMember(engine: BrainEngine, system: string, rawId: unknown, opts: { dryRun?: boolean } = {}): Promise<{ link: MemberLink; applied: boolean }> {+ const externalId = assertExternalId(rawId);+ const existing = await linkRow(engine, system, externalId);+ if (!existing) throw linkInvalid(`That ${system} id is not linked to any member.`, 'unknown_link', 'List the links with gbrain access member links.');+ if (!opts.dryRun) await engine.executeRaw('DELETE FROM access_member_links WHERE system = $1 AND external_id = $2', [system, externalId]);+ return { link: existing, applied: !opts.dryRun };+}++export async function listMemberLinks(engine: BrainEngine, opts: { member?: string } = {}): Promise<MemberLink[]> {+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT system, external_id, member_id, created_at FROM access_member_links${opts.member ? ' WHERE member_id = $1' : ''} ORDER BY member_id, system, external_id`,+ opts.member ? [opts.member] : []);+ return rows.map(toLink);+}diff --git a/src/core/access/audience.ts b/src/core/access/audience.tsindex bd767ae1bb..66df6c3b78 100644--- a/src/core/access/audience.ts+++ b/src/core/access/audience.ts@@ -103,7 +103,10 @@ export interface AudienceAuditEvent {transport: string;op: string;audience: string[];- outcome: 'accepted' | 'on_behalf_of_invalid_audience' | 'on_behalf_of_not_permitted' | 'on_behalf_of_unknown_member' | 'on_behalf_of_in_arguments';+ outcome: 'accepted' | 'on_behalf_of_invalid_audience' | 'on_behalf_of_not_permitted' | 'on_behalf_of_unknown_member' | 'on_behalf_of_in_arguments'+ | 'actor_not_attested' | 'actor_unlinked';+ /** GST-359 C1: an attested actor's system, the id it named (only when well-formed) and a refusal's reason. */+ actor?: { system: string; external_id?: string; reason?: string };}const audit = createAuditWriter<AudienceAuditEvent>({ featureName: 'access-audience', errorLabel: 'access-audience-audit', errorTrailer: '; continuing' });diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex d3ea4d86f6..cb5d0443ce 100644--- a/src/core/access/caller.ts+++ b/src/core/access/caller.ts@@ -232,6 +232,8 @@ export interface AppliedAccess {member: string | null;groups: string[];audience: string[] | null;+ /** GST-359 C1: present on an attested call (the system that named the person; the id is not echoed). */+ actor?: { system: string };policy_rev: Record<string, number> | null;relaxation: 'none' | 'granted_sources' | 'operator';}@@ -252,6 +254,7 @@ export async function appliedAccessSummary(engine: Pick<BrainEngine, 'executeRawmember,groups: access.identity.filter(p => p.startsWith('group:')).map(p => p.slice('group:'.length)),audience: access.audience ? [...access.audience] : null,+ ...(access.actor ? { actor: { system: access.actor.system } } : {}),policy_rev: policyRev,relaxation: !access.hidePrivate ? 'operator' : access.privateReadableSources.length ? 'granted_sources' : 'none',};diff --git a/src/core/access/members.ts b/src/core/access/members.tsindex a2c494f44f..e8ff58a3a7 100644--- a/src/core/access/members.ts+++ b/src/core/access/members.ts@@ -287,8 +287,13 @@ export function parseMemberFlag(raw: string): string | null {return raw.trim() === 'none' ? null : assertAccessId(raw);}-export interface BindingPatch { member?: string | null; mayActFor?: string[] | null }-export interface BindingResult { member: string | null; may_act_for: string[] | null; changed: boolean }+/** GST-359 C1: attestActor names the system whose actor header this credential may send (null clears it and attestOps). */+export interface BindingPatch { member?: string | null; mayActFor?: string[] | null; attestActor?: string | null; attestOps?: string[] | null }+export interface BindingResult { member: string | null; may_act_for: string[] | null; attest_actor?: string; attest_ops?: string[] | null; changed: boolean }++function attestRefused(message: string, suggestion: string): OperationError {+ return opError('invalid_params', message, suggestion, { why: 'Only a credential bound to no member that authenticates as itself (a client-credentials client with a secret, or a legacy token) may name the people a trusted system serves.' });+}/*** Applies a member / may_act_for binding to one credential. `member` must@@ -299,19 +304,32 @@ export async function bindCredential(engine: BrainEngine, target: { kind: 'tokenif (patch.member != null) await requireEnabledMember(engine, patch.member);const table = target.kind === 'token' ? 'access_tokens' : 'oauth_clients';const key = target.kind === 'token' ? 'id::text' : 'client_id';- const [before] = await engine.executeRaw<{ member_id: string | null; may_act_for: string[] | null }>(- `SELECT member_id, may_act_for FROM ${table} WHERE ${key} = $1`, [target.id]);+ const [before] = await engine.executeRaw<{ member_id: string | null; may_act_for: string[] | null; attest_actor: string | null; attest_ops: string[] | null; grant_types?: string[] | null; confidential?: boolean }>(+ `SELECT member_id, may_act_for, attest_actor, attest_ops${target.kind === 'client' ? ', grant_types, client_secret_hash IS NOT NULL AS confidential' : ''} FROM ${table} WHERE ${key} = $1`, [target.id]);if (!before) {throw opError('invalid_params', `No ${target.kind === 'token' ? 'token' : 'OAuth client'} "${target.id}" exists.`,target.kind === 'token' ? 'List tokens with gbrain auth list.' : 'List clients with gbrain auth clients --json.');}const member = patch.member === undefined ? before.member_id : patch.member;const mayActFor = patch.mayActFor === undefined ? before.may_act_for : patch.mayActFor;- const changed = member !== before.member_id || JSON.stringify(mayActFor ?? null) !== JSON.stringify(before.may_act_for ?? null);+ const attestActor = patch.attestActor === undefined ? before.attest_actor : patch.attestActor;+ const attestOps = attestActor === null ? null : patch.attestOps === undefined ? before.attest_ops : patch.attestOps;+ const what = target.kind === 'token' ? 'This token' : `OAuth client ${target.id}`;+ if (patch.attestOps != null && attestActor === null) throw attestRefused('--attest-ops needs the attest right.', 'Pass --attest-actor qm with it.');+ if (attestActor !== null && (patch.attestActor !== undefined || patch.member !== undefined)) {+ if (member !== null) throw attestRefused(`${what} is bound to member "${member}", so it cannot attest other people.`, 'Use a credential bound to no member (--member none), or a separate client for the trusted system.');+ if (target.kind === 'client' && (!(before.grant_types ?? []).includes('client_credentials') || before.confidential !== true)) {+ throw attestRefused(`${what} is not a confidential client-credentials client, so it cannot attest people.`,+ 'Register one for the trusted system: gbrain auth register-client <name> --grant-types client_credentials, then grant it --attest-actor qm.');+ }+ }+ const changed = member !== before.member_id || JSON.stringify(mayActFor ?? null) !== JSON.stringify(before.may_act_for ?? null)+ || attestActor !== before.attest_actor || JSON.stringify(attestOps ?? null) !== JSON.stringify(before.attest_ops ?? null);if (changed && !opts.dryRun) {- await engine.executeRaw(`UPDATE ${table} SET member_id = $2, may_act_for = $3::text[] WHERE ${key} = $1`, [target.id, member, mayActFor]);+ await engine.executeRaw(`UPDATE ${table} SET member_id = $2, may_act_for = $3::text[], attest_actor = $4, attest_ops = $5::text[] WHERE ${key} = $1`,+ [target.id, member, mayActFor, attestActor, attestOps]);}- return { member, may_act_for: mayActFor ?? null, changed };+ return { member, may_act_for: mayActFor ?? null, ...(attestActor ? { attest_actor: attestActor, attest_ops: attestOps ?? null } : {}), changed };}/** A credential bound to a member that cannot read: verification refuses it. */diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex e4f319ce11..70888089ee 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -41,6 +41,9 @@ export const ERROR_CATALOGUE = {on_behalf_of_unknown_member: { code: 'on_behalf_of_unknown_member', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member' },on_behalf_of_not_permitted: { code: 'on_behalf_of_not_permitted', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted' },on_behalf_of_in_arguments: { code: 'on_behalf_of_in_arguments', docs: 'docs/guides/write-refusals.md#on_behalf_of_in_arguments' },+ // GST-359 C1 attested actor: the person a trusted system names (x-qm-actor) on a credential holding the attest right.+ actor_not_attested: { code: 'actor_not_attested', docs: 'docs/guides/write-refusals.md#actor_not_attested' },+ actor_unlinked: { code: 'actor_unlinked', docs: 'docs/guides/write-refusals.md#actor_unlinked' },// GBRA-218 (A2) folder rules: invalid rules and policy files, pending narrowing.access_rule_invalid: { code: 'access_rule_invalid', docs: 'docs/guides/write-refusals.md#access_rule_invalid' },access_policy_invalid: { code: 'access_policy_invalid', docs: 'docs/guides/write-refusals.md#access_policy_invalid' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 845773c1ce..577e1c49d5 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -68,6 +68,8 @@ export const CODES = {on_behalf_of_invalid_audience: { class: 'caller', summary: "A shared agent's request named its audience (the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of) in a form gbrain does not accept: empty, more than 50 entries, an entry that is not a member id, group:<id> or guest, or a header and _meta that name different audiences. Nothing was read.", why: 'The audience decides whose notes the agent may read, so an audience gbrain cannot read exactly is refused instead of guessed.', docs: 'docs/guides/write-refusals.md#on_behalf_of_invalid_audience', suggestion: 'Fix the harness code that sets the audience: 1-50 entries, each a member id, group:<id> or guest, the same in the header and _meta when both are sent.' },on_behalf_of_unknown_member: { class: 'caller', summary: "A shared agent's audience names a member who is not enabled on this brain, or a group that does not exist, so nothing was read.", why: 'An unknown or disabled entry is refused rather than read as a guest, so a typo or a removed person never quietly changes what the agent reads.', docs: 'docs/guides/write-refusals.md#on_behalf_of_unknown_member', suggestion: 'Name enabled members and existing groups only (gbrain access member list --all, gbrain access group list on the brain host); a person who is not a member joins the audience as guest.' },on_behalf_of_not_permitted: { class: 'host_only', actor: 'user', summary: "A shared agent asserted an audience its credential's may_act_for does not list (for a stdio server, config mcp.stdio_may_act_for), so nothing was read.", why: 'A shared agent acts only for the people the brain operator approved for its credential; widening that list is the operator\'s decision, never the agent\'s.', docs: 'docs/guides/write-refusals.md#on_behalf_of_not_permitted', suggestion: 'The brain operator decides whether to approve the audience: gbrain auth rescope --token <name>|--client <id> --may-act-for <list> on the brain host. Until then, call without the audience.' },+ actor_not_attested: { class: 'host_only', actor: 'user', reasons: ['no_attest_right', 'op_not_attested', 'argument_mismatch', 'argument_without_attestation', 'invalid_actor_id'], summary: "A call named the person it serves (the x-qm-actor header or the acting_user argument) in a way gbrain does not honour: the credential holds no attest right, the operation is not in its attested operations, the argument differs from the header or comes without an attested header, or the id is not 1-256 visible ASCII characters. Nothing was read or written.", why: 'Naming a person decides whose notes are read and written as; only a credential the brain operator granted the attest right may do it, only for the operations it lists, and text in a conversation never chooses it.', docs: 'docs/guides/write-refusals.md#actor_not_attested', suggestion: 'Read reason: no_attest_right and op_not_attested are the brain operator\'s call (gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]); argument_mismatch, argument_without_attestation and invalid_actor_id are fixed in the calling harness.' },+ actor_unlinked: { class: 'host_only', actor: 'user', summary: 'An attested call named a person whose canonical id is not linked to an enabled member of this brain (never linked, unlinked, or the member is disabled or removed), so nothing was read or written.', why: 'An attested call reads and writes as exactly one member; an unknown person is refused rather than read as a guest, and unlinking or disabling takes effect on the next call.', docs: 'docs/guides/write-refusals.md#actor_unlinked', suggestion: 'The brain operator links the id to its member: gbrain access member link <member> --qm <id> (or enables the member).' },on_behalf_of_in_arguments: { class: 'caller', summary: 'A tool call carried on_behalf_of inside its arguments, where conversation text could set it, so it was refused and nothing was read.', why: 'Only harness code may name whose notes a shared agent reads: the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of, never tool arguments.', docs: 'docs/guides/write-refusals.md#on_behalf_of_in_arguments', suggestion: 'Remove on_behalf_of from the tool arguments. Harness code sends it as the X-Gbrain-On-Behalf-Of header or request-level _meta.on_behalf_of; other stdio clients use a credential bound to one member or config mcp.stdio_member.' },access_policy_invalid: { class: 'host_only', actor: 'user', docs: 'docs/guides/write-refusals.md#access_policy_invalid', summary: "A source's folder-rule policy (the committed .gbrain/access.yml, or a file given to gbrain access rule import) does not validate, so it was not applied: the last applied rules stay in force and every prefix the bad file names reads as nobody (the whole source when its prefixes cannot be read).", why: 'A typo in an access file must never open a folder: an unreadable revision keeps the previous rules and hides what it touches until it is fixed.', suggestion: 'Show each problem with its line (gbrain access rule list --source <id>), fix the file, commit it with gbrain git commit-push and sync the source (gbrain sync --source <id> --no-pull).', fix: { argv: ['gbrain', 'access', 'rule', 'list', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the applied rules and each problem in the policy file with its line; changes nothing.' } },access_policy_pending: { class: 'retryable', docs: 'docs/guides/write-refusals.md#access_policy_pending', summary: "A narrowing change to a source's folder rules is still being applied to its pages, so the prefixes it touches read as nobody until it finishes; pages under other prefixes keep the last applied rules.", why: 'Pages under a newly restricted folder are restamped in batches; until the last batch and its re-check pass land, they read as nobody instead of under the old rules.', suggestion: 'Retry shortly. If it stays pending, the apply was interrupted: the brain host finishes it with gbrain access resume --source <id> (database store) or gbrain sync --source <id> --no-pull (git store).', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the pending prefixes and the revision being applied; changes nothing.' } },@@ -75,7 +77,7 @@ export const CODES = {access_policy_store_mismatch: { class: 'host_only', actor: 'user', summary: "A source's persisted folder-rule store (sources.config.access_store) disagrees with what this host sees (a git store with no visible work tree, or a database store whose root became a repository), so the persisted store and its applied rules stay in force and nothing switches on its own.", why: 'Inferring the store per host would let a missing checkout or a stray git init change which rules apply; only gbrain access rule migrate moves them, and neither direction widens.', suggestion: 'On the brain host, preview the move with gbrain access rule migrate --source <id>, then apply it by adding --yes.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the persisted store and the applied rules; changes nothing.' } },access_rule_invalid: { class: 'caller', docs: 'docs/guides/write-refusals.md#access_rule_invalid', summary: 'A folder rule given to gbrain access rule add is invalid (its prefix is not a literal lower-case folder ending in /, holds .. or *, its readers are not member ids or group:<id>, or another rule already covers the prefix), so nothing was written.', why: 'Prefixes are matched literally against slugs; a pattern or a typo would silently restrict the wrong pages or none.', suggestion: 'Write the prefix as a slug folder ending in / (partners/alice-example/) and the readers as member ids or group:<id>.' },access_member_id_retired: { class: 'caller', summary: "The member id was removed earlier and member ids are never reused, so nothing was created or enabled.", why: 'Pages and audit history may still name a removed id; reusing it would hand that history to a different person.', docs: 'docs/guides/write-refusals.md#access_member_id_retired', suggestion: 'Choose a new member id.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status, removed ones included.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },- access_member_invalid: { class: 'caller', reasons: ['ill_formed', 'unknown', 'disabled', 'removed', 'exists', 'unknown_group'], summary: "A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, so nothing was read or changed.", why: 'Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view.', docs: 'docs/guides/write-refusals.md#access_member_invalid', suggestion: 'Check the id with gbrain access member list --all, or add the member first.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },+ access_member_invalid: { class: 'caller', reasons: ['ill_formed', 'unknown', 'disabled', 'removed', 'exists', 'unknown_group', 'invalid_external_id', 'link_exists', 'unknown_link'], summary: "A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, so nothing was read or changed.", why: 'Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view.', docs: 'docs/guides/write-refusals.md#access_member_invalid', suggestion: 'Check the id with gbrain access member list --all, or add the member first.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },access_denied_test_user: { class: 'host_only', summary: "Google connect credential error: access denied test user.", docs: 'docs/guides/google-connect.md#troubleshooting' },access_env_missing: { class: 'caller', summary: "Google connect credential error: access env missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },acknowledgment_unavailable: { class: 'unavailable', summary: "This batch is unknown or outside the retained replay window." },diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.tsindex 3de234bc28..18841746b8 100644--- a/src/core/minions/submission-authority.ts+++ b/src/core/minions/submission-authority.ts@@ -11,6 +11,7 @@ import { normalizeSlugPrefix } from '../ops/context.ts';import { hasScope } from '../scope.ts';import { authSourcesFromGrant, grantFromTokenRow } from '../grants/model.ts';import { isValidSourceId } from '../source-id.ts';+import { parseStoredActor } from '../access/actor-model.ts';import { discoverGitRoot } from '../sync-git.ts';import type { MinionJob } from './types.ts';@@ -25,7 +26,9 @@ export interface RemoteAgentAuthority {* GBRA-231: `actingFor` is the audience a shared agent asserted when it submitted the job. Every tool call the job* makes reads as that audience, re-resolved against the client's live may_act_for, never as the client's own member.*/- grant: { scopes: string[]; sourceId: string; sourceCreatedAt: string; allowedTools: string[]; allowedSlugPrefixes: string[]; actingFor?: string[] };+ grant: { scopes: string[]; sourceId: string; sourceCreatedAt: string; allowedTools: string[]; allowedSlugPrefixes: string[]; actingFor?: string[];+ /** GST-359 C1: the attested actor the job was submitted for; every tool call re-resolves it through actorCoverage. */+ actor?: { system: string; external_id: string; member: string } };payloadHash: string;}export interface RemoteJobAuthority {@@ -83,6 +86,7 @@ export function parseSubmissionAuthority(value: unknown): SubmissionAuthority |!Array.isArray(g.allowedTools) || !g.allowedTools.length || !g.allowedTools.every(v => typeof v === 'string' && v.length) ||!Array.isArray(g.allowedSlugPrefixes) || !g.allowedSlugPrefixes.every(v => typeof v === 'string') ||(g.actingFor !== undefined && (!Array.isArray(g.actingFor) || !g.actingFor.length || g.actingFor.length > 50 || !g.actingFor.every(v => typeof v === 'string' && v.length))) ||+ (g.actor !== undefined && (g.actingFor !== undefined || !parseStoredActor(g.actor))) ||typeof a.payloadHash !== 'string' || !/^[a-f0-9]{64}$/.test(a.payloadHash)) return null;return structuredClone(a) as unknown as RemoteAgentAuthority;}@@ -258,12 +262,12 @@ export async function prepareRemoteAgent(ctx: OperationContext, data: Record<strconst [source] = await ctx.engine.executeRaw<Record<string, unknown>>('SELECT archived, created_at FROM sources WHERE id = $1', [data.source_id]);if (!source || source.archived !== false) deny('agent source must be active', `Source ${data.source_id} is archived or missing. Name an active source in source_id.`);const { currentCallerAccess } = await import('../search/private-visibility.ts');- const actingFor = currentCallerAccess().audience;+ const { actor, audience: actingFor } = currentCallerAccess();const authority: RemoteAgentAuthority = {version: 1, kind: 'remote_agent', principal: { kind: 'oauth_client', id: principal.id },grant: { scopes: [...ctx.auth!.scopes], sourceId: data.source_id, sourceCreatedAt: new Date(source.created_at as string).toISOString(),allowedTools: [...data.allowed_tools as string[]], allowedSlugPrefixes: [...data.allowed_slug_prefixes as string[]],- ...(actingFor?.length ? { actingFor: [...actingFor] } : {}) },+ ...(actor ? { actor: { ...actor } } : actingFor?.length ? { actingFor: [...actingFor] } : {}) },payloadHash: authorityDigest(data),};if (!parseSubmissionAuthority(authority)) deny('invalid agent grant', 'Send allowed_tools as a non-empty list of tool names and allowed_slug_prefixes as a list of strings.');diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex d9e9a3d002..2a0e19a123 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -36,6 +36,7 @@ import { BRAIN_TOOL_ALLOWLIST } from './brain-tool-allowlist.ts';import { stagePutPage } from './staged-put-page.ts';import { withCallerAccess } from '../../search/private-visibility.ts';import { remoteCallerAccess } from '../../access/caller.ts';+import { attestedCallerAccess, storedActorIdentity } from '../../access/actor.ts';import type { AudiencePrincipal } from '../../access/audience.ts';import { currentSubmissionAuthority } from '../submission-authority.ts';@@ -316,7 +317,12 @@ function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {// GBRA-231: a job a shared agent submitted for an audience reads as that audience, re-checked the same way.const submitted = currentSubmissionAuthority();const actingFor = submitted?.kind === 'remote_agent' ? submitted.grant.actingFor as AudiencePrincipal[] | undefined : undefined;- const output = opCtx.auth+ // GST-359 C1: a job submitted for an attested actor reads as that member only while actorCoverage still covers it.+ const agent = submitted?.kind === 'remote_agent' ? submitted : undefined;+ const actor = agent?.grant.actor;+ const output = agent && actor+ ? await withCallerAccess(await attestedCallerAccess(ctx.engine, actor, await storedActorIdentity(ctx.engine, agent.principal, actor)), run)+ : opCtx.auth? await withCallerAccess(await remoteCallerAccess(ctx.engine, opCtx.auth, [], undefined, actingFor), run): await run();const rejection = op.name === 'put_page' ? putPageRejection(output) : null;diff --git a/src/core/oauth-grants.ts b/src/core/oauth-grants.tsindex d7103e0fb8..f5404c71ff 100644--- a/src/core/oauth-grants.ts+++ b/src/core/oauth-grants.ts@@ -270,7 +270,7 @@ export class OAuthGrants {const target = this.resource(row.resource, requested);const scopes = this.currentScopes(client, row.scopes as string[]);await sql`DELETE FROM oauth_codes WHERE code_hash = ${hashToken(code)} AND client_id = ${clientId}`;- return this.issue(sql, client, scopes, target, true);+ return this.issue(sql, client, scopes, target, true, 'authorization_code');});}@@ -287,7 +287,7 @@ export class OAuthGrants {const scopes = this.currentScopes(client, requested ?? original);const target = this.resource(row.resource, requestedResource);await sql`DELETE FROM oauth_tokens WHERE token_hash = ${hashToken(token)} AND token_type = 'refresh' AND client_id = ${clientId}`;- return this.issue(sql, client, scopes, target, true);+ return this.issue(sql, client, scopes, target, true, 'refresh_token');});}@@ -322,7 +322,7 @@ export class OAuthGrants {if (!Array.isArray(client.grant_types) || !client.grant_types.includes('client_credentials')) throw new InvalidGrantError('Client credentials grant not authorized for this client');if (typeof client.client_secret_hash !== 'string' || !/^[a-f0-9]{64}$/i.test(client.client_secret_hash) || !safeHexEqual(client.client_secret_hash, hashToken(secret))) throw new InvalidClientError('Invalid client secret');this.assertCredentialPolicy(client, client.client_secret_hash);- return this.issue(sql, client, grantScopes(client, requested ? parseScopeString(requested) : undefined), undefined, false);+ return this.issue(sql, client, grantScopes(client, requested ? parseScopeString(requested) : undefined), undefined, false, 'client_credentials');});}@@ -346,19 +346,20 @@ export class OAuthGrants {});}- private async issue(sql: SqlQuery, client: ClientRow, scopes: string[], resource: URL | undefined, refresh: boolean): Promise<OAuthTokens> {+ /** GST-359 C1: each token records the grant that issued it (oauth_tokens.grant_type); only client_credentials tokens may attest an actor. */+ private async issue(sql: SqlQuery, client: ClientRow, scopes: string[], resource: URL | undefined, refresh: boolean, grant: 'authorization_code' | 'refresh_token' | 'client_credentials'): Promise<OAuthTokens> {const clientId = client.client_id as string;const override = Number(client.token_ttl);const ttl = Math.min(Number.isFinite(override) && override > 0 ? override : this.options.tokenTtl, TOKEN_TTL_MAX_SECONDS);const now = Math.floor(this.now() / 1000);const access = generateToken('gbrain_at_');- await sql`INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource, created_at)- VALUES (${hashToken(access)}, ${'access'}, ${clientId}, ${oauthPgArray(scopes)}, ${now + ttl}, ${resource?.toString() ?? null}, to_timestamp(${now}))`;+ await sql`INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource, created_at, grant_type)+ VALUES (${hashToken(access)}, ${'access'}, ${clientId}, ${oauthPgArray(scopes)}, ${now + ttl}, ${resource?.toString() ?? null}, to_timestamp(${now}), ${grant})`;const result: OAuthTokens = { access_token: access, token_type: 'bearer', expires_in: ttl, scope: scopes.join(' ') };if (refresh) {const token = generateToken('gbrain_rt_');- await sql`INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource, created_at)- VALUES (${hashToken(token)}, ${'refresh'}, ${clientId}, ${oauthPgArray(scopes)}, ${now + this.options.refreshTtl}, ${resource?.toString() ?? null}, to_timestamp(${now}))`;+ await sql`INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource, created_at, grant_type)+ VALUES (${hashToken(token)}, ${'refresh'}, ${clientId}, ${oauthPgArray(scopes)}, ${now + this.options.refreshTtl}, ${resource?.toString() ?? null}, to_timestamp(${now}), ${grant})`;result.refresh_token = token;}return result;diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex 2a0bf8210d..b2433bbb56 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -56,6 +56,7 @@ export { assertValidSlugPrefixes } from './grants/encoding.ts';import type { SqlQuery, SqlValue } from './sql-query.ts';import { storedMinTrust } from './trust/tier.ts';import { tokenMemberBinding } from './access/token-binding.ts';+import { withAttestRight } from './access/actor-model.ts';export type { SqlQuery, SqlValue };export interface AgentClientBindings {@@ -691,7 +692,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {let oauthRows: Record<string, unknown>[];try {oauthRows = await this.sql`- SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name, c.scope AS current_scopes,+ SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name, c.scope AS current_scopes, to_jsonb(t)->>'grant_type' AS token_grant,(to_jsonb(c) - 'client_secret_hash') AS current_grant,EXISTS(SELECT 1 FROM sources s WHERE s.id = to_jsonb(c)->>'source_id'AND NOT COALESCE((to_jsonb(s)->>'archived')::boolean, false)) AS source_active,@@ -884,7 +885,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {token,clientId: row.client_id as string,principal: { kind: 'oauth_client', id: row.client_id as string },- ...(await tokenMemberBinding(this.sql, currentGrant.member_id, currentGrant.may_act_for)),+ ...withAttestRight(await tokenMemberBinding(this.sql, currentGrant.member_id, currentGrant.may_act_for), currentGrant, row.token_grant),clientName: (row.client_name as string | null) ?? undefined,scopes: effectiveScopes,issuedScopes,@@ -956,7 +957,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {token,clientId: name,principal: { kind: 'legacy_token', id: String(legacyRows[0].id) },- ...(await tokenMemberBinding(this.sql, legacyRows[0].member_id, legacyRows[0].may_act_for)),+ ...withAttestRight(await tokenMemberBinding(this.sql, legacyRows[0].member_id, legacyRows[0].may_act_for), legacyRows[0], 'legacy'),clientName: name,scopes: grant.scopes,...(grant.allowedOperations === null ? {} : { allowedOperations: grant.allowedOperations }),diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 9ad2ee42f6..272615d601 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -289,6 +289,12 @@ export interface AuthInfo {member?: { id: string; groups: string[] } | null;/** GBRA-218: the stored `may_act_for` audience list (shared agents, PR B); stored and reported only. */mayActFor?: string[] | null;+ /**+ * GST-359 C1: the live right to name the person a call serves (x-qm-actor), joined by the verifier: the system and+ * the operations an attested call may run. Null when the credential holds none, is bound to a member, or (an OAuth+ * client) its token did not come from the client-credentials grant. Undefined when no verifier joined it.+ */+ attest?: { system: string; ops: string[] } | null;/*** Human-readable agent name resolved at token-verification time.* For OAuth clients this is `oauth_clients.client_name`; for legacydiff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 6099b7a556..d33c9e69c9 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -11,6 +11,7 @@ import { readLocalWriter, currentVerifiedLocalWriter, takeRegisteredWriterRow, vimport type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';import { authorizePageVisibility, excludesPrivateWrites } from './page-visibility.ts';import { currentCallerAccess } from '../search/private-visibility.ts';+import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';function deny(message: string): never { throw new OperationError('permission_denied', message, 'Inspect the current writer registration and source/operation grants.'); }@@ -58,8 +59,9 @@ export async function submissionAuthority(ctx: OperationContext, operation: striif (!localGrant.sourceIds.includes('*') && !localGrant.sourceIds.includes(sourceId)) deny('The local grant excludes this source.');}const delegatedJobId = ctx.auth && ctx.viaSubagent ? jobNamespaceKey(ctx.subagentId) : undefined;- const audience = ctx.remote !== false ? currentCallerAccess().audience : null;- const actingFor = audience?.length ? [...audience] : undefined;+ const access = ctx.remote !== false ? currentCallerAccess() : null;+ // GST-359 C1: an attested call stores its actor (never the bare one-member audience), so publication re-resolves the link.+ const actingFor: WriteAuthority['actingFor'] = access?.actor ? { ...access.actor } : access?.audience?.length ? [...access.audience] : undefined;const a: WriteAuthority = {version: 1, principal, remote: ctx.remote !== false, sourceId, sourceIncarnation,// GBRA-231: a channel audience (anything but one member) never relaxes privacy, so its ceiling hides private pages.@@ -143,6 +145,11 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operaassertSkillWriteScopes(a.scopes, operation, a.remote);if (!hasScope(a.scopes, a.delegated ? 'agent' : 'write') || !operationAllowed(a.operations, operation) || !prefixAllowed(a.slugPrefixes, slug)) deny('The operation exceeds its original accepted grant.');if ((a.delegated || a.restrictedNamespace) && (!a.delegatedPrefixes?.length || !matchesSlugAllowList(slug, a.delegatedPrefixes))) deny('The target exceeds the accepted delegated namespace.');+ if (a.actingFor && !Array.isArray(a.actingFor)) {+ const actor = parseStoredActor(a.actingFor);+ if (!actor) deny('The accepted attested actor is malformed.');+ await storedActorIdentity(engine, a.principal, actor);+ }const suffix = lock ? ' FOR SHARE' : '';if (a.principal.kind === 'oauth_client') {const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT deleted_at,scope,source_id,allowed_operations,diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 5b8ae83526..c6c014a1e9 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -13,7 +13,12 @@ export interface WriteAuthority {* GBRA-231: the audience a shared agent asserted for the write (normalized member:<id>, group:<g>, guest). Preparation* and publication re-resolve it against the principal's live may_act_for and members, never the principal's own member.*/- actingFor?: string[];+ /**+ * GST-359 C1: or the attested actor { system, external_id, member } the write was accepted for. Preparation and+ * publication re-resolve it through actorCoverage (access/actor.ts): the principal's live attest right and a live+ * link from the id to the same enabled member, so an unlink, a disabled member or a revoked right refuses it.+ */+ actingFor?: string[] | { system: string; external_id: string; member: string };databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached';autoLinkTrusted?: boolean;restrictedNamespace?: boolean;diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.tsindex 1657e7253d..d3c705ecec 100644--- a/src/core/persistence/page-visibility.ts+++ b/src/core/persistence/page-visibility.ts@@ -3,6 +3,7 @@ import { callerAccessAllowedSql, callerIdentities, currentCallerAccess, readPoliimport { parseMarkdown } from '../markdown.ts';import { folderAccessForAll, memberIdentityFor, resolveAudienceIdentities } from '../access/caller.ts';import type { AudiencePrincipal } from '../access/audience.ts';+import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';import { hasReaders, normalizePrincipal, normalizeReaders, readersAllow, NOBODY } from '../access/principals.ts';import { catalogueError } from '../error-catalogue.ts';import type { SqlEngine, WriteAuthority } from './model.ts';@@ -38,6 +39,11 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writ* or naming a disabled member resolves to the guest identity, which reads no restricted page (fail closed).*/async function writerIdentities(engine: SqlEngine, authority: WriteAuthority): Promise<string[][]> {+ if (authority.actingFor && !Array.isArray(authority.actingFor)) {+ // GST-359 C1: an attested write reads as its member only while actorCoverage still covers the same member.+ const actor = parseStoredActor(authority.actingFor);+ return [actor ? await storedActorIdentity(engine, authority.principal, actor).catch(() => []) : []];+ }if (!authority.actingFor?.length) return [await memberIdentityFor(engine, authority)];try {return await resolveAudienceIdentities(engine, { principal: authority.principal, transport: authority.principal.kind === 'local_stdio' ? 'stdio' : 'http' },@@ -109,7 +115,8 @@ export async function remoteReadersChecked<T extends { parsedPage: { frontmatterthrow catalogueError('readable_by_invalid', 'This write removes readable_by from a page that names readers.','Nothing was written. A remote write keeps the readable_by line: read the page with get_page include_content:true and keep its frontmatter, or ask the user to widen the page on the brain host.');}- assertRemoteReadersValid(after, await writerIdentities(engine, authority), authority.actingFor);+ const acting = authority.actingFor;+ assertRemoteReadersValid(after, await writerIdentities(engine, authority), Array.isArray(acting) ? acting : acting ? [`member:${acting.member}`] : undefined);return prepared;}diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 83003b79a8..978c2471a0 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -211,6 +211,11 @@ export interface CallerAccess {*/audience: readonly string[] | null;audienceIdentities: readonly (readonly string[])[];+ /**+ * GST-359 C1: the attested actor (a trusted system named the person; access/actor.ts), or null. Its audience is that+ * one member and its privacy is never relaxed. Queued writes and agent jobs carry it and re-resolve it live.+ */+ actor?: Readonly<{ system: string; external_id: string; member: string }> | null;/** GBRA-218 (A2): the source-qualified folder-rule ids (`<source>:<rule>`) the identity satisfies, from the applied rulebook. */satisfiedRuleIds: readonly string[];/** GBRA-218 (A2): prefixes that read as nobody (a narrowing being stamped, an invalid policy file); prefix '' is the whole source. */@@ -225,7 +230,7 @@ const callerAccessStore = new AsyncLocalStorage<CallerAccess>();/** The current read's caller-access record (see CallerAccess). */export function currentCallerAccess(): CallerAccess {- return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false, restricted: true };+ return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false, restricted: true };}/** Runs `fn` under `access` merged over the current record; an invalid identity or source id empties that set (fail closed). */@@ -238,12 +243,14 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):const audienceIdentities = (access.audienceIdentities ?? (fresh ? [] : base.audienceIdentities)).map(id => id.length && validIdentity(id) ? Object.freeze([...new Set(id)].sort()) : Object.freeze([] as string[]));const audience = access.audience !== undefined ? access.audience : fresh ? null : base.audience;+ const actor = access.actor !== undefined ? access.actor : fresh ? null : base.actor ?? null;const satisfiedOk = validIds || audienceIdentities.some(id => id.length > 0);const satisfied = satisfiedOk ? access.satisfiedRuleIds ?? (fresh ? [] : base.satisfiedRuleIds) : [];return callerAccessStore.run(Object.freeze({identity: validIds && audienceIdentities.length <= 1 ? Object.freeze([...new Set(identity)].sort()) : Object.freeze([]),audience: audience && audience.every(validAudienceEntry) ? Object.freeze([...audience]) : audience ? Object.freeze([GUEST_ENTRY]) : null,audienceIdentities: Object.freeze(audienceIdentities.length > 1 ? audienceIdentities : []),+ actor: actor ? Object.freeze({ system: actor.system, external_id: actor.external_id, member: actor.member }) : null,satisfiedRuleIds: satisfied.length && satisfied.every(validQualifiedRuleId) ? Object.freeze([...new Set(satisfied)].sort()) : Object.freeze([]),folderCoverage: Object.freeze([...(access.folderCoverage ?? base.folderCoverage)].map(c => Object.freeze({ source_id: c.source_id, prefix: c.prefix }))),privateReadableSources: sources.length && sources.every(isValidSourceId) ? Object.freeze([...new Set(sources)]) : Object.freeze([]),diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex d4eceaa4f3..7d9b810e25 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -17,6 +17,7 @@ import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../coreimport { withCallerAccess } from '../core/search/private-visibility.ts';import { appliedAccessSummary, remoteCallerAccess } from '../core/access/caller.ts';import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';+import { ACTOR_ARGUMENT, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';import { resolveBrainId } from '../core/brain-resolver.ts';import { getCliOptions } from '../core/cli-options.ts';import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';@@ -165,9 +166,13 @@ export interface ToolResult {* tool call still succeeds.*/_meta?: Record<string, unknown>;+ /** GST-359 C1: set only on refusals of a call that named an attested actor (`{ error: { code, message, reason, fix } }`). */+ structuredContent?: Record<string, unknown>;}export interface DispatchOpts {+ /** GST-359 C1: the x-qm-actor header the HTTP transport read (a trusted system names the person); stdio never sets it. */+ actor?: ActorChannels;/*** GBRA-231: the shared-agent audience channels the transport read from the request (the X-Gbrain-On-Behalf-Of* header, request-level `_meta`), set by harness code. Never populated from tool arguments, which are refused.@@ -909,22 +914,31 @@ export async function dispatchToolCall(// GBRA-231: or the audience a shared agent's harness asserts, resolved (and refused) on every call before any work.const run = async () => {if (opts.remote === false) return withCallerAccess({ privateReadableSources: [] }, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved)));+ // GST-359 C1: or the person a trusted system attests (x-qm-actor), decided here too, before any work (access/actor.ts).let audience: AudiencePrincipal[] | null = null;+ let attested: Awaited<ReturnType<typeof resolveAttestedActor>> = null;let access: Awaited<ReturnType<typeof remoteCallerAccess>>;- const assertion = (outcome: AudienceAuditEvent['outcome']) => logAudienceAssertion({ outcome, op: name, audience: audience ?? [], transport: opts.transport ?? 'unknown',- principal: opts.auth?.principal ? `${opts.auth.principal.kind}:${opts.auth.principal.id}` : opts.transport === 'stdio' ? 'local_stdio' : 'unknown' });+ const header = opts.actor?.header ?? undefined;+ const actorNamed = header !== undefined || (!!params && Object.prototype.hasOwnProperty.call(params, ACTOR_ARGUMENT));+ const assertion = (outcome: AudienceAuditEvent['outcome'], reason?: string) => logAudienceAssertion({ outcome, op: name,+ audience: [...(attested?.access.audience ?? audience ?? [])], transport: opts.transport ?? 'unknown',+ principal: opts.auth?.principal ? `${opts.auth.principal.kind}:${opts.auth.principal.id}` : opts.transport === 'stdio' ? 'local_stdio' : 'unknown',+ ...(actorNamed ? { actor: { system: 'qm', ...(header && EXTERNAL_ID_RE.test(header) ? { external_id: header } : {}), ...(reason ? { reason } : {}) } } : {}) });try {if (audienceInArguments(params)) throw audienceInArgumentsError();audience = parseAudience(opts.onBehalfOf);- access = await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience);+ attested = await resolveAttestedActor(engine, { channels: opts.actor, params, op: name, opShape: operations.find(o => o.name === name),+ 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) || !String(e.code).startsWith('on_behalf_of_')) throw e;- assertion(e.code as AudienceAuditEvent['outcome']);- return errorResult(e, opts, { op: name });+ if (!(e instanceof OperationError) || !/^(on_behalf_of_|actor_)/.test(String(e.code))) throw e;+ assertion(e.code as AudienceAuditEvent['outcome'], e.reason);+ return actorNamed ? actorRefusal(e, opts, name) : errorResult(e, opts, { op: name });}- if (audience) assertion('accepted');+ if (audience || attested) assertion('accepted');+ const callParams = attested ? attested.params : params;return withCallerAccess(access, async () => {- const out = await withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, resolved));+ const out = await withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, callParams, resolved));// _meta.access (MCP_META_CHANNELS.md): the view this call was answered under, for the harness; own producer, isolated.try { out._meta = { ...(out._meta ?? {}), access: await appliedAccessSummary(engine, opts.auth, [opts.sourceId, ...(opts.localFederatedSourceIds ?? [])]) }; } catch { /* the key is absent */ }return out;@@ -936,6 +950,20 @@ export async function dispatchToolCall(: withoutRequestConfigSnapshot(run);}+/**+ * GST-359 C1: the refusal of a call that named an attested actor: gbrain's envelope (top-level `code` in the JSON text+ * block) plus `structuredContent.error`, both of which QM reads. The single seam where memory_recall (layer D) answers+ * actor_unlinked as a success instead: empty content and structuredContent {facts: [], truncated: false, code: 'actor_unlinked'}.+ */+function actorRefusal(e: OperationError, opts: DispatchOpts, op: string): ToolResult {+ const out = errorResult(e, opts, { op });+ 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 } : {}) } };+ } catch { /* the text block still carries the code */ }+ return out;+}+/** The response-meta hook's keys, or its failure message; never rejects (a hook failure degrades to no keys). */async function runMetaHook(hook: NonNullable<DispatchOpts['metaHook']>, name: string, ctx: OperationContext): Promise<{ meta?: Record<string, unknown>; failure?: string }> {try { return { meta: await hook(name, ctx) }; }diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 28b7e5a3ae..b0f80e9c4a 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -32,12 +32,13 @@ import { CAPABILITIES_URI } from './capabilities.ts';import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';import type { BrainEngine } from '../core/engine.ts';import { buildToolDefs } from './tool-defs.ts';-import { readInstructionContent, resolveMcpInstructions } from './instructions.ts';+import { MCP_SERVER_DESCRIPTION, readInstructionContent, resolveMcpInstructions } from './instructions.ts';import { httpInstructionTools } from './initialize-context.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';import { operations, operationsByName, opAllowedForBoundClient } from '../core/operations.ts';import { scopeDeniedError } from '../core/ops/op-fix.ts';import { ON_BEHALF_OF_HEADER } from '../core/access/audience.ts';+import { ACTOR_HEADER, withAttestRight } from '../core/access/actor-model.ts';import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';import type { AuthInfo } from '../core/operations.ts';import { VERSION } from '../version.ts';@@ -297,7 +298,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {token,clientId: rowId,principal: { kind: 'legacy_token', id: rowId },- ...binding,+ ...withAttestRight(binding, row, 'legacy'),clientName: rowName,scopes: grant.scopes,sourceId,@@ -453,7 +454,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {{result: {protocolVersion: '2025-03-26',- serverInfo: { name: 'gbrain', version: VERSION },+ serverInfo: { name: 'gbrain', version: VERSION, description: MCP_SERVER_DESCRIPTION },capabilities: { tools: {}, resources: {} },// #4748: contract (+ opt-in writeback section) + deployment identity.instructions: resolveMcpInstructions(fileConfig, process.env, {@@ -554,6 +555,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {takesHoldersAllowList: auth.takesHoldersAllowList,sourceId: auth.sourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta },+ actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined },// #1336: thread the token's federated_read grant so read ops scope// to the operator-granted sources via sourceScopeOpts.auth: auth.auth,diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex d5e559f535..0422d46a0c 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -23,6 +23,12 @@ import { buildAmbientWritebackSection } from '../core/facts/writeback-instructioimport type { AmbientWritebackOpts } from '../core/facts/writeback-instructions.ts';import { readEntityReferencesConfig } from '../core/entity-references-config.ts';+/**+ * GST-359 C1: initialize's serverInfo.description on every transport, at most 120 characters: the brain-first rule+ * for hosts that show the description but drop `instructions`. `instructions` is unchanged by it.+ */+export const MCP_SERVER_DESCRIPTION = 'Shared memory: search gbrain before external lookup; remember what the user explicitly asks you to keep.';+/** Which tools this connection can call (the tools/list predicate). */export type CallablePredicate = (toolName: string) => boolean;diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 789a722318..ce1b3f3d8f 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -18,7 +18,7 @@ import { parseResultRowsMode, resolveResultRowsMode } from './result-rows.ts';import { loadConfig } from '../core/config.ts';import { requestConfigRows, withRequestConfigSnapshot } from '../core/config-snapshot.ts';import { gcSessionContextState } from '../core/context/session-state.ts';-import { installInstructionsResolver, readInstructionContent, resolveMcpInstructions } from './instructions.ts';+import { installInstructionsResolver, MCP_SERVER_DESCRIPTION, readInstructionContent, resolveMcpInstructions } from './instructions.ts';import { instructionReadiness, stdioCapabilityReadiness } from './initialize-context.ts';import { STATUS_TOOL_DEF, STATUS_TOOL_NAME, attemptStatusRecovery, statusHeadline, statusInstructionLine, statusModeErrorResult, statusModeOf, statusPayload, statusToolResult } from './status-mode.ts';import { installCapabilitiesResource, mcpAdministrationGuidance } from './capabilities.ts';@@ -359,7 +359,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSextractFacts: session.allowedOps ? session.allowedOps.has('extract_facts') : true,}) : null;server = new Server(- { name: 'gbrain', version: VERSION },+ { name: 'gbrain', version: VERSION, description: MCP_SERVER_DESCRIPTION },// listChanged: a client that handshakes during DEGRADED mode receives the// gate-hidden catalog (stdioVisibleTools fail-closes every publishGateKey// op on engine failure) and caches it — recovery sends the notification