Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(qm): memory_propose, owner-approved held writes in memory_proposals (GST-1158 C1)

garrytan7eca0eb76f3b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index db2f561cf2..e97199707d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,8 @@ identifiers and attribution are available in the pre-removal Git revision
QM clients that read v1 keep working unchanged. A shared-scope turn should name its sources and read the v2 contract.
+**QM can propose a timeline entry or link on a shared page, and nothing is written until you approve it.** The new attested operation `memory_propose` holds the proposal in its own `memory_proposals` table, never in git, an export, search or recall. You review it with `gbrain memory-proposals list`, `show`, `approve <request_id>` and `deny <request_id> --reason "<why>"`; QM reads the outcome with `get_write_request` and can withdraw it with `cancel_write_request`. An approved proposal re-checks the person, the grant and the page, then becomes an ordinary write under the same request id with the person's member id (never QM's id) in its provenance. A page or link target that changed while the proposal waited closes it as `conflict`. Proposals expire after 7 days, at most 10 wait per person and 50 per credential, text is capped at 1,000 characters and deny reasons at 500, and closed proposals are deleted after 30 days; each limit is a `proposals.*` config key. `gbrain doctor` (`memory_proposals_pending`) and `gbrain status` show what is waiting. Add `memory_propose` (and `cancel_write_request`) to the client's `--attest-ops` to use it. Repo-less brains work the same. The wire contract does not list it yet.
+
## [0.60.555.0] - 2026-11-02
**`gbrain query --limit N` without a token budget returns N rows again, a budgeted facts block takes at most N rows, the facts block never outscores the pages, and the CLI names fact rows instead of printing `undefined` (#8411).** Since the facts block went on by default (v0.60.491.0), it also ran on queries that passed no budget, because the shipped no-budget evidence plan carries an implicit 24,000-token budget. Its 22% share let up to 40 fact rows in ahead of the pages, so `--limit 3` could print more than a dozen fact rows before the 3 pages. Each block row was scored a hair above the top page, so they all showed the same score and outranked every hit, and the human CLI printed them as `[0.84xx] undefined -- …` because fact rows have no page slug.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 7da1bd9182..c5cf8084ed 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3463,6 +3463,38 @@ More: [docs/guides/repair.md#projection-owner-resident](../../docs/guides/repair
|---|---|---|---|---|---|---|
| The current text projection is not ready. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |
+### proposal_closed
+
+<a id="proposal_closed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The memory proposal is no longer awaiting the owner (approved, denied, expired, cancelled, failed or in conflict), so it was not approved or denied again. | A proposal is decided once; the decision and the receipt it left stay as they are. | Read how it ended with gbrain memory-proposals show <request_id>; the proposer sends a new proposal if the change is still wanted. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/qm.md#proposed-writes](../../docs/guides/qm.md#proposed-writes)
+
+### proposal_expired
+
+<a id="proposal_expired"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The memory proposal passed its TTL (proposals.ttl_hours) before the owner decided, so nothing was written. | A held proposal is only as current as the page QM showed the person; an old one is closed rather than applied. | The proposer sends a new proposal if the change is still wanted; the operator raises proposals.ttl_hours to give owners longer. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/qm.md#proposed-writes](../../docs/guides/qm.md#proposed-writes)
+
+### proposals_pending_limit
+
+<a id="proposals_pending_limit"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Too many memory proposals already await the owner for this person (proposals.max_pending_per_actor) or this credential (proposals.max_pending_per_credential), so this one was not saved. | The caps keep one system credential from flooding the owner with held text. | Wait for the owner to decide or for a proposal to expire, or cancel one with cancel_write_request; the operator sets the caps. | agent | `repeat the read that failed` | 1 | yes |
+
+Reasons: `actor`, `credential`.
+
+More: [docs/guides/qm.md#proposed-writes](../../docs/guides/qm.md#proposed-writes)
+
### provenance_required
<a id="provenance_required"></a>
diff --git a/docs/guides/qm.md b/docs/guides/qm.md
index c8cf081af1..a89507c799 100644
--- a/docs/guides/qm.md
+++ b/docs/guides/qm.md
@@ -19,14 +19,52 @@ Add `forget` with `--attest-ops forget,get_write_request,memory_recall,memory_wr
should withdraw facts; an attested `forget` reaches only facts on the person's own
page, and any other id is `not_found`.
Direct page writes (`add_timeline_entry`, `add_link`, `put_page`, `edit_page`) are not
-attestable: a person's words reach a shared page only through an owner-approved proposal,
-which is not served yet. `--attest-ops` refuses them, and a list that already names one
-is refused for it on every call (`actor_not_attested`, reason `op_not_attested`).
+attestable: a person's words reach a shared page only through an owner-approved proposal
+(`memory_propose`, [below](#proposed-writes)). `--attest-ops` refuses them, and a list that
+already names one is refused for it on every call (`actor_not_attested`, reason `op_not_attested`).
A client whose `bound_slug_prefixes` do not cover `memory/members/<member>` is refused
(`permission_denied`) when it saves for that member.
Links and the right are database state, so a repo-less brain works the same; where
a repo exists, saved facts go through the same git-first writer door as `remember`.
+## Proposed writes
+
+`memory_propose` lets QM suggest one timeline entry or one link on a shared page for
+the person it serves. Nothing is written until the brain owner says yes. Grant it with
+`--attest-ops cancel_write_request,get_write_request,memory_propose,memory_recall,memory_write`.
+
+- `memory_propose {kind, target, idempotency_key, expected_revision?, ...}`: `kind: "timeline"`
+ takes `date` (`YYYY-MM-DD`), `summary`, `detail?` and `source?`; `kind: "link"` takes `to`,
+ `link_type?`, `context?`, `valid_from?` and `valid_until?`. A field of the other kind is
+ refused (`invalid_params`, reason `proposal_kind_field`). The person must be able to read the
+ target (and a link's `to` page). The answer is `{status: "awaiting_owner", request_id, kind,
+ target, expires_at}`; the same key from the same person returns that proposal's current
+ status, and the same key with other fields is `idempotency_conflict`.
+- `get_write_request {request_id}` reads the proposal: `awaiting_owner`, then `approved`
+ (with the write's own receipt), `denied` (with the owner's reason), `expired`, `cancelled`,
+ `failed` or `conflict` (the page or the link target changed while it waited). Only the
+ 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:
+
+```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 deny <request_id> --reason "<why>"
+```
+
+An approved proposal becomes an ordinary write admitted at approval, under the same
+`request_id`, with the person's member id (never QM's id) in its provenance. Until then the
+text lives only in the `memory_proposals` table: it never reaches git, an export, search or
+recall. `gbrain doctor` (`memory_proposals_pending`) and `gbrain status` show how many wait.
+Limits, all set with `gbrain config set`: `proposals.ttl_hours` (168), `proposals.max_pending_per_actor`
+(10), `proposals.max_pending_per_credential` (50; over either cap is `proposals_pending_limit`),
+`proposals.max_payload_chars` (1,000; over it is `invalid_params`, reason `proposal_too_large`),
+`proposals.max_reason_chars` (500) and `proposals.retention_days` (30: closed proposals are
+deleted after it; awaiting ones expire at their TTL first). A repo-less brain works the same.
+
## What the tools do
- `memory_recall {query, max_chars?, source_id?, source_ids?}` answers plain text, one fact per line
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index ed17169204..b3d26f9c50 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -163,6 +163,8 @@ a receipt can report has a row here.
| <a id="managed-guard-page-children"></a>`writer_coordinator_required: canonical writer must use the persistence coordinator` on a tag, timeline or take write; on the client `storage_error: Publication failed (P0001)` | `writer_coordinator_required` (`storage_error` on the stored receipt) | On a managed brain whose `tags`, `timeline_entries` or `takes` table has a `source_id` column gbrain does not create, the managed writer guard of a gbrain older than v0.60.38.0 refuses every insert and update of those rows, including coordinated ones. gbrain v0.60.38.0 and later take those rows' source from their page and ignore the column; an uncoordinated delete of such a row on a live page is refused, as on every other brain. | Upgrade to v0.60.38.0 or later on the brain host, then follow its recovery steps in the [CHANGELOG](../../CHANGELOG.md#060380---2026-10-03) (or [repair](repair.md#recover-after-an-upgrade)): `gbrain sync … --no-pull`, `gbrain extract --stale`, `gbrain extract timeline --source db`, a previewed `gbrain facts relink`, then `gbrain repair failed-writes` (preview, then `--apply --expect <hash>`) for the refused `put_page`, `add_timeline_entry` and `remember` calls; see [failed writes](repair.md#failed-writes). |
| `writer_coordinator_required` | `writer_coordinator_required` | The operation needs managed persistence (the write coordinator) and this brain or call path does not use it. A file write refused because the path sits in a managed canonical worktree names that worktree in the message, and its `detail` reads `root=<directory> source=<id or unknown> evidence=<marker file, managed-root registry or source binding>`. | Run the operation through the command the message names, on a managed brain. When the brain is not managed and the evidence is an ownership file (`.gbrain-owner.json`, `.gbrain-owner-<hash>.json`, `.gbrain-managed`), check it with `gbrain sources writer status` before removing anything: a half-finished claim is finished or rolled back through writer administration. A `gbrain-managed.json` an older gbrain wrote in a repository that only encloses a managed root (a dotfiles home) is named in the message; `gbrain sources writer deactivate` removes it (preview with `--dry-run --json`), then activate again. |
| `fact_already_expired` | `fact_already_expired` | The fact the write targets is already expired or withdrawn. | Nothing to do; list active facts to find the current one. |
+| `proposal_expired` | `proposal_expired` | The owner's `gbrain memory-proposals approve` or `deny` came after the proposal's `expires_at` (`proposals.ttl_hours`, default 168). The proposal closes `expired` and nothing was written. | QM reads `expired` on `get_write_request` and sends a new [proposal](qm.md#proposed-writes) with a new `idempotency_key` if the change is still wanted. The brain operator raises `proposals.ttl_hours` to give owners longer. |
+| `proposal_closed` | `proposal_closed` | `gbrain memory-proposals approve` or `deny` named a proposal that is no longer awaiting the owner (approved, denied, expired, cancelled, failed or in conflict). It is decided once, and its decision and receipt stay as they are. Nothing was written. | `gbrain memory-proposals show <request_id>` says how it ended; the proposer sends a new proposal if the change is still wanted. |
| `source_writeback_required` | `source_writeback_required` | The write needs a correction to the source's repository files, and this caller or profile never writes them. | Make the correction in the source repository, then sync. |
| `writer_upgrade_required` | `writer_upgrade_required` | The brain's schema is older than this operation needs. | Run `gbrain upgrade` (or `gbrain apply-migrations --yes`) on the brain host. |
| `skill_bundle_required` | `skill_bundle_required` | The write targets a shared-skill path, which only the shared skill publisher may write. | Publish the skill through the shared skill publisher instead. |
@@ -1008,6 +1010,7 @@ Links and the right live in the database, so they are the same on a repo-less br
|---|---|---|
| <a id="actor_not_attested"></a>`actor_not_attested` | The call named a person in a way gbrain does not honour. `reason` says which: `no_attest_right` (the credential holds no attest right, or the token of an attest client was issued before the upgrade or by another grant: the message then says to take a new client-credentials token), `op_not_attested` (the operation is not in the credential's attested operations, or is not attestable yet: `list_write_conflicts`, `capture`, `extract_facts`, `takes_add|update|resolve|supersede` and the direct page writes `add_timeline_entry`, `add_link`, `put_page` and `edit_page`; also when a queued write or agent job tool call runs after its operation was removed from the list), `argument_mismatch` (the `acting_user` argument differs from the header, or, with no header on a credential bound to a member, names anyone but that member; its own member id or a canonical id linked to it is dropped and the call runs exactly as the credential), `argument_without_attestation` (`acting_user` came without an attested header from a credential bound to no member, over stdio, or beside an `on_behalf_of` audience), `invalid_actor_id` (the header or argument is not 1-256 visible ASCII characters), `actor_required` (`memory_write` named no attested person) or `audience_not_supported` (the request carries `x-qm-audience`, QM's channel audience, which is refused on every call until wave 2). Nothing was read or written. | `no_attest_right` and `op_not_attested` are the brain operator's call: `fix` carries `gbrain auth rescope --client <id> --attest-actor qm [--attest-ops <list>]`. The other five are fixed in the calling harness: send the canonical id unchanged in the header from the attest credential, the same value or nothing in `acting_user` (on a member-bound credential with no header: its own member id, a canonical id linked to it, or nothing), and no `x-qm-audience`. |
| <a id="actor_unlinked"></a>`actor_unlinked` | The id is not linked to an enabled member: never linked, unlinked, or the member is disabled or removed. Ids compare exactly, with no case folding. Nothing was read or written. A queued write or agent job made for the person is refused the same way when its link is gone or now names another member. `memory_recall` answers it as an empty success instead (`structuredContent: {facts: [], truncated: false, code: "actor_unlinked"}`), so a person not yet linked reads nothing. | The brain operator links it: `gbrain access member link <member> --qm <id>` (or `gbrain access member enable <member>`). |
+| <a id="proposals_pending_limit"></a>`proposals_pending_limit` | A `memory_propose` found too many [proposals](qm.md#proposed-writes) already awaiting the owner: `reason` is `actor` (this person, `proposals.max_pending_per_actor`, default 10) or `credential` (this QM credential, `proposals.max_pending_per_credential`, default 50). An overdue proposal frees its slot first. Nothing was saved. | Wait for the owner to decide or for a proposal to expire, or withdraw one with `cancel_write_request`, then send it again with the same `idempotency_key`. The brain operator sets the caps. |
## Related
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 2789e58730..e45354b25b 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -260,8 +260,8 @@ only a fact on the person's own page (also for a credential bound to a member).
A request carrying `x-qm-audience` is refused (`audience_not_supported`). Not attestable yet, because what they
read or write is not yet kept to the person: `list_write_conflicts`, `capture`,
`extract_facts`, `takes_add|update|resolve|supersede`, and the direct page writes
-`add_timeline_entry`, `add_link`, `put_page` and `edit_page`, which wait for owner-approved
-proposals. An `--attest-ops` list that already names one of these is refused for it
+`add_timeline_entry`, `add_link`, `put_page` and `edit_page`; an attested timeline entry or link goes
+through `memory_propose` and waits for your `gbrain memory-proposals approve` ([QM guide](../guides/qm.md#proposed-writes)). An `--attest-ops` list that already names one of these is refused for it
(`actor_not_attested`, reason `op_not_attested`), and a queued attested write of one fails when it publishes.
`gbrain access check --token <name>` shows the
result ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 02c4a7def9..0799e3a6cc 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: 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 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1614 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +4 GST-1094/GST-900: the memory_recall scope-read, member-bound acting_user, recall max_chars and unknown_param _meta-only rows (since TBD until the merge slot)
+src/core/behavior-change-notice.ts 1616 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +1 GST-1158 F9 attest_direct_page_writes_deferred row, +1 GST-1158 memory_propose_held_writes row (since TBD until the merge slot); +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; +4 GST-1094/GST-900: the memory_recall scope-read, member-bound acting_user, recall max_chars and unknown_param _meta-only rows (since TBD until the merge slot)
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 60fc328945..2a015f7d0b 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -398,6 +398,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
{ name: 'questions', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/questions.ts') },
// CLI_ONLY: relationship-contradiction proposals (temporal typed edges); host-local, writes canonical timeline lines.
{ name: 'edge-proposals', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/edge-proposals.ts') },
+ // CLI_ONLY: the owner's review of QM's proposed timeline entries and links (GST-1158); host-local, never an MCP op.
+ { name: 'memory-proposals', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/memory-proposals.ts') },
// selfHelp: core prints its own usage (commands/core.ts). Always-loaded core memory, docs/guides/core-memory.md.
{ name: 'core', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/core.ts') },
// selfHelp: connectors ships its own printHelp (commands/connectors/index.ts) with the
diff --git a/src/cli/commands/memory-proposals.ts b/src/cli/commands/memory-proposals.ts
new file mode 100644
index 0000000000..85f5244428
--- /dev/null
+++ b/src/cli/commands/memory-proposals.ts
@@ -0,0 +1,10 @@
+/**
+ * `gbrain memory-proposals`: post-connect dispatch (the owner's review of QM's proposed writes, GST-1158). The record
+ * lives in src/cli/command-table.ts.
+ */
+import type { BrainEngine } from '../../core/engine.ts';
+
+export async function run(engine: BrainEngine, args: string[]): Promise<void> {
+ const { runMemoryProposals } = await import('../../commands/memory-proposals.ts');
+ await runMemoryProposals(engine, args);
+}
diff --git a/src/cli/flag-equals.ts b/src/cli/flag-equals.ts
index 5bc6513770..6e5a18ee38 100644
--- a/src/cli/flag-equals.ts
+++ b/src/cli/flag-equals.ts
@@ -94,6 +94,9 @@ export const EQUALS_READERS: Readonly<Record<string, readonly string[]>> = {
doctor: ['--scope', '--tier', '--budget-ms', '--only', '--skills-dir', '--expect'],
// edge-proposals.ts:81 flag() used only by list (:91,:93); other subs take the first numeric token as the id (:86).
'edge-proposals list': ['--status', '--limit'],
+ // memory-proposals.ts flag() reads list's --source/--limit and deny's --reason in both forms.
+ 'memory-proposals list': ['--source', '--limit'],
+ 'memory-proposals deny': ['--reason'],
// embed.ts:841 parsePaceArgs (--pace bare or =mode); core/consent.ts:126 via embed-consent.ts:129 and held-embedding.ts:234.
embed: ['--pace', '--pace-max-concurrency', '--max-usd', '--max-cost'],
// eval-conversation-parser.ts:48-53 (main.ts handleCliOnly's eval conversation-parser branch and eval.ts:106 both reach it).
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 629a13a1bf..e26e2d10b8 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -146,6 +146,7 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, true | (() => Promise<(engine: ne
loops: async () => (await import('../commands/loops.ts')).runLoops as never,
beliefs: async () => (await import('../commands/beliefs.ts')).runBeliefs as never,
'edge-proposals': async () => (await import('../commands/edge-proposals.ts')).runEdgeProposals as never,
+ 'memory-proposals': async () => (await import('../commands/memory-proposals.ts')).runMemoryProposals as never,
questions: async () => (await import('../commands/questions.ts')).runQuestions as never, // --help before the engine
waiting: async () => (await import('../commands/loops.ts')).runWaiting as never,
access: async () => (await import('../commands/access.ts')).runAccess as never, // GBRA-218: usage prints before the engine
diff --git a/src/cli/router-help.ts b/src/cli/router-help.ts
index 56aee3a762..d5b5746a60 100644
--- a/src/cli/router-help.ts
+++ b/src/cli/router-help.ts
@@ -18,6 +18,7 @@ export const ROUTER_MODULES: Readonly<Record<string, () => Promise<RouterModule>
hook: () => import('../commands/hook.ts'),
search: () => import('../commands/search.ts'),
'edge-proposals': () => import('../commands/edge-proposals.ts'),
+ 'memory-proposals': () => import('../commands/memory-proposals.ts'),
schema: () => import('../commands/schema.ts'),
config: () => import('../commands/config.ts'),
quarantine: () => import('../commands/quarantine.ts'),
diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.ts
index 02ab3e38fc..a19c8cf848 100644
--- a/src/cli/subcommands.ts
+++ b/src/cli/subcommands.ts
@@ -23,6 +23,7 @@ export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress
export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;
export const SEARCH_SUBCOMMANDS = ['modes', 'stats', 'tune', 'diagnose'] as const;
export const EDGE_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'accept', 'reject', 'undo', 'date', 'retry'] as const;
+export const MEMORY_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'approve', 'deny'] as const;
export const CONFIG_SUBCOMMANDS = ['show', 'get', 'set', 'unset'] as const;
export const QUARANTINE_SUBCOMMANDS = ['list', 'clear', 'scan', 'release', 'drop'] as const;
export const CORE_SUBCOMMANDS = ['list', 'show', 'status', 'add', 'remove', 'diff', 'ack', 'init', 'suggest'] as const;
@@ -51,6 +52,7 @@ export const ROUTERS: Readonly<Record<string, RouterInventory>> = {
hook: { subcommands: HOOK_SUBCOMMANDS, bareHelpFirst: true },
search: { subcommands: SEARCH_SUBCOMMANDS, bareHelpFirst: false },
'edge-proposals': { subcommands: EDGE_PROPOSALS_SUBCOMMANDS, bareHelpFirst: true },
+ 'memory-proposals': { subcommands: MEMORY_PROPOSALS_SUBCOMMANDS, bareHelpFirst: true },
schema: { subcommands: SCHEMA_SUBCOMMANDS, bareHelpFirst: true },
config: { subcommands: CONFIG_SUBCOMMANDS, bareHelpFirst: true },
quarantine: { subcommands: QUARANTINE_SUBCOMMANDS, bareHelpFirst: true },
diff --git a/src/cli/top-help.ts b/src/cli/top-help.ts
index a8535c4a02..1dacb4d8d1 100644
--- a/src/cli/top-help.ts
+++ b/src/cli/top-help.ts
@@ -121,6 +121,7 @@ TOOLS
compile-context --target <t> Compile a deterministic, scanned, budgeted context
[--budget N] [--check] file (claude-code | codex | openclaw)
decide <status|probe|enable|...> System One decision support (Jev); every slot off by default
+ memory-proposals list|show|approve|deny QM's proposed timeline entries and links awaiting your decision
facts relink [--dry-run] Link facts saved without an entity to the entity they name
check-resolvable [--json] [--fix] Validate skill tree (reachability/MECE/DRY)
report --type <name> --content ... Save timestamped report to brain/reports/
diff --git a/src/commands/doctor/checks/memory-proposals.ts b/src/commands/doctor/checks/memory-proposals.ts
new file mode 100644
index 0000000000..e9e94fe692
--- /dev/null
+++ b/src/commands/doctor/checks/memory-proposals.ts
@@ -0,0 +1,27 @@
+/**
+ * memory_proposals_pending (GST-1158, GBRA-284): QM's proposed timeline entries and links waiting for the owner's
+ * decision. Reports the count and the oldest one's age so a held proposal does not quietly expire unseen; the fix
+ * lists them. A brain with none, or a schema before the table, reports ok.
+ */
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { doctorVerify } from '../check-fix.ts';
+
+export async function runMemoryProposalsDoctor(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ const { pendingProposalSummary } = await import('../../../core/persistence/memory-proposals.ts');
+ const { pending, oldest_hours: oldest } = await pendingProposalSummary(engine);
+ if (pending === 0) {
+ checks.push({ name: 'memory_proposals_pending', status: 'ok', message: 'No memory proposals await the owner.' });
+ return checks;
+ }
+ checks.push({ name: 'memory_proposals_pending', status: 'warn',
+ message: `${pending} memory proposal(s) from QM await your decision${oldest !== null ? ` (oldest ${oldest} hours)` : ''}; review: gbrain memory-proposals list`,
+ details: { pending, oldest_hours: oldest },
+ fix: { argv: ['gbrain', 'memory-proposals', 'list'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Lists the proposed timeline entries and links with their pages; approving or denying each one is the owner\'s call.', verify: doctorVerify('memory_proposals_pending') } });
+ return checks;
+}
+
+export const memoryProposalsEntry: DoctorEntry = { name: 'memory_proposals_pending', emits: ['memory_proposals_pending'], run: runMemoryProposalsDoctor };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 0cac843d8d..76e8d45080 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -107,6 +107,7 @@ import { autoChronicleEntry } from './checks/auto-chronicle.ts';
import { factsDrainEntry } from './checks/facts-drain.ts';
import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
+import { memoryProposalsEntry } from './checks/memory-proposals.ts';
import { supersessionCalibrationEntry } from './checks/supersession-calibration.ts';
import { factAdmissionFloorsEntry } from './checks/fact-admission-floors.ts';
import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';
@@ -270,6 +271,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
gitConvergenceEntry,
gitWriterEntry,
decideHealthEntry,
+ memoryProposalsEntry,
unlinkedFactsEntry,
edgeValidityEntry,
autoChronicleEntry,
diff --git a/src/commands/memory-proposals.ts b/src/commands/memory-proposals.ts
new file mode 100644
index 0000000000..189e7fda8e
--- /dev/null
+++ b/src/commands/memory-proposals.ts
@@ -0,0 +1,113 @@
+/**
+ * `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.
+ *
+ * gbrain memory-proposals list [--source <id>] [--all] [--limit N] [--json]
+ * gbrain memory-proposals show <request_id> [--json]
+ * gbrain memory-proposals approve <request_id> [--dry-run] [--json]
+ * gbrain memory-proposals deny <request_id> --reason "<why>" [--dry-run] [--json]
+ *
+ * The proposed text comes from a system credential, so list and show print it inside the transcript fence (quoted:
+ * transcript) and approve takes exactly one request id.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { OperationError, type OperationContext } from '../core/ops/contract.ts';
+import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { intFlagValue } from '../cli/flag-values.ts';
+import { MEMORY_PROPOSALS_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';
+import type { MemoryProposal } from '../core/persistence/memory-proposals.ts';
+
+export { MEMORY_PROPOSALS_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';
+
+function usage(): string {
+ return [
+ 'Usage: gbrain memory-proposals <list|show|approve|deny> [args]',
+ ' list [--source <id>] [--all] [--limit N] [--json] awaiting your decision, oldest first (--all: closed ones too)',
+ ' show <request_id> [--json]',
+ ' approve <request_id> [--dry-run] re-check the person, the grant and the page, then write it',
+ ' deny <request_id> --reason "<why>" [--dry-run] the proposer reads the reason on its receipt',
+ ].join('\n');
+}
+
+export function printUsage(): void {
+ console.log(usage());
+}
+
+/** The owner's view of one proposal: the proposed text fenced as untrusted transcript text. */
+export async function ownerView(row: MemoryProposal): Promise<Record<string, unknown>> {
+ const { fenceTranscriptText } = await import('../core/search/transcript-quote.ts');
+ const payload = Object.fromEntries(Object.entries(row.payload ?? {}).map(([k, v]) =>
+ [k, typeof v === 'string' && ['summary', 'detail', 'source', 'context'].includes(k) && v ? fenceTranscriptText(v, row.slug) : v]));
+ return {
+ request_id: row.request_id, state: row.state, kind: row.kind, source_id: row.source_id, target: row.slug, ...(row.to_slug ? { to: row.to_slug } : {}),
+ member_id: row.member_id, system: row.system, external_id: row.external_id, principal_kind: row.principal_kind, principal_id: row.principal_id,
+ created_at: row.created_at, expires_at: row.expires_at, ...(row.decided_at ? { decided_at: row.decided_at, decided_by: row.decided_by } : {}),
+ ...(row.reason ? { reason: row.reason } : {}), ...(row.error_code ? { error_code: row.error_code } : {}),
+ payload: row.payload === null ? null : payload, quoted: 'transcript',
+ };
+}
+
+function line(view: Record<string, any>): string {
+ const what = view.kind === 'timeline' ? `${view.payload?.date ?? ''} ${view.payload?.summary ?? ''}` : `-> ${view.to} ${view.payload?.link_type ?? ''}`;
+ return `${view.request_id} [${view.state}] ${view.kind} on ${view.source_id}:${view.target} for member:${view.member_id}\n ${what}`;
+}
+
+async function decidedBy(engine: BrainEngine): Promise<string> {
+ try { return `cli:${(await (await import('../core/persistence/identity.ts')).readLocalWriter(engine, 'cli')).id}`; } catch { return 'cli'; }
+}
+
+export async function runMemoryProposals(engine: BrainEngine, args: string[]): Promise<void> {
+ if (subcommandHelpRequested(args, ROUTERS['memory-proposals'])) { printUsage(); return; }
+ const [sub, ...rest] = args as [(typeof MEMORY_PROPOSALS_SUBCOMMANDS)[number] | undefined, ...string[]];
+ const json = rest.includes('--json');
+ const dryRun = rest.includes('--dry-run');
+ const flag = (name: string) => {
+ const at = rest.findIndex(a => a === name || a.startsWith(`${name}=`));
+ if (at < 0) return undefined;
+ return rest[at] === name ? rest[at + 1] ?? '' : rest[at]!.slice(name.length + 1);
+ };
+ const id = rest.find(a => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a));
+ const out = (value: unknown, text: string) => console.log(json ? JSON.stringify(value, null, 2) : text);
+ const lib = await import('../core/persistence/memory-proposals.ts');
+ if (!sub) { printUsage(); return; }
+ try {
+ if (sub === 'list') {
+ const rawLimit = flag('--limit');
+ const limit = rawLimit === undefined ? 50 : intFlagValue(rawLimit, '--limit', { min: 1, example: 50 });
+ const rows = await lib.listMemoryProposals(engine, { sourceId: flag('--source'), all: rest.includes('--all'), limit });
+ const views = await Promise.all(rows.map(ownerView));
+ out({ proposals: views }, views.length ? views.map(line).join('\n') + '\n\nNext: gbrain memory-proposals show <request_id>, then approve <request_id> or deny <request_id> --reason "<why>"'
+ : 'No memory proposals await your decision.');
+ return;
+ }
+ if (!id) { console.error(`${usage()}\n\nA request id is required (gbrain memory-proposals list shows them).`); setCliExitVerdict(2); return; }
+ if (sub === 'show') {
+ const view = await ownerView(await lib.ownerProposal(engine, id));
+ 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;
+ 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);
+ return;
+ }
+ if (sub === 'deny') {
+ const reason = flag('--reason');
+ if (reason === undefined) { console.error('deny needs --reason "<why>": the proposer reads it on the receipt.'); setCliExitVerdict(2); return; }
+ const result = await lib.denyMemoryProposal(ctx, id, reason, { decidedBy: await decidedBy(engine) });
+ out(result, result.dry_run ? `${id}: would be denied` : `${id}: denied`);
+ return;
+ }
+ } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ console.error(`${error.code}: ${error.message}\n${error.suggestion}`);
+ setCliExitVerdict(error.code === 'invalid_params' ? 2 : 1);
+ return;
+ }
+ console.error(usage());
+ setCliExitVerdict(2);
+}
diff --git a/src/commands/status.ts b/src/commands/status.ts
index 02c3c6e406..0712adc642 100644
--- a/src/commands/status.ts
+++ b/src/commands/status.ts
@@ -54,6 +54,7 @@ import {
summarizeCrashes,
} from '../core/minions/handlers/supervisor-audit.ts';
import { formatSyncFreshness, readSyncFreshness, type SourceFreshness } from '../core/persistence/sync-freshness.ts';
+import { pendingProposalSummary } from '../core/persistence/memory-proposals.ts';
import { withReadMeta } from '../core/read-heartbeat.ts';
const SCHEMA_VERSION = 1 as const;
@@ -167,6 +168,8 @@ export interface StatusReport {
workers?: WorkerSummary | RemoteWorkersSnapshot | SectionUnavailable | RemoteUnsupported | { local_only_remote: true };
queue?: QueueCounts | RemoteQueueSnapshot | SectionUnavailable | RemoteUnsupported | { local_only_remote: true };
autopilot?: AutopilotStatus | { local_only_remote: true };
+ /** GBRA-284: held QM proposals awaiting the owner (local mode, full snapshot; counts only, never the proposed text). */
+ memory_proposals?: { pending: number; oldest_hours: number | null };
warnings?: string[];
/** #1984: true when a --deadline-ms budget elided one or more sections. */
partial?: boolean;
@@ -529,6 +532,14 @@ async function buildLocalReport(
warnings.push(`cycle section failed: ${(err as Error).message}`);
}
}
+ if (!opts.sections) {
+ try {
+ const proposals = await withSectionDeadline(pendingProposalSummary(engine), remaining(), () => {});
+ if (proposals?.pending) report.memory_proposals = proposals;
+ } catch (err) {
+ warnings.push(`memory proposals read failed: ${(err as Error).message}`);
+ }
+ }
if (want('locks')) {
report.locks = await withSectionDeadline(buildLocks(engine), remaining(), () => markStale('locks'));
}
@@ -780,6 +791,12 @@ export function renderHuman(report: StatusReport): string {
lines.push('');
}
+ if (report.memory_proposals?.pending) {
+ const { pending, oldest_hours: oldest } = report.memory_proposals;
+ lines.push(`Memory proposals: ${pending} awaiting the owner${oldest === null ? '' : ` (oldest ${oldest}h)`} (review: gbrain memory-proposals list)`);
+ lines.push('');
+ }
+
// Warnings
if (report.warnings && report.warnings.length > 0) {
lines.push('Warnings:');
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 228296895c..6574044179 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1416,6 +1416,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', id: 'member_bound_acting_user_gst900', text: 'A credential bound to a member may now send `acting_user` with no `x-qm-actor` header: its own member id, or a canonical id linked to that member, is dropped and the call runs exactly as the credential; any other value is refused (`actor_not_attested` reason `argument_mismatch`). A credential bound to no member is still refused (`argument_without_attestation`).' },
{ since: 'TBD', id: 'recall_max_chars_harn15', text: '`recall` now takes `max_chars` (a whole number from 200 to 12000, as `memory_recall`): it keeps the whole facts, then results, whose text fits, adds no marker and returns `truncated`; without it `recall` is unchanged.' },
{ since: 'TBD', id: 'attest_direct_page_writes_deferred_gst1158', text: 'An attested call (`x-qm-actor`) may no longer run `add_timeline_entry`, `add_link`, `put_page` or `edit_page`: they write pages every reader of the page sees, so they wait for owner-approved proposals. `gbrain auth rescope --attest-ops` refuses a list that names one, a credential whose list already names one is refused for it on every attested call (`actor_not_attested`, reason `op_not_attested`), and a queued attested write of one fails when it publishes. Unattested calls and member-bound credentials are unchanged.' },
+ { since: 'TBD', id: '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: 'TBD', id: 'unknown_param_meta_only_harn15', text: 'A read that ignores a parameter the tool does not declare (`mcp.strict_params` `warn`, the default) no longer adds a `[gbrain notice unknown_param kind=info]` text block to the result: the warning is only in `_meta.warnings` (`{code: \'unknown_param\', param, suggestion?}`), so a harness that stores tool output in its turns never stores it. Writes still refuse unknown parameters, and `reject` mode is unchanged.' },
];
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 0b077b701b..906a287009 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -51,7 +51,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -86,6 +86,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],
'mcp': ['--admin-token-file', '--advertise', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
+ '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'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
@@ -200,6 +201,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
'lsd': ['--brain'],
'maintain': ['--brain'],
'mcp': ['--brain'],
+ 'memory-proposals': ['--brain'],
'migrate': ['--brain'],
'models': ['--brain'],
'notability-eval': ['--brain'],
diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.ts
index e7500c5893..de7e589268 100644
--- a/src/core/config-runtime-keys.ts
+++ b/src/core/config-runtime-keys.ts
@@ -24,4 +24,6 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = [
'serve.vector_prewarm', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve prewarms the HNSW indexes into shared_buffers at start when they fit, default off
'mcp.stdio_member', // access/caller.ts (GBRA-218): binds a local stdio MCP server to one member; unbound, stdio reads no page that names readers
'mcp.stdio_may_act_for', // access/audience.ts (GBRA-231): whom a local stdio server may act for (_meta.on_behalf_of); unset, stdio refuses every audience
+ 'proposals.ttl_hours', 'proposals.max_pending_per_actor', 'proposals.max_pending_per_credential', // persistence/memory-proposals.ts: held QM proposal TTL (168 h) and pending caps (10 per person, 50 per credential)
+ 'proposals.retention_days', 'proposals.max_payload_chars', 'proposals.max_reason_chars', // persistence/memory-proposals.ts: closed-row retention (30 d), payload (1,000) and deny-reason (500) character caps
];
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 5260f9eca3..80ebd4066a 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -104,6 +104,7 @@ const ROWS: readonly Row[] = [
['mcp_request_log', 'out_of_scope', 'probed_reported', 'token_name agent_name operation status params error_message', 'params error_message'],
['mcp_spend_log', 'out_of_scope', 'no_memory_text', 'client_id token_name operation provider model budget_key'],
['mcp_spend_reservations', 'out_of_scope', 'no_memory_text', 'client_id model provider status usage_unknown_reason budget_key'],
+ ['memory_proposals', 'out_of_scope', 'probed_reported', 'principal_kind principal_id system external_id member_id source_id kind operation slug to_slug payload payload_digest expected_revision authority state reason decided_by error_code', 'payload reason'],
['mention_gazetteer_entries', 'out_of_scope', 'no_memory_text', 'source_id name_norm target_slug'],
['mention_index_status', 'out_of_scope', 'no_memory_text', 'source_id state policy_fingerprint error'],
['migration_impact_log', 'out_of_scope', 'probed_reported', 'remediation_id metric_name source_id brain_id idempotency_key applied_by details', 'details'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 0513efa87e..91312006cf 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -231,6 +231,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'takes_weight_grid',
// #5836: active facts with no entity (invisible to entity recall and the conflict sweep).
'unlinked_facts',
+ // GST-1158: QM's proposed writes awaiting the owner (doctor/checks/memory-proposals.ts).
+ 'memory_proposals_pending',
// #7160: title-prefixed person pages that likely duplicate an unprefixed page (preview only).
'person_title_duplicates',
// Git-canonical G1: the database compared with the commit at HEAD per source, informational (doctor/checks/db-ahead-of-git.ts).
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9c42093632..072eb92031 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -590,6 +590,9 @@ export const CODES = {
keyword_candidates_incomplete: { class: 'unavailable', summary: "Hybrid search's keyword arm returned a bounded result on a large corpus (the CJK arm's deadline or candidate cap, or a common-word match ranked from a sample), so some keyword matches can be missing.", why: 'The CJK fallback is an unindexed LIKE scan, and a query whose words match hundreds of thousands of chunks ranks a bounded sample of them (an OR retry also keeps only its rarer words); each bound keeps a large brain from stalling every hybrid search. An incomplete keyword search is not evidence of absence.', docs: 'docs/guides/multi-language-fts.md#cjk-keyword-budget', suggestion: 'Add a rarer word or an exact "phrase", or narrow the search with --source-id (MCP source_id) or --types; for CJK text, ask the user to raise search.cjk_keyword_deadline_ms.', fix: { argv: ['gbrain', 'config', 'get', 'search.cjk_keyword_deadline_ms'], consent: [], actor: 'agent', why: 'Shows the deadline in effect (unset means 3000 ms); read-only.', requires_exclusive: false } },
keyword_skipped_after_timeout: { class: 'unavailable', summary: "Hybrid search's Postgres keyword arm skipped a statement that hit the keyword statement timeout within the negative-cache TTL; the search reports keyword_arm_failed with reason skipped_after_timeout and the vector arm still answers.", why: 'Running the same broad keyword statement again would hold a backend for the whole search.keyword_statement_timeout_ms and fail the same way. The skip covers that exact statement and scope only, lasts search.keyword_timeout_negative_cache_seconds (default 600, 0 turns it off) and is per serving process. A skipped keyword arm is not evidence of absence.', docs: 'docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain', suggestion: 'Narrow the search (source_id, types, since or until) to run keyword search now, or wait for the entry to expire; the user may raise search.keyword_statement_timeout_ms or change the TTL.', fix: { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the keyword statement bound, the recorded keyword timeouts and skips, and whether broad terms can be ranked inside the bound.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'] } } },
projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },
+ proposal_closed: { class: 'caller', summary: "The memory proposal is no longer awaiting the owner (approved, denied, expired, cancelled, failed or in conflict), so it was not approved or denied again.", why: 'A proposal is decided once; the decision and the receipt it left stay as they are.', docs: 'docs/guides/qm.md#proposed-writes', suggestion: 'Read how it ended with gbrain memory-proposals show <request_id>; the proposer sends a new proposal if the change is still wanted.' },
+ proposal_expired: { class: 'caller', summary: "The memory proposal passed its TTL (proposals.ttl_hours) before the owner decided, so nothing was written.", why: 'A held proposal is only as current as the page QM showed the person; an old one is closed rather than applied.', docs: 'docs/guides/qm.md#proposed-writes', suggestion: 'The proposer sends a new proposal if the change is still wanted; the operator raises proposals.ttl_hours to give owners longer.' },
+ proposals_pending_limit: { class: 'retryable', summary: "Too many memory proposals already await the owner for this person (proposals.max_pending_per_actor) or this credential (proposals.max_pending_per_credential), so this one was not saved.", reasons: ['actor', 'credential'], why: 'The caps keep one system credential from flooding the owner with held text.', docs: 'docs/guides/qm.md#proposed-writes', suggestion: 'Wait for the owner to decide or for a proposal to expire, or cancel one with cancel_write_request; the operator sets the caps.' },
provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },
publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },
pull_blocked_local_changes: { class: 'caller', retryable: false, actor: 'user',
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 46a02e2444..05be6d6f74 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -212,6 +212,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"unpurge_page": [load_purge, "purgeOperations"],
"memory_recall": [load_qm_memory, "qmMemoryOperations"],
"memory_write": [load_qm_memory, "qmMemoryOperations"],
+ "memory_propose": [load_qm_memory, "qmMemoryOperations"],
"find_contradictions": [load_insights, "find_contradictions"],
"find_experts": [load_insights, "find_experts"],
"find_trajectory": [load_insights, "find_trajectory"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index d81f674ea9..858b1b8c39 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -6262,6 +6262,84 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"area": "memory"
},
+ {
+ "name": "memory_propose",
+ "mutating": true,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Propose one timeline entry or link on a shared page for the person this call serves; the brain owner approves it before it is written. Needs an attested person. Poll get_write_request with the request_id; the same idempotency_key replays.",
+ "params": {
+ "kind": {
+ "type": "string",
+ "required": true,
+ "enum": [
+ "timeline",
+ "link"
+ ],
+ "description": "timeline (date, summary) or link (to)."
+ },
+ "target": {
+ "type": "string",
+ "required": true,
+ "description": "Slug the write lands on (a link's from page)."
+ },
+ "idempotency_key": {
+ "type": "string",
+ "required": true,
+ "description": "1-128 visible ASCII characters; the same key replays this proposal."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "The revision shown to the person; refused when the page moved."
+ },
+ "date": {
+ "type": "string",
+ "description": "timeline: YYYY-MM-DD."
+ },
+ "summary": {
+ "type": "string",
+ "description": "timeline: one line."
+ },
+ "detail": {
+ "type": "string",
+ "description": "timeline: details."
+ },
+ "source": {
+ "type": "string",
+ "description": "timeline: where it came from."
+ },
+ "to": {
+ "type": "string",
+ "description": "link: the page it points to."
+ },
+ "link_type": {
+ "type": "string",
+ "description": "link: a type the schema pack declares."
+ },
+ "context": {
+ "type": "string",
+ "description": "link: context."
+ },
+ "valid_from": {
+ "type": "string",
+ "description": "link: YYYY-MM-DD."
+ },
+ "valid_until": {
+ "type": "string",
+ "description": "link: YYYY-MM-DD."
+ },
+ "acting_user": {
+ "type": "string",
+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit.",
+ "fullSurfaceOnly": true
+ }
+ },
+ "scope": "write",
+ "annotations": {
+ "title": "memory_propose (QM proposed write)",
+ "idempotentHint": true
+ }
+ },
{
"name": "find_contradictions",
"mutating": false,
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 70207a8b0d..cf066ac243 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -68,7 +68,7 @@ import {
export { MANAGED_LINK_SOURCES };
/** add_link valid_from / valid_until: calendar dates on a dated relation type. Null when neither is given. */
-function validateLinkDates(ctx: OperationContext, p: Record<string, unknown>, linkType: string): { validFrom?: string; validUntil?: string } | null {
+export function validateLinkDates(ctx: OperationContext, p: Record<string, unknown>, linkType: string): { validFrom?: string; validUntil?: string } | null {
const validFrom = p.valid_from, validUntil = p.valid_until;
if (validFrom === undefined && validUntil === undefined) return null;
for (const [name, value] of [['valid_from', validFrom], ['valid_until', validUntil]] as const) {
diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.ts
index 37fecab2c2..65a8ae728c 100644
--- a/src/core/ops/persistence.ts
+++ b/src/core/ops/persistence.ts
@@ -158,6 +158,28 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: W
};
}
+/**
+ * GST-1158: a memory proposal under this request id, when no journal row has it yet: visible to the same principal and the
+ * same attested person only (OV8: not to the live attest ops, so a proposer keeps reading and cancelling its held rows after
+ * memory_propose is revoked); every other caller gets the same not_found as a missing id.
+ */
+async function ownProposal(ctx: OperationContext, principal: Principal, requestId: string) {
+ const { getProposal } = await import('../persistence/memory-proposals.ts');
+ const proposal = await getProposal(ctx.engine, principal, requestId).catch(async error => {
+ if ((await import('../utils.ts')).isMissingSchemaObject(error, 'table', 'memory_proposals')) return null;
+ throw error;
+ });
+ const { sameAttestedActor } = await import('../access/member-facts.ts');
+ return proposal && sameAttestedActor(proposal.authority.actingFor) ? proposal : null;
+}
+
+/** The proposal an approved write came from, on its journal receipt. */
+async function approvedProposal(ctx: OperationContext, principal: Principal, row: WriteRequest): Promise<Record<string, unknown>> {
+ if (row.authority?.attestedOp !== 'memory_propose') return {};
+ const proposal = await ownProposal(ctx, principal, row.request_id);
+ return proposal ? { proposal: { kind: proposal.kind, target: proposal.slug, ...(proposal.to_slug ? { to: proposal.to_slug } : {}), decided_at: proposal.decided_at } } : {};
+}
+
/** A receipt the terminal classifier reads: ended without committing, or holding a publication recovery record outside an in-flight claim (committed or parked `recovering`). */
function isTerminalOrRecovering(row: WriteRequest): boolean {
return ['failed', 'conflict', 'cancelled'].includes(row.state) || ((row.state === 'committed' || row.state === 'recovering') && row.recovery != null);
@@ -186,8 +208,13 @@ export const persistenceOperations: Operation[] = [
const { principal } = await receiptAccess(ctx, 'get_write_request');
const { getWriteRequest, writeHealthFacts } = await import('../persistence/journal.ts');
const row = await getWriteRequest(ctx.engine, principal, id);
- if (!row || !await visible(ctx, row)) throw missing(callerSource(ctx));
- const receipt = await publicReceipt(ctx, row, (await writeHealthFacts(ctx.engine, [row])).get(row.id));
+ if (!row) {
+ const proposal = await ownProposal(ctx, principal, id);
+ if (!proposal) throw missing(callerSource(ctx));
+ return (await import('../persistence/memory-proposals.ts')).proposalReceipt(proposal);
+ }
+ if (!await visible(ctx, row)) throw missing(callerSource(ctx));
+ const receipt = { ...await publicReceipt(ctx, row, (await writeHealthFacts(ctx.engine, [row])).get(row.id)), ...await approvedProposal(ctx, principal, row) };
if (params.applied !== true) return receipt;
const applied = await (await import('../persistence/write-applied.ts')).readWriteApplied(ctx.engine, row).catch(() => null);
return applied ? { ...receipt, applied } : receipt;
@@ -273,7 +300,14 @@ export const persistenceOperations: Operation[] = [
const { principal } = await receiptAccess(ctx, 'cancel_write_request');
const { getWriteRequest, writeHealthFacts } = await import('../persistence/journal.ts');
const row = await getWriteRequest(ctx.engine, principal, id);
- if (!row || !await visible(ctx, row)) throw missing(callerSource(ctx));
+ if (!row) {
+ const proposal = await ownProposal(ctx, principal, id);
+ if (!proposal) throw missing(callerSource(ctx));
+ if (ctx.dryRun) return { dry_run: true, action: 'cancel_write_request', request_id: id, state: proposal.state };
+ const { cancelOwnProposal, proposalReceipt } = await import('../persistence/memory-proposals.ts');
+ return proposalReceipt(await cancelOwnProposal(ctx.engine, proposal));
+ }
+ if (!await visible(ctx, row)) throw missing(callerSource(ctx));
if (ctx.dryRun) return { dry_run: true, action: 'cancel_write_request', request_id: id, state: row.state };
const { cancelWriteRequest } = await import('../persistence/control.ts');
const cancelled = await cancelWriteRequest(ctx.engine, principal, id, {
diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.ts
index b73e73d702..baf74d59c3 100644
--- a/src/core/ops/qm-memory.ts
+++ b/src/core/ops/qm-memory.ts
@@ -305,6 +305,141 @@ const memory_write: Operation = {
},
};
+const PROPOSE_FIELDS = { timeline: ['date', 'summary', 'detail', 'source'], link: ['to', 'link_type', 'context', 'valid_from', 'valid_until'] } as const;
+const oneLine = (value: string) => !CONTROL_RE.test(value) && !UNPAIRED_SURROGATE_RE.test(value);
+
+/**
+ * GST-1158 (GBRA-284): one timeline entry or typed link proposed for a shared page, held in memory_proposals until the
+ * brain owner approves it (persistence/memory-proposals.ts). Attested only. Replay first: the request id derives from the
+ * member and the key, and a resend with the same fields returns the proposal's current state even after the page moved.
+ * Everything is checked before anything is held: the fields of the kind, the date, one-line text, the payload cap, the
+ * slug fence, the grant and attested person (attestedOp memory_propose), the target (and a link's target) existing and
+ * readable by the person, and expected_revision when sent. The published provenance names the member, never the
+ * person's external id.
+ */
+const memory_propose: Operation = {
+ name: 'memory_propose',
+ mutating: true,
+ idempotent: true,
+ outputRedaction: 'no_stored_text',
+ description: 'Propose one timeline entry or link on a shared page for the person this call serves; the brain owner approves it before it is written. Needs an attested person. Poll get_write_request with the request_id; the same idempotency_key replays.',
+ params: {
+ kind: { type: 'string', required: true, enum: ['timeline', 'link'], description: 'timeline (date, summary) or link (to).' },
+ target: { type: 'string', required: true, description: 'Slug the write lands on (a link\'s from page).' },
+ idempotency_key: { type: 'string', required: true, description: '1-128 visible ASCII characters; the same key replays this proposal.' },
+ expected_revision: { type: 'string', description: 'The revision shown to the person; refused when the page moved.' },
+ date: { type: 'string', description: 'timeline: YYYY-MM-DD.' },
+ summary: { type: 'string', description: 'timeline: one line.' },
+ detail: { type: 'string', description: 'timeline: details.' },
+ source: { type: 'string', description: 'timeline: where it came from.' },
+ to: { type: 'string', description: 'link: the page it points to.' },
+ link_type: { type: 'string', description: 'link: a type the schema pack declares.' },
+ context: { type: 'string', description: 'link: context.' },
+ valid_from: { type: 'string', description: 'link: YYYY-MM-DD.' },
+ valid_until: { type: 'string', description: 'link: YYYY-MM-DD.' },
+ [ACTOR_ARGUMENT]: actorParam,
+ },
+ scope: 'write',
+ annotations: { title: 'memory_propose (QM proposed write)', idempotentHint: true },
+ handler: async (ctx, p) => {
+ const actor = ctx.remote === false ? null : currentCallerAccess().actor ?? null;
+ if (!actor) {
+ const { actorNotAttested } = await import('../access/actor.ts');
+ throw actorNotAttested('actor_required', { auth: ctx.auth }, { op: 'memory_propose', transport: ctx.transport });
+ }
+ if (typeof p.idempotency_key !== 'string' || !IDEMPOTENCY_KEY_RE.test(p.idempotency_key)) {
+ throw invalid('idempotency_key must be 1 to 128 visible ASCII characters (no spaces).', 'Send a stable key per proposal, for example a UUID; the same key replays the same proposal.');
+ }
+ const kind = p.kind;
+ if (kind !== 'timeline' && kind !== 'link') throw invalid('kind must be timeline or link.', 'Pass kind: "timeline" with date and summary, or kind: "link" with to.');
+ const target = typeof p.target === 'string' ? p.target.trim().toLowerCase() : '';
+ if (!target) throw invalid('target is required: the slug the write lands on.', 'Pass the page slug as target (for a link, the page it starts from).');
+ const stray = PROPOSE_FIELDS[kind === 'timeline' ? 'link' : 'timeline'].filter(k => p[k] !== undefined);
+ if (stray.length) throw opError('invalid_params', `A ${kind} proposal does not take ${stray.join(', ')}.`, `Drop ${stray.join(', ')}; a ${kind} proposal takes ${PROPOSE_FIELDS[kind].join(', ')}.`, { reason: 'proposal_kind_field' });
+ for (const k of [...PROPOSE_FIELDS[kind], 'expected_revision']) {
+ if (p[k] !== undefined && typeof p[k] !== 'string') throw invalid(`${k} must be a string.`, `Pass ${k} as text, or omit it.`);
+ }
+ const sent: Record<string, unknown> = { kind, target, ...Object.fromEntries([...PROPOSE_FIELDS[kind], 'expected_revision'].flatMap(k => p[k] === undefined ? [] : [[k, p[k]]])) };
+ const { proposalDigest, proposalRequestId, getProposal, insertProposal, readProposalLimits, linkTargetReadable, PROPOSAL_LINK_SOURCE } = await import('../persistence/memory-proposals.ts');
+ const { requestPrincipalForContext, pageMutationSource } = await import('../persistence/page-mutations.ts');
+ const digest = proposalDigest(sent);
+ const principal = await requestPrincipalForContext(ctx);
+ const requestId = proposalRequestId(actor.member, p.idempotency_key);
+ const replay = (row: { payload_digest: string; state: string; request_id: string; kind: string; slug: string; expires_at: string }) => {
+ if (row.payload_digest !== digest) {
+ throw opError('idempotency_conflict', 'This idempotency_key was used for a different proposal; send a new key.',
+ 'A key is reused only to resend the same proposal. Send this one with a new idempotency_key; the earlier proposal keeps its receipt (get_write_request).');
+ }
+ return { status: row.state, request_id: row.request_id, kind: row.kind, target: row.slug, expires_at: row.expires_at, text: `Proposal ${row.state.replace('_', ' ')}.` };
+ };
+ const existing = await getProposal(ctx.engine, principal, requestId);
+ if (existing) return replay(existing);
+ const limits = await readProposalLimits(ctx.engine);
+ let text: string;
+ if (kind === 'timeline') {
+ const { assertTimelineDate } = await import('./timeline.ts');
+ assertTimelineDate(ctx, p.date);
+ const summary = typeof p.summary === 'string' ? p.summary.trim() : '';
+ if (!summary || !oneLine(summary)) throw invalid('summary is required and must be one line of text.', 'Pass the entry as one line, without line breaks or control characters; put more in detail.');
+ for (const k of ['detail', 'source'] as const) {
+ const v = p[k] as string | undefined;
+ if (v !== undefined && (v.includes('\u0000') || UNPAIRED_SURROGATE_RE.test(v) || (k === 'source' && !oneLine(v)))) throw invalid(`${k} holds a control character or malformed Unicode.`, `Pass ${k} as plain text${k === 'source' ? ' on one line' : ''}.`);
+ }
+ text = [summary, p.detail ?? '', p.source ?? ''].join('');
+ } else {
+ if (typeof p.to !== 'string' || !p.to.trim()) throw invalid('to is required: the page the link points to.', 'Pass the slug of the page the link points to as to.');
+ const linkType = (p.link_type as string | undefined) ?? '';
+ if (linkType) {
+ const { loadActivePackForWriteVocabulary, packDeclaresLinkType, undeclaredLinkTypeMessage, undeclaredLinkTypeSuggestion } = await import('../schema-pack/write-vocabulary.ts');
+ const pack = await loadActivePackForWriteVocabulary(ctx);
+ if (pack && !packDeclaresLinkType(pack, linkType)) throw opError('invalid_params', undeclaredLinkTypeMessage(linkType, pack, 'memory_propose'), undeclaredLinkTypeSuggestion(pack));
+ }
+ const { primeRelationSemantics } = await import('../link-semantics-pack.ts');
+ await primeRelationSemantics(ctx.engine);
+ const { validateLinkDates } = await import('./links.ts');
+ validateLinkDates(ctx, p, linkType);
+ if (p.context !== undefined && !oneLine(p.context as string)) throw invalid('context must be one line of text.', 'Pass context without line breaks or control characters.');
+ text = (p.context as string | undefined) ?? '';
+ }
+ if (text.length > limits.maxPayloadChars) {
+ throw opError('invalid_params', `The proposal's text is ${text.length} characters; the cap is ${limits.maxPayloadChars}.`,
+ `Shorten ${kind === 'timeline' ? 'summary, detail and source' : 'context'} to ${limits.maxPayloadChars} characters together; nothing was saved.`, { reason: 'proposal_too_large' });
+ }
+ const { enforceClientSlugFence, requireWritablePage, validatePageSlug } = await import('./context.ts');
+ validatePageSlug(target);
+ enforceClientSlugFence(ctx, target, 'memory_propose');
+ const sourceId = pageMutationSource(ctx, {}, 'memory_propose');
+ const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation, archived FROM sources WHERE id=$1', [sourceId]);
+ if (!source || source.archived) throw opError('source_changed', 'The write source is not active.', `Source ${sourceId} is archived or not registered, so nothing was saved.`);
+ const operation = kind === 'timeline' ? 'add_timeline_entry' as const : 'add_link' as const;
+ const to = kind === 'link' ? String(p.to).trim().toLowerCase() : null;
+ await requireWritablePage({ ...ctx, sourceId }, target, 'memory_propose', kind === 'link' ? 'from' : 'page');
+ if (to) { validatePageSlug(to); await requireWritablePage({ ...ctx, sourceId }, to, 'memory_propose', 'to'); }
+ const { submissionAuthority } = await import('../persistence/authority.ts');
+ const authority = await submissionAuthority({ ...ctx, attestedOp: 'memory_propose' }, operation, sourceId, String(source.incarnation), target);
+ if (to && !await linkTargetReadable(ctx.engine, authority, sourceId, to)) {
+ const { pageNotVisibleError } = await import('../persistence/page-visibility.ts');
+ throw pageNotVisibleError();
+ }
+ const snapshot = await ctx.engine.readPageSnapshot(target, { sourceId });
+ if (typeof p.expected_revision === 'string' && p.expected_revision !== snapshot?.revision) {
+ throw opError('invalid_params', `${target} changed since the revision shown to the person.`,
+ 'Show the person the page again (get_page) and propose against its current revision; nothing was saved.', { reason: 'proposal_revision_changed' });
+ }
+ if (ctx.dryRun) return { dry_run: true, action: 'memory_propose', kind, target };
+ // OV4: the published provenance names the member; the external id stays on the proposal row, read by the owner.
+ const note = `${PROPOSAL_LINK_SOURCE}; member:${actor.member}; approved by owner`;
+ const payload: Record<string, unknown> = kind === 'timeline'
+ ? { slug: target, date: p.date, summary: (p.summary as string).trim(), ...(p.detail !== undefined ? { detail: p.detail } : {}), source: p.source ? `${note}; ${p.source}` : note }
+ : { slug: target, to, link_type: (p.link_type as string | undefined) ?? '', link_source: PROPOSAL_LINK_SOURCE, context: p.context ? `${p.context} (${note})` : note,
+ ...(p.valid_from !== undefined ? { valid_from: p.valid_from } : {}), ...(p.valid_until !== undefined ? { valid_until: p.valid_until } : {}) };
+ const { row, created } = await insertProposal(ctx.engine, { principal, requestId, actor, sourceId, sourceIncarnation: String(source.incarnation), kind, operation,
+ slug: target, toSlug: to, payload, digest, expectedRevision: snapshot?.revision ?? null, authority }, limits);
+ if (!created) return replay(row);
+ return { status: 'awaiting_owner', request_id: row.request_id, kind, target, expires_at: row.expires_at, text: `Proposal held for the brain owner's approval until ${row.expires_at}.` };
+ },
+};
+
/**
* A successful memory_recall or memory_write result as QM reads it: the model's text alone in `content` (notices stay
* in `_meta.gbrain_notices`, so memory_recall's text stays within max_chars) and the result in `structuredContent`.
@@ -312,7 +447,7 @@ const memory_write: Operation = {
* refusals carry it, so QM classifies every error from structuredContent. Dry runs and every other tool pass through.
*/
export function qmMemoryToolResult<T extends { content: Array<{ type: 'text'; text: string }>; isError?: boolean; structuredContent?: Record<string, unknown> }>(name: string, out: T): T {
- if (!QM_MEMORY_OPS.has(name)) return out;
+ if (!QM_MEMORY_OPS.has(name) && name !== 'memory_propose') return out;
let result: unknown;
try { result = JSON.parse(out.content[0]?.text ?? ''); } catch { return out; }
if (out.isError) {
@@ -330,4 +465,4 @@ export function unlinkedRecallResult(): { content: Array<{ type: 'text'; text: s
return { content: [{ type: 'text', text: '' }], structuredContent: { facts: [], truncated: false, code: 'actor_unlinked' } };
}
-export const qmMemoryOperations: Operation[] = [memory_recall, memory_write];
+export const qmMemoryOperations: Operation[] = [memory_recall, memory_write, memory_propose];
diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.ts
index 72e0bca21b..490b26032a 100644
--- a/src/core/ops/timeline.ts
+++ b/src/core/ops/timeline.ts
@@ -8,7 +8,7 @@ import { MERGE_PRECONDITION_PARAMS, WRITE_REQUEST_PARAM } from '../persistence/p
* (cycle).
*/
-import { opError, type Operation } from './contract.ts';
+import { opError, type Operation, type OperationContext } from './contract.ts';
import { opTransport } from './op-fix.ts';
import { readPolicyOpts } from './context.ts';
import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';
@@ -22,6 +22,23 @@ import {
// --- Timeline ---
+/**
+ * A timeline date: a strict YYYY-MM-DD with year 1900-2199 and a real calendar day. PG DATE accepts year 5874897
+ * silently, a semantic bug nobody wants. Shared by add_timeline_entry and memory_propose, which checks it before
+ * anything is held.
+ */
+export function assertTimelineDate(ctx: Pick<OperationContext, 'transport' | 'remote'>, value: unknown): void {
+ const date = String(value);
+ const badDate = (message: string) => opError('invalid_params', message,
+ `Nothing was written. Pass ${opTransport(ctx) === 'cli' ? 'the date argument' : '`date`'} as a strict YYYY-MM-DD calendar date (year 1900-2199), for example 2026-04-03.`);
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw badDate(`Invalid date format "${date}" (expected YYYY-MM-DD)`);
+ const [y, m, d] = date.split('-').map(Number);
+ if (y < 1900 || y > 2199 || m < 1 || m > 12 || d < 1 || d > 31) throw badDate(`Invalid date "${date}" (year 1900-2199, month 1-12, day 1-31)`);
+ // Round-trip through Date to catch e.g. Feb 30.
+ const parsed = new Date(date);
+ if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) throw badDate(`Invalid calendar date "${date}"`);
+}
+
const add_timeline_entry: Operation = {
name: 'add_timeline_entry',
@@ -47,24 +64,7 @@ const add_timeline_entry: Operation = {
enforceSubagentSlugFence(ctx, p.slug as string, 'add_timeline_entry');
enforceClientSlugFence(ctx, p.slug as string, 'add_timeline_entry');
if (ctx.dryRun) return { dry_run: true, action: 'add_timeline_entry', slug: p.slug };
- const date = p.date as string;
- const badDate = (message: string) => opError('invalid_params', message,
- `Nothing was written. Pass ${opTransport(ctx) === 'cli' ? 'the date argument' : '`date`'} as a strict YYYY-MM-DD calendar date (year 1900-2199), for example 2026-04-03.`);
- // Reject anything that isn't a strict YYYY-MM-DD with year 1900-2199 and
- // a real calendar day. PG DATE accepts year 5874897 silently — that's a
- // semantic bug nobody actually wants.
- if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
- throw badDate(`Invalid date format "${date}" (expected YYYY-MM-DD)`);
- }
- const [y, m, d] = date.split('-').map(Number);
- if (y < 1900 || y > 2199 || m < 1 || m > 12 || d < 1 || d > 31) {
- throw badDate(`Invalid date "${date}" (year 1900-2199, month 1-12, day 1-31)`);
- }
- // Round-trip through Date to catch e.g. Feb 30.
- const parsed = new Date(date);
- if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
- throw badDate(`Invalid calendar date "${date}"`);
- }
+ assertTimelineDate(ctx, p.date);
// #8377: an entry an agent copied out of a quoted read (get_timeline, chronicle) is stored without the fence, so its replay key matches; #8384: its source too.
const unquote = (v: unknown) => typeof v === 'string' && ctx.remote !== false ? unquoteTranscriptText(v, String(p.slug).toLowerCase()) : v;
return submitPageMutation(ctx, { operation: 'add_timeline_entry', params: { ...p, summary: unquote(p.summary), ...(p.detail !== undefined ? { detail: unquote(p.detail) } : {}), ...(p.source !== undefined ? { source: unquote(p.source) } : {}) } });
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 6af992e567..e08cdcc665 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -21,6 +21,7 @@ import { laneClaim, laneOf, laneRoots, laneTask } from './sync-lanes.ts';
import { runPersistenceEffects } from './effects.ts';
import { settleNoopEmbeddingEffects, type NoopSettleCursor } from './embedding-noop-settle.ts';
import { runCompactionPass } from './compaction-pass.ts';
+import { runMemoryProposalUpkeep } from './memory-proposals.ts';
import { claimHousekeepingTurn, completeHousekeepingTurn, housekeepingIntervalMs } from './housekeeping-turn.ts';
import { currentEmbeddingSignature } from '../embedding.ts';
import { isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
@@ -615,6 +616,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));
// F4b: idle maintenance also refreshes stale PGLite planner statistics (a no-op on Postgres).
this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(yieldToEventLoop).then(() => maybeRefreshPlannerStats(this.engine, 'idle'))
+ .then(yieldToEventLoop).then(() => runMemoryProposalUpkeep(this.engine).catch(error => this.report(error)))
.catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });
}
return;
@@ -653,6 +655,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
this.publishedSinceMaintenance = 0;
this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice })
.then(yieldToEventLoop).then(() => sweepSegmentStorage(this.engine).catch(error => this.report(error)))
+ .then(yieldToEventLoop).then(() => runMemoryProposalUpkeep(this.engine).catch(error => this.report(error)))
.then(yieldToEventLoop).then(() => vacuumPersistenceQueues(this.engine))
.then(rows => { this.maintenanceVolume = 50 + Math.ceil(rows * 0.2); }).catch(error => this.report(error))
.finally(() => { this.maintenanceWorker = undefined; });
diff --git a/src/core/persistence/control.ts b/src/core/persistence/control.ts
index b5d7f50681..1a20248521 100644
--- a/src/core/persistence/control.ts
+++ b/src/core/persistence/control.ts
@@ -24,7 +24,7 @@ export async function listWriteRequests(engine: BrainEngine, principal: Principa
WHERE length(p.prefix)>0 AND (CASE WHEN right(p.prefix,1)='/'
THEN left(lower(r.slug),length(p.prefix))=p.prefix
ELSE lower(r.slug)=p.prefix OR left(lower(r.slug),length(p.prefix)+1)=p.prefix||'/' END)))
- AND ($7::text[] IS NULL OR r.operation=ANY($7::text[]))
+ AND ($7::text[] IS NULL OR COALESCE(r.authority->>'attestedOp', r.operation)=ANY($7::text[]))
AND ($8::text[] IS NULL OR EXISTS (SELECT 1 FROM unnest($8::text[]) AS a(pattern)
WHERE CASE WHEN right(a.pattern,2)='/*' THEN left(r.slug,length(a.pattern)-1)=left(a.pattern,length(a.pattern)-1)
ELSE r.slug=a.pattern END))
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index a6c4d0f167..a41de645d3 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -98,6 +98,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('mcp_request_log', 'operational', 'MCP request log.'),
carry('mcp_spend_log', 'operational', 'MCP spend log.'),
carry('mcp_spend_reservations', 'operational', 'Pending and unresolved MCP charges; admission counts them and late settlement needs them.'),
+ carry('memory_proposals', 'user_data', 'Held QM proposals awaiting owner review and their closed outcomes until retention; replays and receipts read them.'),
carry('mention_gazetteer_entries', 'operational', 'Entity mention index: the linkable names the last mention pass used per source; a name change rescans only affected pages.'),
carry('mention_index_status', 'operational', 'Entity mention index: per-source pass state, generation and coverage the entity card reports.'),
carry('migration_impact_log', 'operational', 'Remediation impact log.'),
diff --git a/src/core/persistence/manual-links.ts b/src/core/persistence/manual-links.ts
index 1bfe002b0d..35ae2de480 100644
--- a/src/core/persistence/manual-links.ts
+++ b/src/core/persistence/manual-links.ts
@@ -39,6 +39,13 @@ export async function prepareManualLinkMutation(engine: BrainEngine, row: WriteR
const snapshot = (await wholeBodySnapshot(engine, stored, row.operation))!;
const section = linksFenceSection(snapshot.page);
const to = String(p.to).toLowerCase();
+ // GST-1158 OV3: a proposed link publishes only while its target exists and the person it was proposed for may read it,
+ // so a page deleted or turned private after the owner's yes never lands in a shared Links fence.
+ if (row.operation === 'add_link' && row.authority?.attestedOp === 'memory_propose'
+ && !await (await import('./memory-proposals.ts')).linkTargetReadable(engine, row.authority, row.source_id, to)) {
+ throw opError('page_not_found', `The link target ${to} was removed or is no longer readable by the person this link was proposed for.`,
+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} changed nothing; a new proposal is needed if the link is still wanted.`);
+ }
const linkType = optional(p.link_type), linkSource = optional(p.link_source);
const validFrom = optional(p.valid_from), validUntil = optional(p.valid_until);
let body: string;
diff --git a/src/core/persistence/memory-proposals.ts b/src/core/persistence/memory-proposals.ts
new file mode 100644
index 0000000000..cac36e7ada
--- /dev/null
+++ b/src/core/persistence/memory-proposals.ts
@@ -0,0 +1,367 @@
+/**
+ * GST-1158 memory_propose (GBRA-284): QM's held writes, a timeline entry or a typed link it proposes for the person it
+ * attests, waiting in memory_proposals (v287) for the brain owner's yes. Nothing here is page content and nothing here
+ * reaches git, an export or a recall: on approval the write is admitted into the persistence journal under the
+ * proposal's stored authority, in the same transaction that marks the proposal approved (the failed-writes replay seam,
+ * replayAuthority), and published through the normal writer door. One request id names the proposal and the write.
+ *
+ * States: awaiting_owner until the owner approves (approved: a journal row now carries the write), denies (denied, with
+ * the owner's reason), the TTL passes (expired), the proposer cancels (cancelled), or the approval checks refuse it
+ * (failed: the person was unlinked, the attest right or grant revoked, the page gone; conflict: the page or the link
+ * target changed while it waited). Every closed row is purged after the retention window.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { uuidV5 } from './preconditions.ts';
+import { sha256 } from './digest.ts';
+import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';
+import { principalKey } from './model.ts';
+
+export const PROPOSAL_STATES = ['awaiting_owner', 'approved', 'denied', 'expired', 'cancelled', 'failed', 'conflict'] as const;
+export type ProposalState = typeof PROPOSAL_STATES[number];
+export const PROPOSAL_KINDS = ['timeline', 'link'] as const;
+export type ProposalKind = typeof PROPOSAL_KINDS[number];
+/** Namespace of the per-member proposal request-id namespaces. Changing it orphans every held proposal's receipt. */
+export const QM_PROPOSE_REQUEST_NAMESPACE = '0c4f1d7e-93a2-4b6c-8e15-7a9d2f3b6c41';
+/** The link_source every proposed link publishes with. */
+export const PROPOSAL_LINK_SOURCE = 'qm-proposal';
+/** How soon a proposer polls an awaiting_owner proposal (or its expiry, when sooner). */
+export const PROPOSAL_RETRY_AFTER_MS = 300_000;
+/** Approval checks whose refusal closes a proposal: failed (the person or the grant) and conflict (the target moved). */
+const FAILED_CODES = new Set(['actor_unlinked', 'actor_not_attested', 'permission_denied', 'page_not_found', 'source_changed']);
+
+export interface ProposalLimits {
+ ttlHours: number; maxPendingPerActor: number; maxPendingPerCredential: number; retentionDays: number; maxPayloadChars: number; maxReasonChars: number;
+}
+/** Operator-tunable (gbrain config set proposals.<key>), each clamped to its range; the payload and reason caps only go down. */
+export const PROPOSAL_LIMIT_KEYS: Record<keyof ProposalLimits, { key: string; min: number; max: number; default: number }> = {
+ ttlHours: { key: 'proposals.ttl_hours', min: 1, max: 720, default: 168 },
+ maxPendingPerActor: { key: 'proposals.max_pending_per_actor', min: 1, max: 1000, default: 10 },
+ maxPendingPerCredential: { key: 'proposals.max_pending_per_credential', min: 1, max: 10_000, default: 50 },
+ retentionDays: { key: 'proposals.retention_days', min: 1, max: 365, default: 30 },
+ maxPayloadChars: { key: 'proposals.max_payload_chars', min: 100, max: 1000, default: 1000 },
+ maxReasonChars: { key: 'proposals.max_reason_chars', min: 1, max: 500, default: 500 },
+};
+
+export async function readProposalLimits(engine: Pick<BrainEngine, 'getConfig'>): Promise<ProposalLimits> {
+ const entries = await Promise.all(Object.entries(PROPOSAL_LIMIT_KEYS).map(async ([name, spec]) => {
+ const raw = await engine.getConfig(spec.key).catch(() => null);
+ const value = raw === null || raw === undefined || String(raw).trim() === '' ? NaN : Number(raw);
+ return [name, Number.isInteger(value) && value >= spec.min && value <= spec.max ? value : spec.default] as const;
+ }));
+ return Object.fromEntries(entries) as unknown as ProposalLimits;
+}
+
+export interface MemoryProposal {
+ principal_kind: string; principal_id: string; request_id: string; system: string; external_id: string; member_id: string;
+ source_id: string; source_incarnation: string; kind: ProposalKind; operation: 'add_timeline_entry' | 'add_link'; slug: string; to_slug: string | null;
+ payload: Record<string, unknown> | null; payload_digest: string; expected_revision: string | null; authority: WriteAuthority; state: ProposalState;
+ reason: string | null; error_code: string | null; decided_by: string | null; decided_at: string | null; created_at: string; updated_at: string; expires_at: string;
+}
+
+const iso = (value: unknown): string | null => value === null || value === undefined ? null : new Date(value as string).toISOString();
+const parsed = <T>(value: unknown): T => (typeof value === 'string' ? JSON.parse(value) : value) as T;
+function normalize(row: Record<string, unknown>): MemoryProposal {
+ return { ...row, request_id: String(row.request_id), source_incarnation: String(row.source_incarnation),
+ payload: row.payload === null ? null : parsed(row.payload), authority: parsed(row.authority),
+ decided_at: iso(row.decided_at), created_at: iso(row.created_at)!, updated_at: iso(row.updated_at)!, expires_at: iso(row.expires_at)! } as MemoryProposal;
+}
+
+/** The request id of a proposal: uuidv5 of the key under the member's own proposal namespace, so a key never crosses members or collides with a memory_write. */
+export function proposalRequestId(member: string, idempotencyKey: string): string {
+ return uuidV5(uuidV5(QM_PROPOSE_REQUEST_NAMESPACE, `member:${member}`), idempotencyKey);
+}
+
+/** Replay identity: only the fields the caller sent. */
+export function proposalDigest(sent: Record<string, unknown>): string {
+ return sha256(JSON.stringify(Object.keys(sent).sort().filter(k => sent[k] !== undefined).map(k => [k, sent[k]])));
+}
+
+export async function getProposal(engine: SqlEngine, principal: Principal, requestId: string): Promise<MemoryProposal | null> {
+ const [row] = await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT * FROM memory_proposals WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid', [principal.kind, principal.id, requestId]);
+ return row ? normalize(row) : null;
+}
+
+const proposalNotFound = (requestId: string) => opError('not_found', `No memory proposal has request id ${requestId}.`,
+ 'List the proposals awaiting a decision with gbrain memory-proposals list, and pass one of their request ids.');
+
+/** The proposal an owner names by request id. Two credentials could only share one by colliding uuidv5 namespaces; that is refused, never guessed. */
+export async function ownerProposal(engine: SqlEngine, requestId: string): Promise<MemoryProposal> {
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(requestId)) throw proposalNotFound(requestId);
+ const rows = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM memory_proposals WHERE request_id=$1::uuid LIMIT 2', [requestId]);
+ if (!rows.length) throw proposalNotFound(requestId);
+ if (rows.length > 1) throw opError('invalid_params', `Request id ${requestId} names proposals from two credentials.`,
+ 'Decide each from its credential\'s list (gbrain memory-proposals list --json shows principal_kind and principal_id).');
+ return normalize(rows[0]!);
+}
+
+export const proposalClosedError = (row: Pick<MemoryProposal, 'request_id' | 'state'>) => opError('proposal_closed',
+ `Proposal ${row.request_id} is ${row.state}; only a proposal awaiting the owner can be approved or denied.`,
+ 'Nothing changed. gbrain memory-proposals show <request_id> shows how it ended; the proposer sends a new proposal if the change is still wanted.');
+export const proposalExpiredError = (row: Pick<MemoryProposal, 'request_id'>) => opError('proposal_expired',
+ `Proposal ${row.request_id} expired before a decision.`,
+ 'Nothing was written. The proposer sends a new proposal if the change is still wanted; proposals.ttl_hours sets how long one waits.');
+
+export interface NewProposal {
+ principal: Principal; requestId: string; actor: { system: string; external_id: string; member: string }; sourceId: string; sourceIncarnation: string;
+ kind: ProposalKind; operation: 'add_timeline_entry' | 'add_link'; slug: string; toSlug: string | null; payload: Record<string, unknown>; digest: string;
+ expectedRevision: string | null; authority: WriteAuthority;
+}
+
+/**
+ * Inserts a proposal under the caps, or returns the existing row for its request id (the caller compares digests).
+ * One advisory lock per credential serializes its inserts, so concurrent calls never pass either cap; the credential's
+ * overdue rows are expired first in the same transaction, so a stale row never holds a slot.
+ */
+export async function insertProposal(engine: BrainEngine, input: NewProposal, limits: ProposalLimits): Promise<{ row: MemoryProposal; created: boolean }> {
+ return engine.transaction(async tx => {
+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [`memory_proposals:${principalKey(input.principal)}`]);
+ const [existing] = await tx.executeRaw<Record<string, unknown>>(
+ 'SELECT * FROM memory_proposals WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid', [input.principal.kind, input.principal.id, input.requestId]);
+ if (existing) return { row: normalize(existing), created: false };
+ await tx.executeRaw(`UPDATE memory_proposals SET state='expired', reason=$3, decided_by='gbrain:expiry', decided_at=now(), updated_at=now()
+ WHERE principal_kind=$1 AND principal_id=$2 AND state='awaiting_owner' AND expires_at<=now()`,
+ [input.principal.kind, input.principal.id, expiryReason(limits)]);
+ const [counts] = await tx.executeRaw<{ actor: number | string; credential: number | string }>(`SELECT count(*) FILTER (WHERE member_id=$3) AS actor, count(*) AS credential
+ FROM memory_proposals WHERE principal_kind=$1 AND principal_id=$2 AND state='awaiting_owner' AND expires_at>now()`,
+ [input.principal.kind, input.principal.id, input.actor.member]);
+ const actor = Number(counts?.actor ?? 0), credential = Number(counts?.credential ?? 0);
+ if (actor >= limits.maxPendingPerActor) throw pendingLimit('actor', actor, limits.maxPendingPerActor);
+ if (credential >= limits.maxPendingPerCredential) throw pendingLimit('credential', credential, limits.maxPendingPerCredential);
+ const [row] = await tx.executeRaw<Record<string, unknown>>(`INSERT INTO memory_proposals (principal_kind, principal_id, request_id, system, external_id,
+ member_id, source_id, source_incarnation, kind, operation, slug, to_slug, payload, payload_digest, expected_revision, authority, expires_at)
+ VALUES ($1,$2,$3::uuid,$4,$5,$6,$7,$8::uuid,$9,$10,$11,$12,$13::text::jsonb,$14,$15,$16::text::jsonb, now() + ($17::integer * interval '1 hour'))
+ RETURNING *`,
+ [input.principal.kind, input.principal.id, input.requestId, input.actor.system, input.actor.external_id, input.actor.member, input.sourceId,
+ input.sourceIncarnation, input.kind, input.operation, input.slug, input.toSlug, JSON.stringify(input.payload), input.digest, input.expectedRevision,
+ JSON.stringify(input.authority), limits.ttlHours]);
+ return { row: normalize(row!), created: true };
+ });
+}
+
+function pendingLimit(scope: 'actor' | 'credential', pending: number, cap: number): OperationError {
+ return opError('proposals_pending_limit', `${pending} proposals already await the owner for this ${scope === 'actor' ? 'person' : 'credential'} (cap ${cap}).`,
+ 'Nothing was saved. Wait for the owner to decide or for a proposal to expire, or cancel one with cancel_write_request; the operator sets the cap (proposals.max_pending_per_' + (scope === 'actor' ? 'actor' : 'credential') + ').',
+ { reason: scope });
+}
+
+const expiryReason = (limits: ProposalLimits) => `No owner decision within ${limits.ttlHours} hours.`;
+
+/** Closes an awaiting_owner proposal; returns the row as it is afterwards (unchanged when another decision got there first). */
+async function closeProposal(engine: SqlEngine, row: MemoryProposal, state: Exclude<ProposalState, 'awaiting_owner' | 'approved'>,
+ fields: { reason: string | null; code?: string | null; decidedBy: string }): Promise<MemoryProposal> {
+ const [updated] = await engine.executeRaw<Record<string, unknown>>(`UPDATE memory_proposals SET state=$4, reason=$5, error_code=$6, decided_by=$7,
+ decided_at=now(), updated_at=now() WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid AND state='awaiting_owner' RETURNING *`,
+ [row.principal_kind, row.principal_id, row.request_id, state, fields.reason, fields.code ?? null, fields.decidedBy]);
+ if (updated) return normalize(updated);
+ return (await getProposal(engine, { kind: row.principal_kind, id: row.principal_id } as Principal, row.request_id)) ?? row;
+}
+
+async function overdue(engine: SqlEngine, row: MemoryProposal): Promise<boolean> {
+ const [r] = await engine.executeRaw<{ overdue: boolean }>(`SELECT expires_at<=now() AS overdue FROM memory_proposals
+ WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid`, [row.principal_kind, row.principal_id, row.request_id]);
+ return r?.overdue === true;
+}
+
+/** The proposer withdraws an awaiting proposal (cancel_write_request); a closed one is returned as it is. */
+export async function cancelOwnProposal(engine: SqlEngine, row: MemoryProposal): Promise<MemoryProposal> {
+ if (row.state !== 'awaiting_owner') return row;
+ return closeProposal(engine, row, 'cancelled', { reason: 'Cancelled by the proposer.', code: null, decidedBy: 'proposer' });
+}
+
+/**
+ * The upkeep pass (consumer maintenance and the one-shot housekeeping turn): expires overdue proposals, closes awaiting
+ * ones whose stored authority no longer resolves (the person unlinked or disabled, memory_propose or the grant revoked;
+ * OV8: the proposer still reads and cancels them meanwhile), and purges every closed row older than the retention window.
+ */
+export async function runMemoryProposalUpkeep(engine: BrainEngine, opts: { scanLimit?: number } = {}): Promise<{ expired: number; closed: number; purged: number }> {
+ const limits = await readProposalLimits(engine);
+ let expired: unknown[];
+ try {
+ expired = await engine.executeRaw(`UPDATE memory_proposals SET state='expired', reason=$1, decided_by='gbrain:expiry', decided_at=now(), updated_at=now()
+ WHERE state='awaiting_owner' AND expires_at<=now() RETURNING 1`, [expiryReason(limits)]);
+ } catch (error) {
+ const { isMissingSchemaObject } = await import('../utils.ts');
+ if (isMissingSchemaObject(error, 'table', 'memory_proposals')) return { expired: 0, closed: 0, purged: 0 };
+ throw error;
+ }
+ const { authorizeWrite } = await import('./authority.ts');
+ const pending = (await engine.executeRaw<Record<string, unknown>>(`SELECT * FROM memory_proposals WHERE state='awaiting_owner'
+ ORDER BY created_at LIMIT $1`, [opts.scanLimit ?? 200])).map(normalize);
+ let closed = 0;
+ for (const row of pending) {
+ try { await authorizeWrite(engine, row.authority, row.operation, row.slug); } catch (error) {
+ if (!(error instanceof OperationError) || !['actor_unlinked', 'actor_not_attested', 'permission_denied'].includes(error.code)) throw error;
+ const after = await closeProposal(engine, row, 'failed', { reason: error.message, code: error.code, decidedBy: 'gbrain:upkeep' });
+ if (after.state === 'failed') closed++;
+ }
+ }
+ const purged = await engine.executeRaw(`DELETE FROM memory_proposals WHERE state<>'awaiting_owner'
+ AND COALESCE(decided_at, updated_at) <= now() - ($1::integer * interval '1 day') RETURNING 1`, [limits.retentionDays]);
+ return { expired: expired.length, closed, purged: purged.length };
+}
+
+/** What QM reads for a proposal with no journal row (get_write_request, cancel_write_request): never the proposed text. */
+export function proposalReceipt(row: MemoryProposal, now = Date.now()): Record<string, unknown> {
+ const waiting = row.state === 'awaiting_owner';
+ const untilExpiry = Math.max(0, new Date(row.expires_at).getTime() - now);
+ return {
+ request_id: row.request_id, state: row.state, retry_after_ms: waiting ? Math.min(PROPOSAL_RETRY_AFTER_MS, untilExpiry) : null,
+ operation: row.operation, source_id: row.source_id, slug: row.slug,
+ proposal: { kind: row.kind, target: row.slug, ...(row.to_slug ? { to: row.to_slug } : {}), expires_at: row.expires_at },
+ ...(waiting ? {} : { decision: { reason: row.reason, decided_at: row.decided_at } }),
+ ...(row.error_code ? { write_error: row.error_code } : {}),
+ };
+}
+
+type Prepared = { admission: import('./journal.ts').WriteAdmission } | { prior: WriteRequest } | { state: 'failed' | 'conflict'; code: string; reason: string };
+
+/**
+ * The approval checks, re-run on today's state under the proposal's stored authority: the person still linked to the
+ * same enabled member with memory_propose still attested, the live grant, the page still there at the revision QM
+ * showed, a link's target still there and readable by that person, and the write-through decision as the source is
+ * configured now. Returns the admission to commit, or the refusal that closes the proposal.
+ */
+async function prepareApproval(ctx: OperationContext, row: MemoryProposal): Promise<Prepared> {
+ const engine = ctx.engine;
+ const authority = row.authority;
+ const refusal = (error: unknown): Prepared => {
+ if (!(error instanceof OperationError)) throw error;
+ if (FAILED_CODES.has(error.code)) return { state: 'failed', code: error.code, reason: error.message };
+ if (error.code === 'revision_conflict') return { state: 'conflict', code: 'revision_changed', reason: error.message };
+ throw error;
+ };
+ const { parseStoredActor, storedActorIdentity, attestedCallerAccess } = await import('../access/actor.ts');
+ const actor = parseStoredActor(authority.actingFor);
+ if (!actor) return { state: 'failed', code: 'permission_denied', reason: 'The stored attested person is malformed.' };
+ let identity: string[];
+ try { identity = await storedActorIdentity(engine, authority.principal, actor, 'memory_propose'); } catch (error) { return refusal(error); }
+ const { withCallerAccess } = await import('../search/private-visibility.ts');
+ const access = await attestedCallerAccess(engine, actor, identity);
+ return withCallerAccess(access, async (): Promise<Prepared> => {
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot || snapshot.page.deleted_at) return { state: 'failed', code: 'page_not_found', reason: `The target page ${row.slug} no longer exists.` };
+ if (row.expected_revision && snapshot.revision !== row.expected_revision) {
+ return { state: 'conflict', code: 'revision_changed', reason: `${row.slug} changed while the proposal waited; the person should see the page again before proposing.` };
+ }
+ if (row.kind === 'link' && row.to_slug && !await linkTargetReadable(engine, authority, row.source_id, row.to_slug)) {
+ return { state: 'conflict', code: 'link_target_changed', reason: `The link target ${row.to_slug} was removed or is no longer readable by the person it was proposed for.` };
+ }
+ const lane: OperationContext = { ...ctx, auth: undefined, remote: authority.remote, replayAuthority: authority, attestedOp: 'memory_propose',
+ takesHoldersAllowList: [...(authority.takesHolders ?? ['world'])], sourceId: row.source_id };
+ try {
+ const { preparePageAdmission } = await import('./page-mutations.ts');
+ const params: Record<string, unknown> = { ...row.payload, request_id: row.request_id,
+ ...(row.kind === 'timeline' && row.expected_revision ? { expected_revision: row.expected_revision } : {}) };
+ const prepared = await preparePageAdmission(lane, { operation: row.operation, params });
+ return prepared.prior ? { prior: prepared.prior } : { admission: prepared.admission! };
+ } catch (error) { return refusal(error); }
+ });
+}
+
+/** OV3: a proposed link's target exists in the source and the person it was proposed for may still read it. */
+export async function linkTargetReadable(engine: SqlEngine & Pick<BrainEngine, 'readPageSnapshot'>, authority: WriteAuthority, sourceId: string, slug: string): Promise<boolean> {
+ const target = await engine.readPageSnapshot(slug, { sourceId });
+ if (!target || target.page.deleted_at) return false;
+ const { authorizePageVisibility } = await import('./page-visibility.ts');
+ return authorizePageVisibility(engine, authority, slug).then(() => true, () => false);
+}
+
+function publicJournal(row: WriteRequest): Record<string, unknown> {
+ return { request_id: row.request_id, state: row.state, operation: row.operation, source_id: row.source_id, slug: row.slug,
+ ...(row.error_code ? { write_error: row.error_code, write_error_message: row.error_message } : {}) };
+}
+
+/**
+ * The owner's yes: re-runs the approval checks, then in one transaction locks the proposal, admits the write into the
+ * journal under the same request id and marks the proposal approved, so neither commits without the other; then waits
+ * for publication like any write. A refused check closes the proposal failed or conflict with that code. A second
+ * approve after a lost reply returns the same journal receipt.
+ */
+export async function approveMemoryProposal(ctx: OperationContext, requestId: string, opts: { decidedBy: string; waitMs?: number }): Promise<Record<string, unknown>> {
+ const engine = ctx.engine;
+ const row = await ownerProposal(engine, requestId);
+ const principal = { kind: row.principal_kind, id: row.principal_id } as Principal;
+ const { getWriteRequest } = await import('./journal.ts');
+ if (row.state === 'approved') {
+ const written = await getWriteRequest(engine, principal, row.request_id);
+ return { status: 'approved', request_id: row.request_id, decided_at: row.decided_at, ...(written ? { write_request: publicJournal(written) } : {}) };
+ }
+ if (row.state !== 'awaiting_owner') throw proposalClosedError(row);
+ if (await overdue(engine, row)) {
+ if (!ctx.dryRun) await closeProposal(engine, row, 'expired', { reason: expiryReason(await readProposalLimits(engine)), decidedBy: 'gbrain:expiry' });
+ throw proposalExpiredError(row);
+ }
+ const prepared = await prepareApproval(ctx, row);
+ if ('state' in prepared) {
+ if (ctx.dryRun) return { dry_run: true, action: 'approve', request_id: row.request_id, would: prepared.state, error_code: prepared.code, reason: prepared.reason };
+ const closed = await closeProposal(engine, row, prepared.state, { reason: prepared.reason, code: prepared.code, decidedBy: opts.decidedBy });
+ return { status: closed.state, request_id: row.request_id, error_code: closed.error_code, reason: closed.reason };
+ }
+ if (ctx.dryRun) return { dry_run: true, action: 'approve', request_id: row.request_id, would: 'approved' };
+ const { admitWriteInTransaction } = await import('./journal.ts');
+ const { declareDurablePersistence } = await import('./protocol.ts');
+ const outcome = await engine.transaction(async tx => {
+ await declareDurablePersistence(tx);
+ const [locked] = await tx.executeRaw<{ state: string; overdue: boolean }>(`SELECT state, expires_at<=now() AS overdue FROM memory_proposals
+ WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid FOR UPDATE`, [row.principal_kind, row.principal_id, row.request_id]);
+ if (!locked) throw proposalNotFound(row.request_id);
+ if (locked.state !== 'awaiting_owner') return { closed: locked.state } as const;
+ if (locked.overdue) return { expired: true } as const;
+ const written = 'prior' in prepared ? prepared.prior : await admitWriteInTransaction(tx, prepared.admission);
+ await tx.executeRaw(`UPDATE memory_proposals SET state='approved', decided_by=$4, decided_at=now(), updated_at=now()
+ WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid`, [row.principal_kind, row.principal_id, row.request_id, opts.decidedBy]);
+ return { written } as const;
+ });
+ if ('closed' in outcome) throw proposalClosedError({ request_id: row.request_id, state: outcome.closed as ProposalState });
+ if ('expired' in outcome) {
+ await closeProposal(engine, row, 'expired', { reason: expiryReason(await readProposalLimits(engine)), decidedBy: 'gbrain:expiry' });
+ throw proposalExpiredError(row);
+ }
+ const { waitForWrite } = await import('./service.ts');
+ const settled = await waitForWrite(engine, outcome.written, ctx.config, opts.waitMs ?? 5000);
+ return { status: 'approved', request_id: row.request_id, write_request: publicJournal(settled) };
+}
+
+/** The owner's no, with a reason (1 to proposals.max_reason_chars characters). */
+export async function denyMemoryProposal(ctx: OperationContext, requestId: string, rawReason: unknown, opts: { decidedBy: string }): Promise<Record<string, unknown>> {
+ const limits = await readProposalLimits(ctx.engine);
+ const reason = typeof rawReason === 'string' ? rawReason.trim() : '';
+ if (!reason || reason.length > limits.maxReasonChars) {
+ throw opError('invalid_params', `A denial needs a reason of 1 to ${limits.maxReasonChars} characters.`, 'Pass --reason "<why>"; the proposer reads it on the receipt.');
+ }
+ const row = await ownerProposal(ctx.engine, requestId);
+ if (row.state !== 'awaiting_owner') throw proposalClosedError(row);
+ if (await overdue(ctx.engine, row)) {
+ if (!ctx.dryRun) await closeProposal(ctx.engine, row, 'expired', { reason: expiryReason(limits), decidedBy: 'gbrain:expiry' });
+ throw proposalExpiredError(row);
+ }
+ if (ctx.dryRun) return { dry_run: true, action: 'deny', request_id: row.request_id, would: 'denied' };
+ const after = await closeProposal(ctx.engine, row, 'denied', { reason, decidedBy: opts.decidedBy });
+ if (after.state !== 'denied') throw proposalClosedError(after);
+ 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[]> {
+ 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))]);
+ return rows.map(normalize);
+}
+
+/** Pending count and the oldest pending proposal's age, for doctor and status; zero on a schema that predates v287. */
+export async function pendingProposalSummary(engine: SqlEngine): Promise<{ pending: number; oldest_hours: number | null }> {
+ try {
+ const [row] = await engine.executeRaw<{ n: number | string; oldest: number | string | null }>(`SELECT count(*) AS n,
+ EXTRACT(EPOCH FROM now() - min(created_at)) / 3600 AS oldest FROM memory_proposals WHERE state='awaiting_owner' AND expires_at>now()`);
+ const pending = Number(row?.n ?? 0);
+ return { pending, oldest_hours: pending && row?.oldest !== null && row?.oldest !== undefined ? Math.floor(Number(row.oldest)) : null };
+ } catch (error) {
+ const { isMissingSchemaObject } = await import('../utils.ts');
+ if (isMissingSchemaObject(error, 'table', 'memory_proposals')) return { pending: 0, oldest_hours: null };
+ throw error;
+ }
+}
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 1cc03f5078..7f0d6e1be8 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 286;
+export const LATEST_SCHEMA_VERSION = 287;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 7bb4dcc090..6760e4b0d3 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -287,6 +287,7 @@ import { v283 } from './v283-folder-access-rules.ts';
import { v284 } from './v284-access-page-indexes.ts';
import { v285 } from './v285-slug-rename-history.ts';
import { v286 } from './v286-qm-actor-links.ts';
+import { v287 } from './v287-memory-proposals.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -572,4 +573,5 @@ export const MIGRATIONS: Migration[] = [
v284,
v285,
v286,
+ v287,
];
diff --git a/src/core/schema-migrations/v287-memory-proposals.ts b/src/core/schema-migrations/v287-memory-proposals.ts
new file mode 100644
index 0000000000..5081366aa4
--- /dev/null
+++ b/src/core/schema-migrations/v287-memory-proposals.ts
@@ -0,0 +1,62 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GST-1158 memory_propose (GBRA-284): QM's held writes. One row per proposed
+// timeline entry or link, keyed like a write receipt (principal, request_id),
+// waiting for the brain owner's yes. Nothing here is page content: an
+// approved proposal is admitted into persistence_requests in the same
+// transaction and published through the normal writer door, so git (where a
+// repo exists) never sees unapproved text. Every closed row (approved,
+// denied, expired, cancelled, failed, conflict) is purged after the retention
+// window (proposals.retention_days). Database only, so a repo-less brain gets
+// it unchanged. No schema.sql mirror: like v282, v283 and v286, it exists only
+// through migrations. Numbered when its PR takes the merge slot.
+export const v287: Migration = {
+ version: 287,
+ name: 'memory_proposals',
+ idempotent: true,
+ sql: `
+CREATE TABLE IF NOT EXISTS memory_proposals (
+ principal_kind TEXT NOT NULL,
+ principal_id TEXT NOT NULL,
+ request_id UUID NOT NULL,
+ system TEXT NOT NULL,
+ external_id TEXT NOT NULL,
+ member_id TEXT NOT NULL,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ source_incarnation UUID NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('timeline', 'link')),
+ operation TEXT NOT NULL CHECK (operation IN ('add_timeline_entry', 'add_link')),
+ slug TEXT NOT NULL,
+ to_slug TEXT,
+ payload JSONB,
+ payload_digest TEXT NOT NULL,
+ expected_revision TEXT,
+ authority JSONB NOT NULL,
+ state TEXT NOT NULL DEFAULT 'awaiting_owner'
+ CHECK (state IN ('awaiting_owner', 'approved', 'denied', 'expired', 'cancelled', 'failed', 'conflict')),
+ reason TEXT,
+ error_code TEXT,
+ decided_by TEXT,
+ decided_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ expires_at TIMESTAMPTZ NOT NULL,
+ PRIMARY KEY (principal_kind, principal_id, request_id)
+);
+CREATE INDEX IF NOT EXISTS memory_proposals_request_idx ON memory_proposals (request_id);
+CREATE INDEX IF NOT EXISTS memory_proposals_pending_actor_idx ON memory_proposals (principal_kind, principal_id, member_id, expires_at)
+ WHERE state = 'awaiting_owner';
+CREATE INDEX IF NOT EXISTS memory_proposals_pending_source_idx ON memory_proposals (source_id, created_at)
+ WHERE state = 'awaiting_owner';
+CREATE INDEX IF NOT EXISTS memory_proposals_closed_idx ON memory_proposals (decided_at)
+ WHERE state <> 'awaiting_owner';
+DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN
+ ALTER TABLE memory_proposals ENABLE ROW LEVEL SECURITY;
+ END IF;
+END $rls$;
+`,
+};
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index faa5a94caa..437b50de84 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -120,6 +120,7 @@
" compile-context --target <t> Compile a deterministic, scanned, budgeted context",
" [--budget N] [--check] file (claude-code | codex | openclaw)",
" decide <status|probe|enable|...> System One decision support (Jev); every slot off by default",
+ " memory-proposals list|show|approve|deny QM's proposed timeline entries and links awaiting your decision",
" facts relink [--dry-run] Link facts saved without an entity to the entity they name",
" check-resolvable [--json] [--fix] Validate skill tree (reachability/MECE/DRY)",
" report --type <name> --content ... Save timestamped report to brain/reports/",
@@ -348,6 +349,7 @@
" compile-context --target <t> Compile a deterministic, scanned, budgeted context",
" [--budget N] [--check] file (claude-code | codex | openclaw)",
" decide <status|probe|enable|...> System One decision support (Jev); every slot off by default",
+ " memory-proposals list|show|approve|deny QM's proposed timeline entries and links awaiting your decision",
" facts relink [--dry-run] Link facts saved without an entity to the entity they name",
" check-resolvable [--json] [--fix] Validate skill tree (reachability/MECE/DRY)",
" report --type <name> --content ... Save timestamped report to brain/reports/",
@@ -576,6 +578,7 @@
" compile-context --target <t> Compile a deterministic, scanned, budgeted context",
" [--budget N] [--check] file (claude-code | codex | openclaw)",
" decide <status|probe|enable|...> System One decision support (Jev); every slot off by default",
+ " memory-proposals list|show|approve|deny QM's proposed timeline entries and links awaiting your decision",
" facts relink [--dry-run] Link facts saved without an entity to the entity they name",
" check-resolvable [--json] [--fix] Validate skill tree (reachability/MECE/DRY)",
" report --type <name> --content ... Save timestamped report to brain/reports/",
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 59c0a17a68..f60d7276ca 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 269480,
- "stdoutSha256": "a5efd152d5b57d8cab862c842421d4b321090631a5c72139cc5d1195e2849563",
+ "stdoutBytes": 272301,
+ "stdoutSha256": "c3d3b8b5c69b60ac1c9f014ba7323d2be0905cd0df259baaa7f2ac834b10105e",
"toolNames": [
"remember",
"entity",
@@ -158,6 +158,7 @@
"unpurge_page",
"memory_recall",
"memory_write",
+ "memory_propose",
"find_contradictions",
"find_experts",
"find_trajectory",
@@ -7227,6 +7228,101 @@
},
"scope": "write"
},
+ {
+ "description": "Propose one timeline entry or link on a shared page for the person this call serves; the brain owner approves it before it is written. Needs an attested person. Poll get_write_request with the request_id; the same idempotency_key replays.",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": true,
+ "name": "memory_propose",
+ "parameters": {
+ "acting_user": "string?",
+ "context": "string?",
+ "date": "string?",
+ "detail": "string?",
+ "expected_revision": "string?",
+ "idempotency_key": "string",
+ "kind": "string",
+ "link_type": "string?",
+ "source": "string?",
+ "summary": "string?",
+ "target": "string",
+ "to": "string?",
+ "valid_from": "string?",
+ "valid_until": "string?"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "acting_user": {
+ "description": "Set by the trusted system: equal to the x-qm-actor header, or omit.",
+ "type": "string"
+ },
+ "context": {
+ "description": "link: context.",
+ "type": "string"
+ },
+ "date": {
+ "description": "timeline: YYYY-MM-DD.",
+ "type": "string"
+ },
+ "detail": {
+ "description": "timeline: details.",
+ "type": "string"
+ },
+ "expected_revision": {
+ "description": "The revision shown to the person; refused when the page moved.",
+ "type": "string"
+ },
+ "idempotency_key": {
+ "description": "1-128 visible ASCII characters; the same key replays this proposal.",
+ "type": "string"
+ },
+ "kind": {
+ "description": "timeline (date, summary) or link (to).",
+ "enum": [
+ "timeline",
+ "link"
+ ],
+ "type": "string"
+ },
+ "link_type": {
+ "description": "link: a type the schema pack declares.",
+ "type": "string"
+ },
+ "source": {
+ "description": "timeline: where it came from.",
+ "type": "string"
+ },
+ "summary": {
+ "description": "timeline: one line.",
+ "type": "string"
+ },
+ "target": {
+ "description": "Slug the write lands on (a link's from page).",
+ "type": "string"
+ },
+ "to": {
+ "description": "link: the page it points to.",
+ "type": "string"
+ },
+ "valid_from": {
+ "description": "link: YYYY-MM-DD.",
+ "type": "string"
+ },
+ "valid_until": {
+ "description": "link: YYYY-MM-DD.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "target",
+ "idempotency_key"
+ ],
+ "type": "object"
+ },
+ "scope": "write"
+ },
{
"description": "Return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. Use this when the user asks 'what's inconsistent in my brain', 'show me contradictions about Acme', 'high-severity issues only', or wants to act on the probe's findings without re-running it. Returns {contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. Remote, source-scoped or min_trust callers get only findings whose two sides they can read now (each side re-read live, with source_id, trust_tier and origin) and total_visible instead of the run total. Reads the stored run without triggering a new probe; users run `gbrain eval suspected-contradictions` for that.",
"idempotent": true,
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 3885dd16cd..bfe4a81495 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1068,7 +1068,7 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "All 172 table(s) the applied migrations create exist.",
+ "message": "All 173 table(s) the applied migrations create exist.",
"name": "schema_missing_tables",
"status": "ok"
},
@@ -2466,6 +2466,13 @@
"name": "decide_health",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "No memory proposals await the owner.",
+ "name": "memory_proposals_pending",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index a4c0ccefa0..2b6b21d5a1 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1115,7 +1115,7 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "All 172 table(s) the applied migrations create exist.",
+ "message": "All 173 table(s) the applied migrations create exist.",
"name": "schema_missing_tables",
"status": "ok"
},
@@ -2522,6 +2522,13 @@
"name": "decide_health",
"status": "ok"
},
+ {
+ "category": "brain",
+ "elapsed_ms": "<volatile>",
+ "message": "No memory proposals await the owner.",
+ "name": "memory_proposals_pending",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index da3e4c0c44..702d3c6cc8 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -885,6 +885,10 @@
"category": "ops",
"name": "decide_health"
},
+ {
+ "category": "brain",
+ "name": "memory_proposals_pending"
+ },
{
"category": "brain",
"name": "unlinked_facts"
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 237f7b9d91..3bc302e3e8 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6711,7 +6711,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 57238451b6..8989628686 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 156, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 157, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.ts
index c1b15b6928..51f60d2165 100644
--- a/test/helpers/config-reader-registry.ts
+++ b/test/helpers/config-reader-registry.ts
@@ -132,6 +132,7 @@ export const UNRESOLVED_CONFIG_READS: readonly UnresolvedConfigRead[] = [
{ file: 'src/core/pace-mode.ts', expr: 'k', why: P },
{ file: 'src/core/page-body/limits.ts', expr: 'key', why: P },
{ file: 'src/core/persistence/group-publish.ts', expr: 'name', why: P },
+ { file: 'src/core/persistence/memory-proposals.ts', expr: 'spec.key', why: 'Object.entries walk over PROPOSAL_LIMIT_KEYS (registered in config-runtime-keys.ts)' },
{ file: 'src/core/persistence/page-mutations.ts', expr: 'name', why: P },
{ file: 'src/core/persistence/sync-drain.ts', expr: 'key', why: P },
{ file: 'src/core/persistence/sync-group.ts', expr: 'key', why: P },
diff --git a/test/qm-memory-propose.test.ts b/test/qm-memory-propose.test.ts
new file mode 100644
index 0000000000..a27a02f615
--- /dev/null
+++ b/test/qm-memory-propose.test.ts
@@ -0,0 +1,582 @@
+/**
+ * GST-1158 (GBRA-284): memory_propose, QM's held timeline entries and links, approved by the brain owner.
+ *
+ * 1. Protects: an attested proposal is checked before anything is held and is held in memory_proposals, never in the
+ * journal, git, an export or a recall, until the owner approves it; approval re-checks the person, the grant, the page
+ * revision and a link's target under the stored authority and admits the write into the journal in the same
+ * transaction that marks the proposal approved; deny, expiry, the proposer's cancel and refused checks close it with a
+ * reason; QM reads one request id from proposal to publication through get_write_request; the caps, the payload cap,
+ * the TTL and the retention purge hold; the published provenance names the member, never the external id.
+ * 2. Fails when: a proposal publishes without the owner, an unlinked person's or a changed page's proposal publishes, a
+ * second approve writes twice, a cap or the payload cap can be passed, another member under the same credential reads
+ * or cancels it, a held receipt or an export or a recall carries the proposed text, a closed row outlives retention,
+ * or the journal's state lists change.
+ * 3. Existing coverage: test/qm-memory-tools.test.ts (memory_write), test/access-qm-actor.test.ts (F9 deferred ops).
+ * 4. Real seams: OAuth client-credentials tokens verified by the provider and dispatched through MCP dispatch on a
+ * repo-less brain; owner actions through the library and the gbrain memory-proposals command module; publication
+ * through the persistence consumer.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+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, type ToolResult } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { addMember, bindCredential, disableMember, enableMember } from '../src/core/access/members.ts';
+import { linkMember, unlinkMember } from '../src/core/access/actor.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { WRITE_REQUEST_STATES } from '../src/core/persistence/types.ts';
+import { DELETION_INVENTORY_BY_TABLE } from '../src/core/deletion-inventory.ts';
+import {
+ approveMemoryProposal, denyMemoryProposal, listMemoryProposals, pendingProposalSummary, proposalRequestId, runMemoryProposalUpkeep, PROPOSAL_LIMIT_KEYS, PROPOSAL_STATES,
+} from '../src/core/persistence/memory-proposals.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+import { deleteSourceRow } from '../src/core/source-delete.ts';
+import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';
+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const SRC = 'qm-propose';
+const ALICE_ID = '[email protected]';
+const BOB_ID = 'U0BOB';
+const CAROL_ID = 'U0CAROL';
+const ACME = 'companies/acme-example';
+const GLOBEX = 'companies/globex-example';
+const INITECH = 'companies/initech-example';
+const QUIET = 'notes/quiet-example';
+const BOBONLY = 'notes/bob-only-example';
+const ATTEST_OPS = ['cancel_write_request', 'get_write_request', 'list_write_requests', 'memory_propose', 'memory_recall', 'memory_write'];
+
+const pageText = (title: string, extra: string[] = [], body = 'Harbor ledger notes.') => ['---', 'type: company', 'title: ' + title, ...extra, '---', '# ' + title, '', body].join('\n');
+
+for (const kind of testBackends()) {
+ describe('memory_propose (' + kind + ', repo-less)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let qmClient: string;
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const tokens: Record<string, string> = {};
+ const verify = async (bearer: string) => await provider().verifyAccessToken(bearer) as unknown as AuthInfo;
+ type Who = { token: string; actor?: string };
+ const alice: Who = { token: 'qm', actor: ALICE_ID };
+ const bob: Who = { token: 'qm', actor: BOB_ID };
+ const carol: Who = { token: 'qm', actor: CAROL_ID };
+
+ async function call(as: Who, op: string, params: Record<string, unknown>, extra: Record<string, unknown> = {}) {
+ const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {
+ remote: true, transport: 'http', auth: await verify(tokens[as.token]!), sourceId: SRC, takesHoldersAllowList: ['world'],
+ ...(as.actor !== undefined ? { actor: { header: as.actor } } : {}), ...extra,
+ });
+ const text = out.content.map(c => c.text).join('\n');
+ let json: Record<string, any> = {};
+ try { json = JSON.parse(text); } catch { /* plain text */ }
+ return { isError: out.isError === true, text, json, structured: out.structuredContent as Record<string, any> | undefined,
+ all: text + JSON.stringify(out._meta ?? {}) + JSON.stringify(out.structuredContent ?? {}) };
+ }
+ const propose = (as: Who, params: Record<string, unknown>, key: string = randomUUID()) => call(as, 'memory_propose', { idempotency_key: key, ...params });
+ const timeline = (as: Who, summary: string, extra: Record<string, unknown> = {}, key?: string) =>
+ propose(as, { kind: 'timeline', target: ACME, date: '2026-10-30', summary, source: 'slack:C0123/p1', ...extra }, key);
+ const receipt = (as: Who, id: string) => call(as, 'get_write_request', { request_id: id });
+ const owner = (extra: Partial<OperationContext> = {}) => ({ engine, config: { engine: kind } as never, remote: false, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } as never, ...extra }) as OperationContext;
+ const approve = (id: string, extra: Partial<OperationContext> = {}) => approveMemoryProposal(owner(extra), id, { decidedBy: 'cli:test', waitMs: 30_000 });
+ const timelineRows = async (needle: string) => engine.executeRaw<{ summary: string; source: string }>(
+ 'SELECT t.summary, t.source FROM timeline_entries t JOIN pages p ON p.id = t.page_id WHERE p.source_id = $1 AND t.summary LIKE $2', [SRC, '%' + needle + '%']);
+ 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 * FROM persistence_requests WHERE request_id = $1::uuid', [id]);
+ const setConfig = (key: string, value: string | null) => value === null
+ ? engine.executeRaw('DELETE FROM config WHERE key = $1', [key]) : engine.setConfig(key, value);
+
+ 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]);
+ for (const id of ['alice-example', 'bob-example', 'carol-example']) await addMember(engine, id);
+ await importFromContent(engine, ACME, pageText('Acme Example'), { sourceId: SRC });
+ await importFromContent(engine, GLOBEX, pageText('Globex Example'), { sourceId: SRC });
+ await importFromContent(engine, INITECH, pageText('Initech Example'), { sourceId: SRC });
+ await importFromContent(engine, QUIET, pageText('Quiet Example', ['visibility: private']), { sourceId: SRC });
+ await importFromContent(engine, BOBONLY, pageText('Bob Only Example', ['readable_by: [bob-example]']), { sourceId: SRC });
+ const register = async (name: string) => {
+ const c = await provider().registerClientManual('p-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);
+ return { id: c.clientId, secret: c.clientSecret ?? '' };
+ };
+ const qm = await register('qm');
+ qmClient = qm.id;
+ await bindCredential(engine, { kind: 'client', id: qm.id }, { attestActor: 'qm', attestOps: ATTEST_OPS });
+ const plain = await register('plain');
+ for (const [name, c] of [['qm', qm], ['plain', plain]] as const) tokens[name] = (await provider().exchangeClientCredentials(c.id, c.secret)).access_token;
+ await linkMember(engine, 'alice-example', 'qm', ALICE_ID);
+ await linkMember(engine, 'bob-example', 'qm', BOB_ID);
+ await linkMember(engine, 'carol-example', 'qm', CAROL_ID);
+ }, 120_000);
+
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine).catch(() => undefined);
+ await close?.();
+ });
+
+ test('approve: a held timeline entry publishes once with member provenance, never the external id; one request id throughout', async () => {
+ const key = randomUUID();
+ const held = await timeline(alice, 'Acme signed the harbor lease canaryapprove', {}, key);
+ expect(held.isError).toBe(false);
+ const id = held.structured!.request_id as string;
+ expect(id).toBe(proposalRequestId('alice-example', key));
+ expect(held.structured).toMatchObject({ status: 'awaiting_owner', request_id: id, kind: 'timeline', target: ACME, expires_at: expect.any(String) });
+ expect(await timelineRows('canaryapprove')).toHaveLength(0);
+ expect(await journalRows(id)).toHaveLength(0);
+ const waiting = await receipt(alice, id);
+ expect(waiting.json).toMatchObject({ request_id: id, state: 'awaiting_owner', proposal: { kind: 'timeline', target: ACME } });
+ expect(waiting.json.retry_after_ms).toBeGreaterThan(0);
+ expect(waiting.all).not.toContain('canaryapprove');
+ const out = await approve(id);
+ expect(out).toMatchObject({ status: 'approved', request_id: id, write_request: { state: 'committed' } });
+ const rows = await timelineRows('canaryapprove');
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.source).toContain('member:alice-example');
+ expect(rows[0]!.source).toContain('slack:C0123/p1');
+ expect(rows[0]!.source).not.toContain(ALICE_ID);
+ const page = await engine.getPage(ACME, { sourceId: SRC });
+ expect(JSON.stringify(page)).not.toContain(ALICE_ID);
+ const done = await receipt(alice, id);
+ expect(done.json).toMatchObject({ request_id: id, state: 'committed', proposal: { kind: 'timeline', target: ACME } });
+ const again = await approve(id);
+ expect(again).toMatchObject({ status: 'approved', request_id: id, write_request: { state: 'committed' } });
+ expect(await timelineRows('canaryapprove')).toHaveLength(1);
+ expect(await journalRows(id)).toHaveLength(1);
+ expect((await proposalRow(id))!.decided_by).toBe('cli:test');
+ }, 90_000);
+
+ test('the request id is uuidv5 of the member and key, apart from memory_write ids and other members', async () => {
+ const key = 'same-key-' + randomUUID();
+ const a = await timeline(alice, 'Key derivation canarykeyid a', {}, key);
+ const b = await timeline(bob, 'Key derivation canarykeyid a', {}, key);
+ expect(a.structured!.request_id).toBe(proposalRequestId('alice-example', key));
+ expect(b.structured!.request_id).toBe(proposalRequestId('bob-example', key));
+ expect(a.structured!.request_id).not.toBe(b.structured!.request_id);
+ const { memoryWriteRequestId } = await import('../src/core/ops/qm-memory.ts');
+ expect(await memoryWriteRequestId('alice-example', key, 0)).not.toBe(a.structured!.request_id);
+ }, 60_000);
+
+ test('deny: the receipt says denied with the reason, the page is unchanged, approve afterwards is proposal_closed', async () => {
+ const held = await timeline(alice, 'Acme moved offices canarydeny');
+ const id = held.structured!.request_id as string;
+ await expect(denyMemoryProposal(owner(), id, ' ', { decidedBy: 'cli:test' })).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(denyMemoryProposal(owner(), id, 'x'.repeat(501), { decidedBy: 'cli:test' })).rejects.toMatchObject({ code: 'invalid_params' });
+ const dry = await denyMemoryProposal(owner({ dryRun: true }), id, 'Not accurate', { decidedBy: 'cli:test' });
+ expect(dry).toMatchObject({ dry_run: true, would: 'denied' });
+ expect((await proposalRow(id))!.state).toBe('awaiting_owner');
+ const out = await denyMemoryProposal(owner(), id, 'Not accurate', { decidedBy: 'cli:test' });
+ expect(out).toMatchObject({ status: 'denied', reason: 'Not accurate' });
+ const r = await receipt(alice, id);
+ expect(r.json).toMatchObject({ state: 'denied', retry_after_ms: null, decision: { reason: 'Not accurate' } });
+ expect(r.all).not.toContain('canarydeny');
+ expect(await timelineRows('canarydeny')).toHaveLength(0);
+ await expect(approve(id)).rejects.toMatchObject({ code: 'proposal_closed' });
+ await expect(denyMemoryProposal(owner(), id, 'again', { decidedBy: 'cli:test' })).rejects.toMatchObject({ code: 'proposal_closed' });
+ }, 60_000);
+
+ test('expiry: the upkeep pass expires an overdue proposal; approve refuses an overdue one even when no pass ran', async () => {
+ const a = (await timeline(alice, 'Expiry one canaryexpire')).structured!.request_id as string;
+ const b = (await timeline(alice, 'Expiry two canaryexpire')).structured!.request_id as string;
+ await engine.executeRaw("UPDATE memory_proposals SET expires_at = now() - interval '1 minute' WHERE request_id = ANY($1::uuid[])", [[a, b]]);
+ await expect(approve(b)).rejects.toMatchObject({ code: 'proposal_expired' });
+ expect((await proposalRow(b))!.state).toBe('expired');
+ const pass = await runMemoryProposalUpkeep(engine);
+ expect(pass.expired).toBeGreaterThanOrEqual(1);
+ const r = await receipt(alice, a);
+ expect(r.json).toMatchObject({ state: 'expired', decision: { reason: expect.stringContaining('No owner decision') } });
+ expect(await timelineRows('canaryexpire')).toHaveLength(0);
+ await expect(approve(a)).rejects.toMatchObject({ code: 'proposal_closed' });
+ }, 60_000);
+
+ test('replay: the same key and fields return the same proposal even after the page moved; other fields are idempotency_conflict', async () => {
+ const key = 'replay-' + randomUUID();
+ const first = await timeline(alice, 'Replay canaryreplay', {}, key);
+ await importFromContent(engine, ACME, pageText('Acme Example', [], 'Harbor ledger notes, revised ' + randomUUID()), { sourceId: SRC });
+ const again = await timeline(alice, 'Replay canaryreplay', {}, key);
+ expect(again.isError).toBe(false);
+ expect(again.structured).toMatchObject({ status: 'awaiting_owner', request_id: first.structured!.request_id });
+ const changed = await timeline(alice, 'Replay changed canaryreplay', {}, key);
+ expect(changed.isError).toBe(true);
+ expect(changed.json.code).toBe('idempotency_conflict');
+ expect(await engine.executeRaw('SELECT 1 FROM memory_proposals WHERE request_id = $1::uuid', [first.structured!.request_id])).toHaveLength(1);
+ }, 60_000);
+
+ test('page changed while waiting: timeline and link proposals close as conflict revision_changed', async () => {
+ const t = (await timeline(alice, 'Revision canaryrevision')).structured!.request_id as string;
+ const l = (await propose(alice, { kind: 'link', target: GLOBEX, to: INITECH, context: 'partner canaryrevisionlink' })).structured!.request_id as string;
+ await importFromContent(engine, ACME, pageText('Acme Example', [], 'Edited while held ' + randomUUID()), { sourceId: SRC });
+ await importFromContent(engine, GLOBEX, pageText('Globex Example', [], 'Edited while held ' + randomUUID()), { sourceId: SRC });
+ expect(await approve(t)).toMatchObject({ status: 'conflict', error_code: 'revision_changed' });
+ expect(await approve(l)).toMatchObject({ status: 'conflict', error_code: 'revision_changed' });
+ expect((await receipt(alice, t)).json).toMatchObject({ state: 'conflict', write_error: 'revision_changed' });
+ expect(await timelineRows('canaryrevision')).toHaveLength(0);
+ expect(await journalRows(t)).toHaveLength(0);
+ }, 60_000);
+
+ test('a sent expected_revision that is not current is refused before anything is held', async () => {
+ const out = await timeline(alice, 'Stale revision canarystalerev', { expected_revision: 'not-the-revision' });
+ expect(out.isError).toBe(true);
+ expect({ code: out.json.code, reason: out.json.reason }).toEqual({ code: 'invalid_params', reason: 'proposal_revision_changed' });
+ expect(await engine.executeRaw("SELECT 1 FROM memory_proposals WHERE payload::text LIKE '%canarystalerev%'")).toHaveLength(0);
+ }, 60_000);
+
+ test('link approve: the link publishes to the from page with qm-proposal provenance on a repo-less unmanaged brain', async () => {
+ const held = await propose(alice, { kind: 'link', target: GLOBEX, to: INITECH, link_type: '', context: 'supplier canarylink' });
+ expect(held.isError).toBe(false);
+ const id = held.structured!.request_id as string;
+ const out = await approve(id);
+ expect(out).toMatchObject({ status: 'approved', write_request: { state: 'committed' } });
+ const links = await engine.executeRaw<{ link_source: string; context: string }>(
+ 'SELECT l.link_source, l.context FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id WHERE f.slug = $1 AND t.slug = $2 AND f.source_id = $3',
+ [GLOBEX, INITECH, SRC]);
+ expect(links.some(l => l.link_source === 'qm-proposal' && l.context.includes('member:alice-example'))).toBe(true);
+ expect(JSON.stringify(links)).not.toContain(ALICE_ID);
+ }, 90_000);
+
+ test('link target deleted or turned private while held: conflict link_target_changed, and the slug never reaches the fence', async () => {
+ const gone = 'companies/gone-example';
+ const hidden = 'companies/hidden-example';
+ await importFromContent(engine, gone, pageText('Gone Example'), { sourceId: SRC });
+ await importFromContent(engine, hidden, pageText('Hidden Example'), { sourceId: SRC });
+ const a = (await propose(alice, { kind: 'link', target: ACME, to: gone })).structured!.request_id as string;
+ const b = (await propose(alice, { kind: 'link', target: ACME, to: hidden })).structured!.request_id as string;
+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE source_id = $1 AND slug = $2', [SRC, gone]);
+ await importFromContent(engine, hidden, pageText('Hidden Example', ['visibility: private']), { sourceId: SRC });
+ expect(await approve(a)).toMatchObject({ status: 'conflict', error_code: 'link_target_changed' });
+ expect(await approve(b)).toMatchObject({ status: 'conflict', error_code: 'link_target_changed' });
+ const page = await engine.getPage(ACME, { sourceId: SRC });
+ expect(JSON.stringify(page)).not.toContain(hidden);
+ expect(JSON.stringify(page)).not.toContain(gone);
+ }, 60_000);
+
+ test('publish re-check (OV3): a proposed link whose target went away after the yes refuses page_not_found at publish', async () => {
+ const late = 'companies/late-example';
+ await importFromContent(engine, late, pageText('Late Example'), { sourceId: SRC });
+ const id = (await propose(alice, { kind: 'link', target: ACME, to: late })).structured!.request_id as string;
+ const held = (await proposalRow(id))!;
+ const from = (await engine.getPage(ACME, { sourceId: SRC }))!;
+ const row = { request_id: id, operation: 'add_link', source_id: SRC, slug: ACME, page_id: from.id,
+ intent: { to: late, link_type: '', link_source: 'qm-proposal' }, authority: { ...held.authority, attestedOp: 'memory_propose' } };
+ const { prepareManualLinkMutation } = await import('../src/core/persistence/manual-links.ts');
+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE source_id = $1 AND slug = $2', [SRC, late]);
+ await expect(prepareManualLinkMutation(engine, row as never, { engine: engine.kind } as never)).rejects.toMatchObject({ code: 'page_not_found' });
+ const plain = await prepareManualLinkMutation(engine, { ...row, authority: { ...row.authority, attestedOp: 'add_link' } } as never, { engine: engine.kind } as never)
+ .then(() => 'prepared', (e: { code?: string }) => e.code);
+ expect(plain).not.toBe('page_not_found');
+ await call(alice, 'cancel_write_request', { request_id: id });
+ }, 60_000);
+
+ test('proposer cancel: cancel_write_request closes it cancelled; approve afterwards is proposal_closed', async () => {
+ const id = (await timeline(alice, 'Cancel me canarycancel')).structured!.request_id as string;
+ const out = await call(alice, 'cancel_write_request', { request_id: id });
+ expect(out.isError).toBe(false);
+ expect(out.json).toMatchObject({ request_id: id, state: 'cancelled' });
+ await expect(approve(id)).rejects.toMatchObject({ code: 'proposal_closed' });
+ expect(await timelineRows('canarycancel')).toHaveLength(0);
+ }, 60_000);
+
+ test('another member under the same credential gets not_found for get and cancel', async () => {
+ const id = (await timeline(alice, 'Private to alice canaryforeign')).structured!.request_id as string;
+ const get = await receipt(bob, id);
+ expect({ isError: get.isError, code: get.json.code }).toEqual({ isError: true, code: 'not_found' });
+ const cancel = await call(bob, 'cancel_write_request', { request_id: id });
+ expect({ isError: cancel.isError, code: cancel.json.code }).toEqual({ isError: true, code: 'not_found' });
+ expect((await proposalRow(id))!.state).toBe('awaiting_owner');
+ expect(get.all + cancel.all).not.toContain('canaryforeign');
+ }, 60_000);
+
+ test('caps: per person and per credential; an overdue row frees its slot at the next proposal', async () => {
+ await engine.executeRaw("UPDATE memory_proposals SET state = 'cancelled', decided_at = now() WHERE state = 'awaiting_owner'");
+ await setConfig('proposals.max_pending_per_actor', '2');
+ await setConfig('proposals.max_pending_per_credential', '3');
+ try {
+ const ids = [];
+ for (let i = 0; i < 2; i++) ids.push((await timeline(carol, 'Cap ' + i + ' canarycap')).structured!.request_id);
+ const third = await timeline(carol, 'Cap 2 canarycap');
+ expect({ isError: third.isError, code: third.json.code, reason: third.json.reason }).toEqual({ isError: true, code: 'proposals_pending_limit', reason: 'actor' });
+ await timeline(bob, 'Cap bob canarycap');
+ const fourth = await timeline(alice, 'Cap alice canarycap');
+ expect({ code: fourth.json.code, reason: fourth.json.reason }).toEqual({ code: 'proposals_pending_limit', reason: 'credential' });
+ await engine.executeRaw("UPDATE memory_proposals SET expires_at = now() - interval '1 minute' WHERE request_id = $1::uuid", [ids[0]]);
+ const freed = await timeline(carol, 'Cap freed canarycap');
+ expect(freed.isError).toBe(false);
+ expect((await proposalRow(ids[0] as string))!.state).toBe('expired');
+ if (kind === 'postgres') {
+ await engine.executeRaw("UPDATE memory_proposals SET state = 'cancelled', decided_at = now() WHERE state = 'awaiting_owner'");
+ const burst = await Promise.all(Array.from({ length: 6 }, (_, i) => timeline(carol, 'Burst ' + i + ' canaryburst')));
+ expect(burst.filter(b => !b.isError)).toHaveLength(2);
+ expect(burst.filter(b => b.json.code === 'proposals_pending_limit')).toHaveLength(4);
+ }
+ } finally {
+ await setConfig('proposals.max_pending_per_actor', null);
+ await setConfig('proposals.max_pending_per_credential', null);
+ await engine.executeRaw("UPDATE memory_proposals SET state = 'cancelled', decided_at = now() WHERE state = 'awaiting_owner'");
+ }
+ }, 90_000);
+
+ test('payload cap: 1,001 characters refused proposal_too_large, exactly 1,000 accepted', async () => {
+ const base = 'canarycap1000 ';
+ const fill = (n: number) => base + 'x'.repeat(n - base.length - 'slack:C0123/p1'.length);
+ const over = await timeline(alice, fill(1001));
+ expect({ code: over.json.code, reason: over.json.reason }).toEqual({ code: 'invalid_params', reason: 'proposal_too_large' });
+ const at = await timeline(alice, fill(1000));
+ expect(at.isError).toBe(false);
+ await call(alice, 'cancel_write_request', { request_id: at.structured!.request_id });
+ }, 60_000);
+
+ test('refusals: no actor, the trusted local CLI, fields of the other kind, a bad date, a private or unreadable target', async () => {
+ const none = await call({ token: 'qm' }, 'memory_propose', { idempotency_key: randomUUID(), kind: 'timeline', target: ACME, date: '2026-10-30', summary: 'x' });
+ expect({ code: none.json.code, reason: none.json.reason }).toEqual({ code: 'actor_not_attested', reason: 'actor_required' });
+ const { operationsByName } = await import('../src/core/operations.ts');
+ await expect(operationsByName.memory_propose!.handler(owner(), { idempotency_key: 'k', kind: 'timeline', target: ACME, date: '2026-10-30', summary: 'x' }))
+ .rejects.toMatchObject({ code: 'actor_not_attested' });
+ const mixed = await propose(alice, { kind: 'timeline', target: ACME, date: '2026-10-30', summary: 'x', to: GLOBEX });
+ expect({ code: mixed.json.code, reason: mixed.json.reason }).toEqual({ code: 'invalid_params', reason: 'proposal_kind_field' });
+ const badDate = await propose(alice, { kind: 'timeline', target: ACME, date: '2026-02-30', summary: 'x' });
+ expect(badDate.json.code).toBe('invalid_params');
+ const twoLines = await propose(alice, { kind: 'timeline', target: ACME, date: '2026-10-30', summary: 'a\nb' });
+ expect(twoLines.json.code).toBe('invalid_params');
+ const quiet = await timeline(alice, 'Quiet canaryquiet', { target: QUIET });
+ expect(quiet.json.code).toBe('page_not_found');
+ const unreadable = await timeline(alice, 'Bob only canarybobonly', { target: BOBONLY });
+ expect(unreadable.json.code).toBe('page_not_found');
+ const toQuiet = await propose(alice, { kind: 'link', target: ACME, to: QUIET });
+ expect(toQuiet.json.code).toBe('page_not_found');
+ expect(await engine.executeRaw("SELECT 1 FROM memory_proposals WHERE payload::text LIKE '%canaryquiet%' OR payload::text LIKE '%canarybobonly%' OR to_slug = $1", [QUIET])).toHaveLength(0);
+ const direct = await call(alice, 'add_timeline_entry', { slug: ACME, date: '2026-10-30', summary: 'direct canarydirect' });
+ expect(direct.json.code).toBe('actor_not_attested');
+ }, 60_000);
+
+ test('unlinked, disabled or no longer attested at approval: failed with that code, nothing written', async () => {
+ const a = (await timeline(alice, 'Unlinked canaryunlinked')).structured!.request_id as string;
+ await unlinkMember(engine, 'qm', ALICE_ID);
+ try { expect(await approve(a)).toMatchObject({ status: 'failed', error_code: 'actor_unlinked' }); }
+ finally { await linkMember(engine, 'alice-example', 'qm', ALICE_ID); }
+ const b = (await timeline(alice, 'Disabled canarydisabled')).structured!.request_id as string;
+ await disableMember(engine, 'alice-example');
+ try { expect(await approve(b)).toMatchObject({ status: 'failed', error_code: 'actor_unlinked' }); }
+ finally { await enableMember(engine, 'alice-example'); }
+ const c = (await timeline(alice, 'Revoked canaryrevoked')).structured!.request_id as string;
+ await bindCredential(engine, { kind: 'client', id: qmClient }, { attestActor: 'qm', attestOps: ATTEST_OPS.filter(o => o !== 'memory_propose') });
+ try {
+ // OV8: the proposer still reads and cancels its held rows after memory_propose is revoked.
+ expect((await receipt(alice, c)).json).toMatchObject({ state: 'awaiting_owner' });
+ expect(await approve(c)).toMatchObject({ status: 'failed', error_code: 'actor_not_attested' });
+ } finally { await bindCredential(engine, { kind: 'client', id: qmClient }, { attestActor: 'qm', attestOps: ATTEST_OPS }); }
+ for (const n of ['canaryunlinked', 'canarydisabled', 'canaryrevoked']) expect(await timelineRows(n)).toHaveLength(0);
+ }, 90_000);
+
+ test('revoked op: the upkeep pass closes held rows failed; the proposer reads and cancels meanwhile', async () => {
+ const a = (await timeline(bob, 'Held one canaryheldrevoke')).structured!.request_id as string;
+ const b = (await timeline(bob, 'Held two canaryheldrevoke')).structured!.request_id as string;
+ await bindCredential(engine, { kind: 'client', id: qmClient }, { attestActor: 'qm', attestOps: ATTEST_OPS.filter(o => o !== 'memory_propose') });
+ try {
+ const cancelled = await call(bob, 'cancel_write_request', { request_id: a });
+ expect(cancelled.json).toMatchObject({ state: 'cancelled' });
+ await runMemoryProposalUpkeep(engine);
+ expect((await proposalRow(b))!).toMatchObject({ state: 'failed', error_code: 'actor_not_attested' });
+ expect((await receipt(bob, b)).json).toMatchObject({ state: 'failed', write_error: 'actor_not_attested' });
+ } finally { await bindCredential(engine, { kind: 'client', id: qmClient }, { attestActor: 'qm', attestOps: ATTEST_OPS }); }
+ }, 60_000);
+
+ test('race: approve, deny, cancel and the upkeep pass on one proposal end in exactly one outcome and at most one write', async () => {
+ const id = (await timeline(bob, 'Race canaryrace')).structured!.request_id as string;
+ const results = await Promise.allSettled([
+ approve(id), denyMemoryProposal(owner(), id, 'race', { decidedBy: 'cli:test' }), call(bob, 'cancel_write_request', { request_id: id }), runMemoryProposalUpkeep(engine),
+ ]);
+ const row = (await proposalRow(id))!;
+ expect(['approved', 'denied', 'cancelled']).toContain(row.state);
+ expect((await journalRows(id)).length).toBe(row.state === 'approved' ? 1 : 0);
+ expect((await timelineRows('canaryrace')).length).toBeLessThanOrEqual(1);
+ expect(results.filter(r => r.status === 'fulfilled').length).toBeGreaterThan(0);
+ }, 90_000);
+
+ test('fresh admission: the approved write gets a sequence admitted at approval, after every write since the proposal', async () => {
+ const id = (await timeline(bob, 'Fresh canaryfresh')).structured!.request_id as string;
+ await call(bob, 'memory_write', { facts: [{ fact: 'Bob noted a later fact canaryfreshfact', provenance: 'turn 2' }], idempotency_key: randomUUID() }, { writeWaitMs: 30_000 });
+ const [{ max }] = await engine.executeRaw<{ max: string }>('SELECT max(sequence)::text AS max FROM persistence_requests');
+ await approve(id);
+ const [row] = await journalRows(id);
+ expect(BigInt(row!.sequence)).toBeGreaterThan(BigInt(max));
+ expect(row!.authority.attestedOp).toBe('memory_propose');
+ }, 90_000);
+
+ test('list_write_requests shows an approved proposal to a client whose allowed operations name memory_propose, not add_timeline_entry', async () => {
+ await engine.executeRaw('UPDATE oauth_clients SET allowed_operations = $2 WHERE client_id = $1',
+ [qmClient, ['cancel_write_request', 'get_write_request', 'list_write_requests', 'memory_propose', 'memory_recall', 'memory_write']]);
+ try {
+ const id = (await timeline(bob, 'Narrow grant canarynarrow')).structured!.request_id as string;
+ await approve(id);
+ const list = await call(bob, 'list_write_requests', { source_id: SRC, limit: 100 });
+ expect(list.isError).toBe(false);
+ expect(list.json.requests.map((r: { request_id: string }) => r.request_id)).toContain(id);
+ } finally { await engine.executeRaw('UPDATE oauth_clients SET allowed_operations = NULL WHERE client_id = $1', [qmClient]); }
+ }, 90_000);
+
+ test('unapproved text never reaches recall, search or an export; doctor and status count the pending proposals', async () => {
+ const id = (await timeline(bob, 'Held secret canaryneverout')).structured!.request_id as string;
+ const recall = await call(bob, 'memory_recall', { query: 'canaryneverout held secret' });
+ expect(recall.all).not.toContain('canaryneverout');
+ const search = await call(bob, 'search', { query: 'canaryneverout' });
+ expect(search.all).not.toContain('canaryneverout');
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-propose-export-'));
+ try {
+ const { runExport } = await import('../src/commands/export.ts');
+ const log = console.log; console.log = () => {};
+ try { await runExport(engine, ['--dir', dir, '--source', SRC]); } finally { console.log = log; }
+ const walk = (d: string): string[] => readdirSync(d).flatMap(n => statSync(join(d, n)).isDirectory() ? walk(join(d, n)) : [join(d, n)]);
+ const files = walk(dir);
+ expect(files.length).toBeGreaterThan(0);
+ for (const f of files) expect(readFileSync(f, 'utf-8')).not.toContain('canaryneverout');
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+ const summary = await pendingProposalSummary(engine);
+ expect(summary.pending).toBeGreaterThanOrEqual(1);
+ const { runMemoryProposalsDoctor } = await import('../src/commands/doctor/checks/memory-proposals.ts');
+ const [check] = await runMemoryProposalsDoctor({ engine } as never);
+ expect(check).toMatchObject({ name: 'memory_proposals_pending', status: 'warn' });
+ expect(String(check!.message)).toContain('gbrain memory-proposals list');
+ const { runStatus } = await import('../src/commands/status.ts');
+ let human = '';
+ const status = await runStatus(engine, [], { stdout: (s) => { human += s; }, stderr: () => {} });
+ expect(status.report!.memory_proposals).toMatchObject({ pending: summary.pending });
+ expect(human).toContain(`Memory proposals: ${summary.pending} awaiting the owner`);
+ expect(human).toContain('review: gbrain memory-proposals list');
+ expect(human).not.toContain('canaryneverout');
+ await call(bob, 'cancel_write_request', { request_id: id });
+ let after = '';
+ await runStatus(engine, [], { stdout: (s) => { after += s; }, stderr: () => {} });
+ if ((await pendingProposalSummary(engine)).pending === 0) expect(after).not.toContain('Memory proposals:');
+ }, 90_000);
+
+ test('retention: every closed row is purged after proposals.retention_days; awaiting rows stay', async () => {
+ const held = (await timeline(bob, 'Stays canarypurge')).structured!.request_id as string;
+ const closed = (await timeline(bob, 'Purged canarypurge')).structured!.request_id as string;
+ await denyMemoryProposal(owner(), closed, 'no', { decidedBy: 'cli:test' });
+ await engine.executeRaw("UPDATE memory_proposals SET decided_at = now() - interval '29 days' WHERE request_id = $1::uuid", [closed]);
+ await runMemoryProposalUpkeep(engine);
+ expect(await proposalRow(closed)).toBeDefined();
+ await engine.executeRaw("UPDATE memory_proposals SET decided_at = now() - interval '31 days' WHERE request_id = $1::uuid", [closed]);
+ const pass = await runMemoryProposalUpkeep(engine);
+ expect(pass.purged).toBeGreaterThanOrEqual(1);
+ expect(await proposalRow(closed)).toBeUndefined();
+ expect((await proposalRow(held))!.state).toBe('awaiting_owner');
+ const purged = await receipt(bob, closed);
+ expect(purged.json.code).toBe('not_found');
+ await call(bob, 'cancel_write_request', { request_id: held });
+ }, 60_000);
+
+ test('owner command: list and show fence the proposed text, approve takes one id, deny needs --reason', async () => {
+ const id = (await timeline(bob, 'Owner view canaryownerview')).structured!.request_id as string;
+ const { runMemoryProposals } = await import('../src/commands/memory-proposals.ts');
+ 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, ['list', '--json']);
+ const listed = JSON.parse(lines.join('\n'));
+ const mine = listed.proposals.find((p: { request_id: string }) => p.request_id === id);
+ expect(mine.payload.summary).toContain('canaryownerview');
+ expect(mine.payload.summary).not.toBe('Owner view canaryownerview');
+ expect(mine.quoted).toBe('transcript');
+ lines.length = 0;
+ await runMemoryProposals(engine, ['deny', id]);
+ expect(lines.join('\n')).toContain('--reason');
+ expect(currentExitCode()).toBe(2);
+ setCliExitVerdict(0);
+ expect((await proposalRow(id))!.state).toBe('awaiting_owner');
+ lines.length = 0;
+ await runMemoryProposals(engine, ['approve', id, '--dry-run']);
+ expect((await proposalRow(id))!.state).toBe('awaiting_owner');
+ lines.length = 0;
+ await runMemoryProposals(engine, ['deny', id, '--reason', 'Not now']);
+ expect((await proposalRow(id))!).toMatchObject({ state: 'denied', reason: 'Not now' });
+ expect(String((await proposalRow(id))!.decided_by)).toMatch(/^cli/);
+ expect(currentExitCode()).toBe(0);
+ } finally { console.log = log; console.error = err; setCliExitVerdict(0); }
+ }, 60_000);
+
+ test('source removal cascades; the table is classified for deletion; journal state lists stay as they were', async () => {
+ expect(DELETION_INVENTORY_BY_TABLE.get('memory_proposals')).toMatchObject({ class: 'out_of_scope', reason: 'probed_reported', probe: ['payload', 'reason'] });
+ expect([...WRITE_REQUEST_STATES]).toEqual(['queued', 'running', 'recovering', 'committed', 'conflict', 'failed', 'cancelled']);
+ expect([...PROPOSAL_STATES]).toEqual(['awaiting_owner', 'approved', 'denied', 'expired', 'cancelled', 'failed', 'conflict']);
+ const held = (await timeline(alice, 'Cascade held canarycascade')).structured!.request_id as string;
+ const closed = (await timeline(bob, 'Cascade closed canarycascade')).structured!.request_id as string;
+ await denyMemoryProposal(owner(), closed, 'no', { decidedBy: 'cli:test' });
+ expect((await proposalRow(held))!.state).toBe('awaiting_owner');
+ expect((await proposalRow(closed))!.state).toBe('denied');
+ const n = Number((await engine.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM memory_proposals WHERE source_id = $1', [SRC]))[0]!.n);
+ expect(n).toBeGreaterThan(0);
+ const listed = await listMemoryProposals(engine, { all: true, limit: 500 });
+ expect(listed.length).toBeGreaterThan(0);
+ await engine.executeRaw('DELETE FROM oauth_clients WHERE source_id = $1', [SRC]);
+ expect(await deleteSourceRow(engine, SRC)).toBe(true);
+ expect(Number((await engine.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM memory_proposals WHERE source_id = $1', [SRC]))[0]!.n)).toBe(0);
+ expect(await proposalRow(held)).toBeUndefined();
+ expect(await proposalRow(closed)).toBeUndefined();
+ }, 60_000);
+ });
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ describe('memory_propose (' + backend + ', managed git brain)', () => {
+ test('held text never reaches git; an approved timeline entry and link land in the page file and a commit, a denied one never does', () => managedBrain(async ({ engine, ctx, root }) => {
+ __resetPrivateVisibilityCacheForTests();
+ const put = (slug: string, title: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: pageText(title) } });
+ await put(ACME, 'Acme Example');
+ await put(GLOBEX, 'Globex Example');
+ await settleManagedGitEffects(engine);
+ await addMember(engine, 'alice-example');
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const c = await provider.registerClientManual('p-qm-git-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], 'default');
+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: ATTEST_OPS });
+ await linkMember(engine, 'alice-example', 'qm', ALICE_ID);
+ const token = (await provider.exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;
+ const propose = async (params: Record<string, unknown>) => {
+ const out = await dispatchToolCall(engine, 'memory_propose', { idempotency_key: randomUUID(), ...params }, {
+ remote: true, transport: 'http', auth: await provider.verifyAccessToken(token) as unknown as AuthInfo, sourceId: 'default', actor: { header: ALICE_ID } });
+ expect(out.isError).not.toBe(true);
+ return (out.structuredContent as Record<string, any>).request_id as string;
+ };
+ const history = () => git(root, 'log', '-p', '--all') + git(root, 'status', '--porcelain') + readFileSync(join(root, ACME + '.md'), 'utf8') + readFileSync(join(root, GLOBEX + '.md'), 'utf8');
+ const owner = { ...ctx, config: { ...ctx.config } } as OperationContext;
+ const t = await propose({ kind: 'timeline', target: ACME, date: '2026-10-30', summary: 'Signed canarygitheld', source: 'slack:C0123/p1' });
+ const l = await propose({ kind: 'link', target: GLOBEX, to: ACME, context: 'supplier canarylinkheld' });
+ const d = await propose({ kind: 'timeline', target: ACME, date: '2026-10-31', summary: 'Rumor canarygitdenied' });
+ await settleManagedGitEffects(engine);
+ for (const needle of ['canarygitheld', 'canarylinkheld', 'canarygitdenied']) expect(history()).not.toContain(needle);
+ expect(await approveMemoryProposal(owner, t, { decidedBy: 'cli:test', waitMs: 30_000 })).toMatchObject({ status: 'approved', write_request: { state: 'committed' } });
+ expect(await approveMemoryProposal(owner, l, { decidedBy: 'cli:test', waitMs: 30_000 })).toMatchObject({ status: 'approved', write_request: { state: 'committed' } });
+ await denyMemoryProposal(owner, d, 'Not confirmed', { decidedBy: 'cli:test' });
+ await settleManagedGitEffects(engine);
+ const file = readFileSync(join(root, ACME + '.md'), 'utf8');
+ expect(file).toContain('canarygitheld');
+ expect(readFileSync(join(root, GLOBEX + '.md'), 'utf8')).toContain(ACME);
+ expect(git(root, 'log', '-p', '--all')).toContain('canarygitheld');
+ expect(git(root, 'log', '-p', '--all')).toContain('canarylinkheld');
+ expect(git(root, 'status', '--porcelain', '--', ACME + '.md').trim()).toBe('');
+ expect(history()).not.toContain('canarygitdenied');
+ expect(history()).not.toContain(ALICE_ID);
+ }, { databaseUrl, setup: ({ root }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); } }), 120_000);
+ });
+}
+
+describe('memory_propose limits', () => {
+ test('every proposals.* limit is a registered config key, so the operator can tune it without --force', () => {
+ for (const spec of Object.values(PROPOSAL_LIMIT_KEYS)) expect(KNOWN_CONFIG_KEYS).toContain(spec.key);
+ });
+});