Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keep a page private when a less trusted local write drops or widens its privacy labels, until the owner accepts (GST-2518)
garrytan0e1f0df5be8d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d99547f8d4..06189be784 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**An agent edit can no longer make a private page readable before you decide.** A local `put_page` (or `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) from a writer less trusted than the page used to publish at once even when it dropped or widened the page's `visibility`, `access`, `confidentiality` or `readable_by`. The only safeguard was a `lower_page` item in `gbrain trust review`, and until you dealt with it, remote callers and other members could read the page. The usual cause was an agent that rewrote a page and forgot its frontmatter. Now that write publishes with the page's earlier labels kept, in the database and in the file it commits, and its receipt names the kept keys (`privacy_labels_kept`). The `lower_page` item shows the labels the edit asked for. `gbrain trust confirm tp<id>` applies exactly those labels if the page hasn't changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm puts them back. A credential bound to you reads the page throughout. Unaffected: writes that only narrow a label, writes that leave the labels alone, writers at or above the page's tier, your own synced edits, and `gbrain repair visibility` (GST-2518).++### Itemized changes++- `src/core/trust/page-write.ts`, `src/core/persistence/page-prepare.ts`: a local content write below `operator_curated`, and below the page's label guard tier, keeps the stored labels it would widen. The guard tier is the page's tier, raised to the earlier tier recorded on the page's newest `lower_page` item unless you confirmed it. The `lower_page` item records the kept and requested labels, and a later write by the same tier replaces them with what it asked for, so a write that puts the label back withdraws the request. A write that changes only labels publishes nothing and still files its item.+- `src/core/trust/page-handlers.ts`: confirming a held item writes the requested labels in the same owner page write that confirms the page. New undo for a confirmed held item restores the kept labels and the edit's tier.+- `src/core/trust/owner-actions.ts`, `src/core/trust/review.ts`: the confirm and drop previews and the review item name the held labels.+- Tests: `test/lower-tier-label-hold.test.ts` covers each label dropped and widened, remote reads (unbound, another member, the owner), accept, reject, undo, a withdrawn request, the two-step bypass, the cases that must pass unheld, and the committed file on a managed Git source, on PGLite and Postgres.+## [0.60.687.0] - 2026-11-12**An upgrade can no longer run the same schema step twice at once.** When two gbrain processes started on one brain together (a cron job and an agent, or two hosts after an upgrade), both could apply the same schema migration. On Postgres reached through a transaction-mode pooler such as PgBouncer or Supabase's pooler, the lock meant to keep them apart did not hold. The pooler hands each statement to whichever server connection is free, so the lock could be taken on one connection and left behind on another. The second process then ran the step too, which showed up as a failed migration (for example a duplicate key on `pg_proc` while a function was being created) or as a step applied twice, and a lock left behind could keep later upgrades waiting until they timed out. Every path that changes the schema now takes one lock that holds for the whole run, through a pooler or a direct connection, and on PGLite. There is nothing to do beyond upgrading.diff --git a/docs/guides/memory-trust.md b/docs/guides/memory-trust.mdindex 30fe1fabe2..05afb411f2 100644--- a/docs/guides/memory-trust.md+++ b/docs/guides/memory-trust.md@@ -279,6 +279,27 @@ page's tier, file no `lower_page` item, and change only the label lines of itsfile. A `put_page` that adds the same label is an agent edit and lowers thepage, because a local agent with a shell is indistinguishable from you.+A local agent edit can't make a page more readable on its own. When a write+below your tier drops or widens a page's `visibility`, `access`,+`confidentiality` or `readable_by`, gbrain publishes the rest of the edit with+the page's earlier labels kept, in the database and in the file it commits.+The write's receipt names the kept keys under `privacy_labels_kept`. The+page's `lower_page` item in `gbrain trust review` shows what the edit asked+for, for example `visibility private -> (none)`.++- `gbrain trust confirm tp<id>` endorses the edit and applies exactly those+ labels, if the page hasn't changed since.+- `gbrain trust drop tp<id>` keeps the earlier labels.+- Undoing a confirm puts the earlier labels and the edit's tier back.++Until you decide, the page stays private to remote callers and to members+who weren't readers; a credential bound to you still reads it. The hold also+applies after you drop the item, and after an earlier agent edit that lowered+the page, so a later agent write still can't widen the labels. It doesn't+apply to a write that only narrows a label, to a write that leaves the labels+alone, to a writer at or above the page's tier, or to your own edits (a file+you edit and sync, `gbrain repair visibility`).+```bashgbrain trust backfill --label-lowerings [--source <id>] [--json] # read-only```diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 3420adff28..01986da777 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -49,5 +49,5 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1745 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1+src/core/behavior-change-notice.ts 1746 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2518 page_label_widening_held_gst2518 row (since TBD until the merge slot; rows are data and cannot move)src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot movediff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 1eb3ff7858..7efbd96f0f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1547,6 +1547,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.685.0', id: 'owner_facts_shared_gst2346', text: 'A credential bound to the brain owner (`gbrain access owner set`), or a stdio server started with `--stdio-member <owner>`, speaking for itself, now saves `remember` facts the way a credential bound to no member does: with no `visibility`, a fact is shared on its subject\'s page and every reader of the source recalls it, where it used to be kept private on the owner\'s member page. It stays private on that page when the call passes `visibility: "private"` or the subject\'s page or `facts.default_visibility` keeps facts private, and the reply names the `page` and `visibility` either way. Its `visibility: "world"` is saved instead of refused (`member_share_required`), except onto a page whose facts are kept private (`share_target_restricted`, as `share: true`), and its `forget` withdraws a shared fact it reads instead of saying only the brain host can. An owner agent that follows a planted instruction can therefore share a fact without passing any flag; to keep a fact private, pass `visibility: "private"`. Member credentials, attested QM calls (`x-qm-actor`), audiences (`X-Gbrain-On-Behalf-Of`), subagent jobs and slug-fenced clients are unchanged, and with writeback on the owner\'s credential is no longer told its saves stay private.' },{ since: '0.60.686.0', id: 'readers_label_setter_gst2476', text: 'New `gbrain repair visibility (--slug <page>... | --slugs-file <file>) --readers <ids|none>` sets or removes a page\'s `readable_by` through the label-only door: the page keeps its trust tier and provenance and its file changes only on that line. Unknown or disabled members and unknown groups refuse `access_member_invalid`; a list without the brain owner refuses unless `--allow-without-owner`. Every `repair visibility` write to a managed page with no file outside a declared `storage.db_only` path is now held `canonical_file_missing` with nothing written, instead of failing `source_changed`.' },{ since: '0.60.686.0', id: 'fence_fact_private_in_place_gst2487', text: 'A page write that only makes a `## Facts` row private (same claim, world to private) now makes the stored row private in place, keeping its id and trust tier, even when the row is more trusted than the writer. Before, such a row stayed live and world beside a contested private copy, so `gbrain repair visibility --class facts` could leave a fact remote callers still read while the page and its file read as fixed (`fact_left_readable`, `fact_left_world`). On a brain without managed persistence the repair now also makes the fenced row private. A write that makes a more trusted private row world is still held for the owner as before.' },+ { since: 'TBD', id: 'page_label_widening_held_gst2518', text: 'A local agent write (`put_page`, `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) less trusted than a page that drops or widens its `visibility`, `access`, `confidentiality` or `readable_by` now publishes with the page\'s earlier labels kept, in the database and in the committed file, and its receipt lists them under `privacy_labels_kept`. Before, the page became readable to remote callers and other members at once, and only a `lower_page` item waited for the owner. That item now records the requested labels: `gbrain trust confirm tp<id>` applies them if the page has not changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm restores them. Narrowing writes, label-neutral writes, writers at or above the page\'s tier, synced owner edits and `gbrain repair visibility` are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 4720613a21..e8b641f366 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -98,8 +98,9 @@ import { preparePagePurge, purgePageInTransaction, type PreparedPagePurge } fromimport { originCommitted } from './sync-markers.ts';import { syncDeleteOrigin } from './sync-delete-tombstones.ts';import { withTrustKeep } from './context.ts';-import { isFenceEditWrite, pageGateTrust, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier } from '../trust/page-write.ts';-import { compareTrust, type WriteTrust } from '../trust/tier.ts';+import { holdPrivacyLabels, isFenceEditWrite, pageGateTrust, privacyLabelGuard, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier,+ type HeldPrivacyLabels } from '../trust/page-write.ts';+import { compareTrust, maxTrust, type WriteTrust } from '../trust/tier.ts';import { suppliedTrustMarkerView } from '../trust/channel.ts';import { gateField, gateInput } from '../trust/gate-outcomes.ts';import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';@@ -903,6 +904,19 @@ function assertPrivateRequestAllowed(row: WriteRequest, content: string, frontmaassertPrivateRequestKept(row, frontmatter);}+/**+ * Core marking is owner-only: a remote write that omits always_load or+ * core_priority keeps the stored values instead of silently un-coring the page.+ */+function remoteCoreMarkingKept(row: WriteRequest, snapshot: PageSnapshot | null, content: string, activePack: ParseOpts['activePack']): string {+ if (!row.authority.remote || !snapshot || snapshot.page.deleted_at || typeof content !== 'string'+ || (snapshot.page.frontmatter?.always_load === undefined && snapshot.page.frontmatter?.core_priority === undefined)) return content;+ const parsed = parseMarkdown(content, row.slug, { activePack });+ const carried = carryCoreMarking(snapshot.page.frontmatter, parsed.frontmatter ?? {});+ if (carried.always_load === parsed.frontmatter?.always_load && carried.core_priority === parsed.frontmatter?.core_priority) return content;+ return serializePageToMarkdown({ ...snapshot.page, ...parsed, frontmatter: carried }, parsed.tags);+}+async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: WriteRequest, _config: Parameters<typeof preparePageMutation>[2],preparedIntent: Parameters<typeof preparePageMutation>[3], signal: AbortSignal | undefined,options: NonNullable<Parameters<typeof preparePageMutation>[5]>): Promise<PreparedMutation> {@@ -986,16 +1000,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wriif (compiled_truth!==parsed.compiled_truth || timeline!==(parsed.timeline??'')) content=serializePageToMarkdown({...(snapshot?.page??{id:0,source_id:row.source_id,created_at:new Date(),updated_at:new Date()}),...parsed,compiled_truth,timeline},parsed.tags);}- // Core marking is owner-only: a remote write that omits always_load or- // core_priority keeps the stored values instead of silently un-coring the page.- if (row.authority.remote && snapshot && !snapshot.page.deleted_at && typeof content === 'string'- && (snapshot.page.frontmatter?.always_load !== undefined || snapshot.page.frontmatter?.core_priority !== undefined)) {- const parsed = parseMarkdown(content, row.slug, { activePack });- const carried = carryCoreMarking(snapshot.page.frontmatter, parsed.frontmatter ?? {});- if (carried.always_load !== parsed.frontmatter?.always_load || carried.core_priority !== parsed.frontmatter?.core_priority) {- content = serializePageToMarkdown({ ...snapshot.page, ...parsed, frontmatter: carried }, parsed.tags);- }- }+ content = remoteCoreMarkingKept(row, snapshot, content, activePack);const projected = !(options.unprojected || row.operation === 'remember' || row.operation.startsWith('takes_') || (row.operation === 'extract_facts' && p.kind === 'managed_facts_entity'));const writer = replacesTombstone || ((row.operation === 'put_page' || row.operation === 'edit_page') && p.kind !== 'managed_maintenance_page'&& (preparedIntent !== undefined || typeof p.expected_revision === 'string')) ? 'editing' : 'preserving';@@ -1032,6 +1037,9 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri// #5575: the page's tier, computed once before import so the write gate sees exactly it (ENG-18).const trust = provenanceWriteTrust(row, typeof content === 'string' && !isFenceEditWrite(row) ? parseMarkdown(content, row.slug, { activePack }).frontmatter : null, snapshot?.page.frontmatter);const gateTrust = pageGateTrust(row, trust, storedTier);+ // GST-2518: a lower-tier local write keeps the page's privacy labels it would widen; its proposal carries the request.+ const labelGuard = await privacyLabelGuard(engine, row, trust, snapshot?.page ?? null, storedTier);+ let heldLabels: HeldPrivacyLabels | null = null;const defaultSourceWriter = row.operation === 'restore_page' || row.operation === 'revert_version' ? null : await defaultSourceMemberWriter(engine, row.authority), defaultSourceOwner = await defaultSourceWriterIsOwner(engine, defaultSourceWriter);// The apply diet: the publisher's locked read of row.slug is the import base, and one read after the// last page write serves the read-back check, the seal, the core notice and the receipt (as sync does).@@ -1053,6 +1061,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: WriprepareFrontmatter: page => {provenance = putProvenance(row, snapshot, page);suppliedTrustMarker = page.frontmatter.trust_tier;+ if (labelGuard) heldLabels = holdPrivacyLabels(page.frontmatter, snapshot?.page.frontmatter);stampPageTrustMarker(row, page.frontmatter, trust, storedTier, snapshot?.page.frontmatter);defaultSourceWriterReaders(defaultSourceWriter, page.frontmatter, snapshot?.page, defaultSourceOwner);if (privateRequest) assertPrivateRequestKept(row, page.frontmatter);@@ -1144,7 +1153,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wriconst applied = await (isFenceEditWrite(row) ? withTrustKeep(tx, ['pages'], () => ready.apply(tx, lean ? preimage : undefined)) : ready.apply(tx, lean ? preimage : undefined));projectionPending = applied?.segmented?.complete === false || applied?.projectionPending === true;segmentedWrite = applied?.segmented !== undefined;- lowered = prior ? await recordAgentPageLowering(tx, row, { tier: prior, revision: snapshot!.revision }) : null;+ lowered = prior ? await recordAgentPageLowering(tx, row, { tier: heldLabels && labelGuard ? maxTrust(prior, labelGuard) : prior, revision: snapshot!.revision }, undefined, heldLabels) : null;// Mandatory metadata shares publication rollback; exact no-ops never heal it. These, and the// projections (facts, takes, timeline rows of the page the import just wrote live), are independent and sent together.const [, pinned] = await pipelined(tx, [@@ -1183,6 +1192,9 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wrielse if (!applied?.projectionPending && !(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);}+ } else if (heldLabels && snapshot && labelGuard) {+ // GST-2518: a write that only widened labels publishes nothing once they are kept; its request still reaches the owner.+ lowered = await recordAgentPageLowering(tx, row, { tier: labelGuard, revision: snapshot.revision }, undefined, heldLabels);}const coreUsage = core?.usage();const gate = noop ? undefined : gateField(ready.result.gate, `p:${row.source_id}/${row.slug}`, null);@@ -1201,7 +1213,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri...(!noop && quarantineOutcome(ready.parsedPage.frontmatter) ? { quarantined: quarantineOutcome(ready.parsedPage.frontmatter) } : {}),...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}),...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized, ...fenceRepairOutcome,- ...(lowered ? { trust_lowered: lowered } : {}), ...(gate ? { gate } : {}),+ ...(lowered ? { trust_lowered: lowered } : {}), ...(lowered && heldLabels ? { privacy_labels_kept: { keys: heldLabels.keys, proposal_ref: lowered.proposal_ref } } : {}), ...(gate ? { gate } : {}),// DX-1: a guarded supersession reports contested (the first proposal; every one when the write contested several rows)....(contested.length ? { contested: { proposal_ref: contested[0], ...(contested.length > 1 ? { proposal_refs: contested } : {}) } } : {}) };} };diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.tsindex 6b449a35bc..20aa2bcbd0 100644--- a/src/core/trust/owner-actions.ts+++ b/src/core/trust/owner-actions.ts@@ -27,6 +27,7 @@ import type { OwnerConfirmation } from './confirm.ts';import { tierRaiseFix } from './confirm.ts';import { releaseSuppressedFields, suppressedFields } from '../belief/purge.ts';import { decideTrustProposal } from './decide.ts';+import { heldLabelsText } from './page-write.ts';import { resolveContestedFactOnConfirm } from './supersede-handlers.ts';import { getTrustProposal, pendingTrustProposalsFor, trustProposalRef, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';import {@@ -308,9 +309,11 @@ function proposalSummary(p: TrustProposalRow, verb: 'Accept' | 'Dismiss' | 'Reveif (p.action === 'lower_page') {const s = lowerPageState(p);const page = pageRef(p.source_id, s.slug);- if (verb === 'Accept') return `Endorse the agent edit of ${page}: raise it from "${trustLabel(s.edited_tier)}" to "confirmed by you"`;+ // GST-2518: the privacy labels the edit asked for and the page kept.+ const labels = s.labels ? heldLabelsText(s.labels) : '';+ if (verb === 'Accept') return `Endorse the agent edit of ${page}: raise it from "${trustLabel(s.edited_tier)}" to "confirmed by you"${labels ? ` and change its privacy labels: ${labels}` : ''}`;if (verb === 'Revert') return `Revert the agent edit of ${page}: restore version ${s.version_id ?? '?'} and its tier "${trustLabel(s.prior_tier)}"`;- return `Dismiss ${trustProposalRef(p.id)}: ${page} stays "${trustLabel(s.edited_tier)}"`;+ return `Dismiss ${trustProposalRef(p.id)}: ${page} stays "${trustLabel(s.edited_tier)}"${labels ? ' and keeps its privacy labels' : ''}`;}const target = `${p.target_table === 'facts' ? 'f' : p.target_table === 'takes' ? 't' : p.target_table === 'timeline_entries' ? 'timeline row ' : ''}${p.target_id}`;const related = p.related_id === null ? '' : ` with ${p.related_table === 'facts' ? 'f' : p.related_table === 'takes' ? 't' : ''}${p.related_id}`;diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.tsindex 894a8e645a..a78dade5d0 100644--- a/src/core/trust/page-handlers.ts+++ b/src/core/trust/page-handlers.ts@@ -15,6 +15,9 @@* replaced a higher-tier page): accept = the owner endorses the edited page* (confirm it); reject = dismiss, the page stays lowered; revert* (`revertLoweredPage`) = restore the prior owner version's content and tier.+ * GST-2518: when the agent write was held from widening privacy labels, accept+ * also writes the labels it asked for (in the same owner page write), and undo+ * (`undoPageLabels`) puts the kept labels and the edited tier back.* - #6550 marker repair (`repairPageMarker`, local CLI only): rewrite a page's* `trust_tier: unknown` marker to its stored tier (removed at owner tiers);* the row keeps its tier. trust/marker-repair.ts decides which pages.@@ -30,7 +33,7 @@*/import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';-import { queueTierProjection, recordAgentPageLowering } from './page-write.ts';+import { heldPrivacyLabels, queueTierProjection, recordAgentPageLowering, withLabels, type HeldPrivacyLabels } from './page-write.ts';import { plannedDigest, readPageDrift } from './provenance-drift.ts';import type { GBrainConfig } from '../config.ts';import type { OperationContext } from '../ops/contract.ts';@@ -51,7 +54,7 @@ import {decisionResult, registerTrustProposalHandler, transitionTrustProposal, type TrustProposalAction,type TrustDecisionContext, type TrustDecisionResult, type TrustProposalRow,} from './proposals.ts';-import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, minTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';+import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, isTrustTier, minTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';import { propagateTierLowering } from './propagation.ts';import { beliefStreamSlugs, lockedBeliefBatch } from '../belief/writers.ts';import { markBeliefCommits } from '../belief/append.ts';@@ -89,9 +92,9 @@ function changedSincePreview(ref: string, what: string): Error {'Run the command again: it shows the page as it is now and asks for a new confirmation.');}-/** The page with the CEO-21 marker removed (or set to `marker`), as canonical markdown. */-function markdownWithoutMarker(snapshot: PageSnapshot, marker: TrustTier | null = null): string {- const { trust_tier: _marker, ...rest } = (snapshot.page.frontmatter ?? {}) as Record<string, unknown>;+/** The page with the CEO-21 marker removed (or set to `marker`) and `labels` applied (GST-2518), as canonical markdown. */+function markdownWithoutMarker(snapshot: PageSnapshot, marker: TrustTier | null = null, labels?: Record<string, unknown>): string {+ const { trust_tier: _marker, ...rest } = withLabels((snapshot.page.frontmatter ?? {}) as Record<string, unknown>, labels ?? {});const frontmatter = marker ? { ...rest, trust_tier: marker } : rest;return serializeMarkdown(frontmatter, snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? '', {type: (snapshot.page.type as PageType) ?? 'note', title: snapshot.page.title ?? '', tags: snapshot.tags,@@ -178,8 +181,10 @@ export interface PageActionInput {confirmation: OwnerConfirmation;by?: Principal | null;config?: GBrainConfig;- /** A lower_page proposal this action decides, closed in the same transaction. */- proposal?: { id: number; to: 'accepted' | 'rejected'; after: Record<string, unknown> };+ /** A lower_page proposal this action decides, closed in the same transaction (from pending unless `from` says accepted, for an undo). */+ proposal?: { id: number; from?: 'pending' | 'accepted'; to: 'accepted' | 'rejected' | 'undone'; after: Record<string, unknown> };+ /** GST-2518: privacy labels the action writes with the page (null removes a key). */+ labels?: Record<string, unknown>;/** The remote context of a memory_confirm caller (managed admission authority); local CLI otherwise. */ctx?: OperationContext;}@@ -194,8 +199,11 @@ export interface PageActionResult {}type OwnerPageIntent = {- mode: 'confirm' | 'revert' | 'repair_marker' | 'restore_provenance';+ mode: 'confirm' | 'revert' | 'repair_marker' | 'restore_provenance' | 'undo_labels';expected_revision: string;+ /** GST-2518: confirm and undo_labels write these privacy labels (null removes a key); undo_labels restores `tier`. */+ labels?: Record<string, unknown>;+ tier?: TrustTier;version_id?: number;/** restore_provenance: the digest of the change the preview showed, and whether unattributed damage was included. */planned?: string;@@ -207,7 +215,7 @@ type OwnerPageIntent = {/** Closes a decided proposal inside the publication transaction, or refuses (it was decided meanwhile). */async function closeProposal(tx: BrainEngine, proposal: PageActionInput['proposal'], by: Principal | null | undefined): Promise<void> {if (!proposal) return;- if (!(await transitionTrustProposal(tx, proposal.id, 'pending', proposal.to, { after: proposal.after, decidedBy: by ?? null }))) {+ if (!(await transitionTrustProposal(tx, proposal.id, proposal.from ?? 'pending', proposal.to, { after: proposal.after, decidedBy: by ?? null }))) {throw opError('preview_changed', `Trust proposal tp${proposal.id} was decided by someone else meanwhile; nothing was changed.`,'Run gbrain trust review to see its current state.');}@@ -219,6 +227,11 @@ export async function confirmPage(engine: BrainEngine, input: PageActionInput):const state = await readPageTrustState(engine, input.sourceId, input.slug);if (!state) throw opError('page_not_found', `No live page ${ref}.`, 'Check the ref; gbrain trust review lists pages waiting for you.');if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, 'its confirmation');+ if (input.labels) {+ await publishOwnerPage(engine, input, { mode: 'confirm', expected_revision: input.expectedRevision, via: input.confirmation.via, proposal: input.proposal, labels: input.labels },+ markdownWithoutMarker(state.snapshot, null, input.labels), 'user_confirmed');+ return { status: 'confirmed', ref, tier: 'user_confirmed', prior_tier: state.tier, marker_removed: state.hasMarker };+ }if (state.tier === 'user_confirmed' && !state.hasMarker) {await engine.transaction(tx => closeProposal(tx, input.proposal, input.by));return { status: 'unchanged', ref, tier: state.tier, prior_tier: state.tier };@@ -241,7 +254,25 @@ export async function confirmPage(engine: BrainEngine, input: PageActionInput):/** #6550: the marker a repaired page carries: its stored tier, none at owner tiers (CEO-21 stamps none there). */export const repairedMarker = (tier: TrustTier): TrustTier | null => compareTrust(tier, OWNER_TIER_FLOOR) >= 0 ? null : tier;-const ACTION_NAMES: Record<OwnerPageIntent['mode'], string> = { confirm: 'its confirmation', revert: 'the revert', repair_marker: 'the marker repair', restore_provenance: 'the provenance restore' };+const ACTION_NAMES: Record<OwnerPageIntent['mode'], string> = { confirm: 'its confirmation', revert: 'the revert', repair_marker: 'the marker repair', restore_provenance: 'the provenance restore',+ undo_labels: 'the undo' };+/** GST-2518: the keys an owner page intent may write as labels. */+const LABEL_KEYS = ['visibility', 'access', 'confidentiality', 'readable_by'];++/**+ * GST-2518: undoes an accepted held-label proposal: the page gets `input.labels` (the labels the hold kept) and `tier`+ * (the edited tier the accept raised), with its marker, bound to the approved revision. Only lowers.+ */+export async function undoPageLabels(engine: BrainEngine, input: PageActionInput & { tier: TrustTier }): Promise<PageActionResult> {+ const ref = pageRef(input.sourceId, input.slug);+ const state = await readPageTrustState(engine, input.sourceId, input.slug);+ if (!state) throw opError('page_not_found', `No live page ${ref}.`, 'Check the ref; gbrain trust review lists pages waiting for you.');+ if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, ACTION_NAMES.undo_labels);+ const tier = minTrust(input.tier, state.tier);+ await publishOwnerPage(engine, input, { mode: 'undo_labels', expected_revision: input.expectedRevision, via: input.confirmation.via, proposal: input.proposal,+ labels: input.labels, tier }, markdownWithoutMarker(state.snapshot, repairedMarker(tier), input.labels), tier);+ return { status: 'restored', ref, tier, prior_tier: state.tier };+}/** Owner page modes only the trusted local CLI may run. */const LOCAL_ONLY_MODES: ReadonlyArray<OwnerPageIntent['mode']> = ['repair_marker', 'restore_provenance'];@@ -397,7 +428,9 @@ async function submitOwnerPage(engine: BrainEngine, input: PageActionInput, inte*/export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const intent = row.intent as unknown as OwnerPageIntent | null;- if (row.operation !== TRUST_OWNER_PAGE_OPERATION || !intent || !Object.hasOwn(ACTION_NAMES, intent.mode) || typeof intent.expected_revision !== 'string'+ const labelsValid = intent?.labels === undefined || (typeof intent.labels === 'object' && intent.labels !== null && Object.keys(intent.labels).every(key => LABEL_KEYS.includes(key)));+ if (row.operation !== TRUST_OWNER_PAGE_OPERATION || !intent || !Object.hasOwn(ACTION_NAMES, intent.mode) || typeof intent.expected_revision !== 'string' || !labelsValid+ || (intent.mode === 'undo_labels' && (!intent.labels || !isTrustTier(intent.tier)))|| (row.authority.remote && (LOCAL_ONLY_MODES.includes(intent.mode) || !(row.authority.scopes ?? []).includes(MEMORY_CONFIRM_SCOPE)))) {throw opError('confirmation_required', 'This owner page action is not confirmed by the owner; nothing was changed.','Run the gbrain trust command on the brain host in an interactive terminal.');@@ -418,7 +451,10 @@ export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: Wrtier = state.tier;content = markdownWithoutMarker(state.snapshot, repairedMarker(tier));} else if (intent.mode === 'restore_provenance') ({ content, tier } = await plannedProvenanceRestore(engine, state, intent));- else content = markdownWithoutMarker(state.snapshot);+ else if (intent.mode === 'undo_labels') {+ tier = minTrust(intent.tier!, state.tier);+ content = markdownWithoutMarker(state.snapshot, repairedMarker(tier), intent.labels);+ } else content = markdownWithoutMarker(state.snapshot, null, intent.labels);// The request keeps its own operation, so page-prepare stamps no CEO-21 marker and files no lower_page item for it.const { preparePageMutation } = await import('../persistence/page-prepare.ts');const page = await preparePageMutation(engine, row, config, { content, expectedRevision: intent.expected_revision, ...(tags ? { tags } : {}) });@@ -445,6 +481,8 @@ export interface LowerPageState {/** The latest agent edit (after_state). */edited_revision: string | null;edited_tier: TrustTier;+ /** GST-2518: the privacy labels the edit asked to widen and the page kept, or null. */+ labels: HeldPrivacyLabels | null;}export function lowerPageState(proposal: TrustProposalRow): LowerPageState {@@ -454,7 +492,7 @@ export function lowerPageState(proposal: TrustProposalRow): LowerPageState {slug: String(b.slug ?? ''), prior_tier: storedTrustTier(b.prior_tier),prior_revision: typeof b.prior_revision === 'string' ? b.prior_revision : null,version_id: b.version_id === null || b.version_id === undefined ? null : Number(b.version_id),- edited_revision: typeof a.revision === 'string' ? a.revision : null, edited_tier: storedTrustTier(a.tier),+ edited_revision: typeof a.revision === 'string' ? a.revision : null, edited_tier: storedTrustTier(a.tier), labels: heldPrivacyLabels(a),};}@@ -487,13 +525,32 @@ registerTrustProposalHandler('lower_page', {const state = lowerPageState(proposal);const page = await staleUnlessAt(engine, proposal, state);if (!('pageId' in page)) return page;+ const labels = heldPrivacyLabels(proposal.after_state);const result = await confirmPage(engine, {sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, confirmation: ctx.confirmation,- by: ctx.decidedBy, config: ctx.config,+ by: ctx.decidedBy, config: ctx.config, ...(labels ? { labels: labels.requested } : {}),proposal: { id: proposal.id, to: 'accepted', after: { ...proposal.after_state, resolution: 'confirmed' } },});return decisionResult(proposal, 'accept', 'accepted', { detail: { ...result } });},+ // GST-2518: only a proposal that held privacy labels undoes: its kept labels and edited tier come back, while the page still has the accepted labels.+ async undo(engine, proposal, ctx) {+ const labels = heldPrivacyLabels(proposal.after_state);+ if (!labels) return decisionResult(proposal, 'undo', 'refused', { reason: 'undo_unsupported' });+ const state = lowerPageState(proposal);+ const page = state.slug ? await readPageTrustState(engine, proposal.source_id, state.slug) : null;+ if (!page || page.pageId !== proposal.target_id) return decisionResult(proposal, 'undo', 'stale', { reason: 'page_missing' });+ const frontmatter = (page.snapshot.page.frontmatter ?? {}) as Record<string, unknown>;+ if (labels.keys.some(key => JSON.stringify(frontmatter[key] ?? null) !== JSON.stringify(labels.requested[key] ?? null))) {+ return decisionResult(proposal, 'undo', 'stale', { reason: 'labels_changed_since' });+ }+ const result = await undoPageLabels(engine, {+ sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, confirmation: ctx.confirmation, by: ctx.decidedBy, config: ctx.config,+ labels: labels.kept, tier: state.edited_tier,+ proposal: { id: proposal.id, from: 'accepted', to: 'undone', after: { ...proposal.after_state, resolution: 'undone' } },+ });+ return decisionResult(proposal, 'undo', 'undone', { detail: { ...result } });+ },async reject(engine, proposal, ctx) {return await transitionTrustProposal(engine, proposal.id, 'pending', 'rejected', { after: { ...proposal.after_state, resolution: 'dismissed' }, decidedBy: ctx.decidedBy })? decisionResult(proposal, 'reject', 'rejected', { reason: 'dismissed' })diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.tsindex 11b7908cdc..51854a558f 100644--- a/src/core/trust/page-write.ts+++ b/src/core/trust/page-write.ts@@ -23,6 +23,10 @@* derived page publication that lowers a page.* - #7918: a derivation declaration that is present but unreadable (a malformed* input, a missing origin) rates the write `unknown`, never the source default.+ * - GST-2518: a local content write below the page's label guard tier that widens+ * a privacy label publishes with the stored labels kept (holdPrivacyLabels), and+ * its `lower_page` proposal carries the labels it asked for; the owner's accept+ * applies them (trust/page-handlers.ts).*/import type { BrainEngine } from '../engine.ts';import { queuePageProjection } from '../page-state/projections.ts';@@ -31,7 +35,10 @@ import { frontmatterTrustCaps, requestChannelTrust, stampTrustMarker } from './cimport { declaredWriteTrust, readDerivationDeclaration } from './taint.ts';import { insertTrustProposal, updatePendingTrustProposalAfter } from './proposals.ts';import { propagateTierLowering } from './propagation.ts';-import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, minTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';+import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, isTrustTier, maxTrust, minTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';+import { PRIVACY_ALIASES } from '../search/private-visibility.ts';+import { normalizeReaders } from '../access/principals.ts';+import { asciiLower } from '../edge-whitespace.ts';/** Page writes that only edit a gbrain-managed fence (or strike a row) and keep the page's tier. */const FENCE_EDIT_OPERATIONS = ['remember', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove',@@ -97,33 +104,121 @@ export function stampPageTrustMarker(row: Pick<WriteRequest, 'operation' | 'inteif (stamped !== frontmatter) frontmatter.trust_tier = stamped.trust_tier;}+/** GST-2518: the privacy flag keys (visibility and its aliases) and the readers key a lower-tier write cannot widen alone. */+const PRIVACY_FLAG_KEYS = ['visibility', ...Object.keys(PRIVACY_ALIASES)];+const READERS_KEY = 'readable_by';++/** GST-2518: the labels a held write asked to change: the stored values the page kept and the requested ones (null: absent). */+export interface HeldPrivacyLabels { keys: string[]; kept: Record<string, unknown>; requested: Record<string, unknown> }++/** The held labels a lower_page proposal's after_state carries, or null. */+export function heldPrivacyLabels(state: Record<string, unknown> | null | undefined): HeldPrivacyLabels | null {+ const labels = state?.labels as HeldPrivacyLabels | undefined;+ return labels && Array.isArray(labels.keys) && labels.keys.length && typeof labels.kept === 'object' && typeof labels.requested === 'object' ? labels : null;+}++/** GST-2518: held labels for a person, e.g. `visibility private -> (none)`. */+export function heldLabelsText(labels: HeldPrivacyLabels): string {+ const show = (value: unknown) => value === null || value === undefined ? '(none)' : Array.isArray(value) ? `[${value.join(', ')}]` : String(value);+ return labels.keys.map(key => `${key} ${show(labels.kept[key])} -> ${show(labels.requested[key])}`).join(', ');+}++/** Private by the page's own labels: `visibility: private`, or with no visibility a privacy alias. Independent of visibility.honor_aliases. */+function labelledPrivate(frontmatter: Record<string, unknown>): boolean {+ if (frontmatter.visibility != null) return frontmatter.visibility === 'private';+ return Object.entries(PRIVACY_ALIASES).some(([key, values]) => typeof frontmatter[key] === 'string' && values.includes(asciiLower((frontmatter[key] as string).trim())));+}++/** The incoming readers let someone in that the stored readers did not (none named reads as everyone). */+function readersWidened(stored: Record<string, unknown>, incoming: Record<string, unknown>): boolean {+ const before = normalizeReaders(stored);+ if (before === null) return false;+ const after = normalizeReaders(incoming);+ return after === null || after.some(reader => !before.includes(reader));+}++/**+ * GST-2518: the label guard tier when a write must keep the page's privacy labels, else null. It applies to a local content+ * write below operator_curated over a page that is private by its labels or names readers, when the write is below the+ * guard: the stored tier, raised to the prior tier of the page's newest `lower_page` proposal unless the owner accepted it+ * (pending, dismissed, reverted or undone). So an earlier lowering edit, or a rejected or undone widening, does not let an+ * equal-tier write widen the page. Other writes send no query.+ */+export async function privacyLabelGuard(engine: BrainEngine, row: Pick<WriteRequest, 'operation' | 'intent' | 'authority'>, trust: WriteTrust | undefined,+ page: { id: number; frontmatter?: Record<string, unknown> | null } | null, stored: TrustTier | null): Promise<TrustTier | null> {+ if (!trust || !page || !stored || row.authority?.remote === true || !CONTENT_OPERATIONS.includes(row.operation) || isFenceEditWrite(row)+ || compareTrust(trust.tier, OWNER_TIER_FLOOR) >= 0) return null;+ const labels = page.frontmatter ?? {};+ if (!labelledPrivate(labels) && normalizeReaders(labels) === null) return null;+ const [newest] = await engine.executeRaw<{ status: string; prior: string | null }>(`SELECT status, before_state->>'prior_tier' AS prior FROM trust_proposals+ WHERE target_table = 'pages' AND target_id = $1 AND action = 'lower_page' ORDER BY id DESC LIMIT 1`, [Number(page.id)]);+ const guard = newest && newest.status !== 'accepted' && isTrustTier(newest.prior) ? maxTrust(stored, newest.prior) : stored;+ return compareTrust(trust.tier, guard) < 0 ? guard : null;+}++/**+ * GST-2518: in place, puts back the stored labels `frontmatter` would widen: the visibility and alias keys when the stored+ * page is private by them and the incoming one is not, and readable_by when the incoming readers let anyone new in.+ * A narrowing of the other kind is kept. Returns what was kept and asked for, or null when nothing widened.+ */+export function holdPrivacyLabels(frontmatter: Record<string, unknown>, stored: Record<string, unknown> | null | undefined): HeldPrivacyLabels | null {+ if (!stored) return null;+ const guarded = [...(labelledPrivate(stored) && !labelledPrivate(frontmatter) ? PRIVACY_FLAG_KEYS : []), ...(readersWidened(stored, frontmatter) ? [READERS_KEY] : [])];+ const keys = guarded.filter(key => JSON.stringify(stored[key] ?? null) !== JSON.stringify(frontmatter[key] ?? null));+ if (!keys.length) return null;+ const held: HeldPrivacyLabels = { keys, kept: {}, requested: {} };+ for (const key of keys) {+ held.kept[key] = stored[key] ?? null;+ held.requested[key] = frontmatter[key] ?? null;+ if (stored[key] === undefined) delete frontmatter[key];+ else frontmatter[key] = stored[key];+ }+ return held;+}++/** `frontmatter` with `labels` applied: a null value removes the key. */+export function withLabels(frontmatter: Record<string, unknown>, labels: Record<string, unknown>): Record<string, unknown> {+ const out = { ...frontmatter };+ for (const [key, value] of Object.entries(labels)) {+ if (value === null || value === undefined) delete out[key];+ else out[key] = value;+ }+ return out;+}+/*** CEO-12, inside the publication transaction after the page write: when the* write lowered a page's tier, file (or refresh) its `lower_page` proposal.* `prior` is the tier and revision read under the page lock before the write.* Content writes and derived page publications (#7917) file it; another writer- * that lowers a page on purpose names itself in `proposer`.+ * that lowers a page on purpose names itself in `proposer`. GST-2518: `labels` (a held write's, with `prior` at the label+ * guard tier) ride the after state, and a later write's after state without them withdraws them.*/export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteRequest, 'operation' | 'source_id' | 'slug'> & { intent?: WriteRequest['intent'] | null },- prior: { tier: TrustTier; revision: string | null } | null, proposer?: string): Promise<{ proposal_ref: string } | null> {+ prior: { tier: TrustTier; revision: string | null } | null, proposer?: string, labels?: HeldPrivacyLabels | null): Promise<{ proposal_ref: string } | null> {const derived = !CONTENT_OPERATIONS.includes(row.operation) && declaresDerivation(row.intent);if (!prior || !(proposer || CONTENT_OPERATIONS.includes(row.operation) || derived)) return null;const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });const [page] = snapshot ? await tx.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE id = $1', [snapshot.page.id]) : [];if (!snapshot || !page) return null;const pageId = Number(snapshot.page.id);- const after = { tier: storedTrustTier(page.trust_tier), revision: snapshot.revision };+ const after = { tier: storedTrustTier(page.trust_tier), revision: snapshot.revision, ...(labels ? { labels } : {}) };if (compareTrust(after.tier, prior.tier) >= 0) {// A later edit of an already-lowered page folds into its pending item (ENG-22): the revert binds to the newest revision.const [pending] = await tx.executeRaw<{ id: number }>(`SELECT id FROM trust_proposals WHERE status = 'pending' AND action = 'lower_page'AND target_table = 'pages' AND target_id = $1 LIMIT 1`, [pageId]);- if (!pending) return null;- await updatePendingTrustProposalAfter(tx, Number(pending.id), after);- return { proposal_ref: `tp${pending.id}` };+ if (pending) {+ await updatePendingTrustProposalAfter(tx, Number(pending.id), after);+ return { proposal_ref: `tp${pending.id}` };+ }+ // GST-2518: held labels reach the owner even when the write did not lower the page.+ if (!labels) return null;+ } else {+ // W1 #6783 §12 (b): rows derived from the page follow it down.+ await propagateTierLowering(tx, [{ table: 'pages', id: pageId }]);}- // W1 #6783 §12 (b): rows derived from the page follow it down.- await propagateTierLowering(tx, [{ table: 'pages', id: pageId }]);- const [version] = await tx.executeRaw<{ id: number }>(+ // GST-2518: a held write that changed nothing has no edit to revert.+ const [version] = snapshot.revision === prior.revision ? [] : await tx.executeRaw<{ id: number }>('SELECT id FROM page_versions WHERE page_id = $1 AND trust_tier = $2 ORDER BY id DESC LIMIT 1', [pageId, prior.tier]);const proposal = await insertTrustProposal(tx, {action: 'lower_page', sourceId: row.source_id, target: { table: 'pages', id: pageId }, proposer: proposer ?? (derived ? `derived_page:${row.operation}` : `agent_page_edit:${row.operation}`),diff --git a/src/core/trust/review.ts b/src/core/trust/review.tsindex f88b5ef3e3..078b07a381 100644--- a/src/core/trust/review.ts+++ b/src/core/trust/review.ts@@ -25,6 +25,7 @@ import { opError } from '../ops/contract.ts';import { currentHoldStore, trustKillSwitchState } from './owner-actions.ts';import { getTrustProposal, listTrustProposals, pendingTrustProposalsFor, trustProposalRef, type TrustProposalAction, type TrustProposalRow } from './proposals.ts';import { lowerPageState, readPageTrustState } from './page-handlers.ts';+import { heldLabelsText } from './page-write.ts';import { TRUST_MARKER_REPAIR_COMMAND } from './marker-repair.ts';import { formatTrustRef, pageRef, parseTrustRef, resolvePageRef } from './refs.ts';import { compareTrust, OWNER_TIER_FLOOR, storedTrustTier, trustLabel, USER_SAID_ORIGIN_MARKER, type TrustTier } from './tier.ts';@@ -142,7 +143,8 @@ function proposalItem(p: TrustProposalRow, page: string | null, markerRepair = freturn {ref, kind: 'lowered_page', detail: p.action, source_id: p.source_id, page, day: day(p.updated_at), created_at: p.created_at,tier: s.edited_tier, label: trustLabel(s.edited_tier),- summary: `An agent edit lowered ${page ?? `page ${p.target_id}`} from "${trustLabel(s.prior_tier)}" to "${trustLabel(s.edited_tier)}"`,+ summary: `An agent edit lowered ${page ?? `page ${p.target_id}`} from "${trustLabel(s.prior_tier)}" to "${trustLabel(s.edited_tier)}"`+ + (s.labels ? `; it asked to widen privacy labels (${heldLabelsText(s.labels)}), which stay as they were until you confirm` : ''),commands: { confirm: trust('confirm', ref), ...(s.version_id !== null ? { revert: trust('revert', ref) } : {}), drop: trust('drop', ref),...(markerRepair ? { repair: [...TRUST_MARKER_REPAIR_COMMAND] } : {}), explain: trust('explain', ref) },};diff --git a/test/lower-tier-label-hold.test.ts b/test/lower-tier-label-hold.test.tsnew file mode 100644index 0000000000..13e7325c65--- /dev/null+++ b/test/lower-tier-label-hold.test.ts@@ -0,0 +1,311 @@+/**+ * GST-2518: a lower-tier local page write that drops or widens a privacy label keeps the page's earlier privacy until+ * the owner accepts.+ *+ * 1. Protects: a local put_page (agent_written) over a more trusted page that drops or widens `visibility`, `access`,+ * `confidentiality` or `readable_by` publishes with the stored labels kept, in the database row and in the committed+ * file, and its `lower_page` proposal carries the labels it asked for. Accept applies exactly those labels (while the+ * page is still at the held revision), reject keeps the earlier ones, undo restores them. An unbound remote read and a+ * non-owner member read see nothing before accept; a credential bound to the owner reads the page before, during and+ * after the hold. A later lower-tier write that puts the label back withdraws the widening; an earlier body edit that+ * lowered the page does not open a second-step bypass.+ * 2. Fails when: the held write publishes the wider label, the proposal loses the requested labels, accept widens a+ * withdrawn or changed page, reject or undo leaves the page wider, or a write that should pass is held (the owner's+ * own sync, an equal-tier writer, a narrowing, a label-neutral edit, the operator readers setter).+ * 3. Real seams: local put_page (remote:false) through the write coordinator, remote reads through MCP dispatch with+ * legacy tokens (unbound, bound to a member, bound to the owner), owner decisions through decideTrustProposal, the+ * managed-brain harness (claimed Git worktree, managed sync, the Git effect) and a repo-less brain. PGLite, and+ * Postgres with DATABASE_URL.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import { operations } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { withCoordinatedWrite, withTrustBackfill } from '../src/core/persistence/context.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { addMember, bindCredential } from '../src/core/access/members.ts';+import { setOwner } from '../src/core/access/owner.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { decideTrustProposal } from '../src/core/trust/decide.ts';+import { listTrustProposals, parseTrustProposalRef, type TrustProposalRow } from '../src/core/trust/proposals.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const NL = String.fromCharCode(10);+const putPage = operations.find(op => op.name === 'put_page')!;+const OWNER = 'owner-example';+const owner = { confirmation: { via: 'tty' as const } };+/** A page file with its label lines and a canary word in the body. */+const file = (slug: string, labels: string[], canary: string, body = 'Second paragraph.') =>+ ['---', 'title: Example Page', 'type: note', ...labels, 'tags:', ' - alpha', '---', '', 'Body line one of ' + slug + ' ' + canary + '.', '', body, ''].join(NL);+/** A canary counts only as a whole token. */+const has = (text: string, canary: string) => new RegExp(canary + '(?![A-Za-z0-9])').test(text);+const READERS = 'readable_by: [alice-example, ' + OWNER + ']';++/** Each label, dropped and widened: the stored line, the line the writer sends (none = dropped), and who reads after accept. */+const CASES = [+ { label: 'visibility', stored: 'visibility: private', sent: null, keys: ['visibility'] },+ { label: 'visibility', stored: 'visibility: private', sent: 'visibility: world', keys: ['visibility'] },+ { label: 'access', stored: 'access: private', sent: null, keys: ['access'] },+ { label: 'access', stored: 'access: private', sent: 'access: public', keys: ['access'] },+ { label: 'confidentiality', stored: 'confidentiality: secret', sent: null, keys: ['confidentiality'] },+ { label: 'confidentiality', stored: 'confidentiality: secret', sent: 'confidentiality: public', keys: ['confidentiality'] },+ { label: 'readable_by', stored: READERS, sent: null, keys: ['readable_by'] },+ { label: 'readable_by', stored: READERS, sent: 'readable_by: [alice-example, bob-example, ' + OWNER + ']', keys: ['readable_by'] },+] as const;++interface Brain { engine: BrainEngine; ctx: OperationContext; sourceId: string; home: string }+type Reader = 'unbound' | 'bob' | 'owner';++async function seedOwnerPage(engine: BrainEngine, sourceId: string, slug: string, text: string) {+ expect((await importFromContent(engine, slug, text, { noEmbed: true, sourceId })).status).toBe('imported');+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => withTrustBackfill(tx, () => tx.executeRaw(+ "UPDATE pages SET trust_tier='operator_curated' WHERE source_id=$1 AND slug=$2", [sourceId, slug])), TEST_WRITE_ATTRIBUTION));+}+const pageRow = async (engine: BrainEngine, sourceId: string, slug: string) => (await engine.executeRaw<{ tier: string; frontmatter: Record<string, unknown>; revision: string; body: string }>(+ 'SELECT trust_tier::text AS tier, frontmatter, knowledge_revision::text AS revision, compiled_truth AS body FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))[0]!;+const labelsOf = (fm: Record<string, unknown>) => Object.fromEntries(['visibility', 'access', 'confidentiality', 'readable_by'].filter(k => fm[k] !== undefined).map(k => [k, fm[k]]));+const lineLabels = (line: string | null) => line === null ? {} : (() => {+ const [key, value] = [line.slice(0, line.indexOf(':')), line.slice(line.indexOf(':') + 1).trim()];+ return { [key]: value.startsWith('[') ? value.slice(1, -1).split(',').map(s => s.trim()) : value };+})();++/** Remote reads through MCP dispatch with a legacy token: unbound, bound to bob-example (a member, no reader), bound to the owner. */+async function remoteReaders(engine: BrainEngine, sourceId: string) {+ for (const member of ['alice-example', 'bob-example', OWNER]) await addMember(engine, member);+ await setOwner(engine, OWNER);+ const tokens: Record<Reader, string> = { unbound: '', bob: '', owner: '' };+ for (const [who, member] of [['unbound', null], ['bob', 'bob-example'], ['owner', OWNER]] as const) {+ const minted = await mintLegacyToken(engine, { name: 'reader-' + who, scopes: ['read'], takesHolders: ['world'], sourceGrant: [sourceId] });+ tokens[who] = minted.token;+ if (member) await bindCredential(engine, { kind: 'token', id: minted.id }, { member });+ }+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ return async (who: Reader, slug: string, canary: string): Promise<boolean> => {+ const auth = await provider.verifyAccessToken(tokens[who]) as unknown as AuthInfo;+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, auth.sourceId ?? sourceId);+ const out = await dispatchToolCall(engine, 'get_page', { slug }, { remote: true, transport: 'http', auth, sourceId: auth.sourceId ?? sourceId,+ takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'], ...(localFederated ? { localFederatedSourceIds: localFederated } : {}) });+ return has(out.content.map(c => c.text).join(NL), canary);+ };+}++async function put(b: Brain, slug: string, content: string): Promise<Record<string, any>> {+ return await putPage.handler(b.ctx, { slug, content, request_id: randomUUID(), wait_ms: 30_000,+ expected_revision: (await pageRow(b.engine, b.sourceId, slug)).revision }) as Record<string, any>;+}+const proposalsOf = async (b: Brain, slug: string): Promise<TrustProposalRow[]> =>+ (await listTrustProposals(b.engine, { sourceId: b.sourceId, status: 'all' })).filter(p => p.action === 'lower_page' && p.before_state.slug === slug);+const decide = (b: Brain, ref: string, decision: 'accept' | 'reject' | 'undo') => decideTrustProposal(b.engine, parseTrustProposalRef(ref)!, decision, owner);++/** A repo-less brain (no managed persistence, no checkout: the default keyless install) is the database record. */+for (const backend of testBackends()) describe('[' + backend + '] a lower-tier local write that widens a privacy label, on a repo-less brain', () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const SRC = 'labels-src';+ async function repoless(fn: (b: Brain, reads: Awaited<ReturnType<typeof remoteReaders>>) => Promise<void>) {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-label-hold-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ __resetPrivateVisibilityCacheForTests();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ const ctx: OperationContext = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: SRC, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } };+ await fn({ engine, ctx, sourceId: SRC, home }, await remoteReaders(engine, SRC));+ } finally { await disposePersistenceConsumer(engine); await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }++ test('each label dropped and widened: nothing reaches an unbound or non-owner read until accept, the owner reads throughout, accept applies exactly the request', () => repoless(async (b, reads) => {+ for (const [i, c] of CASES.entries()) {+ const slug = 'notes/held-' + i + '-example', canary = 'canaryhold' + i;+ await seedOwnerPage(b.engine, SRC, slug, file(slug, [c.stored], canary));+ const before = { unbound: await reads('unbound', slug, canary), bob: await reads('bob', slug, canary), owner: await reads('owner', slug, canary) };+ expect(before).toEqual({ unbound: false, bob: false, owner: true });+ // The first case changes only the label; the others rewrite the body too.+ const body = i === 0 ? 'Second paragraph.' : 'An agent rewrote this paragraph.';+ const written = await put(b, slug, file(slug, c.sent ? [c.sent] : [], canary, body));+ expect({ unbound: await reads('unbound', slug, canary), bob: await reads('bob', slug, canary), owner: await reads('owner', slug, canary) }).toEqual(before);+ expect(written.privacy_labels_kept).toEqual({ keys: [...c.keys], proposal_ref: expect.stringMatching(/^tp\d+$/) });+ const held = await pageRow(b.engine, SRC, slug);+ expect(labelsOf(held.frontmatter)).toEqual(lineLabels(c.stored));+ expect(held.body).toContain(body);+ // A label-only write publishes nothing once its label is kept, so it lowers nothing; its request still waits for the owner.+ expect(held.tier).toBe(i === 0 ? 'operator_curated' : 'agent_written');+ const [proposal] = await proposalsOf(b, slug);+ expect(proposal!.after_state.labels).toMatchObject({ keys: [...c.keys], kept: lineLabels(c.stored) });+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted' });+ const accepted = await pageRow(b.engine, SRC, slug);+ expect(labelsOf(accepted.frontmatter)).toEqual(lineLabels(c.sent));+ expect(accepted.tier).toBe('user_confirmed');+ const widenedReaders = c.label === 'readable_by' && c.sent !== null;+ expect({ unbound: await reads('unbound', slug, canary), bob: await reads('bob', slug, canary), owner: await reads('owner', slug, canary) })+ .toEqual({ unbound: !widenedReaders, bob: true, owner: true });+ }+ }), 300_000);++ test('reject keeps the earlier label, and a later lower-tier write that drops it again is held again', () => repoless(async (b, reads) => {+ const slug = 'notes/reject-example', canary = 'canaryreject';+ await seedOwnerPage(b.engine, SRC, slug, file(slug, ['visibility: private'], canary));+ const first = await put(b, slug, file(slug, [], canary, 'Rewritten once.'));+ expect(await decide(b, first.privacy_labels_kept.proposal_ref, 'reject')).toMatchObject({ status: 'rejected' });+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.visibility).toBe('private');+ expect(await reads('unbound', slug, canary)).toBe(false);+ // The page is at agent_written now; the owner's rejected decision still guards its label.+ const again = await put(b, slug, file(slug, ['visibility: world'], canary, 'Rewritten twice.'));+ expect(again.privacy_labels_kept?.keys).toEqual(['visibility']);+ expect(again.privacy_labels_kept.proposal_ref).not.toBe(first.privacy_labels_kept.proposal_ref);+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.visibility).toBe('private');+ expect(await reads('unbound', slug, canary)).toBe(false);+ expect(await reads('owner', slug, canary)).toBe(true);+ expect((await proposalsOf(b, slug)).map(p => p.status)).toEqual(['rejected', 'pending']);+ }), 180_000);++ test('undo restores the earlier label and the edited tier; a later lower-tier write stays held', () => repoless(async (b, reads) => {+ const slug = 'notes/undo-example', canary = 'canaryundo';+ await seedOwnerPage(b.engine, SRC, slug, file(slug, [READERS], canary));+ const written = await put(b, slug, file(slug, [], canary, 'Rewritten.'));+ const ref = written.privacy_labels_kept.proposal_ref;+ expect(await decide(b, ref, 'accept')).toMatchObject({ status: 'accepted' });+ expect(await reads('bob', slug, canary)).toBe(true);+ expect(await decide(b, ref, 'undo')).toMatchObject({ status: 'undone' });+ const undone = await pageRow(b.engine, SRC, slug);+ expect(undone.frontmatter.readable_by).toEqual(['alice-example', OWNER]);+ expect(undone.tier).toBe('agent_written');+ expect(undone.body).toContain('Rewritten.');+ expect({ unbound: await reads('unbound', slug, canary), bob: await reads('bob', slug, canary), owner: await reads('owner', slug, canary) })+ .toEqual({ unbound: false, bob: false, owner: true });+ const later = await put(b, slug, file(slug, [], canary, 'Rewritten again.'));+ expect(later.privacy_labels_kept?.keys).toEqual(['readable_by']);+ expect(await reads('bob', slug, canary)).toBe(false);+ }), 180_000);++ test('a write that puts the label back withdraws the widening: accept then widens nothing', () => repoless(async (b, reads) => {+ const slug = 'notes/withdrawn-example', canary = 'canarywithdrawn';+ await seedOwnerPage(b.engine, SRC, slug, file(slug, ['visibility: private'], canary));+ const widened = await put(b, slug, file(slug, [], canary, 'Rewritten.'));+ const back = await put(b, slug, file(slug, ['visibility: private'], canary, 'Rewritten with the label.'));+ expect(back.privacy_labels_kept).toBeUndefined();+ const [proposal, ...rest] = await proposalsOf(b, slug);+ expect(rest).toEqual([]);+ expect(proposal!.after_state.labels).toBeUndefined();+ expect(await decide(b, widened.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted' });+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.visibility).toBe('private');+ expect(await reads('unbound', slug, canary)).toBe(false);+ }), 180_000);++ test('a body edit that lowers the page first does not let a second write drop the label', () => repoless(async (b, reads) => {+ const slug = 'notes/two-step-example', canary = 'canarytwostep';+ await seedOwnerPage(b.engine, SRC, slug, file(slug, ['visibility: private'], canary));+ const first = await put(b, slug, file(slug, ['visibility: private'], canary, 'Edited body only.'));+ expect(first.privacy_labels_kept).toBeUndefined();+ expect((await pageRow(b.engine, SRC, slug)).tier).toBe('agent_written');+ const second = await put(b, slug, file(slug, [], canary, 'Edited body only.'));+ expect(second.privacy_labels_kept).toEqual({ keys: ['visibility'], proposal_ref: first.trust_lowered.proposal_ref });+ expect(await reads('unbound', slug, canary)).toBe(false);+ expect((await proposalsOf(b, slug)).map(p => p.status)).toEqual(['pending']);+ }), 180_000);++ test('nothing is held that should not be: an equal-tier writer, a narrowing, a label-neutral edit, the owner readers setter', () => repoless(async (b, reads) => {+ // An equal-tier writer: a page an agent wrote (agent_written) and labelled, then dropped by the same tier.+ const own = 'notes/agent-own-example';+ await putPage.handler(b.ctx, { slug: own, content: file(own, ['visibility: private'], 'canaryown'), request_id: randomUUID(), wait_ms: 30_000 });+ expect((await pageRow(b.engine, SRC, own)).tier).toBe('agent_written');+ const dropped = await put(b, own, file(own, [], 'canaryown'));+ expect(dropped.privacy_labels_kept).toBeUndefined();+ expect(labelsOf((await pageRow(b.engine, SRC, own)).frontmatter)).toEqual({});+ expect(await reads('unbound', own, 'canaryown')).toBe(true);+ // A narrowing: a world owner page made private, and a readers list cut to the owner.+ const narrowed = 'notes/narrowed-example', readers = 'notes/readers-narrowed-example';+ await seedOwnerPage(b.engine, SRC, narrowed, file(narrowed, [], 'canarynarrow'));+ expect((await put(b, narrowed, file(narrowed, ['visibility: private'], 'canarynarrow'))).privacy_labels_kept).toBeUndefined();+ expect((await pageRow(b.engine, SRC, narrowed)).frontmatter.visibility).toBe('private');+ await seedOwnerPage(b.engine, SRC, readers, file(readers, [READERS], 'canaryreaders'));+ expect((await put(b, readers, file(readers, ['readable_by: [' + OWNER + ']'], 'canaryreaders'))).privacy_labels_kept).toBeUndefined();+ expect((await pageRow(b.engine, SRC, readers)).frontmatter.readable_by).toEqual([OWNER]);+ // A label-neutral edit of a private owner page.+ const neutral = 'notes/neutral-example';+ await seedOwnerPage(b.engine, SRC, neutral, file(neutral, ['visibility: private', READERS], 'canaryneutral'));+ const edited = await put(b, neutral, file(neutral, ['visibility: private', READERS], 'canaryneutral', 'Edited.'));+ expect(edited.privacy_labels_kept).toBeUndefined();+ expect((await proposalsOf(b, neutral))[0]!.after_state.labels).toBeUndefined();+ // The brain host's readers setter (gbrain repair visibility --readers) widens a page's readers without a hold.+ const host = 'notes/host-example';+ await seedOwnerPage(b.engine, SRC, host, file(host, [READERS], 'canaryhost'));+ const out = async (argv: string[]) => { const log = console.log; let printed = ''; console.log = (...p: unknown[]) => { printed += p.join(' ') + NL; };+ try { await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => runRepairCommand(b.engine, [...argv, '--json'])); } finally { console.log = log; _resetCliExitVerdictForTests(); }+ return JSON.parse(printed).results[0]; };+ const argv = ['visibility', '--source', SRC, '--slug', host, '--readers', 'alice-example,bob-example,' + OWNER];+ const preview = await out(argv);+ expect((await out([...argv, '--apply', '--expect', preview.preview_hash])).applied).toBe(1);+ expect((await pageRow(b.engine, SRC, host)).frontmatter.readable_by).toEqual(['alice-example', 'bob-example', OWNER]);+ expect(await reads('bob', host, 'canaryhost')).toBe(true);+ expect(await proposalsOf(b, host)).toEqual([]);+ }), 240_000);+});++for (const backend of testBackends()) describe('[' + backend + '] a lower-tier local write that widens a privacy label, on a managed git source', () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+ const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), 'archive/' + NL); durableGitRepo(root, ['.gitignore']); };+ const commitAndSync = async (engine: BrainEngine, root: string, files: Record<string, string>) => {+ mkdirSync(join(root, 'notes'), { recursive: true });+ for (const [slug, text] of Object.entries(files)) writeFileSync(join(root, slug + '.md'), text);+ git(root, 'add', '-A');+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'owner notes');+ await performManagedSync(engine, OPTS);+ await settleManagedGitEffects(engine);+ };+ const committed = (root: string, slug: string) => git(root, 'show', 'HEAD:' + slug + '.md');++ test('the committed file carries the kept label until accept; accept and undo commit the label change; the owner\'s own sync is not held', () => managedBrain(async ({ engine, ctx, root }) => {+ const b: Brain = { engine, ctx, sourceId: 'default', home: root };+ const slug = 'notes/git-example', canary = 'canarygit';+ await commitAndSync(engine, root, { [slug]: file(slug, ['visibility: private'], canary) });+ expect((await pageRow(engine, 'default', slug)).tier).toBe('operator_curated');+ const written = await put(b, slug, file(slug, [], canary, 'An agent rewrote this paragraph.'));+ expect(written.privacy_labels_kept?.keys).toEqual(['visibility']);+ await settleManagedGitEffects(engine);+ expect(committed(root, slug)).toContain(NL + 'visibility: private' + NL);+ expect(committed(root, slug)).toContain('An agent rewrote this paragraph.');+ expect(readFileSync(join(root, slug + '.md'), 'utf8')).toBe(committed(root, slug));+ expect((await pageRow(engine, 'default', slug)).frontmatter.visibility).toBe('private');+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted' });+ await settleManagedGitEffects(engine);+ expect(committed(root, slug)).not.toContain('visibility:');+ expect(committed(root, slug)).toContain('An agent rewrote this paragraph.');+ expect((await pageRow(engine, 'default', slug)).frontmatter.visibility).toBeUndefined();+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'undo')).toMatchObject({ status: 'undone' });+ await settleManagedGitEffects(engine);+ expect(committed(root, slug)).toContain(NL + 'visibility: private' + NL);+ expect((await pageRow(engine, 'default', slug)).frontmatter.visibility).toBe('private');+ expect(git(root, 'status', '--porcelain', '--', slug + '.md').trim()).toBe('');++ // The owner's own write: the file edited and committed in the checkout, then synced (operator_curated), drops the label.+ const mine = 'notes/owner-example';+ await commitAndSync(engine, root, { [mine]: file(mine, ['visibility: private'], 'canarymine') });+ await commitAndSync(engine, root, { [mine]: file(mine, [], 'canarymine') });+ expect((await pageRow(engine, 'default', mine)).frontmatter.visibility).toBeUndefined();+ expect((await pageRow(engine, 'default', mine)).tier).toBe('operator_curated');+ expect(await proposalsOf(b, mine)).toEqual([]);+ }, { databaseUrl, setup }), 240_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 6f4a387bab..c6bd221b6f 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -280,6 +280,7 @@ test/links-attendance-blocked.test.tstest/links-extraction-yield.test.tstest/list-jobs-row-bound.test.tstest/list-pages-empty-type-notice-gbra449.test.ts+test/lower-tier-label-hold.test.tstest/maintenance-lowering-7917-7918.test.tstest/maintenance-trust-marker-7905.test.tstest/managed-cycle-pull-upstream.test.ts