Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Accepting a label change on an agent's page writes only the labels, and re-running the label repair guards already-labelled pages (GST-2521)

garrytan70781cdee1a1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f88261f9d2..542d89b2bc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,11 +12,13 @@ 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 and is set only by label repairs run after the upgrade, so labels you set earlier, and a managed Git brain rebuilt from a clone, stay unguarded until you run the label repair again (GST-2521).
+**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. Confirming such an item on a page whose own tier is an agent's changes only its labels and leaves the page at the agent's tier, so saying yes to a label change never vouches for the body; on a page of yours, confirm still endorses the edit at your tier. 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 and is set only by label repairs run after the upgrade, so labels you set earlier, and a managed Git brain rebuilt from a clone, start unguarded: running `gbrain repair visibility --slug <page>` or `--readers <list>` again on a page that already has those labels raises the guard without changing the labels or writing the page (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 when the page is left private or naming readers, and remove it otherwise.
-- `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. An error reading the owner fails the write instead of dropping the owner.
-- 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.
+- `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. An error reading the owner fails the write instead of dropping the owner. The `lower_page` item records the page's own tier before the write (`before_state.page_tier`).
+- `src/core/trust/page-handlers.ts`: accepting a held item whose page's own tier was below `operator_curated` writes only the requested labels, keeps the page's tier and resolves the item `labels_applied` (status `labelled`); on an owner page the confirm is unchanged. Undo of either restores the kept labels.
+- `src/core/repair/visibility.ts`, `src/core/repair/readers.ts`: a named page that is already private, or already names the requested readers, and has no guard row is listed (`visibility private kept, label guard raised`, `readers [...] kept, label guard raised`) and applied by raising the guard under the page's row lock, with no page write or commit.
+- 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, accept on an agent page keeping its tier, a re-run of the label repair raising the guard on already-labelled pages (repo-less and a managed batch with no commit), 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).
diff --git a/docs/guides/memory-trust.md b/docs/guides/memory-trust.md
index 487f07880c..9e71f8c724 100644
--- a/docs/guides/memory-trust.md
+++ b/docs/guides/memory-trust.md
@@ -287,8 +287,12 @@ The write's receipt names the kept keys under `privacy_labels_kept`. The
page's `lower_page` item in `gbrain trust review` shows what the edit asked
for, for example `visibility private -> (none)`.
-- `gbrain trust confirm tp<id>` endorses the edit and applies exactly those
- labels, if the page hasn't changed since.
+- `gbrain trust confirm tp<id>` applies exactly those labels, if the page
+ hasn't changed since. On a page of yours it also endorses the edit, and the
+ page takes your tier. On a page whose own tier is an agent's (one you set
+ labels on, or an agent's page that kept you as a reader), it changes only the
+ labels and the page keeps the agent's tier, so saying yes to a label change
+ never vouches for the body.
- `gbrain trust drop tp<id>` keeps the earlier labels.
- Undoing a confirm puts the earlier labels and the edit's tier back, if the
page hasn't changed since the confirm.
@@ -310,8 +314,13 @@ 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 and set only by a label repair run after the
upgrade, so labels you set earlier, and a managed Git brain rebuilt from a
-clone, start without it; run the label repair again to set it. A repair that
-leaves the page with no privacy label removes the guard.
+clone, start without it. Run the label repair again to set it: on a page that
+already has the labels, `gbrain repair visibility --slug <page>` (for a private
+page) or `--readers <list>` (with the readers the page already names) lists it
+as `... kept, label guard raised` and raises the guard without changing the
+labels or writing the page. `gbrain repair private-labels` raises it only on
+pages it writes. A repair that leaves the page with no privacy label removes the
+guard.
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
diff --git a/scripts/postgres-arm-weights-postgres-only.json b/scripts/postgres-arm-weights-postgres-only.json
index c7cc1f4543..ba7e82c9f6 100644
--- a/scripts/postgres-arm-weights-postgres-only.json
+++ b/scripts/postgres-arm-weights-postgres-only.json
@@ -207,7 +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": 18275,
+ "test/owner-label-guard.test.ts": 26999,
"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 f2299de52c..0405eb0bf9 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -318,7 +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": 38733,
+ "test/owner-label-guard.test.ts": 55926,
"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 51a3ce3cfe..b6ad33d2e7 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: '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`) and set only by label repairs run after the upgrade, so labels set earlier, and a managed Git brain rebuilt from a clone, stay unguarded 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: '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. Accepting such an item (`gbrain trust confirm tp<id>`) on a page whose own tier is an agent\'s writes only the labels and keeps the agent\'s tier; on an owner page it still endorses the edit at the owner\'s tier. The guard is stored in the database (`page_label_guards`) and set only by label repairs run after the upgrade, so labels set earlier, and a managed Git brain rebuilt from a clone, start unguarded; re-running `gbrain repair visibility --slug` or `--readers` on a page that already has those labels raises the guard without changing them. 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 2ed0f25750..6ba7c5d447 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -1155,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?.tier ? maxTrust(prior, labelGuard.tier) : 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, pageTier: prior }, 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, [
@@ -1196,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.tier ?? storedTier!, revision: snapshot.revision }, undefined, heldLabels);
+ lowered = await recordAgentPageLowering(tx, row, { tier: labelGuard.tier ?? storedTier!, revision: snapshot.revision, pageTier: storedTier }, 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/repair/readers.ts b/src/core/repair/readers.ts
index c6de1392b3..ac19b6a715 100644
--- a/src/core/repair/readers.ts
+++ b/src/core/repair/readers.ts
@@ -28,6 +28,8 @@ import { digest } from '../persistence/digest.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { raisePageLabelGuard } from '../trust/page-write.ts';
import { afterCursor, type RepairCursor, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';
/** The operator's request: `--readers` as typed (`none` removes), the owner flag, and the `--slugs-file` path with its slugs. */
@@ -96,18 +98,24 @@ function previewCommand(scope: RepairScope, request: ReadersRequest, slugs: stri
+ ' --readers ' + request.readers + (request.allowWithoutOwner ? ' --allow-without-owner' : '');
}
-/** The named pages whose readers differ from the selection's, in page-id order, with the pages not found and already set. */
+/**
+ * The named pages whose readers differ from the selection's, in page-id order, with the pages not found and already set.
+ * GST-2521: a page that already names the selection's readers but has no label guard (an upgrade, a rebuild from a clone)
+ * is listed too, to raise the guard without a write.
+ */
async function planPages(engine: BrainEngine, selection: Selection) {
- const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; named: boolean; readers: unknown; chars: number }>(
- `SELECT p.id, p.source_id, p.slug, p.frontmatter ? 'readable_by' AS named, p.frontmatter->'readable_by' AS readers, COALESCE(p.body_bytes, 0) AS chars
+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; named: boolean; readers: unknown; chars: number; guarded: boolean }>(
+ `SELECT p.id, p.source_id, p.slug, p.frontmatter ? 'readable_by' AS named, p.frontmatter->'readable_by' AS readers, COALESCE(p.body_bytes, 0) AS chars,
+ EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = p.id) AS guarded
FROM pages p WHERE p.deleted_at IS NULL AND p.source_id = ANY($1::text[]) AND p.slug = ANY($2::text[]) ORDER BY p.id`, [selection.source_ids, selection.slugs], { timeoutMs: 120_000 });
const target = normalized(selection.readers);
const items: ReadersItem[] = rows.flatMap(row => {
const from = normalizeReaders(row.named ? { [READERS_KEY]: row.readers } : {});
- if (same(from, target)) return [];
+ const guardOnly = same(from, target);
+ if (guardOnly && (target === null || row.guarded)) return [];
const id = Number(row.id);
return [{ cursor: { phase: READERS_PHASE, id }, target: { phase: READERS_PHASE, id }, source_id: row.source_id, slug: row.slug, chars: Number(row.chars),
- action: 'readers ' + listText(from) + ' -> ' + listText(selection.readers), readers: { from, to: selection.readers } }];
+ action: guardOnly ? 'readers ' + listText(from) + ' kept, label guard raised' : 'readers ' + listText(from) + ' -> ' + listText(selection.readers), readers: { from, to: selection.readers } }];
});
const found = new Set(rows.map(row => row.slug));
return { items, residuals: { named_not_found: selection.slugs.filter(slug => !found.has(slug)).length, readers_already_set: rows.length - items.length } };
@@ -199,6 +207,28 @@ export async function readersWrite(engine: BrainEngine, item: ReadersItem): Prom
return { snapshot, content: serializePageToMarkdown({ ...snapshot.page, frontmatter }, snapshot.tags), edit };
}
+/**
+ * GST-2521: an item whose labels already match (`unchanged` re-checks the page's frontmatter under its row lock) raises the
+ * page's label guard without a write; false when the page moved since the plan.
+ */
+export async function raiseGuardOnly(engine: BrainEngine, item: { source_id: string; slug: string; target: RepairCursor },
+ unchanged: (frontmatter: Record<string, unknown>) => boolean): Promise<false | RepairItemOutcome> {
+ return maintenanceTransaction(engine, async tx => {
+ const [page] = await tx.executeRaw<{ id: number; frontmatter: Record<string, unknown> | null }>(
+ 'SELECT id, frontmatter FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL FOR UPDATE', [item.source_id, item.slug]);
+ if (!page || Number(page.id) !== item.target.id || !unchanged(page.frontmatter ?? {})) return false;
+ await raisePageLabelGuard(tx, item.source_id, item.slug);
+ return { applied: true, outcome: 'label_guard_raised' };
+ });
+}
+
+/** A readers item that only raises the label guard: its page already names the requested readers. */
+export const readersGuardOnly = (item: ReadersItem) => same(item.readers.from, normalized(item.readers.to));
+
+/** A guard-only readers item applied: the guard raised while the page still names those readers. */
+export const raiseReadersGuard = (engine: BrainEngine, item: ReadersItem) =>
+ raiseGuardOnly(engine, item, frontmatter => same(normalizeReaders(frontmatter), item.readers.from));
+
/** The outcome of a written readers item. */
export const readersOutcome = (item: ReadersItem): RepairItemOutcome => ({ applied: true, outcome: item.readers.to ? 'readers_set' : 'readers_removed' });
@@ -216,6 +246,7 @@ export async function retireReaders(engine: BrainEngine, items: ReadersItem[]):
export async function applyReaders(engine: BrainEngine, item: ReadersItem,
write: (snapshot: PageSnapshot, content: string, edit: LabelEdit, batch?: string) => Promise<RepairItemOutcome | null>): Promise<boolean | RepairItemOutcome> {
try {
+ if (readersGuardOnly(item)) return await raiseReadersGuard(engine, item);
const ready = await readersWrite(engine, item);
if (ready === false || !('snapshot' in ready)) return ready;
return await write(ready.snapshot, ready.content, ready.edit, item.hash ? readersBatch(item.hash, item.source_id) : undefined) ?? readersOutcome(item);
diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.ts
index 869ae0a23f..85bd9b03a3 100644
--- a/src/core/repair/visibility.ts
+++ b/src/core/repair/visibility.ts
@@ -54,7 +54,7 @@ import { CANONICAL_FILE_MISSING } from '../persistence/publication-failure.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope, type RepairSettlement, type RepairCursor } from './core.ts';
import { filesInCheckout, writeLabelFile, writeLabelPage } from './label-write.ts';
-import { applyReaders, planReaders, readersBatch, readersGitCounts, readersOutcome, readersWrite, retireReaders, READERS_PHASE, type ReadersItem, type ReadersWrite } from './readers.ts';
+import { applyReaders, planReaders, raiseGuardOnly, raiseReadersGuard, readersBatch, readersGitCounts, readersGuardOnly, readersOutcome, readersWrite, retireReaders, READERS_PHASE, type ReadersItem, type ReadersWrite } from './readers.ts';
import type { LabelEdit } from '../persistence/label-edit.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
@@ -171,13 +171,16 @@ async function planAliases(engine: BrainEngine, sourceIds: string[], only?: numb
/**
* GST-2468: the pages an operator named with --slug, made private (tighten-only: an explicit private stays). The
- * operator's own single-page label change, which a put_page would rate as an agent edit (trust/channel.ts).
+ * operator's own single-page label change, which a put_page would rate as an agent edit (trust/channel.ts). GST-2521: an
+ * already-private page with no label guard (an upgrade, a rebuild from a clone) is listed private -> private, to raise
+ * the guard without a write.
*/
async function planNamed(engine: BrainEngine, sourceIds: string[], slugs: string[]) {
- const rows = await engine.executeRaw<DerivedRow>(`SELECT p.id,p.source_id,p.slug,p.type,p.frontmatter->>'visibility' AS visibility,COALESCE(p.body_bytes, 0) AS chars
+ const rows = await engine.executeRaw<DerivedRow & { guarded: boolean }>(`SELECT p.id,p.source_id,p.slug,p.type,p.frontmatter->>'visibility' AS visibility,COALESCE(p.body_bytes, 0) AS chars,
+ EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = p.id) AS guarded
FROM pages p WHERE p.deleted_at IS NULL AND p.source_id=ANY($1::text[]) AND p.slug=ANY($2::text[]) ORDER BY p.id`, [sourceIds, slugs], bounded);
const changes = rows.flatMap(page => {
- const next = tightened(page.visibility, 'private');
+ const next = tightened(page.visibility, 'private') ?? (page.visibility === 'private' && !page.guarded ? 'private' : null);
return next ? [{ id: Number(page.id), source_id: page.source_id, slug: page.slug, phase: 5 as const, from: page.visibility, to: next }] : [];
});
const found = new Set(rows.map(row => row.slug));
@@ -374,7 +377,7 @@ async function planClass(engine: BrainEngine, sourceIds: string[], cls: Visibili
const toItems = (part: { changes: VisibilityChange[]; rows: DerivedRow[] }) => {
const chars = new Map(part.rows.map(row => [Number(row.id), Number(row.chars)]));
return part.changes.map(change => ({ cursor: { phase: change.phase, id: change.id }, target: { phase: change.phase, id: change.id }, source_id: change.source_id,
- slug: change.slug, chars: chars.get(change.id) ?? 0, action: `visibility ${change.from ?? '(none)'} -> ${change.to}`, change: { from: change.from, to: change.to } }))
+ slug: change.slug, chars: chars.get(change.id) ?? 0, action: change.from === change.to ? `visibility ${change.to} kept, label guard raised` : `visibility ${change.from ?? '(none)'} -> ${change.to}`, change: { from: change.from, to: change.to } }))
.sort((a, b) => a.cursor.phase - b.cursor.phase || a.cursor.id - b.cursor.id);
};
if (cls === 'facts') {
@@ -490,6 +493,7 @@ export const visibilityRepair: RepairHandler = {
const pages: Array<{ index: number; item: ReadersItem; ready: ReadersWrite; requestId: string }> = [];
try {
for (const [index, item] of run.entries()) {
+ if (readersGuardOnly(item)) { out[index] = await raiseReadersGuard(ctx.engine, item).then(value => ({ value }), (error: unknown) => ({ error })); continue; }
const ready = await readersWrite(ctx.engine, item).catch((error: unknown) => ({ error }));
if (ready !== false && 'snapshot' in ready) pages.push({ index, item, ready, requestId: await repairRequestId(ctx, 'visibility', { ...item, cursor: item.target }, ready.snapshot.revision) });
else out[index] = ready !== false && 'error' in ready ? { error: ready.error } : { value: ready };
@@ -519,6 +523,7 @@ export const visibilityRepair: RepairHandler = {
const fresh = (target.phase === 5 ? await planNamed(ctx.engine, [item.source_id], [item.slug]) : await planVisibilityRepair(ctx.engine, [item.source_id], target.id))
.changes.find(c => c.id === target.id);
if (!fresh || fresh.from !== item.change.from || fresh.to !== item.change.to) return false;
+ if (item.change.from === item.change.to) return await raiseGuardOnly(ctx.engine, { ...item, target }, frontmatter => frontmatter.visibility === item.change!.to);
const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, visibility: item.change.to } };
return await labelWrite(ctx, item, snapshot, serializePageToMarkdown(page, snapshot.tags), { set: { visibility: item.change.to }, remove: [] }) ?? true;
} finally {
diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.ts
index 20aa2bcbd0..bcfd6ea6d0 100644
--- a/src/core/trust/owner-actions.ts
+++ b/src/core/trust/owner-actions.ts
@@ -311,6 +311,8 @@ function proposalSummary(p: TrustProposalRow, verb: 'Accept' | 'Dismiss' | 'Reve
const page = pageRef(p.source_id, s.slug);
// GST-2518: the privacy labels the edit asked for and the page kept.
const labels = s.labels ? heldLabelsText(s.labels) : '';
+ // GST-2521: on an agent page, accept changes only the labels.
+ if (verb === 'Accept' && s.labels_only) return `Change the privacy labels of ${page}: ${labels}; the page stays "${trustLabel(s.edited_tier)}"`;
if (verb === 'Accept') return `Endorse the agent edit of ${page}: raise it from "${trustLabel(s.edited_tier)}" to "confirmed by you"${labels ? ` and change its privacy labels: ${labels}` : ''}`;
if (verb === 'Revert') return `Revert the agent edit of ${page}: restore version ${s.version_id ?? '?'} and its tier "${trustLabel(s.prior_tier)}"`;
return `Dismiss ${trustProposalRef(p.id)}: ${page} stays "${trustLabel(s.edited_tier)}"${labels ? ' and keeps its privacy labels' : ''}`;
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
index 5ad7c8b7fe..43c4243eb2 100644
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@ -17,7 +17,9 @@
* (`revertLoweredPage`) = restore the prior owner version's content and tier.
* GST-2518: when the agent write was held from widening privacy labels, accept
* also writes the labels it asked for (in the same owner page write), and undo
- * (`undoPageLabels`) puts the kept labels and the edited tier back.
+ * (`writePageLabels`) puts the kept labels and the edited tier back. GST-2521: on a page whose own tier was an
+ * agent's before the held write, accept writes only the requested labels and keeps the tier, so saying yes to a
+ * label change never vouches for the body.
* - #6550 marker repair (`repairPageMarker`, local CLI only): rewrite a page's
* `trust_tier: unknown` marker to its stored tier (removed at owner tiers);
* the row keeps its tier. trust/marker-repair.ts decides which pages.
@@ -190,7 +192,7 @@ export interface PageActionInput {
}
export interface PageActionResult {
- status: 'confirmed' | 'reverted' | 'repaired' | 'restored' | 'unchanged';
+ status: 'confirmed' | 'reverted' | 'repaired' | 'restored' | 'labelled' | 'unchanged';
ref: string;
tier: TrustTier;
prior_tier: TrustTier;
@@ -199,9 +201,9 @@ export interface PageActionResult {
}
type OwnerPageIntent = {
- mode: 'confirm' | 'revert' | 'repair_marker' | 'restore_provenance' | 'undo_labels';
+ mode: 'confirm' | 'revert' | 'repair_marker' | 'restore_provenance' | 'write_labels';
expected_revision: string;
- /** GST-2518: confirm and undo_labels write these privacy labels (null removes a key); undo_labels restores `tier`. */
+ /** GST-2518: confirm and write_labels write these privacy labels (null removes a key); write_labels keeps the page at most at `tier`. */
labels?: Record<string, unknown>;
tier?: TrustTier;
version_id?: number;
@@ -259,21 +261,22 @@ export async function confirmPage(engine: BrainEngine, input: PageActionInput):
export const repairedMarker = (tier: TrustTier): TrustTier | null => compareTrust(tier, OWNER_TIER_FLOOR) >= 0 ? null : tier;
const ACTION_NAMES: Record<OwnerPageIntent['mode'], string> = { confirm: 'its confirmation', revert: 'the revert', repair_marker: 'the marker repair', restore_provenance: 'the provenance restore',
- undo_labels: 'the undo' };
+ write_labels: 'the label change' };
/** GST-2518: the keys an owner page intent may write as labels. */
const LABEL_KEYS = ['visibility', 'access', 'confidentiality', 'readable_by'];
/**
- * GST-2518: undoes an accepted held-label proposal: the page gets `input.labels` (the labels the hold kept) and `tier`
- * (the edited tier the accept raised), with its marker, bound to the approved revision. Only lowers.
+ * GST-2518: writes `input.labels` on the page at the revision the owner saw, with the page at most at `tier` and its
+ * marker: an undo of an accepted held-label proposal (the kept labels, the edited tier) and, GST-2521, the accept of a
+ * held-label proposal on an agent page (the requested labels, the page's own tier). Never raises the tier.
*/
-export async function undoPageLabels(engine: BrainEngine, input: PageActionInput & { tier: TrustTier }): Promise<PageActionResult> {
+export async function writePageLabels(engine: BrainEngine, input: PageActionInput & { tier: TrustTier }): Promise<PageActionResult> {
const ref = pageRef(input.sourceId, input.slug);
const state = await readPageTrustState(engine, input.sourceId, input.slug);
if (!state) throw opError('page_not_found', `No live page ${ref}.`, 'Check the ref; gbrain trust review lists pages waiting for you.');
- if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, ACTION_NAMES.undo_labels);
+ if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, ACTION_NAMES.write_labels);
const tier = minTrust(input.tier, state.tier);
- await publishOwnerPage(engine, input, { mode: 'undo_labels', expected_revision: input.expectedRevision, via: input.confirmation.via, proposal: input.proposal,
+ await publishOwnerPage(engine, input, { mode: 'write_labels', expected_revision: input.expectedRevision, via: input.confirmation.via, proposal: input.proposal,
labels: input.labels, tier }, markdownWithoutMarker(state.snapshot, repairedMarker(tier), input.labels), tier);
return { status: 'restored', ref, tier, prior_tier: state.tier };
}
@@ -434,7 +437,7 @@ export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: Wr
const intent = row.intent as unknown as OwnerPageIntent | null;
const labelsValid = intent?.labels === undefined || (typeof intent.labels === 'object' && intent.labels !== null && Object.keys(intent.labels).every(key => LABEL_KEYS.includes(key)));
if (row.operation !== TRUST_OWNER_PAGE_OPERATION || !intent || !Object.hasOwn(ACTION_NAMES, intent.mode) || typeof intent.expected_revision !== 'string' || !labelsValid
- || (intent.mode === 'undo_labels' && (!intent.labels || !isTrustTier(intent.tier)))
+ || (intent.mode === 'write_labels' && (!intent.labels || !isTrustTier(intent.tier)))
|| (row.authority.remote && (LOCAL_ONLY_MODES.includes(intent.mode) || !(row.authority.scopes ?? []).includes(MEMORY_CONFIRM_SCOPE)))) {
throw opError('confirmation_required', 'This owner page action is not confirmed by the owner; nothing was changed.',
'Run the gbrain trust command on the brain host in an interactive terminal.');
@@ -455,7 +458,7 @@ export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: Wr
tier = state.tier;
content = markdownWithoutMarker(state.snapshot, repairedMarker(tier));
} else if (intent.mode === 'restore_provenance') ({ content, tier } = await plannedProvenanceRestore(engine, state, intent));
- else if (intent.mode === 'undo_labels') {
+ else if (intent.mode === 'write_labels') {
tier = minTrust(intent.tier!, state.tier);
content = markdownWithoutMarker(state.snapshot, repairedMarker(tier), intent.labels);
} else content = markdownWithoutMarker(state.snapshot, null, intent.labels);
@@ -487,6 +490,11 @@ export interface LowerPageState {
edited_tier: TrustTier;
/** GST-2518: the privacy labels the edit asked to widen and the page kept, or null. */
labels: HeldPrivacyLabels | null;
+ /**
+ * GST-2521: the held labels are on a page whose own tier before the edit (before_state.page_tier) was an agent's (known
+ * and below operator_curated), so accept writes only the labels and keeps the tier. Unknown and older proposals confirm.
+ */
+ labels_only: boolean;
}
export function lowerPageState(proposal: TrustProposalRow): LowerPageState {
@@ -497,6 +505,7 @@ export function lowerPageState(proposal: TrustProposalRow): LowerPageState {
prior_revision: typeof b.prior_revision === 'string' ? b.prior_revision : null,
version_id: b.version_id === null || b.version_id === undefined ? null : Number(b.version_id),
edited_revision: typeof a.revision === 'string' ? a.revision : null, edited_tier: storedTrustTier(a.tier), labels: heldPrivacyLabels(a),
+ labels_only: heldPrivacyLabels(a) !== null && isTrustTier(b.page_tier) && b.page_tier !== 'unknown' && compareTrust(b.page_tier, OWNER_TIER_FLOOR) < 0,
};
}
@@ -530,6 +539,13 @@ registerTrustProposalHandler('lower_page', {
const page = await staleUnlessAt(engine, proposal, state);
if (!('pageId' in page)) return page;
const labels = heldPrivacyLabels(proposal.after_state);
+ if (labels && state.labels_only) {
+ const written = await writePageLabels(engine, {
+ sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, confirmation: ctx.confirmation, by: ctx.decidedBy, config: ctx.config,
+ labels: labels.requested, tier: page.tier, proposal: { id: proposal.id, to: 'accepted', after: { ...proposal.after_state, resolution: 'labels_applied' } },
+ });
+ return decisionResult(proposal, 'accept', 'accepted', { detail: { ...written, status: 'labelled' } });
+ }
const result = await confirmPage(engine, {
sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, confirmation: ctx.confirmation,
by: ctx.decidedBy, config: ctx.config, ...(labels ? { labels: labels.requested } : {}),
@@ -545,7 +561,7 @@ registerTrustProposalHandler('lower_page', {
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' });
if (page.revision !== proposal.after_state.accepted_revision) return decisionResult(proposal, 'undo', 'stale', { reason: 'page_changed_since' });
- const result = await undoPageLabels(engine, {
+ const result = await writePageLabels(engine, {
sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, confirmation: ctx.confirmation, by: ctx.decidedBy, config: ctx.config,
labels: labels.kept, tier: state.edited_tier,
proposal: { id: proposal.id, from: 'accepted', to: 'undone', after: { ...proposal.after_state, resolution: 'undone' } },
diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.ts
index db3f12ceb0..6986904f81 100644
--- a/src/core/trust/page-write.ts
+++ b/src/core/trust/page-write.ts
@@ -245,13 +245,14 @@ export function withLabels(frontmatter: Record<string, unknown>, labels: Record<
/**
* CEO-12, inside the publication transaction after the page write: when the
* write lowered a page's tier, file (or refresh) its `lower_page` proposal.
- * `prior` is the tier and revision read under the page lock before the write.
+ * `prior` is the tier and revision read under the page lock before the write (GST-2521: `pageTier`, the page's own tier
+ * when `tier` is a raised guard tier, is recorded as before_state.page_tier for the accept of held labels).
* Content writes and derived page publications (#7917) file it; another writer
* that lowers a page on purpose names itself in `proposer`. GST-2518: `labels` (a held write's, with `prior` at the label
* guard tier) ride the after state, and a later write's after state without them withdraws them.
*/
export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteRequest, 'operation' | 'source_id' | 'slug'> & { intent?: WriteRequest['intent'] | null },
- prior: { tier: TrustTier; revision: string | null } | null, proposer?: string, labels?: HeldPrivacyLabels | null): Promise<{ proposal_ref: string } | null> {
+ prior: { tier: TrustTier; revision: string | null; pageTier?: TrustTier | null } | null, proposer?: string, labels?: HeldPrivacyLabels | null): Promise<{ proposal_ref: string } | null> {
const derived = !CONTENT_OPERATIONS.includes(row.operation) && declaresDerivation(row.intent);
if (!prior || !(proposer || CONTENT_OPERATIONS.includes(row.operation) || derived)) return null;
const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
@@ -278,7 +279,7 @@ export async function recordAgentPageLowering(tx: BrainEngine, row: Pick<WriteRe
'SELECT id FROM page_versions WHERE page_id = $1 AND trust_tier = $2 ORDER BY id DESC LIMIT 1', [pageId, prior.tier]);
const proposal = await insertTrustProposal(tx, {
action: 'lower_page', sourceId: row.source_id, target: { table: 'pages', id: pageId }, proposer: proposer ?? (derived ? `derived_page:${row.operation}` : `agent_page_edit:${row.operation}`),
- before: { slug: row.slug, prior_tier: prior.tier, prior_revision: prior.revision, version_id: version ? Number(version.id) : null }, after,
+ before: { slug: row.slug, prior_tier: prior.tier, page_tier: prior.pageTier ?? prior.tier, prior_revision: prior.revision, version_id: version ? Number(version.id) : null }, after,
});
if (!proposal.created) await updatePendingTrustProposalAfter(tx, proposal.id, after);
return { proposal_ref: `tp${proposal.id}` };
diff --git a/test/owner-label-guard.test.ts b/test/owner-label-guard.test.ts
index 5d8fc223dd..5a43334934 100644
--- a/test/owner-label-guard.test.ts
+++ b/test/owner-label-guard.test.ts
@@ -109,6 +109,9 @@ async function repairVisibility(engine: BrainEngine, argv: string[]): Promise<Re
const preview = await run(['visibility', ...argv]);
return run(['visibility', ...argv, '--apply', '--expect', preview.results?.[0]?.preview_hash ?? preview.preview_hash]);
}
+const guardOf = async (engine: BrainEngine, sourceId: string, slug: string) => (await engine.executeRaw<{ tier: string }>(
+ 'SELECT g.tier FROM page_label_guards g JOIN pages p ON p.id = g.page_id WHERE p.source_id=$1 AND p.slug=$2', [sourceId, slug]))[0]?.tier ?? null;
+const labelsOf = (fm: Record<string, unknown>) => Object.fromEntries(['visibility', 'access', 'confidentiality', 'readable_by'].filter(k => fm[k] !== undefined).map(k => [k, fm[k]]));
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) });
@@ -145,7 +148,11 @@ for (const backend of testBackends()) describe('[' + backend + '] owner-set labe
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 decide(b, written.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted', detail: { status: 'labelled', tier: 'agent_written' } });
+ const accepted = await pageRow(b.engine, SRC, slug);
+ expect(accepted.tier).toBe('agent_written');
+ expect(accepted.frontmatter.visibility).toBeUndefined();
+ expect(accepted.body).toContain('An agent rewrote it.');
expect(await readsOf(reads, slug, canary)).toEqual({ unbound: true, bob: true, owner: true });
}), 180_000);
@@ -173,8 +180,9 @@ for (const backend of testBackends()) describe('[' + backend + '] owner-set labe
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 decide(b, written.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted', detail: { status: 'confirmed' } });
expect((await pageRow(b.engine, SRC, slug)).frontmatter.readable_by).toEqual(['alice-example']);
+ expect((await pageRow(b.engine, SRC, slug)).tier).toBe('user_confirmed');
expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: false });
}), 180_000);
@@ -184,6 +192,12 @@ for (const backend of testBackends()) describe('[' + backend + '] owner-set labe
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 });
+ expect(await decide(b, narrowed.privacy_labels_kept.proposal_ref, 'accept')).toMatchObject({ status: 'accepted', detail: { status: 'labelled' } });
+ expect(await pageRow(b.engine, SRC, own)).toMatchObject({ tier: 'agent_written', frontmatter: { readable_by: ['alice-example'] } });
+ expect(await readsOf(reads, own, canary)).toEqual({ unbound: false, bob: false, owner: false });
+ expect(await decide(b, narrowed.privacy_labels_kept.proposal_ref, 'undo')).toMatchObject({ status: 'undone' });
+ expect(await pageRow(b.engine, SRC, own)).toMatchObject({ tier: 'agent_written', frontmatter: { readable_by: ['alice-example', OWNER] } });
+ 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));
@@ -207,6 +221,27 @@ for (const backend of testBackends()) describe('[' + backend + '] owner-set labe
'operator_curated', { readable_by: ['alice-example'] })).rejects.toThrow('connection reset');
}), 120_000);
+ test('re-running the label repair on a page that already has the labels raises the guard without changing them', () => repoless(async (b, reads) => {
+ const slug = 'notes/already-labelled-example', canary = 'canaryalready';
+ await call(b, 'put_page', { slug, content: file(slug, ['visibility: private', 'readable_by: [alice-example, ' + OWNER + ']'], canary) });
+ const before = await pageRow(b.engine, SRC, slug);
+ const revision = async () => (await b.engine.readPageSnapshot(slug, { sourceId: SRC }))?.revision;
+ const written = await revision();
+ expect(await guardOf(b.engine, SRC, slug)).toBeNull();
+ await repairVisibility(b.engine, ['--source', SRC, '--slug', slug]);
+ expect(await guardOf(b.engine, SRC, slug)).toBe('operator_curated');
+ await b.engine.executeRaw('DELETE FROM page_label_guards');
+ await repairVisibility(b.engine, ['--source', SRC, '--slug', slug, '--readers', 'alice-example,' + OWNER]);
+ expect(await guardOf(b.engine, SRC, slug)).toBe('operator_curated');
+ expect(await revision()).toBe(written);
+ const after = await pageRow(b.engine, SRC, slug);
+ expect(labelsOf(after.frontmatter)).toEqual(labelsOf(before.frontmatter));
+ expect(after.tier).toBe('agent_written');
+ const dropped = await put(b, slug, file(slug, [], canary, 'Dropped both.'));
+ expect([...dropped.privacy_labels_kept?.keys ?? []].sort()).toEqual(['readable_by', 'visibility']);
+ expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
+ }), 180_000);
+
test('a label door that clears the labels leaves no guard: the agent\'s own later label is its own to drop', () => repoless(async (b) => {
const slug = 'notes/cleared-example', canary = 'canarycleared';
await call(b, 'put_page', { slug, content: file(slug, ['readable_by: [alice-example, ' + OWNER + ']'], canary) });
@@ -269,4 +304,23 @@ for (const backend of testBackends()) describe('[' + backend + '] owner-set labe
expect(committed()).toContain(OWNER);
expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
}, { databaseUrl, setup }), 240_000);
+
+ test('re-running the readers repair on pages that already name those readers raises their guards with no commit', () => managedBrain(async ({ engine, ctx, root }) => {
+ const b: Brain = { engine, ctx, sourceId: 'default', home: root };
+ await remoteReaders(engine, 'default');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ const slugs = ['notes/rerun-a-example', 'notes/rerun-b-example'];
+ for (const slug of slugs) await call(b, 'put_page', { slug, content: file(slug, ['readable_by: [alice-example, ' + OWNER + ']'], 'canaryrerun') });
+ await settleManagedGitEffects(engine);
+ const head = git(root, 'rev-parse', 'HEAD');
+ await repairVisibility(engine, ['--source', 'default', ...slugs.flatMap(slug => ['--slug', slug]), '--readers', 'alice-example,' + OWNER]);
+ await settleManagedGitEffects(engine);
+ expect(git(root, 'rev-parse', 'HEAD')).toBe(head);
+ for (const slug of slugs) {
+ expect(await guardOf(engine, 'default', slug)).toBe('operator_curated');
+ expect((await pageRow(engine, 'default', slug)).frontmatter.readable_by).toEqual(['alice-example', OWNER]);
+ }
+ const narrowed = await put(b, slugs[0]!, file(slugs[0]!, ['readable_by: [alice-example]'], 'canaryrerun', 'An agent narrowed it.'));
+ expect(narrowed.privacy_labels_kept?.keys).toEqual(['readable_by']);
+ }, { databaseUrl, setup }), 240_000);
});