Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(admin): owner HTTP administration of the attest right, members and qm links (GST-1094 gap 4)
garrytan5e57f0c2b480
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dafc92f4d6..93a9bf532c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**The brain owner can now set a trusted system's attest right and manage members and their canonical-id links from another machine, over the running server, instead of needing a shell on the brain host.** Three owner-session routes back new `gbrain mcp admin` commands. Every refusal the local commands make still applies, and no OAuth token or MCP tool reaches them.++### What changed++| Task | Before | Now |+|---|---|---|+| Grant or clear a client's attest right | `gbrain auth rescope --client <id> --attest-actor qm` on the brain host | also `gbrain mcp admin attest <id> --attest-actor qm\|none [--attest-ops <list>] [--dry-run]` (`/admin/api/access/attest`) |+| Add, disable, enable or list members | `gbrain access member add\|disable\|enable\|list` on the host | also `gbrain mcp admin member-add\|member-disable\|member-enable\|members` (`/admin/api/access/members`) |+| Link or unlink a canonical id | `gbrain access member link\|unlink\|links` on the host | also `gbrain mcp admin link\|unlink\|links` (`/admin/api/access/member-links`) |++These routes accept only the owner session. Each applied change writes an `access_admin` row to the request log. A member-bound or public client still can't hold the attest right, deferred operations still can't be attested, and a link still needs an enabled member and an unlinked id. Removing a member stays a brain-host command.+## [0.60.555.0] - 2026-11-02**`gbrain query --limit N` without a token budget returns N rows again, a budgeted facts block takes at most N rows, the facts block never outscores the pages, and the CLI names fact rows instead of printing `undefined` (#8411).** Since the facts block went on by default (v0.60.491.0), it also ran on queries that passed no budget, because the shipped no-budget evidence plan carries an implicit 24,000-token budget. Its 22% share let up to 40 fact rows in ahead of the pages, so `--limit 3` could print more than a dozen fact rows before the 3 pages. Each block row was scored a hair above the top page, so they all showed the same score and outranked every hit, and the human CLI printed them as `[0.84xx] undefined -- …` because fact rows have no page slug.diff --git a/docs/guides/qm.md b/docs/guides/qm.mdindex f2f0859320..973ea25e17 100644--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@ -15,6 +15,10 @@ gbrain access member add alice-examplegbrain access member link alice-example --qm U0ALICE # the canonical id QM sends, compared exactly```+From another machine, the owner runs the same steps over the running server with+`gbrain mcp admin attest`, `member-add` and `link` (owner session only; see+[ADMIN](../mcp/ADMIN.md#inspect-clients-and-edit-access)).+Add `forget` with `--attest-ops forget,get_write_request,memory_recall,memory_write` if QMshould withdraw facts; an attested `forget` reaches only facts on the person's ownpage, and any other id is `not_found`.diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 6f04e3daab..5003abfd5b 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -263,6 +263,25 @@ read or write is not yet kept to the person: `list_write_conflicts`, `capture`,`gbrain access check --token <name>` shows theresult ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).+From another machine, the owner manages the attest right, members and links+over the running server:++```bash+gbrain mcp admin attest CLIENT_ID --attest-actor qm [--attest-ops <op,...>] --dry-run \+ --url https://brain.example.com/mcp --admin-token-file /absolute/private/admin-token+gbrain mcp admin member-add alice-example --url … --admin-token-file …+gbrain mcp admin link alice-example --qm U0ALICE --dry-run --url … --admin-token-file …+```++The other commands are `--attest-actor none` (clear the right),+`member-disable|member-enable ID`, `members [--all]`, `unlink --qm ID` and+`links [--member ID]`. They call `/admin/api/access/attest`, `/admin/api/access/members` and+`/admin/api/access/member-links`. These routes accept only the owner session:+no OAuth token and no MCP tool reaches them. They refuse exactly what the+local commands refuse, and each applied change is logged as `access_admin` in+the request log. Removing a member stays a brain-host command+(`gbrain access member rm`).+New `memory-reader`, `memory-writer` and `coding-agent` grants are callable onthe full surface and list the seven memory verbs plus `request_tools`, whichreturns any other tool's schema (`gbrain auth clients` shows the surface asdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3950144ddc..b4c0b3a456 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1610 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured+src/core/behavior-change-notice.ts 1611 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot)diff --git a/src/commands/mcp-admin.ts b/src/commands/mcp-admin.tsindex d61b31c19e..f8716806c5 100644--- a/src/commands/mcp-admin.ts+++ b/src/commands/mcp-admin.ts@@ -17,6 +17,13 @@ gbrain mcp admin client IDgbrain mcp admin register NAME --redirect-uri URI [--redirect-uri URI ...]gbrain mcp admin setup ID --harness ID [--flow authorization-code|client-credentials]gbrain mcp admin invalidate-tokens|revoke|delete ID [--yes --if-version N]+gbrain mcp admin attest CLIENT_ID --attest-actor qm|none [--attest-ops LIST] [--dry-run]+gbrain mcp admin members [--all]+gbrain mcp admin member-add ID [--name NAME] [--groups G1,G2]+gbrain mcp admin member-disable|member-enable ID+gbrain mcp admin links [--member ID]+gbrain mcp admin link MEMBER --qm CANONICAL_ID [--dry-run]+gbrain mcp admin unlink --qm CANONICAL_ID [--dry-run]--url URL Running server URL or /mcp endpoint (required)--admin-token-file FILE Private owner credential; otherwise GBRAIN_ADMIN_BOOTSTRAP_TOKEN@@ -30,6 +37,9 @@ gbrain mcp admin invalidate-tokens|revoke|delete ID [--yes --if-version N]--credentials-out FILE Explicit private export; required for confidential registration--dry-run Preview registration or lifecycle consequences--yes --if-version N Apply reviewed lifecycle action; otherwise preview only+--attest-actor qm|none Grant or clear the right to name the person a call serves (x-qm-actor)+--attest-ops LIST Operations an attested call may run (default get_write_request,memory_recall,memory_write)+--qm ID A canonical person id from the trusted system--timeout-ms N Request timeout, 100..300000 (default: 30000)--json Structured result; credentials stay in private exports@@ -53,17 +63,21 @@ const commandValues: Record<string, string[]> = {register: ['--redirect-uri', '--token-endpoint-auth-method', '--source', '--federated-read', '--scopes', '--profile', '--credentials-out', '--harness'],setup: ['--harness', '--flow', '--credentials-out'],'invalidate-tokens': ['--if-version'], revoke: ['--if-version'], delete: ['--if-version'],+ attest: ['--attest-actor', '--attest-ops'], members: [], 'member-add': ['--name', '--groups'], 'member-disable': [], 'member-enable': [],+ links: ['--member'], link: ['--qm'], unlink: ['--qm'],};+const untargeted = ['login-link', 'clients', 'members', 'links', 'unlink'];+const previewable = ['register', 'invalidate-tokens', 'revoke', 'delete', 'attest', 'link', 'unlink'];export function parseMcpAdmin(args: string[]): AdminArgs {const command = args[0];- if (!command || !Object.hasOwn(commandValues, command)) throw new McpAdminError('invalid_admin_command', 'Expected login-link, clients, client, register, setup, invalidate-tokens, revoke, or delete. Use mcp admin --help.');- const targeted = !['login-link', 'clients'].includes(command);+ if (!command || !Object.hasOwn(commandValues, command)) throw new McpAdminError('invalid_admin_command', `Expected one of: ${Object.keys(commandValues).join(', ')}. Use mcp admin --help.`);+ const targeted = !untargeted.includes(command);const target = targeted ? args[1] : undefined;- if (targeted && (!target || target.startsWith('-'))) throw new McpAdminError('missing_target', `${command} requires ${command === 'register' ? 'a name' : 'a client ID'}.`);+ if (targeted && (!target || target.startsWith('-'))) throw new McpAdminError('missing_target', `${command} requires ${command === 'register' ? 'a name' : command.startsWith('member') || command === 'link' ? 'a member ID' : 'a client ID'}.`);const allowedValues = new Set([...common, ...commandValues[command]]);const lifecycle = ['invalidate-tokens', 'revoke', 'delete'].includes(command);- const allowedFlags = new Set(['--json', ...(command === 'register' || lifecycle ? ['--dry-run'] : []), ...(lifecycle ? ['--yes'] : [])]);+ const allowedFlags = new Set(['--json', ...(previewable.includes(command) ? ['--dry-run'] : []), ...(lifecycle ? ['--yes'] : []), ...(command === 'members' ? ['--all'] : [])]);const values = new Map<string, string[]>();const flags = new Set<string>();for (let i = targeted ? 2 : 1; i < args.length; i++) {@@ -84,6 +98,37 @@ export function parseMcpAdmin(args: string[]): AdminArgs {return { command, target, values, flags };}+type AdminClient = ReturnType<typeof createMcpAdminHttp>;+const list = (raw: string | undefined) => raw === undefined ? undefined : raw.split(',').map(s => s.trim()).filter(Boolean);++/** GST-1094 gap 4: the attest right, members and canonical-id links, over the owner session (serve-http-access.ts). */+const ACCESS_COMMANDS: Record<string, (client: AdminClient, parsed: AdminArgs, value: (flag: string) => string | undefined) => Promise<unknown>> = {+ attest: (client, parsed, value) => {+ const actor = value('--attest-actor');+ const ops = value('--attest-ops');+ if (actor === undefined && ops === undefined) throw new McpAdminError('invalid_arguments', 'attest needs --attest-actor qm|none and/or --attest-ops <list>.');+ const dryRun = parsed.flags.has('--dry-run');+ return client.request('/admin/api/access/attest', { method: 'POST', mutation: !dryRun, nextAction: `gbrain mcp admin client ${parsed.target} --url ${client.base}`, body: {+ clientId: parsed.target, dryRun, ...(actor === undefined ? {} : { attestActor: actor === 'none' ? null : actor }), ...(ops === undefined ? {} : { attestOps: list(ops) }) } });+ },+ members: (client, parsed) => client.request(`/admin/api/access/members${parsed.flags.has('--all') ? '?all=1' : ''}`),+ 'member-add': (client, parsed, value) => client.request('/admin/api/access/members', { method: 'POST', mutation: true, nextAction: `gbrain mcp admin members --url ${client.base}`,+ body: { action: 'add', id: parsed.target, ...(value('--name') === undefined ? {} : { name: value('--name') }), ...(value('--groups') === undefined ? {} : { groups: list(value('--groups')) }) } }),+ 'member-disable': (client, parsed) => client.request('/admin/api/access/members', { method: 'POST', mutation: true, nextAction: `gbrain mcp admin members --url ${client.base}`, body: { action: 'disable', id: parsed.target } }),+ 'member-enable': (client, parsed) => client.request('/admin/api/access/members', { method: 'POST', mutation: true, nextAction: `gbrain mcp admin members --url ${client.base}`, body: { action: 'enable', id: parsed.target } }),+ links: (client, _parsed, value) => client.request(`/admin/api/access/member-links${value('--member') ? `?member=${encodeURIComponent(value('--member')!)}` : ''}`),+ link: (client, parsed, value) => linkRequest(client, parsed, value, 'link'),+ unlink: (client, parsed, value) => linkRequest(client, parsed, value, 'unlink'),+};++function linkRequest(client: AdminClient, parsed: AdminArgs, value: (flag: string) => string | undefined, action: 'link' | 'unlink'): Promise<unknown> {+ const externalId = value('--qm');+ if (externalId === undefined) throw new McpAdminError('invalid_arguments', `${action} needs --qm <canonical id>.`);+ const dryRun = parsed.flags.has('--dry-run');+ return client.request('/admin/api/access/member-links', { method: 'POST', mutation: !dryRun, nextAction: `gbrain mcp admin links --url ${client.base}`,+ body: { action, externalId, dryRun, ...(action === 'link' ? { member: parsed.target } : {}) } });+}+function destinationAvailable(path: string): void {const target = resolve(path);assertNoSymlinks(target);@@ -115,7 +160,7 @@ export async function runMcpAdmin(args: string[], dependencies: Pick<McpAdminHttif (!args.length || args.includes('--help') || args.includes('-h')) { console.log(HELP); return; }const parsed = parseMcpAdmin(args);stage = parsed.command;- if (parsed.command !== 'register') clientId = parsed.target;+ if (!['register', 'link'].includes(parsed.command) && !parsed.command.startsWith('member')) clientId = parsed.target;const value = (flag: string) => parsed.values.get(flag)?.[0];const json = parsed.flags.has('--json');const print = (result: unknown) => console.log(sanitize(JSON.stringify(redactAdminValue(result), null, json ? undefined : 2)));@@ -136,6 +181,10 @@ export async function runMcpAdmin(args: string[], dependencies: Pick<McpAdminHttprint(await client.request(parsed.command === 'clients' ? '/admin/api/clients' : path));return;}+ if (parsed.command in ACCESS_COMMANDS) {+ print(await ACCESS_COMMANDS[parsed.command]!(client, parsed, value));+ return;+ }if (parsed.command === 'register') {const redirects = parsed.values.get('--redirect-uri') ?? [];if (!redirects.length) throw new McpAdminError('redirect_uri_required', 'Native OAuth registration requires at least one --redirect-uri supplied by the client harness.');diff --git a/src/commands/serve-http-access.ts b/src/commands/serve-http-access.tsnew file mode 100644index 0000000000..e7d6141ce3--- /dev/null+++ b/src/commands/serve-http-access.ts@@ -0,0 +1,103 @@+import express, { type Express, type Request, type Response, type RequestHandler } from 'express';+import type { BrainEngine } from '../core/engine.ts';+import { OperationError } from '../core/ops/contract.ts';+import { addMember, bindCredential, disableMember, enableMember, listMembers, type BindingPatch } from '../core/access/members.ts';+import { ATTEST_SYSTEMS, linkMember, listMemberLinks, parseAttestOps, unlinkMember } from '../core/access/actor.ts';+import { operationsByName } from '../core/operations.ts';+import { executeRawJsonb } from '../core/sql-query.ts';++/**+ * GST-1094 gap 4: owner administration of the people a trusted system serves, over the running server: the attest+ * right on a client, members, and the canonical ids linked to them. Owner session only (requireAdmin); never an MCP+ * operation or an OAuth scope. Every refusal is the library's, as on the local CLI (gbrain auth rescope --attest-actor,+ * gbrain access member add|disable|enable|link|unlink).+ */+export function mountAdminAccess(app: Express, requireAdmin: RequestHandler, engine: BrainEngine): void {+ const json = express.json();++ app.get('/admin/api/access/members', requireAdmin, async (req, res) => {+ await answer(res, false, async () => ({ members: await listMembers(engine, { includeRemoved: req.query.all === '1' || req.query.all === 'true' }) }));+ });++ app.post('/admin/api/access/members', requireAdmin, json, async (req, res) => {+ const { action, id } = req.body ?? {};+ if (action !== 'add' && action !== 'disable' && action !== 'enable') return refuse(res, 'action must be add, disable or enable.');+ if (action === 'add' && req.body.name !== undefined && typeof req.body.name !== 'string') return refuse(res, 'name must be a string.');+ if (action === 'add' && req.body.groups !== undefined && !(Array.isArray(req.body.groups) && req.body.groups.every((g: unknown) => typeof g === 'string'))) return refuse(res, 'groups must be an array of group ids.');+ await answer(res, true, async () => {+ if (action === 'add') {+ const result = await addMember(engine, id, { name: req.body.name, groups: req.body.groups });+ await audit(engine, 'member_add', { member: result.member.id, groups_created: result.groups_created });+ return { applied: true, ...result };+ }+ const member = await (action === 'disable' ? disableMember : enableMember)(engine, id);+ await audit(engine, `member_${action}`, { member: member.id });+ return { applied: true, member };+ });+ });++ app.get('/admin/api/access/member-links', requireAdmin, async (req, res) => {+ const member = typeof req.query.member === 'string' && req.query.member ? req.query.member : undefined;+ await answer(res, false, async () => ({ links: await listMemberLinks(engine, { member }) }));+ });++ app.post('/admin/api/access/member-links', requireAdmin, json, async (req, res) => {+ const { action, member, externalId, dryRun } = req.body ?? {};+ const system = req.body?.system ?? 'qm';+ if (action !== 'link' && action !== 'unlink') return refuse(res, 'action must be link or unlink.');+ if (!ATTEST_SYSTEMS.includes(system)) return refuse(res, `system must be ${ATTEST_SYSTEMS.join(' or ')}.`);+ if (dryRun !== undefined && typeof dryRun !== 'boolean') return refuse(res, 'dryRun must be a boolean.');+ await answer(res, dryRun !== true, async () => {+ const result = action === 'link' ? await linkMember(engine, member, system, externalId, { dryRun }) : await unlinkMember(engine, system, externalId, { dryRun });+ if (result.applied) await audit(engine, `member_${action}`, { system, external_id: result.link.external_id, member: result.link.member_id });+ return result;+ });+ });++ app.post('/admin/api/access/attest', requireAdmin, json, async (req, res) => {+ const { clientId, attestActor, attestOps, dryRun } = req.body ?? {};+ if (typeof clientId !== 'string' || !clientId) return refuse(res, 'clientId required.');+ if (attestActor === undefined && attestOps === undefined) return refuse(res, 'Pass attestActor (qm or null) and/or attestOps.');+ if (attestActor !== undefined && attestActor !== null && !ATTEST_SYSTEMS.includes(attestActor)) return refuse(res, `attestActor must be ${ATTEST_SYSTEMS.join(' or ')}, or null to clear the right.`);+ if (attestOps !== undefined && attestOps !== null && !(Array.isArray(attestOps) && attestOps.every((op: unknown) => typeof op === 'string'))) return refuse(res, 'attestOps must be an array of operation names, or null for the default.');+ if (dryRun !== undefined && typeof dryRun !== 'boolean') return refuse(res, 'dryRun must be a boolean.');+ await answer(res, dryRun !== true, async () => {+ const patch: BindingPatch = {+ ...(attestActor !== undefined ? { attestActor } : {}),+ ...(attestOps !== undefined ? { attestOps: attestOps === null ? null : parseAttestOps(attestOps.join(','), name => operationsByName[name]) } : {}),+ };+ const result = await bindCredential(engine, { kind: 'client', id: clientId }, patch, { dryRun });+ if (result.changed && !dryRun) await audit(engine, 'client_attest', { client_id: clientId, attest_actor: result.attest_actor ?? null, attest_ops: result.attest_ops ?? null });+ return { applied: result.changed && dryRun !== true, client_id: clientId, attest_actor: result.attest_actor ?? null, attest_ops: result.attest_ops ?? null, changed: result.changed,+ tokenImplications: 'Takes effect on the next request; a client that newly holds the right takes a new token with grant_type=client_credentials.' };+ });+ });+}++function refuse(res: Response, message: string): void {+ res.status(400).json({ error: 'invalid_params', code: 'invalid_params', message, outcome: 'failed' });+}++async function answer(res: Response, mutation: boolean, run: () => Promise<Record<string, unknown>>): Promise<void> {+ res.set('Cache-Control', 'no-store');+ try {+ res.json(await run());+ } catch (error) {+ if (error instanceof OperationError) {+ res.status(400).json({ error: error.code, code: error.code, message: error.message, suggestion: error.suggestion, ...(error.reason ? { reason: error.reason } : {}), outcome: 'failed' });+ return;+ }+ res.status(503).json({ error: 'administration_unavailable', code: 'administration_unavailable', outcome: mutation ? 'unknown' : 'failed',+ message: mutation ? 'The change outcome is unknown. List the members, links or client before another change.' : 'Administration is temporarily unavailable. Retry the read.' });+ }+}++/** One audit row per applied change, in the request log like a surface change; fail-open, as there. */+async function audit(engine: BrainEngine, action: string, detail: Record<string, unknown>): Promise<void> {+ try {+ await executeRawJsonb(engine, `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, params) VALUES ($1, $2, $3, $4, $5, $6::jsonb)`,+ ['admin-api', 'admin-api', 'access_admin', 0, 'success'], [{ actor: 'admin-api', action, ...detail }]);+ } catch (err) {+ process.stderr.write(`[access-admin] failed to write the ${action} audit row: ${err instanceof Error ? err.message : String(err)}\n`);+ }+}diff --git a/src/commands/serve-http-admin-api.ts b/src/commands/serve-http-admin-api.tsindex 46890304b7..8b83c53cf8 100644--- a/src/commands/serve-http-admin-api.ts+++ b/src/commands/serve-http-admin-api.ts@@ -17,6 +17,7 @@ import { mountAdminApiKeys } from './serve-http-api-keys.ts';import { mountAdminClients } from './serve-http-clients.ts';import { mountAdminRegistration } from './serve-http-registration.ts';import { parseAdminGrantRequest, grantHttpStatus, GRANT_TOKEN_IMPLICATIONS, mountAdminGrantDiscovery, mountAdminGrantEdits } from './serve-http-grants.ts';+import { mountAdminAccess } from './serve-http-access.ts';import { probeHealth } from './serve-http-metrics.ts';import type { ServeHttpContext } from './serve-http.ts';@@ -610,6 +611,7 @@ function mountAdminClientApi(app: Express, ctx: ServeHttpContext): void {});mountAdminGrantEdits(app, requireAdmin, engine, oauthProvider);+ mountAdminAccess(app, requireAdmin, engine);// Revoke OAuth clientapp.post('/admin/api/revoke-client', requireAdmin, express.json(), async (req: Request, res: Response) => {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 727fa1fb23..aa0d6eac1b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1412,6 +1412,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.550.0', id: 'mcp_lane_launcher_8426', text: 'The stdio MCP entry `gbrain setup claude-code|codex` and `gbrain bootstrap hooks` (opencode\'s user-global entry included) register now starts `gbrain serve` through `<gbrain config dir>/hook-launcher/gbrain-hook`, and the hooks from `gbrain bootstrap hooks`, `gbrain bootstrap harness`, the Codex SessionEnd capture and the gbrain plugins start gbrain from the launcher\'s or the plugin\'s own directory, so a session opened in a cloned repository never runs that repository\'s bunfig.toml preload or loads its .env; serve still reads .gbrain-source from the session directory. `gbrain post-upgrade` moves a Claude Code setup MCP entry setup still owns and names the command for every Codex (the turn-rule hook included) and bootstrap entry, doctor `hook_session_cwd` covers them, and `gbrain hook` git probes skip core.fsmonitor and run only in the workspace the install receipt names.' },// GST-927 (GBRA-280) schema-ruled-out empty arguments; release:restamp stamps since at the merge slot.{ since: '0.60.553.0', id: 'empty_nonstring_args_gst927', text: 'Read tools now treat an optional argument as not provided when its own schema rules the value out: 0 where the range starts above zero (limit: 0, around_chunk_id: 0, schema_version: 0 and others), [] where the list must not be empty (types, only, traverse_graph hops), {} where the object needs a field (get_page lines and bytes), false on get_versions diff, and get_page context without grep. These calls used to refuse with invalid_params; now they answer as if the argument were left out. get_page known_as_of beside window or view arguments still refuses, and the refusal names the arguments to drop.' },+ { since: 'TBD', id: 'qm_admin_http_gst1094', text: 'The brain owner can now manage the attest right, members and canonical-id links over the running server: `gbrain mcp admin attest <client> --attest-actor qm|none [--attest-ops <list>]`, `member-add`, `member-disable`, `member-enable`, `members`, `link <member> --qm <id>`, `unlink --qm <id>` and `links`, backed by `/admin/api/access/attest`, `/admin/api/access/members` and `/admin/api/access/member-links`. These routes take the owner session only (never an OAuth token or an MCP tool), refuse what the local `gbrain auth rescope` and `gbrain access member` commands refuse, preview with `--dry-run` where those do, and log each applied change as `access_admin`. Removing a member stays a brain-host command.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 0b077b701b..b1aa9c1698 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -85,7 +85,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],- 'mcp': ['--admin-token-file', '--advertise', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],+ 'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],diff --git a/test/mcp-admin-cli.serial.test.ts b/test/mcp-admin-cli.serial.test.tsindex 6fbf0ab9c9..c50793e259 100644--- a/test/mcp-admin-cli.serial.test.ts+++ b/test/mcp-admin-cli.serial.test.ts@@ -172,3 +172,34 @@ test('backend failures stay visible and cannot expose the owner credential', asyexpect(result.output).not.toContain(owner);expect(result.result).not.toHaveProperty('clients');});++test('people administration commands send owner-session requests to the access routes (GST-1094 gap 4)', async () => {+ const cases: Array<[string[], string, unknown]> = [+ [['attest', clientId, '--attest-actor', 'qm', '--attest-ops', 'memory_recall,memory_write', '--dry-run'], '/admin/api/access/attest', { clientId, dryRun: true, attestActor: 'qm', attestOps: ['memory_recall', 'memory_write'] }],+ [['attest', clientId, '--attest-actor', 'none'], '/admin/api/access/attest', { clientId, dryRun: false, attestActor: null }],+ [['members', '--all'], '/admin/api/access/members?all=1', undefined],+ [['member-add', 'alice-example', '--name', 'Alice Example', '--groups', 'team-a,team-b'], '/admin/api/access/members', { action: 'add', id: 'alice-example', name: 'Alice Example', groups: ['team-a', 'team-b'] }],+ [['member-disable', 'alice-example'], '/admin/api/access/members', { action: 'disable', id: 'alice-example' }],+ [['member-enable', 'alice-example'], '/admin/api/access/members', { action: 'enable', id: 'alice-example' }],+ [['links', '--member', 'alice-example'], '/admin/api/access/member-links?member=alice-example', undefined],+ [['link', 'alice-example', '--qm', 'ext-alice', '--dry-run'], '/admin/api/access/member-links', { action: 'link', externalId: 'ext-alice', dryRun: true, member: 'alice-example' }],+ [['unlink', '--qm', 'ext-alice'], '/admin/api/access/member-links', { action: 'unlink', externalId: 'ext-alice', dryRun: false }],+ ];+ for (const [args, path, body] of cases) {+ expect(mcpNeedsEngine(['admin', args[0]!], undefined)).toBe(false);+ const run = await capture(args, () => Response.json({ applied: false }));+ expect(run.exitCode).toBe(0);+ const sent = run.requests.at(-1)!;+ expect(sent.url).toBe(base + path);+ expect(sent.init.body === undefined ? undefined : JSON.parse(String(sent.init.body))).toEqual(body);+ expect(run.output).not.toContain(owner);+ }+ const refused = await capture(['attest', clientId], () => Response.json({}));+ expect(refused.result).toMatchObject({ status: 'error', reason: 'invalid_arguments' });+ const noQm = await capture(['link', 'alice-example'], () => Response.json({}));+ expect(noQm.result).toMatchObject({ status: 'error', reason: 'invalid_arguments' });+ const serverRefusal = await capture(['attest', clientId, '--attest-actor', 'qm'], () => Response.json({ error: 'invalid_params', code: 'invalid_params', message: 'not a confidential client-credentials client', outcome: 'failed' }, { status: 400 }));+ expect(serverRefusal.result.status).toBe('error');+ expect(serverRefusal.exitCode).toBe(1);+});+diff --git a/test/serve-http-access.test.ts b/test/serve-http-access.test.tsnew file mode 100644index 0000000000..fbf5146e24--- /dev/null+++ b/test/serve-http-access.test.ts@@ -0,0 +1,145 @@+/**+ * GST-1094 gap 4: owner administration of QM people over HTTP (serve-http-access.ts).+ *+ * 1. Protects: only an owner session sets a client's attest right and edits members and their canonical-id links+ * remotely, every library refusal still applies (member-bound or public clients never attest, deferred ops never+ * attest, links need an enabled member and never steal an id), a dry run writes nothing, and each applied change+ * leaves an audit row.+ * 2. Fails when: a route answers without the owner session, an HTTP change skips a refusal the local CLI makes, a+ * preview writes, or a change leaves no audit row.+ * 3. Real seams: the routes mounted on an Express app over a real socket, OAuth clients registered and issued tokens by+ * the provider's client-credentials grant and verified by it, on a repo-less brain (PGLite, and Postgres when+ * DATABASE_URL is set).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import express from 'express';+import cookieParser from 'cookie-parser';+import { randomUUID } from 'node:crypto';+import type { Server } from 'node:http';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { addMember, bindCredential, getMember } from '../src/core/access/members.ts';+import { listMemberLinks } from '../src/core/access/actor.ts';+import { mountAdminAccess } from '../src/commands/serve-http-access.ts';+import { createRequireAdmin } from '../src/commands/serve-http-admin-api.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++for (const kind of testBackends()) {+ describe('owner HTTP administration of QM people (' + kind + ', repo-less)', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let server: Server;+ let base = '';+ const sessions = new Map<string, number>();+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const register = async (name: string, grantTypes: string[]) => (await provider().registerClientManual(name + '-' + randomUUID().slice(0, 8), grantTypes, 'read write', [], 'default'));+ async function call(method: 'GET' | 'POST', path: string, body?: unknown, owner = true) {+ const res = await fetch(base + path, { method, headers: { 'Content-Type': 'application/json', ...(owner ? { Cookie: 'gbrain_admin=owner-session' } : {}) },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return { status: res.status, json: await res.json() as Record<string, any> };+ }+ const audits = async () => (await engine.executeRaw<{ params: Record<string, unknown> | string }>("SELECT params FROM mcp_request_log WHERE operation = 'access_admin' ORDER BY id"))+ .map(r => typeof r.params === 'string' ? JSON.parse(r.params) : r.params);++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ sessions.set('owner-session', Date.now() + 3_600_000);+ const app = express();+ app.use(cookieParser());+ mountAdminAccess(app, createRequireAdmin(sessions), engine);+ server = app.listen(0, '127.0.0.1');+ await new Promise<void>(r => server.once('listening', () => r()));+ base = 'http://127.0.0.1:' + (server.address() as { port: number }).port;+ }, 120_000);+ afterAll(async () => {+ server?.closeAllConnections(); await new Promise<void>(r => server ? server.close(() => r()) : r());+ await close?.();+ });++ test('every route refuses a request without the owner session and changes nothing', async () => {+ const qm = await register('qm-unauth', ['client_credentials']);+ const routes: Array<['GET' | 'POST', string, unknown?]> = [+ ['GET', '/admin/api/access/members'], ['POST', '/admin/api/access/members', { action: 'add', id: 'mallory-example' }],+ ['GET', '/admin/api/access/member-links'], ['POST', '/admin/api/access/member-links', { action: 'link', member: 'mallory-example', externalId: 'ext-mallory' }],+ ['POST', '/admin/api/access/attest', { clientId: qm.clientId, attestActor: 'qm' }],+ ];+ for (const [method, path, body] of routes) expect((await call(method, path, body, false)).status).toBe(401);+ expect(await getMember(engine, 'mallory-example')).toBeNull();+ const [row] = await engine.executeRaw<{ attest_actor: string | null }>('SELECT attest_actor FROM oauth_clients WHERE client_id = $1', [qm.clientId]);+ expect(row!.attest_actor).toBeNull();+ expect(await audits()).toEqual([]);+ });++ test('members: add, disable and enable apply with an audit row; a second add and a bad id are refused', async () => {+ const added = await call('POST', '/admin/api/access/members', { action: 'add', id: 'alice-example', name: 'Alice Example', groups: ['team-a'] });+ expect(added.status).toBe(200);+ expect(added.json).toMatchObject({ applied: true, member: { id: 'alice-example', status: 'enabled' }, groups_created: ['team-a'] });+ expect((await call('POST', '/admin/api/access/members', { action: 'add', id: 'alice-example' })).json).toMatchObject({ code: 'access_member_invalid', outcome: 'failed' });+ expect((await call('POST', '/admin/api/access/members', { action: 'add', id: 'Not An Id' })).status).toBe(400);+ expect((await call('POST', '/admin/api/access/members', { action: 'remove', id: 'alice-example' })).json).toMatchObject({ code: 'invalid_params' });+ expect((await call('POST', '/admin/api/access/members', { action: 'disable', id: 'alice-example' })).json.member.status).toBe('disabled');+ expect((await call('POST', '/admin/api/access/members', { action: 'enable', id: 'alice-example' })).json.member.status).toBe('enabled');+ const listed = await call('GET', '/admin/api/access/members');+ expect(listed.json.members.map((m: { id: string }) => m.id)).toContain('alice-example');+ expect((await audits()).map(a => a.action)).toEqual(['member_add', 'member_disable', 'member_enable']);+ });++ test('links: a dry run writes nothing; link and unlink apply; a disabled member or a taken id is refused', async () => {+ await addMember(engine, 'bob-example');+ const preview = await call('POST', '/admin/api/access/member-links', { action: 'link', member: 'bob-example', externalId: 'ext-bob', dryRun: true });+ expect(preview.json).toMatchObject({ applied: false, link: { member_id: 'bob-example', external_id: 'ext-bob' } });+ expect(await listMemberLinks(engine, { member: 'bob-example' })).toEqual([]);+ expect((await call('POST', '/admin/api/access/member-links', { action: 'link', member: 'bob-example', externalId: 'ext-bob' })).json.applied).toBe(true);+ expect((await call('GET', '/admin/api/access/member-links?member=bob-example')).json.links).toMatchObject([{ system: 'qm', external_id: 'ext-bob', member_id: 'bob-example' }]);+ expect((await call('POST', '/admin/api/access/member-links', { action: 'link', member: 'alice-example', externalId: 'ext-bob' })).json).toMatchObject({ code: 'access_member_invalid', reason: 'link_exists' });+ await call('POST', '/admin/api/access/members', { action: 'disable', id: 'alice-example' });+ expect((await call('POST', '/admin/api/access/member-links', { action: 'link', member: 'alice-example', externalId: 'ext-alice' })).status).toBe(400);+ await call('POST', '/admin/api/access/members', { action: 'enable', id: 'alice-example' });+ expect((await call('POST', '/admin/api/access/member-links', { action: 'link', member: 'bob-example', externalId: 'has space' })).json.reason).toBe('invalid_external_id');+ expect((await call('POST', '/admin/api/access/member-links', { action: 'link', member: 'bob-example', externalId: 'ext-x', system: 'other' })).json.code).toBe('invalid_params');+ expect((await call('POST', '/admin/api/access/member-links', { action: 'unlink', externalId: 'ext-bob', dryRun: true })).json.applied).toBe(false);+ expect(await listMemberLinks(engine, { member: 'bob-example' })).toHaveLength(1);+ expect((await call('POST', '/admin/api/access/member-links', { action: 'unlink', externalId: 'ext-bob' })).json.applied).toBe(true);+ expect(await listMemberLinks(engine, { member: 'bob-example' })).toEqual([]);+ expect((await audits()).filter(a => String(a.action).startsWith('member_link') || a.action === 'member_unlink'))+ .toEqual([{ actor: 'admin-api', action: 'member_link', system: 'qm', external_id: 'ext-bob', member: 'bob-example' }, { actor: 'admin-api', action: 'member_unlink', system: 'qm', external_id: 'ext-bob', member: 'bob-example' }]);+ });++ test('attest: a confidential client-credentials client gets the right its next token carries; every CLI refusal holds', async () => {+ const qm = await register('qm-http', ['client_credentials']);+ const preview = await call('POST', '/admin/api/access/attest', { clientId: qm.clientId, attestActor: 'qm', dryRun: true });+ expect(preview.json).toMatchObject({ applied: false, changed: true, attest_actor: 'qm' });+ const [before] = await engine.executeRaw<{ attest_actor: string | null }>('SELECT attest_actor FROM oauth_clients WHERE client_id = $1', [qm.clientId]);+ expect(before!.attest_actor).toBeNull();+ const applied = await call('POST', '/admin/api/access/attest', { clientId: qm.clientId, attestActor: 'qm', attestOps: ['memory_recall', 'memory_write', 'get_write_request'] });+ expect(applied.json).toMatchObject({ applied: true, attest_actor: 'qm', attest_ops: ['get_write_request', 'memory_recall', 'memory_write'] });+ const token = (await provider().exchangeClientCredentials(qm.clientId, qm.clientSecret!)).access_token;+ const auth = await provider().verifyAccessToken(token) as unknown as { attest?: { system: string; ops: string[] } | null };+ expect(auth.attest).toEqual({ system: 'qm', ops: ['get_write_request', 'memory_recall', 'memory_write'] });++ expect((await call('POST', '/admin/api/access/attest', { clientId: qm.clientId, attestOps: ['capture'] })).json).toMatchObject({ code: 'invalid_params' });+ expect((await call('POST', '/admin/api/access/attest', { clientId: qm.clientId, attestOps: ['admin_only_op_example'] })).json).toMatchObject({ code: 'invalid_params' });+ const bound = await register('member-bound', ['client_credentials']);+ await bindCredential(engine, { kind: 'client', id: bound.clientId }, { member: 'bob-example' });+ expect((await call('POST', '/admin/api/access/attest', { clientId: bound.clientId, attestActor: 'qm' })).json).toMatchObject({ code: 'invalid_params' });+ const pub = await register('public-pkce', ['authorization_code', 'refresh_token']);+ expect((await call('POST', '/admin/api/access/attest', { clientId: pub.clientId, attestActor: 'qm' })).json).toMatchObject({ code: 'invalid_params' });+ expect((await call('POST', '/admin/api/access/attest', { clientId: 'no-such-client', attestActor: 'qm' })).json).toMatchObject({ code: 'invalid_params' });+ expect((await call('POST', '/admin/api/access/attest', { clientId: qm.clientId, attestActor: 'other' })).status).toBe(400);+ for (const id of [bound.clientId, pub.clientId]) {+ const [row] = await engine.executeRaw<{ attest_actor: string | null }>('SELECT attest_actor FROM oauth_clients WHERE client_id = $1', [id]);+ expect(row!.attest_actor).toBeNull();+ }++ expect((await call('POST', '/admin/api/access/attest', { clientId: qm.clientId, attestActor: null })).json).toMatchObject({ applied: true, attest_actor: null });+ const cleared = await provider().verifyAccessToken((await provider().exchangeClientCredentials(qm.clientId, qm.clientSecret!)).access_token) as unknown as { attest?: unknown };+ expect(cleared.attest ?? null).toBeNull();+ expect((await audits()).filter(a => a.action === 'client_attest').map(a => [a.client_id, a.attest_actor]))+ .toEqual([[qm.clientId, 'qm'], [qm.clientId, null]]);+ });+ });+}