Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Let the brain owner review QM's memory proposals over the owner HTTP session (GST-2407)

garrytanc57d030d28d0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ba696e4deb..75da6c5a21 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,26 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**The brain owner can now review QM's memory proposals from another machine.** QM is the AI helper that can use gbrain as one of its memories; it proposes timeline entries and links with `memory_propose`, and nothing lands until the owner says yes. Until now that yes needed a shell on the brain host (`gbrain memory-proposals`). The owner's admin session now reaches the same review over the running server.
+
+### What changed
+
+| Area | Before | Now |
+|---|---|---|
+| Reviewing proposals remotely | a shell on the brain host | owner-session routes `GET /admin/api/memory-proposals` (`?source=`, `?cursor=`, oldest first, 50 a page), `GET /admin/api/memory-proposals/<request_id>` and `POST /admin/api/memory-proposals/<request_id>` (`{action: "approve"\|"deny", reason?, dryRun?}`), mirrored by `gbrain mcp admin memory-proposals list\|show\|approve\|deny`; no OAuth token or MCP tool reaches them |
+| Audit | CLI decisions record `decided_by` | HTTP decisions record `decided_by: admin-api` and one `access_admin` request-log row per applied decision, never the proposed text; a change that fails partway answers `outcome: unknown` |
+| `gbrain memory-proposals approve` when the approved write fails | exit 0 | exit 1; the HTTP approve reports `outcome: failed` with the write's receipt |
+
+### Itemized changes
+
+- `src/commands/serve-http-access.ts`, `src/commands/serve-http-admin-api.ts`: `mountAdminMemoryProposals` beside gap 4's access routes, on the same `requireAdmin`, dry-run, audit and `outcome: unknown` pattern; approve and deny call the CLI's library functions, so the one transaction, the re-checked actor and page revision and the writer-door publication are shared.
+- `src/commands/mcp-admin.ts`: the `memory-proposals` mirror; each decision takes exactly one request id, and deny needs a 1-500 character reason.
+- `src/core/persistence/memory-proposals.ts`: a keyset page cursor for the owner list and `approveFailed`, the one rule the CLI exit code and the HTTP outcome share.
+- Docs: `docs/mcp/ADMIN.md`, `docs/guides/qm.md`.
+- Tests: `test/serve-http-memory-proposals.test.ts` (new, PGLite and Postgres), `test/mcp-admin-cli.serial.test.ts`.
+
## [0.60.655.0] - 2026-11-10
**QM, the AI helper that uses gbrain as one of its memories, can now read a person's own brain safely, read shared rooms only as the room's audience, and suggest edits that wait for the brain owner's yes.** This lands the QM internal-provider chain (#8475, #8480, #8557, #8477, #8483, #8479, #8466) as one release. Nothing changes for a brain with no attested (`x-qm-actor`) client: unattested calls and member-bound credentials behave as before, and every new table is database state, so a repo-less brain works the same.
diff --git a/docs/guides/qm.md b/docs/guides/qm.md
index 1263362756..c61d06f7cd 100644
--- a/docs/guides/qm.md
+++ b/docs/guides/qm.md
@@ -124,12 +124,13 @@ the person it serves. Nothing is written until the brain owner says yes. Grant i
person it was made for reads it; anyone else gets `not_found`.
- `cancel_write_request {request_id}` withdraws a proposal still awaiting the owner.
-The owner reviews on the brain host, never over MCP:
+The owner reviews on the brain host, or from another machine with `gbrain mcp admin
+memory-proposals list|show|approve|deny` (owner session only), never over MCP:
```bash
gbrain memory-proposals list # awaiting your decision, oldest first
gbrain memory-proposals show <request_id> # the proposed text, fenced as untrusted transcript text
-gbrain memory-proposals approve <request_id> # re-checks the person, the grant and the page, then writes it
+gbrain memory-proposals approve <request_id> # re-checks the person, the grant and the page, then writes it; exits 1 if the write fails
gbrain memory-proposals deny <request_id> --reason "<why>"
```
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 9de6c92f21..b1fabbf51d 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -288,8 +288,8 @@ audience reads none, and a hidden source is refused like one outside the grant.
`gbrain access check --token <name>` shows the
result ([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:
+From another machine, the owner manages the attest right, members, links and
+QM's memory proposals over the running server:
```bash
gbrain mcp admin attest CLIENT_ID --attest-actor qm [--attest-ops <op,...>] --dry-run \
@@ -297,6 +297,7 @@ gbrain mcp admin attest CLIENT_ID --attest-actor qm [--attest-ops <op,...>] --dr
gbrain mcp admin member-add alice-example --email [email protected] --url … --admin-token-file …
gbrain mcp admin link alice-example --qm U0ALICE --dry-run --url … --admin-token-file …
gbrain mcp admin link --email [email protected] --qm U0ALICE --dry-run --url … --admin-token-file …
+gbrain mcp admin memory-proposals approve <request_id> --dry-run --url … --admin-token-file …
```
The other commands are `--attest-actor none` (clear the right),
@@ -304,8 +305,12 @@ The other commands are `--attest-actor none` (clear the right),
`unlink --qm ID` and `links [--member ID]`. A member's email is optional,
stored lower-case and unique per brain; `link --email` finds the one member that
declares it and makes the same link `link ID` makes, and an unknown email is
-`not_found` and creates nothing. They call `/admin/api/access/attest`, `/admin/api/access/members` and
-`/admin/api/access/member-links`. These routes accept only the owner session:
+`not_found` and creates nothing. `memory-proposals list [--source ID] [--cursor C]`, `show ID`,
+`approve ID` and `deny ID --reason TEXT` review proposals as `gbrain memory-proposals` does
+(text fenced, one request id per decision, `decided_by: admin-api`; an approve whose write did
+not commit reports `outcome: failed` and exits 1). They call `/admin/api/access/attest`,
+`/admin/api/access/members`, `/admin/api/access/member-links` and
+`/admin/api/memory-proposals`. 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
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 5e27fe6bb3..0208664475 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,5 +47,5 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/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 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)
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 1713 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7)
+src/core/behavior-change-notice.ts 1714 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2407 memory_propose PR 2: the memory_proposals_owner_http_gst2407 row (since is the current VERSION until the merge slot; rows are data and cannot move)
src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot move
diff --git a/src/commands/mcp-admin.ts b/src/commands/mcp-admin.ts
index 531f733c47..8a89f14b20 100644
--- a/src/commands/mcp-admin.ts
+++ b/src/commands/mcp-admin.ts
@@ -26,13 +26,19 @@ gbrain mcp admin links [--member ID]
gbrain mcp admin link MEMBER --qm CANONICAL_ID [--dry-run]
gbrain mcp admin link --email ADDR --qm CANONICAL_ID [--dry-run]
gbrain mcp admin unlink --qm CANONICAL_ID [--dry-run]
+gbrain mcp admin memory-proposals list [--source SOURCE] [--cursor CURSOR]
+gbrain mcp admin memory-proposals show REQUEST_ID
+gbrain mcp admin memory-proposals approve REQUEST_ID [--dry-run]
+gbrain mcp admin memory-proposals deny REQUEST_ID --reason TEXT [--dry-run]
--url URL Running server URL or /mcp endpoint (required)
--admin-token-file FILE Private owner credential; otherwise GBRAIN_ADMIN_BOOTSTRAP_TOKEN
--harness ID Setup instructions for this harness (default: generic)
--flow FLOW Required when an existing client supports both flows
--token-endpoint-auth-method METHOD none (default), client_secret_post, client_secret_basic
---source SOURCE New registration write source (default: default)
+--source SOURCE New registration write source (default: default); memory-proposals list: only this source
+--cursor CURSOR memory-proposals list: the next_cursor of the previous page (50 a page, oldest first)
+--reason TEXT memory-proposals deny: 1 to 500 characters the proposer reads on its receipt
--federated-read S1,S2 New registration read sources
--scopes SCOPES New registration scopes (default: read)
--profile PROFILE Apply a named access profile during registration
@@ -56,6 +62,7 @@ OAuth admin scope does not grant owner administration authority.
type Flow = 'authorization-code' | 'client-credentials';
interface AdminArgs {
command: string;
+ sub?: string;
target?: string;
values: Map<string, string[]>;
flags: Set<string>;
@@ -67,23 +74,30 @@ const commandValues: Record<string, string[]> = {
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', '--email'], 'member-set': ['--email'], 'member-disable': [], 'member-enable': [],
- links: ['--member'], link: ['--qm', '--email'], unlink: ['--qm'],
+ links: ['--member'], link: ['--qm', '--email'], unlink: ['--qm'], 'memory-proposals': [],
};
+/** GST-2407: memory-proposals takes a subcommand; show, approve and deny take exactly one request id. */
+const proposalValues: Record<string, string[]> = { list: ['--source', '--cursor'], show: [], approve: [], deny: ['--reason'] };
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 one of: ${Object.keys(commandValues).join(', ')}. Use mcp admin --help.`);
- const targeted = !untargeted.includes(command) && !(command === 'link' && args[1]?.startsWith('-'));
- const target = targeted ? args[1] : undefined;
- 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 proposals = command === 'memory-proposals';
+ const sub = proposals ? args[1] : undefined;
+ if (proposals && !Object.hasOwn(proposalValues, sub ?? '')) throw new McpAdminError('invalid_admin_command', 'memory-proposals takes list, show, approve or deny.');
+ const at = proposals ? 2 : 1;
+ const targeted = proposals ? sub !== 'list' : !untargeted.includes(command) && !(command === 'link' && args[1]?.startsWith('-'));
+ const target = targeted ? args[at] : undefined;
+ if (targeted && (!target || target.startsWith('-'))) throw new McpAdminError('missing_target', `${proposals ? `memory-proposals ${sub}` : command} requires ${proposals ? 'a request ID' : command === 'register' ? 'a name' : command.startsWith('member') || command === 'link' ? 'a member ID' : 'a client ID'}.`);
+ const allowedValues = new Set([...common, ...(proposals ? proposalValues[sub!]! : commandValues[command])]);
const lifecycle = ['invalidate-tokens', 'revoke', 'delete'].includes(command);
- const allowedFlags = new Set(['--json', ...(previewable.includes(command) ? ['--dry-run'] : []), ...(lifecycle ? ['--yes'] : []), ...(command === 'members' ? ['--all'] : [])]);
+ const preview = proposals ? sub === 'approve' || sub === 'deny' : previewable.includes(command);
+ const allowedFlags = new Set(['--json', ...(preview ? ['--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++) {
+ for (let i = targeted ? at + 1 : at; i < args.length; i++) {
const flag = args[i];
if (allowedFlags.has(flag)) {
if (flags.has(flag)) throw new McpAdminError('invalid_arguments', `Duplicate argument: ${flag}`);
@@ -98,7 +112,7 @@ export function parseMcpAdmin(args: string[]): AdminArgs {
if (!values.has('--url')) throw new McpAdminError('invalid_arguments', '--url is required. Point it at the existing running server.');
if (flags.has('--yes') && flags.has('--dry-run')) throw new McpAdminError('invalid_arguments', 'Choose --dry-run or --yes, not both.');
if (flags.has('--yes') && !values.has('--if-version')) throw new McpAdminError('revision_required', 'Preview the action first, then apply with --yes --if-version <reviewed-revision>.');
- return { command, target, values, flags };
+ return { command, ...(sub === undefined ? {} : { sub }), target, values, flags };
}
type AdminClient = ReturnType<typeof createMcpAdminHttp>;
@@ -128,6 +142,19 @@ const ACCESS_COMMANDS: Record<string, (client: AdminClient, parsed: AdminArgs, v
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'),
+ 'memory-proposals': (client, parsed, value) => {
+ if (parsed.sub === 'list') {
+ const query = new URLSearchParams({ ...(value('--source') === undefined ? {} : { source: value('--source')! }), ...(value('--cursor') === undefined ? {} : { cursor: value('--cursor')! }) });
+ return client.request(`/admin/api/memory-proposals${query.size ? `?${query}` : ''}`);
+ }
+ const path = `/admin/api/memory-proposals/${encodeURIComponent(parsed.target!)}`;
+ if (parsed.sub === 'show') return client.request(path);
+ const reason = value('--reason');
+ if (parsed.sub === 'deny' && reason === undefined) throw new McpAdminError('invalid_arguments', 'deny needs --reason TEXT: the proposer reads it on its receipt.');
+ const dryRun = parsed.flags.has('--dry-run');
+ return client.request(path, { method: 'POST', mutation: !dryRun, nextAction: `gbrain mcp admin memory-proposals show ${parsed.target} --url ${client.base}`,
+ body: { action: parsed.sub, dryRun, ...(reason === undefined ? {} : { reason }) } });
+ },
};
function linkRequest(client: AdminClient, parsed: AdminArgs, value: (flag: string) => string | undefined, action: 'link' | 'unlink'): Promise<unknown> {
@@ -171,7 +198,7 @@ export async function runMcpAdmin(args: string[], dependencies: Pick<McpAdminHtt
if (!args.length || args.includes('--help') || args.includes('-h')) { console.log(HELP); return; }
const parsed = parseMcpAdmin(args);
stage = parsed.command;
- if (!['register', 'link'].includes(parsed.command) && !parsed.command.startsWith('member')) clientId = parsed.target;
+ if (!['register', 'link', 'memory-proposals'].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)));
@@ -193,7 +220,9 @@ export async function runMcpAdmin(args: string[], dependencies: Pick<McpAdminHtt
return;
}
if (parsed.command in ACCESS_COMMANDS) {
- print(await ACCESS_COMMANDS[parsed.command]!(client, parsed, value));
+ const result = await ACCESS_COMMANDS[parsed.command]!(client, parsed, value);
+ print(result);
+ if (parsed.sub === 'approve' && (result as { outcome?: string }).outcome === 'failed') setCliExitVerdict(1);
return;
}
if (parsed.command === 'register') {
diff --git a/src/commands/memory-proposals.ts b/src/commands/memory-proposals.ts
index 189e7fda8e..e44b85761a 100644
--- a/src/commands/memory-proposals.ts
+++ b/src/commands/memory-proposals.ts
@@ -1,6 +1,7 @@
/**
* `gbrain memory-proposals` (GST-1158, GBRA-284): the brain owner's review of QM's proposed timeline entries and
- * links (memory_propose). Trusted local CLI only; never an MCP operation.
+ * links (memory_propose). Trusted local CLI; the owner session reaches the same library calls over HTTP
+ * (serve-http-access.ts, gbrain mcp admin memory-proposals). Never an MCP operation.
*
* gbrain memory-proposals list [--source <id>] [--all] [--limit N] [--json]
* gbrain memory-proposals show <request_id> [--json]
@@ -52,6 +53,12 @@ function line(view: Record<string, any>): string {
return `${view.request_id} [${view.state}] ${view.kind} on ${view.source_id}:${view.target} for member:${view.member_id}\n ${what}`;
}
+/** The owner's trusted context for approve and deny, shared by this command and the owner HTTP routes (serve-http-access.ts). */
+export async function ownerContext(engine: BrainEngine, dryRun: boolean): Promise<OperationContext> {
+ const { loadConfig } = await import('../core/config.ts');
+ return { engine, config: loadConfig() ?? { engine: engine.kind }, remote: false, dryRun, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+}
+
async function decidedBy(engine: BrainEngine): Promise<string> {
try { return `cli:${(await (await import('../core/persistence/identity.ts')).readLocalWriter(engine, 'cli')).id}`; } catch { return 'cli'; }
}
@@ -86,13 +93,12 @@ export async function runMemoryProposals(engine: BrainEngine, args: string[]): P
out(view, `${line(view)}\n${JSON.stringify(view.payload, null, 2)}`);
return;
}
- const { loadConfig } = await import('../core/config.ts');
- const ctx = { engine, config: loadConfig() ?? { engine: engine.kind }, remote: false, dryRun, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ const ctx = await ownerContext(engine, dryRun);
if (sub === 'approve') {
const result = await lib.approveMemoryProposal(ctx, id, { decidedBy: await decidedBy(engine) });
out(result, result.dry_run ? `${id}: would be ${result.would}${result.error_code ? ` (${result.error_code}: ${result.reason})` : ''}`
: `${id}: ${result.status}${result.error_code ? ` (${result.error_code}: ${result.reason})` : ''}${(result.write_request as { state?: string } | undefined)?.state ? `; write ${(result.write_request as { state: string }).state}` : ''}`);
- if (!result.dry_run && result.status !== 'approved') setCliExitVerdict(1);
+ if (lib.approveFailed(result)) setCliExitVerdict(1);
return;
}
if (sub === 'deny') {
diff --git a/src/commands/serve-http-access.ts b/src/commands/serve-http-access.ts
index 2f4f124c24..730c53cde2 100644
--- a/src/commands/serve-http-access.ts
+++ b/src/commands/serve-http-access.ts
@@ -84,11 +84,65 @@ export function mountAdminAccess(app: Express, requireAdmin: RequestHandler, eng
});
}
+const PROPOSAL_PAGE = 50;
+const PROPOSAL_DECISION_FIELDS = ['action', 'reason', 'dryRun'];
+
+/**
+ * GST-2407: the owner's review of memory proposals (memory_propose) over the running server, the remote twin of
+ * gbrain memory-proposals list|show|approve|deny. Approve and deny run the command's own library calls (one transaction,
+ * the stored actor and page revision re-checked, publication through the writer door) with decided_by admin-api. The
+ * proposed text is shown only inside the transcript fence, each decision names exactly one request id, and each
+ * applied decision leaves one audit row that never carries the proposed text.
+ */
+export function mountAdminMemoryProposals(app: Express, requireAdmin: RequestHandler, engine: BrainEngine): void {
+ app.get('/admin/api/memory-proposals', requireAdmin, async (req, res) => {
+ const sourceId = typeof req.query.source === 'string' && req.query.source ? req.query.source : undefined;
+ const after = typeof req.query.cursor === 'string' && req.query.cursor ? req.query.cursor : undefined;
+ await answer(res, false, async () => {
+ const { listMemoryProposals, proposalCursor } = await import('../core/persistence/memory-proposals.ts');
+ const { ownerView } = await import('./memory-proposals.ts');
+ const rows = await listMemoryProposals(engine, { sourceId, after, limit: PROPOSAL_PAGE });
+ return { proposals: await Promise.all(rows.map(ownerView)), next_cursor: rows.length === PROPOSAL_PAGE ? proposalCursor(rows.at(-1)!) : null };
+ });
+ });
+
+ app.get('/admin/api/memory-proposals/:request_id', requireAdmin, async (req, res) => {
+ await answer(res, false, async () => {
+ const { ownerProposal } = await import('../core/persistence/memory-proposals.ts');
+ const { ownerView } = await import('./memory-proposals.ts');
+ return ownerView(await ownerProposal(engine, String(req.params.request_id)));
+ });
+ });
+
+ app.post('/admin/api/memory-proposals/:request_id', requireAdmin, express.json(), async (req, res) => {
+ const body = req.body ?? {};
+ const { action, reason, dryRun } = body;
+ if (action !== 'approve' && action !== 'deny') return refuse(res, 'action must be approve or deny.');
+ const unknown = Object.keys(body).find(key => !PROPOSAL_DECISION_FIELDS.includes(key));
+ if (unknown !== undefined) return refuse(res, `Unknown field ${unknown}: a decision takes action, reason and dryRun, for the one request id in the path.`);
+ if (dryRun !== undefined && typeof dryRun !== 'boolean') return refuse(res, 'dryRun must be a boolean.');
+ if (action === 'approve' && reason !== undefined) return refuse(res, 'reason goes with deny; approve takes none.');
+ if (action === 'deny' && typeof reason !== 'string') return refuse(res, 'deny needs reason: 1 to 500 characters the proposer reads on its receipt.');
+ await answer(res, dryRun !== true, async () => {
+ const lib = await import('../core/persistence/memory-proposals.ts');
+ const { ownerContext } = await import('./memory-proposals.ts');
+ const row = await lib.ownerProposal(engine, String(req.params.request_id));
+ const ctx = await ownerContext(engine, dryRun === true);
+ const result = action === 'approve'
+ ? await lib.approveMemoryProposal(ctx, row.request_id, { decidedBy: 'admin-api' })
+ : await lib.denyMemoryProposal(ctx, row.request_id, reason, { decidedBy: 'admin-api' });
+ const applied = dryRun !== true && row.state === 'awaiting_owner';
+ if (applied) await audit(engine, `proposal_${action}`, { request_id: row.request_id, kind: row.kind, slug: row.slug, member: row.member_id, state: result.status });
+ return { applied, ...result, ...(action === 'approve' && lib.approveFailed(result) ? { outcome: 'failed' } : {}) };
+ }, 'Show the proposal (GET /admin/api/memory-proposals/<request_id>)');
+ });
+}
+
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> {
+async function answer(res: Response, mutation: boolean, run: () => Promise<Record<string, unknown>>, inspect = 'List the members, links or client'): Promise<void> {
res.set('Cache-Control', 'no-store');
try {
res.json(await run());
@@ -98,7 +152,7 @@ async function answer(res: Response, mutation: boolean, run: () => Promise<Recor
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.' });
+ message: mutation ? `The change outcome is unknown. ${inspect} before another change.` : 'Administration is temporarily unavailable. Retry the read.' });
}
}
diff --git a/src/commands/serve-http-admin-api.ts b/src/commands/serve-http-admin-api.ts
index 2b43f31588..84dd7b2539 100644
--- a/src/commands/serve-http-admin-api.ts
+++ b/src/commands/serve-http-admin-api.ts
@@ -17,7 +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 { mountAdminAccess, mountAdminMemoryProposals } from './serve-http-access.ts';
import { probeHealth } from './serve-http-metrics.ts';
import type { ServeHttpContext } from './serve-http.ts';
@@ -612,6 +612,7 @@ function mountAdminClientApi(app: Express, ctx: ServeHttpContext): void {
mountAdminGrantEdits(app, requireAdmin, engine, oauthProvider);
mountAdminAccess(app, requireAdmin, engine);
+ mountAdminMemoryProposals(app, requireAdmin, engine);
// Revoke OAuth client
app.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.ts
index 977f74bb21..4a28e7f817 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1515,6 +1515,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.655.0', id: 'memory_propose_held_writes_gst1158', text: 'New attested operation `memory_propose` (add it to `--attest-ops`): QM proposes one timeline entry or link on a shared page for the person it serves, and nothing is written until the brain owner runs `gbrain memory-proposals approve <request_id>` (`list`, `show`, `deny --reason`). `get_write_request` and `cancel_write_request` read and withdraw the proposal; an approved one becomes an ordinary write under the same request id. Held text stays in the `memory_proposals` table, out of git, export, search and recall. Proposals expire after `proposals.ttl_hours` (168), at most 10 wait per person and 50 per credential, and closed ones are deleted after `proposals.retention_days` (30). `gbrain doctor` (`memory_proposals_pending`) and `gbrain status` show the queue.' },
{ since: '0.60.655.0', id: 'member_email_link_gst1158', text: 'A member can carry an operator-declared email: `gbrain access member add <id> --email <addr>` or `gbrain access member set <id> --email <addr>|none`, shown by `member list`, stored lower-case and unique per brain, and cleared when the member is removed. `gbrain access member link --email <addr> --qm <id>` (and `gbrain mcp admin link --email`, `member-add --email`, `member-set` over the owner session) links the one member that declares it, exactly as linking by member id does; an unknown email is `not_found` and creates nothing. No OAuth token, attested call or MCP tool can set an email or make a link.' },
{ since: '0.60.655.0', 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.' },
+ { since: '0.60.655.0', id: 'memory_proposals_owner_http_gst2407', text: 'The brain owner can review QM\'s memory proposals over the running server, not only on the brain host: owner-session routes `GET /admin/api/memory-proposals` (`?source=`, `?cursor=`; oldest first, 50 a page), `GET /admin/api/memory-proposals/<request_id>` and `POST /admin/api/memory-proposals/<request_id>` with `{action: "approve"|"deny", reason?, dryRun?}`, mirrored by `gbrain mcp admin memory-proposals list|show|approve|deny`. They run the same approval as `gbrain memory-proposals` and record `decided_by: admin-api`; each applied decision writes one `access_admin` audit row (never the proposed text), and a change that fails partway answers `outcome: unknown`. `gbrain memory-proposals approve` now exits 1 when the approved write itself ends without committing (it used to exit 0), and the HTTP approve reports `outcome: failed` with the write\'s receipt.' },
];
/** 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.ts
index 60b0a93bb9..665ad796ad 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -86,7 +86,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': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--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', '--ignore-missing', '--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', '--local', '--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', '--no-walk', '--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', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--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', '--skill-loading', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--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', '--email', '--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'],
+ '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', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--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', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'],
'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'],
diff --git a/src/core/persistence/memory-proposals.ts b/src/core/persistence/memory-proposals.ts
index 319de3698c..2d981a88cc 100644
--- a/src/core/persistence/memory-proposals.ts
+++ b/src/core/persistence/memory-proposals.ts
@@ -350,12 +350,37 @@ export async function denyMemoryProposal(ctx: OperationContext, requestId: strin
return { status: 'denied', request_id: row.request_id, reason, decided_at: after.decided_at };
}
-/** The owner's list: oldest first, 50 a page, after the upkeep pass. */
-export async function listMemoryProposals(engine: BrainEngine, opts: { sourceId?: string; all?: boolean; limit?: number } = {}): Promise<MemoryProposal[]> {
+/** An approve that did not publish: the checks closed the proposal, or the approved write ended without committing. */
+export function approveFailed(result: Record<string, unknown>): boolean {
+ if (result.dry_run) return false;
+ if (result.status !== 'approved') return true;
+ const state = (result.write_request as { state?: string } | undefined)?.state;
+ return state === 'conflict' || state === 'failed' || state === 'cancelled';
+}
+
+/** The opaque page cursor after a listed proposal: its creation time (to the millisecond the list orders by) and request id. */
+export function proposalCursor(row: Pick<MemoryProposal, 'created_at' | 'request_id'>): string {
+ return Buffer.from(JSON.stringify([row.created_at, row.request_id])).toString('base64url');
+}
+
+function parseProposalCursor(cursor: string): [string, string] {
+ let at: unknown, id: unknown;
+ try { [at, id] = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')); } catch { /* refused below */ }
+ if (typeof at !== 'string' || !Number.isFinite(Date.parse(at)) || typeof id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
+ throw opError('invalid_params', 'The cursor is not one this list returned.', 'Pass next_cursor from the previous page, or omit it for the first page.');
+ }
+ return [at, id];
+}
+
+/** The owner's list: oldest first, 50 a page, after the upkeep pass; `after` is the previous page's proposalCursor. */
+export async function listMemoryProposals(engine: BrainEngine, opts: { sourceId?: string; all?: boolean; limit?: number; after?: string } = {}): Promise<MemoryProposal[]> {
+ const [afterAt, afterId] = opts.after === undefined ? [null, null] : parseProposalCursor(opts.after);
await runMemoryProposalUpkeep(engine);
const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT * FROM memory_proposals WHERE ($1::text IS NULL OR source_id=$1)
- AND ($2::boolean OR state='awaiting_owner') ORDER BY created_at, request_id LIMIT $3`,
- [opts.sourceId ?? null, opts.all === true, Math.max(1, Math.min(500, opts.limit ?? 50))]);
+ AND ($2::boolean OR state='awaiting_owner')
+ AND ($4::timestamptz IS NULL OR (date_trunc('milliseconds', created_at), request_id) > ($4::timestamptz, $5::uuid))
+ ORDER BY date_trunc('milliseconds', created_at), request_id LIMIT $3`,
+ [opts.sourceId ?? null, opts.all === true, Math.max(1, Math.min(500, opts.limit ?? 50)), afterAt, afterId]);
return rows.map(normalize);
}
diff --git a/test/fixtures/goldens/serve-http/routes-runtime.json b/test/fixtures/goldens/serve-http/routes-runtime.json
index ee3b3e94e3..4289d6e949 100644
--- a/test/fixtures/goldens/serve-http/routes-runtime.json
+++ b/test/fixtures/goldens/serve-http/routes-runtime.json
@@ -660,6 +660,31 @@
"method": "post",
"path": "/admin/api/access/attest"
},
+ {
+ "handlers": [
+ "requireAdmin#4",
+ "<anonymous>"
+ ],
+ "method": "get",
+ "path": "/admin/api/memory-proposals"
+ },
+ {
+ "handlers": [
+ "requireAdmin#4",
+ "<anonymous>"
+ ],
+ "method": "get",
+ "path": "/admin/api/memory-proposals/:request_id"
+ },
+ {
+ "handlers": [
+ "requireAdmin#4",
+ "jsonParser",
+ "<anonymous>"
+ ],
+ "method": "post",
+ "path": "/admin/api/memory-proposals/:request_id"
+ },
{
"handlers": [
"requireAdmin#4",
@@ -1429,6 +1454,31 @@
"method": "post",
"path": "/admin/api/access/attest"
},
+ {
+ "handlers": [
+ "requireAdmin#4",
+ "<anonymous>"
+ ],
+ "method": "get",
+ "path": "/admin/api/memory-proposals"
+ },
+ {
+ "handlers": [
+ "requireAdmin#4",
+ "<anonymous>"
+ ],
+ "method": "get",
+ "path": "/admin/api/memory-proposals/:request_id"
+ },
+ {
+ "handlers": [
+ "requireAdmin#4",
+ "jsonParser",
+ "<anonymous>"
+ ],
+ "method": "post",
+ "path": "/admin/api/memory-proposals/:request_id"
+ },
{
"handlers": [
"requireAdmin#4",
diff --git a/test/fixtures/goldens/serve-http/routes.json b/test/fixtures/goldens/serve-http/routes.json
index b973922b03..d17547ee83 100644
--- a/test/fixtures/goldens/serve-http/routes.json
+++ b/test/fixtures/goldens/serve-http/routes.json
@@ -502,6 +502,34 @@
"path": "/admin/api/access/attest",
"when": []
},
+ {
+ "handlers": [
+ "requireAdmin",
+ "<inline>"
+ ],
+ "method": "get",
+ "path": "/admin/api/memory-proposals",
+ "when": []
+ },
+ {
+ "handlers": [
+ "requireAdmin",
+ "<inline>"
+ ],
+ "method": "get",
+ "path": "/admin/api/memory-proposals/:request_id",
+ "when": []
+ },
+ {
+ "handlers": [
+ "requireAdmin",
+ "express.json()",
+ "<inline>"
+ ],
+ "method": "post",
+ "path": "/admin/api/memory-proposals/:request_id",
+ "when": []
+ },
{
"handlers": [
"requireAdmin",
diff --git a/test/mcp-admin-cli.serial.test.ts b/test/mcp-admin-cli.serial.test.ts
index 453d88559a..5fa803dd96 100644
--- a/test/mcp-admin-cli.serial.test.ts
+++ b/test/mcp-admin-cli.serial.test.ts
@@ -228,3 +228,49 @@ test('GST-1158: member-add and member-set send a declared email, and link finds
expect(notFound.result.status).toBe('error');
expect(notFound.exitCode).toBe(1);
});
+
+test('GST-2407: memory-proposals list, show, approve and deny mirror the owner proposal routes, one request id per decision', async () => {
+ const id = '0f8e2a1c-7b3d-5e9f-8a4b-6c2d1e0f9a8b';
+ const cases: Array<[string[], string, unknown]> = [
+ [['memory-proposals', 'list'], '/admin/api/memory-proposals', undefined],
+ [['memory-proposals', 'list', '--source', 'source-a', '--cursor', 'abc_-'], '/admin/api/memory-proposals?source=source-a&cursor=abc_-', undefined],
+ [['memory-proposals', 'show', id], '/admin/api/memory-proposals/' + id, undefined],
+ [['memory-proposals', 'approve', id, '--dry-run'], '/admin/api/memory-proposals/' + id, { action: 'approve', dryRun: true }],
+ [['memory-proposals', 'approve', id], '/admin/api/memory-proposals/' + id, { action: 'approve', dryRun: false }],
+ [['memory-proposals', 'deny', id, '--reason', 'Not confirmed'], '/admin/api/memory-proposals/' + id, { action: 'deny', dryRun: false, reason: 'Not confirmed' }],
+ ];
+ for (const [args, path, body] of cases) {
+ expect(mcpNeedsEngine(['admin', ...args], 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.method).toBe(body === undefined ? 'GET' : 'POST');
+ expect(sent.init.body === undefined ? undefined : JSON.parse(String(sent.init.body))).toEqual(body);
+ expect(run.output).not.toContain(owner);
+ }
+ for (const args of [['memory-proposals'], ['memory-proposals', 'remove', id], ['memory-proposals', 'approve'], ['memory-proposals', 'approve', id, id],
+ ['memory-proposals', 'approve', id, '--reason', 'because'], ['memory-proposals', 'deny', id], ['memory-proposals', 'list', '--dry-run'], ['memory-proposals', 'show', id, '--source', 'source-a']]) {
+ _resetCliExitVerdictForTests();
+ const refused = await capture(args, () => Response.json({}));
+ expect(refused.result).toMatchObject({ status: 'error' });
+ expect(['invalid_arguments', 'invalid_admin_command', 'missing_target']).toContain(refused.result.reason);
+ expect(refused.requests.filter(r => !r.url.endsWith('/admin/login'))).toEqual([]);
+ expect(refused.exitCode).toBe(1);
+ }
+ _resetCliExitVerdictForTests();
+ const writeFailed = await capture(['memory-proposals', 'approve', id], () => Response.json({ applied: true, status: 'approved', request_id: id, write_request: { state: 'failed', write_error: 'actor_unlinked' }, outcome: 'failed' }));
+ expect(writeFailed.result).toMatchObject({ status: 'approved', outcome: 'failed', write_request: { state: 'failed' } });
+ expect(writeFailed.exitCode).toBe(1);
+ _resetCliExitVerdictForTests();
+ const closed = await capture(['memory-proposals', 'approve', id], () => Response.json({ error: 'proposal_closed', code: 'proposal_closed', message: 'Proposal is denied.', outcome: 'failed' }, { status: 400 }));
+ expect(closed.result).toMatchObject({ status: 'error', reason: 'proposal_closed', outcome: 'failed' });
+ expect(closed.exitCode).toBe(1);
+ _resetCliExitVerdictForTests();
+ const unknown = await capture(['memory-proposals', 'deny', id, '--reason', 'no'], () => Response.json({ error: 'administration_unavailable', code: 'administration_unavailable', message: 'The change outcome is unknown.', outcome: 'unknown' }, { status: 503 }));
+ expect(unknown.result).toMatchObject({ status: 'error', outcome: 'unknown', next_action: 'gbrain mcp admin memory-proposals show ' + id + ' --url ' + base });
+ expect(unknown.exitCode).toBe(1);
+ _resetCliExitVerdictForTests();
+ const preview = await capture(['memory-proposals', 'approve', id, '--dry-run'], () => Response.json({ applied: false, dry_run: true, would: 'failed', error_code: 'actor_unlinked' }));
+ expect(preview.exitCode).toBe(0);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 536e064e93..65198be519 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -537,6 +537,7 @@ test/search/rerank-gate-telemetry.test.ts
test/segmented-untiled-hold-gst1209.test.ts
test/serve-head-watcher-managed.serial.test.ts
test/serve-http-access.test.ts
+test/serve-http-memory-proposals.test.ts
test/shared-content-freshness.test.ts
test/shared-skills-catalog.test.ts
test/shared-skills-retention-capacity.test.ts
diff --git a/test/serve-http-memory-proposals.test.ts b/test/serve-http-memory-proposals.test.ts
new file mode 100644
index 0000000000..50f0aed048
--- /dev/null
+++ b/test/serve-http-memory-proposals.test.ts
@@ -0,0 +1,281 @@
+/**
+ * GST-2407 (memory_propose test 21): the brain owner's review of memory proposals over the running server
+ * (serve-http-access.ts mountAdminMemoryProposals) and the local command's exit code.
+ *
+ * 1. Protects: only an owner session lists, shows, approves or denies a proposal remotely; approve and deny run the
+ * command's own library path with decided_by admin-api (the command keeps cli:<writer>); a dry run changes nothing
+ * and leaves no audit row; each applied decision leaves exactly one access_admin audit row that never carries the
+ * proposed text; list and show give the proposed text only inside the transcript fence; a decision names exactly one
+ * request id; deny needs a reason; a closed proposal answers proposal_closed; a change that fails partway answers
+ * outcome unknown; an approve whose write did not commit says so (HTTP outcome failed, the command exits 1).
+ * 2. Fails when: a route answers without the owner session, a preview writes or audits, an audit row is missing,
+ * duplicated or carries the proposed text, the text leaves the fence, a body names several ids, a reasonless deny
+ * lands, a failed write reads as success, or a partial failure reads as failed instead of unknown.
+ * 3. Real seams: the routes mounted on an Express app over a real socket with the real requireAdmin; proposals made by
+ * an attested OAuth client-credentials token through MCP dispatch; publication through the persistence consumer;
+ * 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 { importFromContent } from '../src/core/import-file.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { linkMember } from '../src/core/access/actor.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { mountAdminAccess, mountAdminMemoryProposals } from '../src/commands/serve-http-access.ts';
+import { createRequireAdmin } from '../src/commands/serve-http-admin-api.ts';
+import { runMemoryProposals } from '../src/commands/memory-proposals.ts';
+import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const SRC = 'source-a';
+const ACME = 'companies/acme-example';
+const ALICE_ID = 'U0ALICE';
+const BOB_ID = 'U0BOB';
+const FENCE = String.fromCharCode(96).repeat(3);
+const ATTEST_OPS = ['cancel_write_request', 'get_write_request', 'memory_propose', 'memory_recall', 'memory_write'];
+const pageText = (title: string) => ['---', 'type: company', 'title: ' + title, '---', '# ' + title, '', 'Harbor ledger notes.'].join('\n');
+
+for (const kind of testBackends()) {
+ describe('owner HTTP review of memory proposals (' + kind + ', repo-less)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let server: Server;
+ let base = '';
+ let token = '';
+ const sessions = new Map<string, number>();
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+
+ 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) }) });
+ const text = await res.text();
+ let json: Record<string, any> = {};
+ try { json = JSON.parse(text); } catch { /* not JSON */ }
+ return { status: res.status, json, text };
+ }
+ async function propose(actor: string, summary: string): Promise<string> {
+ const out = await dispatchToolCall(engine, 'memory_propose', { idempotency_key: randomUUID(), kind: 'timeline', target: ACME, date: '2026-10-30', summary, source: 'slack:C0123/p1' }, {
+ remote: true, transport: 'http', auth: await provider().verifyAccessToken(token) as unknown as AuthInfo, sourceId: SRC, takesHoldersAllowList: ['world'], actor: { header: actor } });
+ expect(out.isError).not.toBe(true);
+ return (out.structuredContent as Record<string, any>).request_id as string;
+ }
+ const proposalRow = async (id: string) => (await engine.executeRaw<Record<string, any>>('SELECT * FROM memory_proposals WHERE request_id = $1::uuid', [id]))[0]!;
+ const journalRows = async (id: string) => engine.executeRaw<Record<string, any>>('SELECT state, error_code FROM persistence_requests WHERE request_id = $1::uuid', [id]);
+ 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) as Array<Record<string, unknown>>;
+ const proposalAudits = async () => (await audits()).filter(a => String(a.action).startsWith('proposal_'));
+ /** Runs inject inside the approval's own transaction (the one that admits the write), once, then restores the engine. */
+ function onApprovalTransaction(inject: (tx: BrainEngine) => Promise<void>): () => void {
+ const original = engine.transaction;
+ const restore = () => { engine.transaction = original; };
+ engine.transaction = (async (fn: (tx: BrainEngine) => Promise<unknown>) => original.call(engine, async (tx: BrainEngine) => {
+ const out = await fn(tx);
+ if (out && typeof out === 'object' && 'written' in out) { restore(); await inject(tx); }
+ return out;
+ })) as typeof engine.transaction;
+ return restore;
+ }
+ const unlinkInside = (externalId: string) => (tx: BrainEngine) => tx.executeRaw("DELETE FROM access_member_links WHERE system = 'qm' AND external_id = $1", [externalId]).then(() => undefined);
+ async function cli(args: string[]) {
+ const lines: string[] = [];
+ const log = console.log, err = console.error;
+ console.log = (...a: unknown[]) => { lines.push(a.join(' ')); };
+ console.error = (...a: unknown[]) => { lines.push(a.join(' ')); };
+ try { await runMemoryProposals(engine, args); return { out: lines.join('\n'), exit: currentExitCode() }; }
+ finally { console.log = log; console.error = err; setCliExitVerdict(0); }
+ }
+
+ 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(); }
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
+ await importFromContent(engine, ACME, pageText('Acme Example'), { sourceId: SRC });
+ for (const id of ['alice-example', 'bob-example']) await addMember(engine, id);
+ const qm = await provider().registerClientManual('p-qm-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);
+ await bindCredential(engine, { kind: 'client', id: qm.clientId }, { attestActor: 'qm', attestOps: ATTEST_OPS });
+ token = (await provider().exchangeClientCredentials(qm.clientId, qm.clientSecret ?? '')).access_token;
+ await linkMember(engine, 'alice-example', 'qm', ALICE_ID);
+ await linkMember(engine, 'bob-example', 'qm', BOB_ID);
+ sessions.set('owner-session', Date.now() + 3_600_000);
+ const app = express();
+ app.use(cookieParser());
+ const requireAdmin = createRequireAdmin(sessions);
+ mountAdminAccess(app, requireAdmin, engine);
+ mountAdminMemoryProposals(app, requireAdmin, 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 disposePersistenceConsumer(engine).catch(() => undefined);
+ await close?.();
+ });
+
+ test('requireAdmin: every route refuses a request without the owner session and changes nothing', async () => {
+ const id = await propose(ALICE_ID, 'Unauthorized canaryunauth');
+ for (const [method, path, body] of [['GET', '/admin/api/memory-proposals'], ['GET', '/admin/api/memory-proposals/' + id],
+ ['POST', '/admin/api/memory-proposals/' + id, { action: 'approve' }], ['POST', '/admin/api/memory-proposals/' + id, { action: 'deny', reason: 'no' }]] as const) {
+ const res = await call(method, path, body, false);
+ expect(res.status).toBe(401);
+ expect(res.text).not.toContain('canaryunauth');
+ }
+ expect((await proposalRow(id)).state).toBe('awaiting_owner');
+ expect(await journalRows(id)).toEqual([]);
+ expect(await proposalAudits()).toEqual([]);
+ await call('POST', '/admin/api/memory-proposals/' + id, { action: 'deny', reason: 'cleanup' });
+ }, 60_000);
+
+ test('list and show give the proposed text only inside the transcript fence; list pages oldest first by cursor', async () => {
+ const id = await propose(BOB_ID, 'Owner view canaryhttpview');
+ const shown = await call('GET', '/admin/api/memory-proposals/' + id);
+ expect(shown.status).toBe(200);
+ expect(shown.json).toMatchObject({ request_id: id, state: 'awaiting_owner', kind: 'timeline', target: ACME, member_id: 'bob-example', quoted: 'transcript' });
+ expect(shown.json.payload.summary).toContain('canaryhttpview');
+ expect(shown.json.payload.summary).not.toBe('Owner view canaryhttpview');
+ expect(shown.json.payload.summary).toContain(FENCE);
+ const listed = await call('GET', '/admin/api/memory-proposals?source=' + SRC);
+ const mine = listed.json.proposals.find((p: { request_id: string }) => p.request_id === id);
+ expect(mine).toMatchObject({ quoted: 'transcript' });
+ expect(mine.payload.summary).toEqual(shown.json.payload.summary);
+ expect(listed.json.next_cursor).toBeNull();
+ expect((await call('GET', '/admin/api/memory-proposals?source=source-b')).json).toEqual({ proposals: [], next_cursor: null });
+ expect((await call('GET', '/admin/api/memory-proposals?cursor=not-a-cursor')).json).toMatchObject({ code: 'invalid_params', outcome: 'failed' });
+ expect((await call('GET', '/admin/api/memory-proposals/' + randomUUID())).json).toMatchObject({ code: 'not_found' });
+
+ await engine.setConfig('proposals.max_pending_per_actor', '100');
+ await engine.setConfig('proposals.max_pending_per_credential', '100');
+ try {
+ const made = [id];
+ for (let i = 0; i < 51; i++) made.push(await propose(ALICE_ID, 'Paging canarypage ' + i));
+ const first = await call('GET', '/admin/api/memory-proposals');
+ expect(first.json.proposals).toHaveLength(50);
+ expect(typeof first.json.next_cursor).toBe('string');
+ const second = await call('GET', '/admin/api/memory-proposals?cursor=' + encodeURIComponent(first.json.next_cursor));
+ const pages = [...first.json.proposals, ...second.json.proposals];
+ const seen = pages.map((p: { request_id: string }) => p.request_id);
+ expect(second.json.next_cursor).toBeNull();
+ expect(new Set(seen).size).toBe(seen.length);
+ expect([...seen].sort()).toEqual([...made].sort());
+ const created = pages.map((p: { created_at: string }) => Date.parse(p.created_at));
+ expect(created).toEqual([...created].sort((a, b) => a - b));
+ for (const p of made) await call('POST', '/admin/api/memory-proposals/' + p, { action: 'deny', reason: 'paging cleanup' });
+ } finally {
+ await engine.executeRaw("DELETE FROM config WHERE key IN ('proposals.max_pending_per_actor', 'proposals.max_pending_per_credential')");
+ }
+ }, 180_000);
+
+ test('dryRun changes nothing and writes no audit row; approve and deny apply with decided_by admin-api and exactly one audit row each, never the text', async () => {
+ const before = (await proposalAudits()).length;
+ const a = await propose(ALICE_ID, 'Approve me canaryhttpapprove');
+ const d = await propose(BOB_ID, 'Deny me canaryhttpdeny');
+ const previewApprove = await call('POST', '/admin/api/memory-proposals/' + a, { action: 'approve', dryRun: true });
+ expect(previewApprove.json).toMatchObject({ applied: false, dry_run: true, would: 'approved' });
+ const previewDeny = await call('POST', '/admin/api/memory-proposals/' + d, { action: 'deny', reason: 'Not now', dryRun: true });
+ expect(previewDeny.json).toMatchObject({ applied: false, dry_run: true, would: 'denied' });
+ for (const id of [a, d]) expect(await proposalRow(id)).toMatchObject({ state: 'awaiting_owner', decided_by: null });
+ expect(await journalRows(a)).toEqual([]);
+ expect((await proposalAudits()).length).toBe(before);
+
+ const approved = await call('POST', '/admin/api/memory-proposals/' + a, { action: 'approve' });
+ expect(approved.status).toBe(200);
+ expect(approved.json).toMatchObject({ applied: true, status: 'approved', request_id: a, write_request: { state: 'committed' } });
+ expect(approved.json.outcome).toBeUndefined();
+ expect((await proposalRow(a)).decided_by).toBe('admin-api');
+ const denied = await call('POST', '/admin/api/memory-proposals/' + d, { action: 'deny', reason: 'Not confirmed' });
+ expect(denied.json).toMatchObject({ applied: true, status: 'denied', reason: 'Not confirmed' });
+ expect(await proposalRow(d)).toMatchObject({ state: 'denied', reason: 'Not confirmed', decided_by: 'admin-api' });
+
+ const again = await call('POST', '/admin/api/memory-proposals/' + a, { action: 'approve' });
+ expect(again.json).toMatchObject({ applied: false, status: 'approved', write_request: { state: 'committed' } });
+ expect(await journalRows(a)).toHaveLength(1);
+ const closed = await call('POST', '/admin/api/memory-proposals/' + d, { action: 'approve' });
+ expect(closed.status).toBe(400);
+ expect(closed.json).toMatchObject({ code: 'proposal_closed', outcome: 'failed' });
+
+ expect((await proposalAudits()).slice(before)).toEqual([
+ { actor: 'admin-api', action: 'proposal_approve', request_id: a, kind: 'timeline', slug: ACME, member: 'alice-example', state: 'approved' },
+ { actor: 'admin-api', action: 'proposal_deny', request_id: d, kind: 'timeline', slug: ACME, member: 'bob-example', state: 'denied' },
+ ]);
+ const everything = JSON.stringify(await audits());
+ for (const needle of ['canaryhttpapprove', 'canaryhttpdeny', 'slack:C0123', ALICE_ID, BOB_ID, 'Not confirmed']) expect(everything).not.toContain(needle);
+ }, 90_000);
+
+ test('decided_by from the command is cli:<writer>; deny needs a 1-500 character reason; one request id per decision', async () => {
+ const viaCli = await propose(ALICE_ID, 'Command approve canaryclidecided');
+ expect((await cli(['approve', viaCli])).exit).toBe(0);
+ expect(await proposalRow(viaCli)).toMatchObject({ state: 'approved' });
+ expect(String((await proposalRow(viaCli)).decided_by)).toMatch(/^cli/);
+
+ const before = (await proposalAudits()).length;
+ const id = await propose(BOB_ID, 'Reasonless canaryreason');
+ const other = await propose(BOB_ID, 'Bulk canarybulk');
+ expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'deny' })).json).toMatchObject({ code: 'invalid_params', outcome: 'failed' });
+ expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'deny', reason: ' ' })).json).toMatchObject({ code: 'invalid_params' });
+ expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'deny', reason: 'x'.repeat(501) })).json).toMatchObject({ code: 'invalid_params' });
+ expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'approve', reason: 'because' })).json).toMatchObject({ code: 'invalid_params' });
+ expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'remove' })).json).toMatchObject({ code: 'invalid_params' });
+ expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'approve', dryRun: 'yes' })).json).toMatchObject({ code: 'invalid_params' });
+ expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'approve', request_ids: [id, other] })).json).toMatchObject({ code: 'invalid_params' });
+ expect((await call('POST', '/admin/api/memory-proposals/' + id + ',' + other, { action: 'approve' })).json).toMatchObject({ code: 'not_found' });
+ expect((await call('POST', '/admin/api/memory-proposals', { action: 'approve', request_id: id })).status).toBe(404);
+ for (const p of [id, other]) expect(await proposalRow(p)).toMatchObject({ state: 'awaiting_owner', decided_by: null });
+ expect(await journalRows(id)).toEqual([]);
+ expect((await proposalAudits()).length).toBe(before);
+ for (const p of [id, other]) await call('POST', '/admin/api/memory-proposals/' + p, { action: 'deny', reason: 'cleanup' });
+ }, 90_000);
+
+ test('an approve whose write did not commit says so: HTTP outcome failed, the command exits 1', async () => {
+ await linkMember(engine, 'alice-example', 'qm', 'U0ALICE2');
+ const viaCli = await propose('U0ALICE2', 'Command write fails canaryclifail');
+ let restore = onApprovalTransaction(unlinkInside('U0ALICE2'));
+ let ran: Awaited<ReturnType<typeof cli>>;
+ try { ran = await cli(['approve', viaCli, '--json']); } finally { restore(); }
+ expect((await proposalRow(viaCli)).state).toBe('approved');
+ const [cliWrite] = await journalRows(viaCli);
+ expect(['failed', 'conflict', 'cancelled']).toContain(cliWrite!.state);
+ expect(ran.out).toContain(cliWrite!.state);
+ expect(ran.exit).toBe(1);
+
+ await linkMember(engine, 'alice-example', 'qm', 'U0ALICE3');
+ const viaHttp = await propose('U0ALICE3', 'HTTP write fails canaryhttpfail');
+ const before = (await proposalAudits()).length;
+ restore = onApprovalTransaction(unlinkInside('U0ALICE3'));
+ let res: Awaited<ReturnType<typeof call>>;
+ try { res = await call('POST', '/admin/api/memory-proposals/' + viaHttp, { action: 'approve' }); } finally { restore(); }
+ const [httpWrite] = await journalRows(viaHttp);
+ expect(['failed', 'conflict', 'cancelled']).toContain(httpWrite!.state);
+ expect(res.json).toMatchObject({ applied: true, status: 'approved', outcome: 'failed', write_request: { state: httpWrite!.state } });
+ expect((await proposalAudits()).slice(before)).toEqual([
+ { actor: 'admin-api', action: 'proposal_approve', request_id: viaHttp, kind: 'timeline', slug: ACME, member: 'alice-example', state: 'approved' },
+ ]);
+ }, 90_000);
+
+ test('a change that fails partway answers outcome unknown, writes no audit row and leaves the proposal awaiting', async () => {
+ const id = await propose(ALICE_ID, 'Partial failure canarypartial');
+ const before = (await proposalAudits()).length;
+ const restore = onApprovalTransaction(async () => { throw new Error('injected failure after admission'); });
+ let res: Awaited<ReturnType<typeof call>>;
+ try { res = await call('POST', '/admin/api/memory-proposals/' + id, { action: 'approve' }); } finally { restore(); }
+ expect(res.status).toBe(503);
+ expect(res.json).toMatchObject({ code: 'administration_unavailable', outcome: 'unknown' });
+ expect(res.text).not.toContain('injected');
+ expect(await proposalRow(id)).toMatchObject({ state: 'awaiting_owner', decided_by: null });
+ expect(await journalRows(id)).toEqual([]);
+ expect((await proposalAudits()).length).toBe(before);
+ expect((await call('POST', '/admin/api/memory-proposals/' + id, { action: 'approve' })).json).toMatchObject({ applied: true, status: 'approved' });
+ }, 90_000);
+ });
+}