Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep owner-set labels on an agent page, and keep the owner as a reader, when a less trusted local write changes them (GST-2521)

garrytane45dd0369c83
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9eef1bc019..80888e91ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,12 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased]
+**Labels you set on an agent's page now hold, and an agent can no longer take you out of a page's readers.** When you made an agent-written page private with `gbrain repair visibility` (or set its readers with `--readers`), the page kept its agent tier, so a later agent write at that tier could drop the label again with nothing held. Your label repairs now raise the page's label guard to your tier, so that write is held the same way as one over a page you wrote: it publishes with your labels kept and waits for you in `gbrain trust review`. Separately, a local write below your tier whose `readable_by` would leave you, the brain owner, out of a page you read now keeps you in the list (the rest of the narrowing still applies), and its `lower_page` item records the readers it asked for, which `gbrain trust confirm tp<id>` applies. Your own readers changes, synced edits, agent narrowing that keeps you, and brains with the owner opt-in to read restricted pages are unaffected. The guard lives in a new database table, so on a managed Git brain rebuilt from a clone it starts empty until you run the label repair again (GST-2521).
+
+- `src/core/schema-migrations/v305-page-label-guards.ts` (provisional number): new `page_label_guards` table, one row per page, removed with the page. `src/core/repair/label-write.ts` and the maintenance door's `keep_trust` path (`src/core/persistence/prepared-maintenance.ts`) raise it to `operator_curated` in the label write's transaction.
+- `src/core/trust/page-write.ts`: the label guard reads the page's guard row as a floor, and names the owner as a reader the write must keep when the owner reads the page by its readers and `access.owner_reads_restricted` is off. The held readers are the requested ones with the owner added, or the stored ones when the request is malformed.
+- Tests: `test/owner-label-guard.test.ts` covers both routes with unbound, other-member and owner-bound reads before, during and after, accept and reject, an agent's own page, a page that named no readers, the cases that must pass, and the committed file on a managed Git source, on PGLite and Postgres.
+
**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 while the page is still as the confirm left it. The same hold covers a derived page publication by a maintenance job (for example a dream patterns run that rewrites one of your pages), a page with no trust tier recorded yet (`unknown`), which counts as yours, and an agent that deletes a page and writes it again: a delete no longer lowers the page's tier. 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
diff --git a/docs/guides/memory-trust.md b/docs/guides/memory-trust.md
index d018e4861b..b1aa5f743a 100644
--- a/docs/guides/memory-trust.md
+++ b/docs/guides/memory-trust.md
@@ -304,6 +304,21 @@ 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`).
+Labels you set on an agent's page hold too. `gbrain repair visibility` (and
+its `--readers` setter, and `gbrain repair private-labels`) keeps the page's
+agent tier, but it raises the page's label guard to your tier, so a later agent
+write at the page's tier that drops or widens your labels is held the same way.
+The guard is kept in the database, so on a managed Git brain rebuilt from a
+clone it starts empty; run the label repair again to set it.
+
+An agent also can't take you out of a page's readers. When a write below your
+tier sets `readable_by` to a list that leaves you, the brain owner, out of a
+page you read now, gbrain publishes the rest of the change with you still in
+the list and records the readers it asked for in the page's `lower_page` item;
+`gbrain trust confirm tp<id>` applies them. An agent narrowing that keeps you
+in the list, your own readers changes, and a brain with
+`access.owner_reads_restricted` on (you read every page anyway) are unaffected.
+
```bash
gbrain trust backfill --label-lowerings [--source <id>] [--json] # read-only
```
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 01986da777..6fc72e73df 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: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 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/core/behavior-change-notice.ts 1747 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); +1 GST-2521 owner_labels_guarded_gst2521 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 move
diff --git a/scripts/postgres-arm-weights-postgres-only.json b/scripts/postgres-arm-weights-postgres-only.json
index 814b1c8bc5..1aee6d9a54 100644
--- a/scripts/postgres-arm-weights-postgres-only.json
+++ b/scripts/postgres-arm-weights-postgres-only.json
@@ -207,6 +207,7 @@
"test/origin-guard-6948.test.ts": 18397,
"test/origin-twins-6948.test.ts": 1635,
"test/overwritten-edits-6712.test.ts": 39503,
+ "test/owner-label-guard.test.ts": 13835,
"test/owner-refusal.test.ts": 5596,
"test/pack-relation-direction-engine.test.ts": 7462,
"test/page-embedding-budget.test.ts": 1684,
diff --git a/scripts/postgres-arm-weights.json b/scripts/postgres-arm-weights.json
index 71d553184d..89efb41ae9 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -318,6 +318,7 @@
"test/orphan-effect-diagnostics-7985.test.ts": 13288,
"test/overwritten-edits-6712.test.ts": 58270,
"test/owner-facts-d1-gst2346.test.ts": 19218,
+ "test/owner-label-guard.test.ts": 30916,
"test/owner-member-boundary.test.ts": 8601,
"test/owner-reads-restricted.test.ts": 75912,
"test/owner-refusal.test.ts": 6032,
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 36179ae654..7cb4d55fe7 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: 'owner_labels_guarded_gst2521', text: 'Labels the owner sets with `gbrain repair visibility` (or its `--readers` setter, or `gbrain repair private-labels`) now raise the page\'s label guard to operator_curated, so a later local agent write at the page\'s own tier that drops or widens them is held like a write over an owner page, with a `lower_page` item. A local write below operator_curated whose `readable_by` would leave the brain owner out of a page the owner reads now publishes with the owner kept in the readers (the rest of the narrowing applies), and its item records the requested readers. The guard is stored in the database (`page_label_guards`), so a managed Git brain rebuilt from a clone starts without it until the owner\'s label repair runs again. The owner\'s own label writes, synced owner edits, agent narrowing that keeps the owner, and brains with `access.owner_reads_restricted` on are unchanged.' },
{ 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`; so does a maintenance job\'s derived page publication, and a page whose tier is still `unknown` counts as the owner\'s. A soft delete no longer lowers the page\'s tier. 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 while the page is unchanged since. Narrowing writes, label-neutral writes, writers at or above the page\'s tier, synced owner edits and `gbrain repair visibility` are unchanged.' },
];
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index acab135615..2ed0f25750 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -1036,10 +1036,11 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
let provenance: CanonicalProvenance | undefined;
let suppliedTrustMarker: unknown;
// #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 incoming = typeof content === 'string' && !isFenceEditWrite(row) ? parseMarkdown(content, row.slug, { activePack }).frontmatter : null;
+ const trust = provenanceWriteTrust(row, incoming, 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);
+ // GST-2518: a lower-tier local write keeps the page's privacy labels it would widen (GST-2521: and the owner as a reader); its proposal carries the request.
+ const labelGuard = await privacyLabelGuard(engine, row, trust, snapshot?.page ?? null, storedTier, incoming);
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
@@ -1062,7 +1063,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
prepareFrontmatter: page => {
provenance = putProvenance(row, snapshot, page);
suppliedTrustMarker = page.frontmatter.trust_tier;
- if (labelGuard) heldLabels = holdPrivacyLabels(page.frontmatter, snapshot?.page.frontmatter);
+ if (labelGuard) heldLabels = holdPrivacyLabels(page.frontmatter, snapshot?.page.frontmatter, labelGuard);
stampPageTrustMarker(row, page.frontmatter, trust, storedTier, snapshot?.page.frontmatter);
defaultSourceWriterReaders(defaultSourceWriter, page.frontmatter, snapshot?.page, defaultSourceOwner);
if (privateRequest) assertPrivateRequestKept(row, page.frontmatter);
@@ -1154,7 +1155,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
const 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: heldLabels && labelGuard ? maxTrust(prior, labelGuard) : prior, revision: snapshot!.revision }, undefined, heldLabels) : null;
+ lowered = prior ? await recordAgentPageLowering(tx, row, { tier: heldLabels && labelGuard?.tier ? maxTrust(prior, labelGuard.tier) : 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, [
@@ -1195,7 +1196,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
}
} 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);
+ lowered = await recordAgentPageLowering(tx, row, { tier: labelGuard.tier ?? storedTier!, revision: snapshot.revision }, undefined, heldLabels);
}
const coreUsage = core?.usage();
const gate = noop ? undefined : gateField(ready.result.gate, `p:${row.source_id}/${row.slug}`, null);
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index ca2b2c6228..86cd90e36e 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -38,7 +38,7 @@ import { isConnectorSourceKind } from './connector-identity.ts';
import { MaintenanceWriteWait } from './maintenance-wait.ts';
import { auditConflictsCommand, FILE_DRIFT_MESSAGE, liveFileDrift } from './drift-conflicts.ts';
import { lowerToDerivedTier, readDerivationDeclaration, recordTaintEdges, type DerivationDeclaration } from '../trust/taint.ts';
-import { derivationWriteTrust, recordAgentPageLowering, storedPageTier } from '../trust/page-write.ts';
+import { derivationWriteTrust, raisePageLabelGuard, recordAgentPageLowering, storedPageTier } from '../trust/page-write.ts';
import { sameInstantTies } from '../facts/claim-ties.ts';
import type { LabelEdit } from './label-edit.ts';
import { factPreimages, recordConsolidationGeneration } from '../generations/adapters/fact-rows.ts';
@@ -621,7 +621,12 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co
if (row.intent?.kind === 'managed_maintenance_page') {
const page = await preparePageMutation(engine, row.intent.expected_revision === null
? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config, undefined, undefined, { clock });
- const prepared: PreparedMutation = row.intent.keep_trust === true ? { ...page, apply: (tx, preimage) => withTrustKeep(tx, ['pages'], () => page.apply(tx, preimage)) } : page;
+ // GST-2521: keep_trust is the owner's label door, which also raises the page's label guard.
+ const prepared: PreparedMutation = row.intent.keep_trust === true ? { ...page, apply: (tx, preimage) => withTrustKeep(tx, ['pages'], async () => {
+ const outcome = await page.apply(tx, preimage);
+ await raisePageLabelGuard(tx, row.source_id, row.slug);
+ return outcome;
+ }) } : page;
const projection = row.intent.event_projection as MaintenanceEventProjection | undefined;
if (!projection) return prepared;
// #5523: the event page and its depth-page timeline row commit together in
diff --git a/src/core/repair/label-write.ts b/src/core/repair/label-write.ts
index d9c52a3ddc..c2dcdcd243 100644
--- a/src/core/repair/label-write.ts
+++ b/src/core/repair/label-write.ts
@@ -9,6 +9,8 @@
* source's checkout (`filesInCheckout`) calls writeLabelFile, which imports the file's own bytes with only the label
* lines edited and writes them back in that transaction, so the next sync reads the same page.
* An ordinary put_page, local or remote, stays an agent content write (trust/channel.ts): it is never used here.
+ * GST-2521: every label write raises the page's label guard (raisePageLabelGuard), so an agent write at the page's own
+ * tier is held from widening what the owner set.
*/
import type { BrainEngine } from '../engine.ts';
import { opError, type OperationContext } from '../ops/contract.ts';
@@ -20,6 +22,7 @@ import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { labelEditFile } from '../persistence/page-prepare.ts';
import { maintenancePreflight, publishMaintenancePage, publishMaintenancePages, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
import type { RepairItemOutcome } from './core.ts';
+import { raisePageLabelGuard } from '../trust/page-write.ts';
const bounded = { timeoutMs: 120_000 };
@@ -50,6 +53,7 @@ export async function importAtRevision(engine: BrainEngine, page: { source_id: s
const result = await withTrustKeep(tx, ['pages'], () => importFromContent(tx, page.slug, content, { sourceId: page.source_id, noEmbed: !embed, preserveGateMarkers: true }));
if (result.status === 'error') throw opError('invalid_params', `${page.source_id}:${page.slug} was not written: ${result.error ?? 'the import refused it'}`,
`Preview ${preview} again; the page is listed with its current state.`);
+ await raisePageLabelGuard(tx, page.source_id, page.slug);
await afterImport?.(tx);
return (await tx.readPageSnapshot(page.slug, { sourceId: page.source_id }))?.revision ?? null;
});
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 06933be159..e228ee6a8c 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 304;
+export const LATEST_SCHEMA_VERSION = 305;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index eb09b0133a..1600ed2d99 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -305,6 +305,7 @@ import { v301 } from './v301-member-email.ts';
import { v302 } from './v302-link-transitions-source.ts';
import { v303 } from './v303-access-page-rules.ts';
import { v304 } from './v304-access-owner-origin.ts';
+import { v305 } from './v305-page-label-guards.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -608,4 +609,5 @@ export const MIGRATIONS: Migration[] = [
v302,
v303,
v304,
+ v305,
];
diff --git a/src/core/schema-migrations/v305-page-label-guards.ts b/src/core/schema-migrations/v305-page-label-guards.ts
new file mode 100644
index 0000000000..1c90951970
--- /dev/null
+++ b/src/core/schema-migrations/v305-page-label-guards.ts
@@ -0,0 +1,31 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// GST-2521: the per-page label guard. The owner's label door (`gbrain repair visibility`, its `--readers` setter,
+// `gbrain repair private-labels`) keeps a page's trust tier, so labels the owner set on an agent-written page were
+// guarded only at the agent tier, and a later agent write at that tier could drop them. The door now records
+// operator_curated here, and the GST-2518 label guard (trust/page-write.ts privacyLabelGuard) reads it as a floor. One
+// row per page, removed with the page. A separate table, not a pages column, so writing it fires none of the page
+// triggers (trust stamp, revision, generation). Database only, so a repo-less brain gets it unchanged; on a managed Git
+// brain it is not in the files, so a brain rebuilt from a clone starts with no rows (the owner's label door sets them
+// again). No schema.sql mirror: like v282, v283 and v300, it exists only through migrations. Provisional number:
+// renumbered at the merge slot.
+export const v305: Migration = {
+ version: 305,
+ name: 'page_label_guards',
+ idempotent: true,
+ sql: `
+CREATE TABLE IF NOT EXISTS page_label_guards (
+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,
+ tier TEXT NOT NULL CHECK (tier IN ('user_confirmed', 'operator_curated', 'tool_observed', 'agent_written', 'unknown', 'external_untrusted')),
+ set_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN
+ ALTER TABLE page_label_guards ENABLE ROW LEVEL SECURITY;
+ END IF;
+END $rls$;
+`,
+};
diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.ts
index 590012b42f..17d39d6dc9 100644
--- a/src/core/trust/page-write.ts
+++ b/src/core/trust/page-write.ts
@@ -37,7 +37,9 @@ import { insertTrustProposal, updatePendingTrustProposalAfter } from './proposal
import { propagateTierLowering } from './propagation.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 { normalizeReaders, readersAllow } from '../access/principals.ts';
+import { memberIdentity } from '../access/members.ts';
+import { ownerMemberId, ownerReadsRestrictedOn } from '../access/owner.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. */
@@ -137,44 +139,81 @@ function readersWidened(stored: Record<string, unknown>, incoming: Record<string
return after === null || after.some(reader => !before.includes(reader));
}
+/** GST-2518, GST-2521: what a held write keeps: the labels it would widen below `tier`, and the brain owner as a reader (`owner`). */
+export interface LabelGuard { tier: TrustTier | null; owner: { member: string; identity: string[] } | null }
+
/**
- * 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 or derived page publication 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 (an unclassified `unknown` page reads as operator_curated lowered by its
- * frontmatter caps, as its marker does), raised to the prior tier of every `lower_page` proposal of the page since the
- * owner last accepted one (pending, dismissed, reverted or undone). So earlier lowering edits, or a rejected or undone
- * widening, do not let an equal-tier write widen the page. Other writes send no query.
+ * GST-2518: the label guard for a local content write or derived page publication below operator_curated, else null. Its
+ * tier holds a page that is private by its labels or names readers when the write is below it: the stored tier (an
+ * unclassified `unknown` page reads as operator_curated lowered by its frontmatter caps, as its marker does), raised to
+ * the tier the owner's label door left (GST-2521, `page_label_guards`) and to the prior tier of every `lower_page`
+ * proposal of the page since the owner last accepted one (pending, dismissed, reverted or undone). So owner-set labels,
+ * earlier lowering edits, or a rejected or undone widening do not let an equal-tier write widen the page.
+ * GST-2521: `owner` is set when the brain owner reads the page by its readers now (and the owner opt-in to read restricted
+ * pages is off), so the write cannot take the owner out of them. `incoming` is the written frontmatter when known; a write
+ * that names no readers over a page that names none sends no owner query, and a page with no labels no guard 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> {
+ page: { id: number; frontmatter?: Record<string, unknown> | null } | null, stored: TrustTier | null, incoming?: Record<string, unknown> | null): Promise<LabelGuard | null> {
if (!trust || !page || !stored || row.authority?.remote === true || !(CONTENT_OPERATIONS.includes(row.operation) || declaresDerivation(row.intent))
|| isFenceEditWrite(row) || compareTrust(trust.tier, OWNER_TIER_FLOOR) >= 0) return null;
const labels = page.frontmatter ?? {};
- if (!labelledPrivate(labels) && normalizeReaders(labels) === null) return null;
- const since = await engine.executeRaw<{ prior: string | null }>(`SELECT before_state->>'prior_tier' AS prior FROM trust_proposals
- WHERE target_table = 'pages' AND target_id = $1 AND action = 'lower_page' AND status <> 'accepted' AND id > COALESCE((SELECT max(id) FROM trust_proposals
- WHERE target_table = 'pages' AND target_id = $1 AND action = 'lower_page' AND status = 'accepted'), 0)`, [Number(page.id)]);
- const guard = maxTrust(stored === 'unknown' ? minTrust(OWNER_TIER_FLOOR, ...frontmatterTrustCaps(labels)) : stored,
- ...since.map(proposal => proposal.prior).filter(isTrustTier));
- return compareTrust(trust.tier, guard) < 0 ? guard : null;
+ let tier: TrustTier | null = null;
+ if (labelledPrivate(labels) || normalizeReaders(labels) !== null) {
+ const [guard] = await engine.executeRaw<{ owner_set: string | null; priors: (string | null)[] | null }>(`SELECT
+ (SELECT tier FROM page_label_guards WHERE page_id = $1) AS owner_set,
+ ARRAY(SELECT before_state->>'prior_tier' FROM trust_proposals WHERE target_table = 'pages' AND target_id = $1 AND action = 'lower_page' AND status <> 'accepted'
+ AND id > COALESCE((SELECT max(id) FROM trust_proposals WHERE target_table = 'pages' AND target_id = $1 AND action = 'lower_page' AND status = 'accepted'), 0)) AS priors`,
+ [Number(page.id)]);
+ tier = maxTrust(stored === 'unknown' ? minTrust(OWNER_TIER_FLOOR, ...frontmatterTrustCaps(labels)) : stored,
+ ...[guard?.owner_set ?? null, ...(guard?.priors ?? [])].filter(isTrustTier));
+ if (compareTrust(trust.tier, tier) >= 0) tier = null;
+ }
+ const owner = normalizeReaders(labels) !== null || !incoming || normalizeReaders(incoming) !== null ? await ownerReader(engine, labels) : null;
+ return tier || owner ? { tier, owner } : null;
+}
+
+/** GST-2521: the brain owner, when the owner reads `frontmatter` by its readers and the opt-in to read past readers is off. */
+async function ownerReader(engine: BrainEngine, frontmatter: Record<string, unknown>): Promise<LabelGuard['owner']> {
+ const member = await ownerMemberId(engine);
+ if (!member || await ownerReadsRestrictedOn(engine)) return null;
+ const identity = await memberIdentity(engine, member).then(found => found.identity, () => null);
+ return identity && readersAllow(frontmatter, identity) ? { member, identity } : null;
+}
+
+/**
+ * GST-2521: the owner's label door (`gbrain repair visibility`, its `--readers` setter, `gbrain repair private-labels`)
+ * keeps the page's tier, so it raises the page's label guard to operator_curated: a later write below that is held from
+ * widening the labels the owner set. In the door's own transaction.
+ */
+export async function raisePageLabelGuard(tx: BrainEngine, sourceId: string, slug: string): Promise<void> {
+ await tx.executeRaw(`INSERT INTO page_label_guards (page_id, tier) SELECT id, $3 FROM pages WHERE source_id = $1 AND slug = $2
+ ON CONFLICT (page_id) DO UPDATE SET tier = EXCLUDED.tier, set_at = now()`, [sourceId, slug, OWNER_TIER_FLOOR]);
}
/**
- * 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.
+ * GST-2518: in place, puts back the stored labels `frontmatter` would widen below the guard tier: 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. GST-2521: readers that would leave out the owner the guard names keep the owner, with the rest of the
+ * narrowing (the stored readers when the incoming ones are malformed). Another narrowing is kept. Returns what was kept
+ * and asked for, or null when nothing was held.
*/
-export function holdPrivacyLabels(frontmatter: Record<string, unknown>, stored: Record<string, unknown> | null | undefined): HeldPrivacyLabels | null {
+export function holdPrivacyLabels(frontmatter: Record<string, unknown>, stored: Record<string, unknown> | null | undefined, guard: LabelGuard): HeldPrivacyLabels | null {
if (!stored) return null;
- const guarded = [...(labelledPrivate(stored) && !labelledPrivate(frontmatter) ? PRIVACY_FLAG_KEYS : []), ...(readersWidened(stored, frontmatter) ? [READERS_KEY] : [])];
+ const widened = guard.tier !== null && readersWidened(stored, frontmatter);
+ const ownerOut = guard.owner !== null && !readersAllow(frontmatter, guard.owner.identity);
+ const guarded = [...(guard.tier && labelledPrivate(stored) && !labelledPrivate(frontmatter) ? PRIVACY_FLAG_KEYS : []), ...(widened || ownerOut ? [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];
+ const requested = frontmatter[key];
+ const withOwner = key === READERS_KEY && !widened ? [...(typeof requested === 'string' ? [requested] : Array.isArray(requested) ? requested : []), guard.owner!.member] : null;
+ const kept = withOwner && readersAllow({ [READERS_KEY]: withOwner }, guard.owner!.identity) ? withOwner : stored[key];
+ held.kept[key] = kept ?? null;
+ held.requested[key] = requested ?? null;
+ if (kept === undefined) delete frontmatter[key];
+ else frontmatter[key] = kept;
}
return held;
}
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 365b1cc774..902473e467 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -315,6 +315,9 @@
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_label_guards.page_label_guards_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_label_guards.page_label_guards_pkey": "p PRIMARY KEY (page_id)",
+ "page_label_guards.page_label_guards_tier_check": "c CHECK ((tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
"page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -946,6 +949,9 @@
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_label_guards": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1518,6 +1524,7 @@
"page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_label_guards_pkey": "CREATE UNIQUE INDEX page_label_guards_pkey ON public.page_label_guards USING btree (page_id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
"page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
@@ -3406,6 +3413,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_label_guards": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 tier text/text NOT NULL",
+ "3 set_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_mention_state": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index f5f37f52ab..c8e6c3ef15 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -315,6 +315,9 @@
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_label_guards.page_label_guards_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_label_guards.page_label_guards_pkey": "p PRIMARY KEY (page_id)",
+ "page_label_guards.page_label_guards_tier_check": "c CHECK ((tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
"page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -946,6 +949,9 @@
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_label_guards": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1518,6 +1524,7 @@
"page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_label_guards_pkey": "CREATE UNIQUE INDEX page_label_guards_pkey ON public.page_label_guards USING btree (page_id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
"page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
@@ -3406,6 +3413,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_label_guards": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 tier text/text NOT NULL",
+ "3 set_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_mention_state": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 717dd57ead..dedabd28c1 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -315,6 +315,9 @@
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_label_guards.page_label_guards_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_label_guards.page_label_guards_pkey": "p PRIMARY KEY (page_id)",
+ "page_label_guards.page_label_guards_tier_check": "c CHECK ((tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
"page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
@@ -946,6 +949,9 @@
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_label_guards": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1514,6 +1520,7 @@
"page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_label_guards_pkey": "CREATE UNIQUE INDEX page_label_guards_pkey ON public.page_label_guards USING btree (page_id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
"page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
@@ -3402,6 +3409,14 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_label_guards": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 tier text/text NOT NULL",
+ "3 set_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_mention_state": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 22feb54248..fd0cca44df 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 299,
+ "count": 300,
"gaps": [
17,
18,
@@ -103,7 +103,7 @@
"widenIdentityIndex": "86a6176bd7637d964dbc1d3cd3b1bdfa3ca0161e1ee248c37d7380a1471282e6",
"withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"
},
- "latest": 304,
+ "latest": 305,
"records": [
{
"handler": {
@@ -4963,6 +4963,19 @@
"transaction": "absent",
"verify": "absent",
"version": 304
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "page_label_guards",
+ "sql": {
+ "length": 537,
+ "sha256": "3aca0f590ee8af3dcbf4a3c220150b62b59b41721df00f4e56a96ebd52475e7d"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 305
}
],
"versions": [
@@ -5264,7 +5277,8 @@
301,
302,
303,
- 304
+ 304,
+ 305
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/owner-label-guard.test.ts b/test/owner-label-guard.test.ts
new file mode 100644
index 0000000000..1f26e1e938
--- /dev/null
+++ b/test/owner-label-guard.test.ts
@@ -0,0 +1,247 @@
+/**
+ * GST-2521: the label hold, part 2 (stacked on GST-2518).
+ *
+ * 1. Protects: (A) labels the owner sets on a page through the owner's label door (`gbrain repair visibility`, its
+ * `--readers` setter) raise the page's label guard tier, so a later local write at the page's own (agent) tier that
+ * drops or widens them is held like a write below an owner page; (B) a local write below operator_curated whose
+ * `readable_by` would stop the brain owner reading a page the owner reads now publishes with the owner still a
+ * reader, and its `lower_page` item records the readers it asked for. An unbound remote read and a non-owner member
+ * read gain nothing; a credential bound to the owner reads before, during and after.
+ * 2. Fails when: an equal-tier agent write drops an owner-set label, an agent write takes the owner out of the readers,
+ * accept does not apply the request, or something that should pass is held (the owner's readers setter, an agent
+ * narrowing that keeps the owner, the owner opt-in to read restricted pages).
+ * 3. Real seams: local put_page through the write coordinator, `gbrain repair visibility` through runRepairCommand, remote
+ * reads through MCP dispatch with legacy tokens, owner decisions through decideTrustProposal, the managed-brain harness
+ * (Git commit) 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, 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 { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { addMember, bindCredential } from '../src/core/access/members.ts';
+import { setOwner, setOwnerReadsRestricted } 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);
+
+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]!;
+
+/** 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);
+async function call(b: Brain, name: string, params: Record<string, unknown>): Promise<Record<string, any>> {
+ return await operations.find(op => op.name === name)!.handler(b.ctx, { request_id: randomUUID(), wait_ms: 30_000, ...params }) as Record<string, any>;
+}
+
+/** `gbrain repair visibility` previewed, then applied with its preview hash, as the owner runs it on the brain host. */
+async function repairVisibility(engine: BrainEngine, argv: string[]): Promise<Record<string, any>> {
+ const run = async (args: string[]) => {
+ const log = console.log;
+ let printed = '';
+ console.log = (...parts: unknown[]) => { printed += parts.join(' ') + NL; };
+ try { await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => runRepairCommand(engine, [...args, '--json'])); } finally { console.log = log; _resetCliExitVerdictForTests(); }
+ return JSON.parse(printed);
+ };
+ const preview = await run(['visibility', ...argv]);
+ return run(['visibility', ...argv, '--apply', '--expect', preview.results?.[0]?.preview_hash ?? preview.preview_hash]);
+}
+const readsOf = async (reads: (who: Reader, slug: string, canary: string) => Promise<boolean>, slug: string, canary: string) =>
+ ({ unbound: await reads('unbound', slug, canary), bob: await reads('bob', slug, canary), owner: await reads('owner', slug, canary) });
+
+for (const backend of testBackends()) describe('[' + backend + '] owner-set labels and the owner as a reader, on a repo-less brain', () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const SRC = 'guard-src';
+ async function repoless(fn: (b: Brain, reads: Awaited<ReturnType<typeof remoteReaders>>) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-owner-guard-'));
+ 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('A: the owner makes an agent page private; an agent write at the page\'s tier that drops the label is held until accept', () => repoless(async (b, reads) => {
+ const slug = 'notes/owner-private-example', canary = 'canaryownerprivate';
+ await call(b, 'put_page', { slug, content: file(slug, [], canary) });
+ expect((await pageRow(b.engine, SRC, slug)).tier).toBe('agent_written');
+ await repairVisibility(b.engine, ['--source', SRC, '--slug', slug]);
+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.visibility).toBe('private');
+ expect((await pageRow(b.engine, SRC, slug)).tier).toBe('agent_written');
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ const written = await put(b, slug, file(slug, [], canary, 'An agent rewrote it.'));
+ expect(written.privacy_labels_kept?.keys).toEqual(['visibility']);
+ const held = await pageRow(b.engine, SRC, slug);
+ expect(held.frontmatter.visibility).toBe('private');
+ expect(held.body).toContain('An agent rewrote it.');
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted' });
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: true, bob: true, owner: true });
+ }), 180_000);
+
+ test('A: readers the owner sets with --readers on an agent page are not widened by an equal-tier agent write; reject keeps them', () => repoless(async (b, reads) => {
+ const slug = 'notes/owner-readers-example', canary = 'canaryownerreaders';
+ await call(b, 'put_page', { slug, content: file(slug, [], canary) });
+ await repairVisibility(b.engine, ['--source', SRC, '--slug', slug, '--readers', 'alice-example,' + OWNER]);
+ expect((await pageRow(b.engine, SRC, slug)).tier).toBe('agent_written');
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ const written = await put(b, slug, file(slug, ['readable_by: [alice-example, bob-example, ' + OWNER + ']'], canary, 'Rewritten.'));
+ expect(written.privacy_labels_kept?.keys).toEqual(['readable_by']);
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'reject')).toMatchObject({ status: 'rejected' });
+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.readable_by).toEqual(['alice-example', OWNER]);
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ }), 180_000);
+
+ test('B: an agent write that takes the owner out of the readers keeps the owner a reader until accept', () => repoless(async (b, reads) => {
+ const slug = 'notes/owner-dropped-example', canary = 'canaryownerdropped';
+ await seedOwnerPage(b.engine, SRC, slug, file(slug, ['readable_by: [alice-example, ' + OWNER + ']'], canary));
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ const written = await put(b, slug, file(slug, ['readable_by: [alice-example]'], canary, 'Narrowed.'));
+ expect(written.privacy_labels_kept?.keys).toEqual(['readable_by']);
+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.readable_by).toEqual(['alice-example', OWNER]);
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ const [proposal] = await proposalsOf(b, slug);
+ expect(proposal!.after_state.labels).toMatchObject({ keys: ['readable_by'], requested: { readable_by: ['alice-example'] } });
+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted' });
+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.readable_by).toEqual(['alice-example']);
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: false });
+ }), 180_000);
+
+ test('B: on an agent\'s own page, and when an agent restricts a page that named no readers, the owner stays a reader', () => repoless(async (b, reads) => {
+ const own = 'notes/agent-readers-example', canary = 'canaryagentreaders';
+ await call(b, 'put_page', { slug: own, content: file(own, ['readable_by: [alice-example, ' + OWNER + ']'], canary) });
+ const narrowed = await put(b, own, file(own, ['readable_by: [alice-example]'], canary, 'Narrowed.'));
+ expect(narrowed.privacy_labels_kept?.keys).toEqual(['readable_by']);
+ expect(await readsOf(reads, own, canary)).toEqual({ unbound: false, bob: false, owner: true });
+
+ const open = 'notes/open-example', openCanary = 'canaryopen';
+ await seedOwnerPage(b.engine, SRC, open, file(open, [], openCanary));
+ expect(await readsOf(reads, open, openCanary)).toEqual({ unbound: true, bob: true, owner: true });
+ const restricted = await put(b, open, file(open, ['readable_by: [alice-example]'], openCanary, 'Restricted.'));
+ expect(restricted.privacy_labels_kept?.keys).toEqual(['readable_by']);
+ expect((await pageRow(b.engine, SRC, open)).frontmatter.readable_by).toEqual(['alice-example', OWNER]);
+ expect(await readsOf(reads, open, openCanary)).toEqual({ unbound: false, bob: false, owner: true });
+ }), 180_000);
+
+ test('nothing is held that should not be: an agent narrowing that keeps the owner, the owner\'s readers setter, the owner opt-in', () => repoless(async (b, reads) => {
+ const keep = 'notes/keeps-owner-example', canary = 'canarykeepsowner';
+ await seedOwnerPage(b.engine, SRC, keep, file(keep, ['readable_by: [alice-example, bob-example, ' + OWNER + ']'], canary));
+ const narrowed = await put(b, keep, file(keep, ['readable_by: [alice-example, ' + OWNER + ']'], canary, 'Narrowed.'));
+ expect(narrowed.privacy_labels_kept).toBeUndefined();
+ expect(await readsOf(reads, keep, canary)).toEqual({ unbound: false, bob: false, owner: true });
+
+ const setter = 'notes/setter-example', setterCanary = 'canarysetter';
+ await seedOwnerPage(b.engine, SRC, setter, file(setter, ['readable_by: [alice-example, ' + OWNER + ']'], setterCanary));
+ await repairVisibility(b.engine, ['--source', SRC, '--slug', setter, '--readers', 'alice-example', '--allow-without-owner']);
+ expect((await pageRow(b.engine, SRC, setter)).frontmatter.readable_by).toEqual(['alice-example']);
+ expect(await proposalsOf(b, setter)).toEqual([]);
+
+ await setOwnerReadsRestricted(b.engine, true, { remote: false });
+ const opted = 'notes/opted-example', optedCanary = 'canaryopted';
+ await seedOwnerPage(b.engine, SRC, opted, file(opted, ['readable_by: [alice-example, ' + OWNER + ']'], optedCanary));
+ const dropped = await put(b, opted, file(opted, ['readable_by: [alice-example]'], optedCanary, 'Narrowed.'));
+ expect(dropped.privacy_labels_kept).toBeUndefined();
+ expect(await reads('owner', opted, optedCanary)).toBe(true);
+ }), 180_000);
+});
+
+for (const backend of testBackends()) describe('[' + backend + '] owner-set labels on an agent page, on a managed git source', () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), 'archive/' + NL); durableGitRepo(root, ['.gitignore']); };
+
+ test('A and B: the committed file keeps the owner\'s label and the owner as a reader', () => managedBrain(async ({ engine, ctx, root }) => {
+ const b: Brain = { engine, ctx, sourceId: 'default', home: root };
+ const reads = await remoteReaders(engine, 'default');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ const slug = 'notes/managed-owner-example', canary = 'canarymanaged';
+ await call(b, 'put_page', { slug, content: file(slug, [], canary) });
+ await settleManagedGitEffects(engine);
+ await repairVisibility(engine, ['--source', 'default', '--slug', slug, '--readers', 'alice-example,' + OWNER]);
+ await settleManagedGitEffects(engine);
+ expect((await pageRow(engine, 'default', slug)).tier).toBe('agent_written');
+ const committed = () => git(root, 'show', 'HEAD:' + slug + '.md');
+ expect(committed()).toContain('readable_by:');
+ const widened = await put(b, slug, file(slug, [], canary, 'An agent rewrote it.'));
+ expect(widened.privacy_labels_kept?.keys).toEqual(['readable_by']);
+ await settleManagedGitEffects(engine);
+ expect(committed()).toContain('An agent rewrote it.');
+ expect((await pageRow(engine, 'default', slug)).frontmatter.readable_by).toEqual(['alice-example', OWNER]);
+ expect(committed()).toContain(OWNER);
+ const narrowed = await put(b, slug, file(slug, ['readable_by: [alice-example]'], canary, 'An agent narrowed it.'));
+ expect(narrowed.privacy_labels_kept?.keys).toEqual(['readable_by']);
+ await settleManagedGitEffects(engine);
+ expect(committed()).toContain('An agent narrowed it.');
+ expect(committed()).toContain(OWNER);
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ }, { databaseUrl, setup }), 240_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index c6bd221b6f..8af961e20a 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -331,6 +331,7 @@ test/origin-twins-6948.test.ts
test/orphan-effect-diagnostics-7985.test.ts
test/overwritten-edits-6712.test.ts
test/owner-facts-d1-gst2346.test.ts
+test/owner-label-guard.test.ts
test/owner-member-boundary.test.ts
test/owner-reads-restricted.test.ts
test/owner-refusal.test.ts