Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Close four bypasses of the label hold: reject then lower, delete then write, unknown-tier pages, derived maintenance publications; bind undo to the accepted revision (GST-2518)
garrytanaa8c675d2fdc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 06189be784..9eef1bc019 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,14 +12,15 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**An agent edit can no longer make a private page readable before you decide.** A local `put_page` (or `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) from a writer less trusted than the page used to publish at once even when it dropped or widened the page's `visibility`, `access`, `confidentiality` or `readable_by`. The only safeguard was a `lower_page` item in `gbrain trust review`, and until you dealt with it, remote callers and other members could read the page. The usual cause was an agent that rewrote a page and forgot its frontmatter. Now that write publishes with the page's earlier labels kept, in the database and in the file it commits, and its receipt names the kept keys (`privacy_labels_kept`). The `lower_page` item shows the labels the edit asked for. `gbrain trust confirm tp<id>` applies exactly those labels if the page hasn't changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm puts them back. A credential bound to you reads the page throughout. Unaffected: writes that only narrow a label, writes that leave the labels alone, writers at or above the page's tier, your own synced edits, and `gbrain repair visibility` (GST-2518).+**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-- `src/core/trust/page-write.ts`, `src/core/persistence/page-prepare.ts`: a local content write below `operator_curated`, and below the page's label guard tier, keeps the stored labels it would widen. The guard tier is the page's tier, raised to the earlier tier recorded on the page's newest `lower_page` item unless you confirmed it. The `lower_page` item records the kept and requested labels, and a later write by the same tier replaces them with what it asked for, so a write that puts the label back withdraws the request. A write that changes only labels publishes nothing and still files its item.-- `src/core/trust/page-handlers.ts`: confirming a held item writes the requested labels in the same owner page write that confirms the page. New undo for a confirmed held item restores the kept labels and the edit's tier.+- `src/core/trust/page-write.ts`, `src/core/persistence/page-prepare.ts`: a local content write below `operator_curated`, and below the page's label guard tier, keeps the stored labels it would widen, and so does a derived page publication. The guard tier is the page's tier (`operator_curated` lowered by its frontmatter caps when the tier is `unknown`), raised to the earlier tier recorded on every `lower_page` item of the page since the last one you confirmed. The `lower_page` item records the kept and requested labels, and a later write by the same tier replaces them with what it asked for, so a write that puts the label back withdraws the request. A write that changes only labels publishes nothing and still files its item.+- `src/core/trust/page-handlers.ts`: confirming a held item writes the requested labels in the same owner page write that confirms the page. New undo for a confirmed held item restores the kept labels and the edit's tier, and only while the page is at the revision the confirm wrote.+- `src/core/persistence/page-prepare.ts`: a soft delete keeps the page's tier (it writes no content). `src/core/persistence/prepared-maintenance.ts`: a derived publication whose labels were kept files one item, with the labels.- `src/core/trust/owner-actions.ts`, `src/core/trust/review.ts`: the confirm and drop previews and the review item name the held labels.-- Tests: `test/lower-tier-label-hold.test.ts` covers each label dropped and widened, remote reads (unbound, another member, the owner), accept, reject, undo, a withdrawn request, the two-step bypass, the cases that must pass unheld, and the committed file on a managed Git source, on PGLite and Postgres.+- Tests: `test/lower-tier-label-hold.test.ts` covers each label dropped and widened, remote reads (unbound, another member, the owner), accept, reject, undo, a stale undo, a withdrawn request, the two-step and reject-then-lower bypasses, a delete then a write, an `unknown` page, a derived maintenance publication, the cases that must pass unheld, and the committed file on a managed Git source, on PGLite and Postgres.## [0.60.687.0] - 2026-11-12diff --git a/docs/guides/memory-trust.md b/docs/guides/memory-trust.mdindex 05afb411f2..d018e4861b 100644--- a/docs/guides/memory-trust.md+++ b/docs/guides/memory-trust.md@@ -290,12 +290,16 @@ for, for example `visibility private -> (none)`.- `gbrain trust confirm tp<id>` endorses the edit and applies exactly thoselabels, if the page hasn't changed since.- `gbrain trust drop tp<id>` keeps the earlier labels.-- Undoing a confirm puts the earlier labels and the edit's tier back.+- Undoing a confirm puts the earlier labels and the edit's tier back, if the+ page hasn't changed since the confirm.Until you decide, the page stays private to remote callers and to memberswho weren't readers; a credential bound to you still reads it. The hold also-applies after you drop the item, and after an earlier agent edit that lowered-the page, so a later agent write still can't widen the labels. It doesn't+applies after you drop the item, after an earlier agent edit that lowered+the page, and after an agent deletes the page and writes it again, so a later+agent write still can't widen the labels. A maintenance job's derived page+(a dream patterns run rewriting one of your pages) is held the same way, and a+page with no recorded tier (`unknown`) counts as yours. It doesn'tapply to a write that only narrows a label, to a write that leaves the labelsalone, to a writer at or above the page's tier, or to your own edits (a fileyou edit and sync, `gbrain repair visibility`).diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 8b82ad8391..16fff08af3 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -497,6 +497,7 @@ src/core/persistence/page-prepare.ts fileMatchesSnapshot field SEGW lane 1d filesrc/core/persistence/page-prepare.ts frontmatterDriftWrite field SEGW #8109: called only for an inline page (bodyUnread excluded at the call site); compares the file's parsed body with the snapshot bodysrc/core/persistence/page-prepare.ts prepareInlineOrSegmentedMutation call:serializePageToMarkdown SEGW lane 1d filesrc/core/persistence/page-prepare.ts prepareInlineOrSegmentedMutation field SEGW lane 1d file: preserveProtectedTakes reads the snapshot body; segmented page: getter throws page_body_segmented+src/core/persistence/page-prepare.ts remoteCoreMarkingKept call:serializePageToMarkdown SEGW lane 1d file: the remote core-marking carry moved out of prepareInlineOrSegmentedMutation (GST-2518, function size); same read as beforesrc/core/persistence/page-prepare.ts segmentedFileMatches field NONE the body fields hold region digests (body-digests.ts) for the canonical comparison; no page body is readsrc/core/persistence/page-prepare.ts unreadPageFile call:serializePageToMarkdown NONE serializes the frontmatter head with an empty body; the body streams from the segments through segmentedExportMarkdownsrc/core/persistence/page-purge.ts purgePageInTransaction field STREAMdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 7efbd96f0f..36179ae654 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1547,7 +1547,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.685.0', id: 'owner_facts_shared_gst2346', text: 'A credential bound to the brain owner (`gbrain access owner set`), or a stdio server started with `--stdio-member <owner>`, speaking for itself, now saves `remember` facts the way a credential bound to no member does: with no `visibility`, a fact is shared on its subject\'s page and every reader of the source recalls it, where it used to be kept private on the owner\'s member page. It stays private on that page when the call passes `visibility: "private"` or the subject\'s page or `facts.default_visibility` keeps facts private, and the reply names the `page` and `visibility` either way. Its `visibility: "world"` is saved instead of refused (`member_share_required`), except onto a page whose facts are kept private (`share_target_restricted`, as `share: true`), and its `forget` withdraws a shared fact it reads instead of saying only the brain host can. An owner agent that follows a planted instruction can therefore share a fact without passing any flag; to keep a fact private, pass `visibility: "private"`. Member credentials, attested QM calls (`x-qm-actor`), audiences (`X-Gbrain-On-Behalf-Of`), subagent jobs and slug-fenced clients are unchanged, and with writeback on the owner\'s credential is no longer told its saves stay private.' },{ since: '0.60.686.0', id: 'readers_label_setter_gst2476', text: 'New `gbrain repair visibility (--slug <page>... | --slugs-file <file>) --readers <ids|none>` sets or removes a page\'s `readable_by` through the label-only door: the page keeps its trust tier and provenance and its file changes only on that line. Unknown or disabled members and unknown groups refuse `access_member_invalid`; a list without the brain owner refuses unless `--allow-without-owner`. Every `repair visibility` write to a managed page with no file outside a declared `storage.db_only` path is now held `canonical_file_missing` with nothing written, instead of failing `source_changed`.' },{ since: '0.60.686.0', id: 'fence_fact_private_in_place_gst2487', text: 'A page write that only makes a `## Facts` row private (same claim, world to private) now makes the stored row private in place, keeping its id and trust tier, even when the row is more trusted than the writer. Before, such a row stayed live and world beside a contested private copy, so `gbrain repair visibility --class facts` could leave a fact remote callers still read while the page and its file read as fixed (`fact_left_readable`, `fact_left_world`). On a brain without managed persistence the repair now also makes the fenced row private. A write that makes a more trusted private row world is still held for the owner as before.' },- { since: 'TBD', id: 'page_label_widening_held_gst2518', text: 'A local agent write (`put_page`, `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) less trusted than a page that drops or widens its `visibility`, `access`, `confidentiality` or `readable_by` now publishes with the page\'s earlier labels kept, in the database and in the committed file, and its receipt lists them under `privacy_labels_kept`. Before, the page became readable to remote callers and other members at once, and only a `lower_page` item waited for the owner. That item now records the requested labels: `gbrain trust confirm tp<id>` applies them if the page has not changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm restores them. Narrowing writes, label-neutral writes, writers at or above the page\'s tier, synced owner edits and `gbrain repair visibility` are unchanged.' },+ { 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.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex e8b641f366..acab135615 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -734,7 +734,8 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,// #7311: the tombstone forgets the survivor's file, as an origin_twin page has, so its purge writes no deletion marker for it.if (preparedPurge && sharedRetention) return purgePageInTransaction(tx, row, { ...snapshot, page: { ...snapshot.page, source_path: null, source_uri: null } }, preparedPurge);if (preparedPurge) return purgePageInTransaction(tx, row, snapshot, preparedPurge);- if (!noop) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }+ // GST-2518: a soft delete authors no content, so the tombstone keeps its tier (and a write over it the page's label guard).+ if (!noop) { await tx.createVersion(row.slug, source); await withTrustKeep(tx, ['pages'], () => tx.softDeletePage(row.slug, source)); }return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop,recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)' };} };diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 1c2e39dbef..ca2b2c6228 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -592,7 +592,8 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Writeif (derived) {const lowered = await lowerToDerivedTier(tx, derived.table, [derived.id], trust);if (declaration) await recordTaintEdges(tx, { ...derived, sourceId: row.source_id }, declaration.inputs);- if (lowered.length && prior?.tier) await recordAgentPageLowering(tx, row, { tier: prior.tier, revision: prior.revision });+ // GST-2518: a publication whose labels were kept already filed its proposal with them; a second record would withdraw them.+ if (lowered.length && prior?.tier && !outcome.privacy_labels_kept) await recordAgentPageLowering(tx, row, { tier: prior.tier, revision: prior.revision });}return outcome;} };diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.tsindex a78dade5d0..5ad7c8b7fe 100644--- a/src/core/trust/page-handlers.ts+++ b/src/core/trust/page-handlers.ts@@ -215,7 +215,11 @@ type OwnerPageIntent = {/** Closes a decided proposal inside the publication transaction, or refuses (it was decided meanwhile). */async function closeProposal(tx: BrainEngine, proposal: PageActionInput['proposal'], by: Principal | null | undefined): Promise<void> {if (!proposal) return;- if (!(await transitionTrustProposal(tx, proposal.id, proposal.from ?? 'pending', proposal.to, { after: proposal.after, decidedBy: by ?? null }))) {+ // GST-2518: an accepted held-label proposal records the revision its accept wrote, so an undo applies only to that page.+ const [accepted] = proposal.to === 'accepted' && heldPrivacyLabels(proposal.after) ? await tx.executeRaw<{ revision: string }>(`SELECT p.knowledge_revision::text AS revision+ FROM trust_proposals t JOIN pages p ON p.id = t.target_id WHERE t.id = $1 AND t.target_table = 'pages'`, [proposal.id]) : [];+ const after = accepted ? { ...proposal.after, accepted_revision: accepted.revision } : proposal.after;+ if (!(await transitionTrustProposal(tx, proposal.id, proposal.from ?? 'pending', proposal.to, { after, decidedBy: by ?? null }))) {throw opError('preview_changed', `Trust proposal tp${proposal.id} was decided by someone else meanwhile; nothing was changed.`,'Run gbrain trust review to see its current state.');}@@ -533,17 +537,14 @@ registerTrustProposalHandler('lower_page', {});return decisionResult(proposal, 'accept', 'accepted', { detail: { ...result } });},- // GST-2518: only a proposal that held privacy labels undoes: its kept labels and edited tier come back, while the page still has the accepted labels.+ // GST-2518: only a proposal that held privacy labels undoes: its kept labels and edited tier come back, while the page is still the one its accept wrote.async undo(engine, proposal, ctx) {const labels = heldPrivacyLabels(proposal.after_state);if (!labels) return decisionResult(proposal, 'undo', 'refused', { reason: 'undo_unsupported' });const state = lowerPageState(proposal);const page = state.slug ? await readPageTrustState(engine, proposal.source_id, state.slug) : null;if (!page || page.pageId !== proposal.target_id) return decisionResult(proposal, 'undo', 'stale', { reason: 'page_missing' });- const frontmatter = (page.snapshot.page.frontmatter ?? {}) as Record<string, unknown>;- if (labels.keys.some(key => JSON.stringify(frontmatter[key] ?? null) !== JSON.stringify(labels.requested[key] ?? null))) {- return decisionResult(proposal, 'undo', 'stale', { reason: 'labels_changed_since' });- }+ if (page.revision !== proposal.after_state.accepted_revision) return decisionResult(proposal, 'undo', 'stale', { reason: 'page_changed_since' });const result = await undoPageLabels(engine, {sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, confirmation: ctx.confirmation, by: ctx.decidedBy, config: ctx.config,labels: labels.kept, tier: state.edited_tier,diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.tsindex 51854a558f..590012b42f 100644--- a/src/core/trust/page-write.ts+++ b/src/core/trust/page-write.ts@@ -139,20 +139,23 @@ function readersWidened(stored: Record<string, unknown>, incoming: Record<string/*** GST-2518: the label guard tier when a write must keep the page's privacy labels, else null. It applies to a local content- * write below operator_curated over a page that is private by its labels or names readers, when the write is below the- * guard: the stored tier, raised to the prior tier of the page's newest `lower_page` proposal unless the owner accepted it- * (pending, dismissed, reverted or undone). So an earlier lowering edit, or a rejected or undone widening, does not let an- * equal-tier write widen the page. Other writes send no query.+ * 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.*/export async function privacyLabelGuard(engine: BrainEngine, row: Pick<WriteRequest, 'operation' | 'intent' | 'authority'>, trust: WriteTrust | undefined,page: { id: number; frontmatter?: Record<string, unknown> | null } | null, stored: TrustTier | null): Promise<TrustTier | null> {- if (!trust || !page || !stored || row.authority?.remote === true || !CONTENT_OPERATIONS.includes(row.operation) || isFenceEditWrite(row)- || compareTrust(trust.tier, OWNER_TIER_FLOOR) >= 0) return null;+ 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 [newest] = await engine.executeRaw<{ status: string; prior: string | null }>(`SELECT status, before_state->>'prior_tier' AS prior FROM trust_proposals- WHERE target_table = 'pages' AND target_id = $1 AND action = 'lower_page' ORDER BY id DESC LIMIT 1`, [Number(page.id)]);- const guard = newest && newest.status !== 'accepted' && isTrustTier(newest.prior) ? maxTrust(stored, newest.prior) : stored;+ 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;}diff --git a/test/lower-tier-label-hold.test.ts b/test/lower-tier-label-hold.test.tsindex 13e7325c65..547e6aeda4 100644--- a/test/lower-tier-label-hold.test.ts+++ b/test/lower-tier-label-hold.test.ts@@ -8,7 +8,8 @@* page is still at the held revision), reject keeps the earlier ones, undo restores them. An unbound remote read and a* non-owner member read see nothing before accept; a credential bound to the owner reads the page before, during and* after the hold. A later lower-tier write that puts the label back withdraws the widening; an earlier body edit that- * lowered the page does not open a second-step bypass.+ * lowered the page, a rejected widening, a delete, or an unclassified (unknown) tier does not open a bypass; a derived+ * maintenance publication is held like a content write; undo applies only to the page its accept wrote.* 2. Fails when: the held write publishes the wider label, the proposal loses the requested labels, accept widens a* withdrawn or changed page, reject or undo leaves the page wider, or a write that should pass is held (the owner's* own sync, an equal-tier writer, a narrowing, a label-neutral edit, the operator readers setter).@@ -46,6 +47,8 @@ import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.timport { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';+import { maintenancePreflight, publishMaintenancePages } from '../src/core/persistence/prepared-maintenance.ts';+import { declareDerivation } from '../src/core/trust/taint.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';const NL = String.fromCharCode(10);@@ -114,6 +117,9 @@ async function put(b: Brain, slug: string, content: string): Promise<Record<striconst 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>;+}/** A repo-less brain (no managed persistence, no checkout: the default keyless install) is the database record. */for (const backend of testBackends()) describe('[' + backend + '] a lower-tier local write that widens a privacy label, on a repo-less brain', () => {@@ -225,6 +231,56 @@ for (const backend of testBackends()) describe('[' + backend + '] a lower-tier lexpect((await proposalsOf(b, slug)).map(p => p.status)).toEqual(['pending']);}), 180_000);+ test('a rejected widening, then a lowering body edit, does not let a later write drop the label', () => repoless(async (b, reads) => {+ const slug = 'notes/rejected-example', canary = 'canaryrejected';+ await seedOwnerPage(b.engine, SRC, slug, file(slug, ['visibility: private'], canary));+ const first = await put(b, slug, file(slug, [], canary, 'Rewritten once.'));+ expect(await decide(b, first.privacy_labels_kept.proposal_ref, 'reject')).toMatchObject({ status: 'rejected' });+ await call(b, 'put_page', { slug, content: file(slug, ['visibility: private'], canary, 'A tool output edit.'), content_origin: 'tool_output',+ expected_revision: (await pageRow(b.engine, SRC, slug)).revision });+ const third = await put(b, slug, file(slug, [], canary, 'Rewritten again.'));+ expect(third.privacy_labels_kept?.keys).toEqual(['visibility']);+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.visibility).toBe('private');+ expect({ unbound: await reads('unbound', slug, canary), bob: await reads('bob', slug, canary), owner: await reads('owner', slug, canary) })+ .toEqual({ unbound: false, bob: false, owner: true });+ }), 180_000);++ test('a delete keeps the tombstone\'s tier, so a write over the tombstone keeps the label', () => repoless(async (b, reads) => {+ const slug = 'notes/tombstone-example', canary = 'canarytombstone';+ await seedOwnerPage(b.engine, SRC, slug, file(slug, ['visibility: private'], canary));+ await call(b, 'delete_page', { slug, expected_revision: (await pageRow(b.engine, SRC, slug)).revision });+ const [tombstone] = await b.engine.executeRaw<{ revision: string; tier: string }>(+ 'SELECT knowledge_revision::text AS revision, trust_tier::text AS tier FROM pages WHERE source_id=$1 AND slug=$2', [SRC, slug]);+ expect(tombstone!.tier).toBe('operator_curated');+ const written = await call(b, 'put_page', { slug, content: file(slug, [], canary, 'Recreated.'), expected_revision: tombstone!.revision });+ expect(written.privacy_labels_kept?.keys).toEqual(['visibility']);+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.visibility).toBe('private');+ expect({ unbound: await reads('unbound', slug, canary), owner: await reads('owner', slug, canary) }).toEqual({ unbound: false, owner: true });+ }), 180_000);++ test('an unclassified (unknown tier) private page is held like an owner page', () => repoless(async (b, reads) => {+ const slug = 'notes/unknown-example', canary = 'canaryunknown';+ await importFromContent(b.engine, slug, file(slug, ['visibility: private'], canary), { noEmbed: true, sourceId: SRC });+ expect((await pageRow(b.engine, SRC, slug)).tier).toBe('unknown');+ const written = await put(b, slug, file(slug, [], canary, 'An agent rewrote it.'));+ expect(written.privacy_labels_kept?.keys).toEqual(['visibility']);+ expect({ unbound: await reads('unbound', slug, canary), owner: await reads('owner', slug, canary) }).toEqual({ unbound: false, owner: true });+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted' });+ expect(await reads('unbound', slug, canary)).toBe(true);+ }), 180_000);++ test('undo after the page changed since accept is stale and changes nothing', () => repoless(async (b) => {+ const slug = 'notes/undo-stale-example', canary = 'canaryundostale';+ await seedOwnerPage(b.engine, SRC, slug, file(slug, ['visibility: private'], canary));+ const written = await put(b, slug, file(slug, [], canary, 'Agent text.'));+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted' });+ await seedOwnerPage(b.engine, SRC, slug, file(slug, [], canary, 'The owner rewrote it later.'));+ expect(await decide(b, written.privacy_labels_kept.proposal_ref, 'undo')).toMatchObject({ status: 'stale' });+ const page = await pageRow(b.engine, SRC, slug);+ expect(page.tier).toBe('operator_curated');+ expect(page.frontmatter.visibility).toBeUndefined();+ }), 180_000);+test('nothing is held that should not be: an equal-tier writer, a narrowing, a label-neutral edit, the owner readers setter', () => repoless(async (b, reads) => {// An equal-tier writer: a page an agent wrote (agent_written) and labelled, then dropped by the same tier.const own = 'notes/agent-own-example';@@ -308,4 +364,21 @@ for (const backend of testBackends()) describe('[' + backend + '] a lower-tier lexpect((await pageRow(engine, 'default', mine)).tier).toBe('operator_curated');expect(await proposalsOf(b, mine)).toEqual([]);}, { databaseUrl, setup }), 240_000);++ test('a derived maintenance publication (dream patterns) keeps the label in the commit and files it for the owner', () => managedBrain(async ({ engine, ctx, root }) => {+ const b: Brain = { engine, ctx, sourceId: 'default', home: root };+ const reads = await remoteReaders(engine, 'default');+ const slug = 'notes/derived-example', canary = 'canaryderived';+ await commitAndSync(engine, root, { [slug]: file(slug, ['visibility: private'], canary) });+ const derivation = declareDerivation({ tier: 'agent_written', origin: { channel: 'derive:patterns' } }, []);+ await publishMaintenancePages(engine, (await maintenancePreflight(engine, 'default'))!, [{ slug, content: file(slug, [], canary, 'A derived rewrite.'),+ expectedRevision: (await pageRow(engine, 'default', slug)).revision, derivation }]);+ await settleManagedGitEffects(engine);+ expect(committed(root, slug)).toContain(NL + 'visibility: private' + NL);+ expect(committed(root, slug)).toContain('A derived rewrite.');+ expect({ unbound: await reads('unbound', slug, canary), owner: await reads('owner', slug, canary) }).toEqual({ unbound: false, owner: true });+ const [proposal, ...rest] = await proposalsOf(b, slug);+ expect(rest).toEqual([]);+ expect(proposal!.after_state.labels).toMatchObject({ keys: ['visibility'], kept: { visibility: 'private' } });+ }, { databaseUrl, setup }), 240_000);});