Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Fail closed when the owner cannot be read, and drop the label guard when the owner clears the labels (GST-2521 review)
garrytane0a4dd85e284
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80888e91ad..f88261f9d2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,10 +12,10 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**Labels you set on an agent's page now hold, and an agent can no longer take you out of a page's readers.** When you made an agent-written page private with `gbrain repair visibility` (or set its readers with `--readers`), the page kept its agent tier, so a later agent write at that tier could drop the label again with nothing held. Your label repairs now raise the page's label guard to your tier, so that write is held the same way as one over a page you wrote: it publishes with your labels kept and waits for you in `gbrain trust review`. Separately, a local write below your tier whose `readable_by` would leave you, the brain owner, out of a page you read now keeps you in the list (the rest of the narrowing still applies), and its `lower_page` item records the readers it asked for, which `gbrain trust confirm tp<id>` applies. Your own readers changes, synced edits, agent narrowing that keeps you, and brains with the owner opt-in to read restricted pages are unaffected. The guard lives in a new database table, so on a managed Git brain rebuilt from a clone it starts empty until you run the label repair again (GST-2521).+**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).-- `src/core/schema-migrations/v305-page-label-guards.ts` (provisional number): new `page_label_guards` table, one row per page, removed with the page. `src/core/repair/label-write.ts` and the maintenance door's `keep_trust` path (`src/core/persistence/prepared-maintenance.ts`) raise it to `operator_curated` in the label write's transaction.-- `src/core/trust/page-write.ts`: the label guard reads the page's guard row as a floor, and names the owner as a reader the write must keep when the owner reads the page by its readers and `access.owner_reads_restricted` is off. The held readers are the requested ones with the owner added, or the stored ones when the request is malformed.+- `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.**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.mdindex b1aa5f743a..487f07880c 100644--- a/docs/guides/memory-trust.md+++ b/docs/guides/memory-trust.md@@ -308,8 +308,10 @@ Labels you set on an agent's page hold too. `gbrain repair visibility` (andits `--readers` setter, and `gbrain repair private-labels`) keeps the page'sagent tier, but it raises the page's label guard to your tier, so a later agentwrite at the page's tier that drops or widens your labels is held the same way.-The guard is kept in the database, so on a managed Git brain rebuilt from a-clone it starts empty; run the label repair again to set it.+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.An agent also can't take you out of a page's readers. When a write below yourtier sets `readable_by` to a list that leaves you, the brain owner, out of adiff --git a/scripts/postgres-arm-weights-postgres-only.json b/scripts/postgres-arm-weights-postgres-only.jsonindex 1aee6d9a54..c7cc1f4543 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": 13835,+ "test/owner-label-guard.test.ts": 18275,"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.jsonindex 89efb41ae9..f2299de52c 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": 30916,+ "test/owner-label-guard.test.ts": 38733,"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.tsindex 7cb4d55fe7..51a3ce3cfe 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`), so a managed Git brain rebuilt from a clone starts without it until the owner\'s label repair runs again. The owner\'s own label writes, synced owner edits, agent narrowing that keeps the owner, and brains with `access.owner_reads_restricted` on are unchanged.' },+ { since: 'TBD', id: '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: '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/trust/page-write.ts b/src/core/trust/page-write.tsindex 17d39d6dc9..db3f12ceb0 100644--- a/src/core/trust/page-write.ts+++ b/src/core/trust/page-write.ts@@ -36,10 +36,10 @@ import { declaredWriteTrust, readDerivationDeclaration } from './taint.ts';import { insertTrustProposal, updatePendingTrustProposalAfter } from './proposals.ts';import { propagateTierLowering } from './propagation.ts';import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, isTrustTier, maxTrust, minTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';-import { PRIVACY_ALIASES } from '../search/private-visibility.ts';-import { normalizeReaders, readersAllow } from '../access/principals.ts';-import { memberIdentity } from '../access/members.ts';-import { ownerMemberId, ownerReadsRestrictedOn } from '../access/owner.ts';+import { OWNER_MEMBER_KEY, PRIVACY_ALIASES } from '../search/private-visibility.ts';+import { ACCESS_ID_RE, identityFor, normalizeReaders, readersAllow } from '../access/principals.ts';+import { getMember } from '../access/members.ts';+import { ownerReadsRestrictedOn } from '../access/owner.ts';import { asciiLower } from '../edge-whitespace.ts';/** Page writes that only edit a gbrain-managed fence (or strike a row) and keep the page's tier. */@@ -173,22 +173,36 @@ export async function privacyLabelGuard(engine: BrainEngine, row: Pick<WriteRequreturn tier || owner ? { tier, owner } : null;}-/** GST-2521: the brain owner, when the owner reads `frontmatter` by its readers and the opt-in to read past readers is off. */+/**+ * GST-2521: the brain owner, when the owner reads `frontmatter` by its readers and the opt-in to read past readers is off.+ * No owner, an ill-formed id, or a member that is not enabled reads as none (nobody reads as such an owner); a read error+ * propagates, so the write fails instead of publishing without the owner.+ */async function ownerReader(engine: BrainEngine, frontmatter: Record<string, unknown>): Promise<LabelGuard['owner']> {- const member = await ownerMemberId(engine);- if (!member || await ownerReadsRestrictedOn(engine)) return null;- const identity = await memberIdentity(engine, member).then(found => found.identity, () => null);- return identity && readersAllow(frontmatter, identity) ? { member, identity } : null;+ const id = (await engine.getConfig(OWNER_MEMBER_KEY))?.trim();+ if (!id || !ACCESS_ID_RE.test(id) || await ownerReadsRestrictedOn(engine)) return null;+ const member = await getMember(engine, id);+ if (member?.status !== 'enabled') return null;+ const identity = identityFor(member.id, member.groups);+ return readersAllow(frontmatter, identity) ? { member: member.id, identity } : null;}/*** GST-2521: the owner's label door (`gbrain repair visibility`, its `--readers` setter, `gbrain repair private-labels`)- * keeps the page's tier, so it raises the page's label guard to operator_curated: a later write below that is held from- * widening the labels the owner set. In the door's own transaction.+ * keeps the page's tier, so it raises the page's label guard to operator_curated when it leaves the page private by its+ * labels or naming readers: a later write below that is held from widening them. A door that leaves no such label+ * removes the guard. In the door's own transaction, after its write.*/export async function raisePageLabelGuard(tx: BrainEngine, sourceId: string, slug: string): Promise<void> {- await tx.executeRaw(`INSERT INTO page_label_guards (page_id, tier) SELECT id, $3 FROM pages WHERE source_id = $1 AND slug = $2- ON CONFLICT (page_id) DO UPDATE SET tier = EXCLUDED.tier, set_at = now()`, [sourceId, slug, OWNER_TIER_FLOOR]);+ const [page] = await tx.executeRaw<{ id: number; frontmatter: Record<string, unknown> | null }>('SELECT id, frontmatter FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]);+ if (!page) return;+ const labels = page.frontmatter ?? {};+ if (!labelledPrivate(labels) && normalizeReaders(labels) === null) {+ await tx.executeRaw('DELETE FROM page_label_guards WHERE page_id = $1', [Number(page.id)]);+ return;+ }+ await tx.executeRaw(`INSERT INTO page_label_guards (page_id, tier) VALUES ($1, $2)+ ON CONFLICT (page_id) DO UPDATE SET tier = EXCLUDED.tier, set_at = now()`, [Number(page.id), OWNER_TIER_FLOOR]);}/**diff --git a/test/owner-label-guard.test.ts b/test/owner-label-guard.test.tsindex 1f26e1e938..5d8fc223dd 100644--- a/test/owner-label-guard.test.ts+++ b/test/owner-label-guard.test.ts@@ -42,6 +42,7 @@ 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 { privacyLabelGuard } from '../src/core/trust/page-write.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';const NL = String.fromCharCode(10);@@ -193,6 +194,30 @@ for (const backend of testBackends()) describe('[' + backend + '] owner-set labeexpect(await readsOf(reads, open, openCanary)).toEqual({ unbound: false, bob: false, owner: true });}), 180_000);+ test('B fails closed: an error reading the owner refuses the write instead of dropping the owner', () => repoless(async (b) => {+ const slug = 'notes/owner-read-error-example', canary = 'canaryownererror';+ await seedOwnerPage(b.engine, SRC, slug, file(slug, ['readable_by: [alice-example, ' + OWNER + ']'], canary));+ const [page] = await b.engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SRC, slug]);+ const failing = new Proxy(b.engine, { get(target, key, receiver) {+ if (key !== 'executeRaw') return Reflect.get(target, key, receiver);+ return (sql: string, params?: unknown[]) => /access_members/.test(sql) ? Promise.reject(new Error('connection reset')) : target.executeRaw(sql, params);+ } });+ const row = { operation: 'put_page', intent: {}, authority: { remote: false } } as any;+ await expect(privacyLabelGuard(failing, row, { tier: 'agent_written' } as any, { id: Number(page!.id), frontmatter: { readable_by: ['alice-example', OWNER] } },+ 'operator_curated', { readable_by: ['alice-example'] })).rejects.toThrow('connection reset');+ }), 120_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) });+ await repairVisibility(b.engine, ['--source', SRC, '--slug', slug, '--readers', 'none']);+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.readable_by).toBeUndefined();+ await put(b, slug, file(slug, ['visibility: private'], canary, 'The agent made it private.'));+ const dropped = await put(b, slug, file(slug, [], canary, 'The agent opened it again.'));+ expect(dropped.privacy_labels_kept).toBeUndefined();+ expect((await pageRow(b.engine, SRC, slug)).frontmatter.visibility).toBeUndefined();+ }), 120_000);+test('nothing is held that should not be: an agent narrowing that keeps the owner, the owner\'s readers setter, the owner opt-in', () => repoless(async (b, reads) => {const keep = 'notes/keeps-owner-example', canary = 'canarykeepsowner';await seedOwnerPage(b.engine, SRC, keep, file(keep, ['readable_by: [alice-example, bob-example, ' + OWNER + ']'], canary));