Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Re-check the owner reader under the page lock, and say plainly why a guard-changed write was refused

garrytan8c58f1c1d4d4
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 49385c5b8f..2a6883775f 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -98,8 +98,8 @@ import { preparePagePurge, purgePageInTransaction, type PreparedPagePurge } from
import { originCommitted } from './sync-markers.ts';
import { syncDeleteOrigin } from './sync-delete-tombstones.ts';
import { withTrustKeep } from './context.ts';
-import { holdPrivacyLabels, isFenceEditWrite, labelGuardApplies, labelGuardTier, pageGateTrust, privacyLabelGuard, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier,
- type HeldPrivacyLabels } from '../trust/page-write.ts';
+import { holdPrivacyLabels, isFenceEditWrite, labelGuardApplies, labelGuardOwner, labelGuardTier, pageGateTrust, privacyLabelGuard, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier,
+ type HeldPrivacyLabels, type LabelGuard } from '../trust/page-write.ts';
import { compareTrust, maxTrust, type TrustTier, type WriteTrust } from '../trust/tier.ts';
import { suppliedTrustMarkerView } from '../trust/channel.ts';
import { gateField, gateInput } from '../trust/gate-outcomes.ts';
@@ -127,14 +127,18 @@ export function pageRefusal(code: RegistryCode, message: string, row: WriteReque
}
/**
- * GST-2521: under the publication's page lock, a write whose label guard tier moved since preparation refuses
- * `revision_conflict` (a guard raised over labels that already match moves no page revision), so it prepares again and is held.
+ * GST-2521: under the publication's page lock, a write whose label guard (its tier, or the owner it keeps as a reader)
+ * moved since preparation refuses `revision_conflict`: a guard raised over labels that already match, or an owner set,
+ * enabled or opted out after preparation, moves no page revision. The write publishes nothing; submitted again, it is
+ * prepared against the current guard and held.
*/
async function assertLabelGuardUnchanged(tx: BrainEngine, row: WriteRequest, trust: WriteTrust | undefined, page: PageSnapshot['page'] | null,
- stored: TrustTier | null, prepared: TrustTier | null): Promise<void> {
- if (!labelGuardApplies(row, trust, page, stored) || await labelGuardTier(tx, trust!, page, stored!) === prepared) return;
- throw pageRefusal('revision_conflict', PAGE_CHANGED_DURING_PREPARATION_MESSAGE, row,
- `The label guard of page ${row.slug} changed while this write was being prepared, so it published nothing. Read the current page and revision, then submit the intended change against it.`);
+ stored: TrustTier | null, incoming: Record<string, unknown> | null, prepared: LabelGuard | null): Promise<void> {
+ if (!labelGuardApplies(row, trust, page, stored)) return;
+ const [tier, owner] = await Promise.all([labelGuardTier(tx, trust!, page, stored!), labelGuardOwner(tx, page.frontmatter ?? {}, incoming)]);
+ if (tier === (prepared?.tier ?? null) && JSON.stringify(owner) === JSON.stringify(prepared?.owner ?? null)) return;
+ throw pageRefusal('revision_conflict', 'The page\'s label guard changed while this write was being prepared.', row,
+ `The label guard of page ${row.slug} (the labels and the owner reader it keeps) changed after this write was prepared, so it published nothing; the page itself is unchanged. Submit the same write again: it is prepared against the current guard.`);
}
/**
@@ -1158,7 +1162,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
const pinMode = sourcePath && mintMode && scannerSourcePath(file!.root, file!.root) && !await readSlugRootMode(engine, row.source_id) ? mintMode : undefined;
const publication: PreparedMutation = { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...databaseOnly,
...(core ? { exclusiveSources: core.exclusiveSources } : {}), ...(trust ? { trust } : {}), ...(ready.afterCommit ? { afterCommit: ready.afterCommit } : {}),
- validate: async tx => { await ready.validate(tx); await core?.validate(tx); await assertLabelGuardUnchanged(tx, row, trust, snapshot?.page ?? null, storedTier, labelGuard?.tier ?? null); },
+ validate: async tx => { await ready.validate(tx); await core?.validate(tx); await assertLabelGuardUnchanged(tx, row, trust, snapshot?.page ?? null, storedTier, incoming, labelGuard); },
apply: async (tx, preimage) => {
let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;
let removedTimeline: TimelineRowsRemoved | null = null;
diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.ts
index ad63d687e2..be270429a4 100644
--- a/src/core/trust/page-write.ts
+++ b/src/core/trust/page-write.ts
@@ -159,10 +159,19 @@ export async function privacyLabelGuard(engine: BrainEngine, row: Pick<WriteRequ
if (!labelGuardApplies(row, trust, page, stored)) return null;
const labels = page.frontmatter ?? {};
const tier = await labelGuardTier(engine, trust!, page, stored!);
- const owner = normalizeReaders(labels) !== null || !incoming || normalizeReaders(incoming) !== null ? await ownerReader(engine, labels) : null;
+ const owner = await labelGuardOwner(engine, labels, incoming);
return tier || owner ? { tier, owner } : null;
}
+/**
+ * privacyLabelGuard's owner for a write of `incoming` over stored labels `labels`. GST-2521: the write's publication reads
+ * it again under the page lock (page-prepare.ts), so an owner set, enabled or opted out of reading past readers after
+ * preparation is not missed.
+ */
+export async function labelGuardOwner(engine: BrainEngine, labels: Record<string, unknown>, incoming?: Record<string, unknown> | null): Promise<LabelGuard['owner']> {
+ return normalizeReaders(labels) !== null || !incoming || normalizeReaders(incoming) !== null ? ownerReader(engine, labels) : null;
+}
+
/** Whether privacyLabelGuard holds anything for this write: a local content write or derived publication below operator_curated over a stored page. */
export function labelGuardApplies(row: Pick<WriteRequest, 'operation' | 'intent' | 'authority'>, trust: WriteTrust | undefined,
page: { id: number; frontmatter?: Record<string, unknown> | null } | null, stored: TrustTier | null): page is { id: number; frontmatter?: Record<string, unknown> | null } {
diff --git a/test/owner-label-guard.test.ts b/test/owner-label-guard.test.ts
index dabea91882..254df77c85 100644
--- a/test/owner-label-guard.test.ts
+++ b/test/owner-label-guard.test.ts
@@ -286,6 +286,31 @@ for (const backend of testBackends()) describe('[' + backend + '] owner-set labe
expect(retried.privacy_labels_kept?.keys).toEqual(['visibility']);
}), 180_000);
+ test('an agent write prepared while the owner read past readers does not drop the owner once the opt-in is off: it refuses revision_conflict', () => repoless(async (b, reads) => {
+ const slug = 'notes/owner-race-example', canary = 'canaryownerrace';
+ await call(b, 'put_page', { slug, content: file(slug, ['readable_by: [alice-example, ' + OWNER + ']'], canary) });
+ await setOwnerReadsRestricted(b.engine, true, { remote: false });
+ await disposePersistenceConsumer(b.engine);
+ const [source] = await b.engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [SRC]);
+ const authority = await submissionAuthority(b.ctx, 'put_page', SRC, source!.incarnation, slug);
+ const dropped = file(slug, ['readable_by: [alice-example]'], canary, 'An agent took the owner out.');
+ const page = await pageRow(b.engine, SRC, slug);
+ const pageId = (await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SRC, slug]))[0]!.id;
+ await admitWrite(b.engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: SRC, sourceIncarnation: source!.incarnation,
+ slug, pageId: Number(pageId), requestId: randomUUID(), callerIntent: { content: dropped, expected_revision: page.revision },
+ intent: { content: dropped, expected_revision: page.revision } });
+ const row = (await claimNextWrite(b.engine, localHostId()))!;
+ const prepared = await preparePageMutation(b.engine, row, b.ctx.config);
+ await setOwnerReadsRestricted(b.engine, false, { remote: false });
+ const published = await publishMutation(b.engine, row, prepared).then(r => r, (error: unknown) => error);
+ expect((published as { code?: string }).code ?? (published as { error_code?: string }).error_code).toBe('revision_conflict');
+ 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 retried = await put(b, slug, dropped);
+ expect(retried.privacy_labels_kept?.keys).toEqual(['readable_by']);
+ expect(await reads('owner', slug, canary)).toBe(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) });