Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

A write prepared before a label guard was raised no longer publishes unheld (GST-2521)

garrytan8fd6a47be6a4
diff --git a/scripts/postgres-arm-weights-postgres-only.json b/scripts/postgres-arm-weights-postgres-only.json
index 65c965ef92..8a78d61ba2 100644
--- a/scripts/postgres-arm-weights-postgres-only.json
+++ b/scripts/postgres-arm-weights-postgres-only.json
@@ -208,7 +208,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": 29339,
+ "test/owner-label-guard.test.ts": 31700,
"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 80271938d1..d486aa34b8 100644
--- a/scripts/postgres-arm-weights.json
+++ b/scripts/postgres-arm-weights.json
@@ -322,7 +322,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": 61117,
+ "test/owner-label-guard.test.ts": 74771,
"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/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 6ba7c5d447..dad5dee489 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -98,9 +98,9 @@ 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, pageGateTrust, privacyLabelGuard, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier,
+import { holdPrivacyLabels, isFenceEditWrite, labelGuardApplies, labelGuardTier, pageGateTrust, privacyLabelGuard, pageWriteTrust, recordAgentPageLowering, stampPageTrustMarker, storedPageTier,
type HeldPrivacyLabels } from '../trust/page-write.ts';
-import { compareTrust, maxTrust, type WriteTrust } from '../trust/tier.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';
import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';
@@ -126,6 +126,17 @@ export function pageRefusal(code: RegistryCode, message: string, row: WriteReque
: ownerStatusFix(row.source_id)) });
}
+/**
+ * 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.
+ */
+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.`);
+}
+
/**
* The parser trims titles, so a stored title differing only in surrounding whitespace is not drift (#5635), and it
* never carries `type`/`title`/`tags`/`slug` into the frontmatter object, so a stored copy of one (#6454: older
@@ -1142,7 +1153,8 @@ 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); }, apply: async (tx, preimage) => {
+ validate: async tx => { await ready.validate(tx); await core?.validate(tx); await assertLabelGuardUnchanged(tx, row, trust, snapshot?.page ?? null, storedTier, labelGuard?.tier ?? null); },
+ apply: async (tx, preimage) => {
let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;
let removedTimeline: TimelineRowsRemoved | null = null;
let lowered: { proposal_ref: string } | null = null;
diff --git a/src/core/repair/readers.ts b/src/core/repair/readers.ts
index ac19b6a715..16c8cbf317 100644
--- a/src/core/repair/readers.ts
+++ b/src/core/repair/readers.ts
@@ -208,12 +208,14 @@ export async function readersWrite(engine: BrainEngine, item: ReadersItem): Prom
}
/**
- * 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.
+ * GST-2521: an item whose labels already match (`unchanged` re-checks the page's frontmatter under its page lock) raises the
+ * page's label guard without a write; false when the page moved since the plan. A write prepared before the raise re-reads
+ * the guard under the same lock at publication and refuses `revision_conflict` (page-prepare.ts).
*/
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 => {
+ await tx.lockPageKeys([{ sourceId: item.source_id, slug: item.slug }]);
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;
diff --git a/src/core/trust/page-write.ts b/src/core/trust/page-write.ts
index c66ee98e0e..ad63d687e2 100644
--- a/src/core/trust/page-write.ts
+++ b/src/core/trust/page-write.ts
@@ -156,8 +156,26 @@ export interface LabelGuard { tier: TrustTier | null; owner: { member: string; i
*/
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, incoming?: Record<string, unknown> | null): Promise<LabelGuard | null> {
- if (!trust || !page || !stored || row.authority?.remote === true || !(CONTENT_OPERATIONS.includes(row.operation) || declaresDerivation(row.intent))
- || isFenceEditWrite(row) || compareTrust(trust.tier, OWNER_TIER_FLOOR) >= 0) return null;
+ 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;
+ return tier || owner ? { tier, owner } : 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 } {
+ return !!trust && !!page && !!stored && row.authority?.remote !== true && (CONTENT_OPERATIONS.includes(row.operation) || declaresDerivation(row.intent))
+ && !isFenceEditWrite(row) && compareTrust(trust.tier, OWNER_TIER_FLOOR) < 0;
+}
+
+/**
+ * privacyLabelGuard's tier for a write at `trust` over `page` (its stored labels, at stored tier `stored`): null when the page
+ * is neither private by its labels nor naming readers, or when the write is at or above the tier. GST-2521: the write's
+ * publication reads it again under the page lock (page-prepare.ts), so a guard raised after preparation is not missed.
+ */
+export async function labelGuardTier(engine: BrainEngine, trust: WriteTrust, page: { id: number; frontmatter?: Record<string, unknown> | null }, stored: TrustTier): Promise<TrustTier | null> {
const labels = page.frontmatter ?? {};
let tier: TrustTier | null = null;
if (labelledPrivate(labels) || normalizeReaders(labels) !== null) {
@@ -171,8 +189,7 @@ export async function privacyLabelGuard(engine: BrainEngine, row: Pick<WriteRequ
...[guard?.owner_set ?? null, ...(guard?.priors ?? [])].filter(isTrustTier));
if (compareTrust(trust.tier, tier) >= 0) tier = null;
}
- const owner = normalizeReaders(labels) !== null || !incoming || normalizeReaders(incoming) !== null ? await ownerReader(engine, labels) : null;
- return tier || owner ? { tier, owner } : null;
+ return tier;
}
/**
diff --git a/test/owner-label-guard.test.ts b/test/owner-label-guard.test.ts
index 9b36b34d0b..dabea91882 100644
--- a/test/owner-label-guard.test.ts
+++ b/test/owner-label-guard.test.ts
@@ -43,6 +43,11 @@ import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
import { privacyLabelGuard } from '../src/core/trust/page-write.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
const NL = String.fromCharCode(10);
@@ -257,6 +262,30 @@ for (const backend of testBackends()) describe('[' + backend + '] owner-set labe
expect(await readsOf(reads, slug, canary)).toEqual({ unbound: false, bob: false, owner: true });
}), 180_000);
+ test('an agent write prepared before a guard-only raise does not publish unheld: it refuses revision_conflict', () => repoless(async (b, reads) => {
+ const slug = 'notes/raise-race-example', canary = 'canaryraiserace';
+ await call(b, 'put_page', { slug, content: file(slug, ['visibility: private'], canary) });
+ expect((await pageRow(b.engine, SRC, slug)).tier).toBe('agent_written');
+ 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, [], canary, 'An agent dropped the label.');
+ 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: (await pageRow(b.engine, SRC, slug)).revision },
+ intent: { content: dropped, expected_revision: (await pageRow(b.engine, SRC, slug)).revision } });
+ const row = (await claimNextWrite(b.engine, localHostId()))!;
+ const prepared = await preparePageMutation(b.engine, row, b.ctx.config);
+ await repairVisibility(b.engine, ['--source', SRC, '--slug', slug]);
+ expect(await guardOf(b.engine, SRC, slug)).toBe('operator_curated');
+ 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.visibility).toBe('private');
+ 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(['visibility']);
+ }), 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) });