Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: /ship Step 7/9 rerun fixes (doctor fix SQL as block comments, v276 skip wording, take/derivation coverage, doc wording)
garrytan56aeb9e53c76
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 1b855bb454..a386496e20 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -390,7 +390,7 @@ segmented chunk (`test/e2e/segmented-switch-off-write-role.test.ts`). With thepolicies above it creates segmented pages and sees only its sources' rows(`test/e2e/segmented-rls-scope.test.ts`).-**Purge and withdrawal guards.** The seven triggers that refuse purged content and+**Purge and withdrawal guards.** The seven guard functions that refuse purged content andkeep withdrawn facts withdrawn read their ledgers (`fact_purges`, `fact_withdrawals`,`take_purges`, `page_purges` and the two derivation purge tables) as the role that ownsthem, which ran the migrations: they are `SECURITY DEFINER` withdiff --git a/llms-full.txt b/llms-full.txtindex cd56849eac..35e3f147c7 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5836,7 +5836,7 @@ segmented chunk (`test/e2e/segmented-switch-off-write-role.test.ts`). With thepolicies above it creates segmented pages and sees only its sources' rows(`test/e2e/segmented-rls-scope.test.ts`).-**Purge and withdrawal guards.** The seven triggers that refuse purged content and+**Purge and withdrawal guards.** The seven guard functions that refuse purged content andkeep withdrawn facts withdrawn read their ledgers (`fact_purges`, `fact_withdrawals`,`take_purges`, `page_purges` and the two derivation purge tables) as the role that ownsthem, which ran the migrations: they are `SECURITY DEFINER` withdiff --git a/src/commands/doctor/checks/guard-functions.ts b/src/commands/doctor/checks/guard-functions.tsindex ba0b14d0b3..aa1dca5c1a 100644--- a/src/commands/doctor/checks/guard-functions.ts+++ b/src/commands/doctor/checks/guard-functions.ts@@ -46,7 +46,7 @@ export async function guardFunctionProblems(engine: BrainEngine): Promise<{ prob}if (g.reads_under_rls.length > 0) {problems.push(`${g.fn}()'s owner ${g.owner} neither bypasses RLS nor owns ${g.reads_under_rls.join(', ')} unforced, so the guard reads them filtered`);- fix.push(`-- give ${g.fn}() an owner that bypasses RLS (ALTER FUNCTION ${g.fn}() OWNER TO <owner of the tables>), or ALTER ROLE ${g.owner} BYPASSRLS;`);+ fix.push(`/* give ${g.fn}() an owner that bypasses RLS (ALTER FUNCTION ${g.fn}() OWNER TO <owner of the tables>), or ALTER ROLE ${g.owner} BYPASSRLS; */`);}}const triggers = await engine.executeRaw<{ trigger: string; before: boolean }>(diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c249e52a25..e019c72a0b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1308,7 +1308,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.464.0', text: 'Security: `gbrain serve --access=read-only` (the `=` form) now sets the read-only ceiling. It passed flag validation before but started the serve with full write access, because only `--access read-only` was read. A config that used the `=` form now gets the read-only tool set and refused mutations it asked for; a repeated `--access` never widens a read-only value, and an invalid value in either form refuses. `--surface=<v>` likewise now sets the serve surface (it was ignored, leaving the full surface), and a repeated `--surface` takes the narrowest value.' },{ since: '0.60.464.0', text: 'A managed sync pass whose process was killed or crashed now reads `resumable` / `pass_interrupted` in `gbrain sync status` (with an `interrupted` block naming the pass and the dead holder) instead of `pass_unfinished`, and a second killed pass reads `blocked` / `pass_abandoned` at once. `gbrain doctor` `managed_sync_blocked` lists both (warn, fail after an hour). A live pass still committing is no longer counted abandoned because its row is old.' },// #7632 guard definers. `since` is stamped at the merge slot.- { since: 'TBD', id: 'guard_triggers_security_definer', text: 'On Postgres, the seven triggers that refuse purged content and keep withdrawn facts withdrawn now read the purge and withdrawal ledgers as the role that owns them (`SECURITY DEFINER`, `search_path = pg_catalog, public, pg_temp`). Before, they read under the writing role\'s row-level security, so a write role with no policy on a ledger saw no purge and no withdrawal: a purged claim, page, take or derivation was stored again and a withdrawn fact was saved active. Owners, roles that bypass RLS and write roles with policies on the ledgers see no change, and `anon` and `authenticated` gain nothing: EXECUTE on the guards is revoked from PUBLIC, `anon` and `authenticated`, and every guard that refuses a write (`facts_refuse_purged`, `takes_refuse_purged`, `pages_refuse_purged` and the new `page_segment_derivations_refuse_stored_purging`) fires AFTER ROW, so RLS refuses a row before any guard reads a ledger. The derivation guard that silently drops a row a purge sweep would delete still runs as the writing role, BEFORE ROW, as before; a row it cannot see is purged and that RLS accepts is then refused by the new AFTER ROW guard with `derivation_purge_pending`. A scoped write role with no policy on a ledger is now refused, with an error, where it was let through; it learns whether content it supplies itself is purged or withdrawn in a source it can already write; and the guards perform two fixed side effects for it as the owner (expiring the facts its own statement just inserted when they are withdrawn, and adding its page to a running derivation purge\'s page list). Every other gbrain function that pins a search_path now ends it with `pg_temp` (ALTER only, no body changes). Where the migrating role does not own a guard or its table, the migration names it on stderr and leaves it, and `gbrain doctor` (`guard_functions`) prints the SQL to run as the owner.' },+ { since: 'TBD', id: 'guard_triggers_security_definer', text: 'On Postgres, the seven guard functions that refuse purged content and keep withdrawn facts withdrawn now read the purge and withdrawal ledgers as the role that owns them (`SECURITY DEFINER`, `search_path = pg_catalog, public, pg_temp`). Before, they read under the writing role\'s row-level security, so a write role with no policy on a ledger saw no purge and no withdrawal: a purged claim, page, take or derivation was stored again and a withdrawn fact was saved active. Owners, roles that bypass RLS and write roles with policies on the ledgers see no change, and `anon` and `authenticated` gain nothing: EXECUTE on the guards is revoked from PUBLIC, `anon` and `authenticated`, and every guard that refuses a write (`facts_refuse_purged`, `takes_refuse_purged`, `pages_refuse_purged` and the new `page_segment_derivations_refuse_stored_purging`) fires AFTER ROW, so RLS refuses a row before any guard reads a ledger. The derivation guard that silently drops a row a purge sweep would delete still runs as the writing role, BEFORE ROW, as before; a row it cannot see is purged and that RLS accepts is then refused by the new AFTER ROW guard with `derivation_purge_pending`. A scoped write role with no policy on a ledger is now refused, with an error, where it was let through; it learns whether content it supplies itself is purged or withdrawn in a source it can already write; and the guards perform two fixed side effects for it as the owner (expiring the facts its own statement just inserted when they are withdrawn, and adding its page to a running derivation purge\'s page list). Every other gbrain function that pins a search_path now ends it with `pg_temp` (ALTER only, no body changes). Where the migrating role does not own a guard or its table, the migration names it on stderr and leaves it, and `gbrain doctor` (`guard_functions`) prints the SQL to run as the owner.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.tsindex 95af6b37a5..f1f1895428 100644--- a/src/core/engine-sql/page-body.ts+++ b/src/core/engine-sql/page-body.ts@@ -490,7 +490,9 @@ export async function readSegmentDerivations(exec: LegacyUnscopedRead, pageId: n* Insert or replace rows keyed (page, kind, occurrence), in statements bounded like manifest rows. A replaced row* keeps its created_at and moves updated_at. Outputs and receipts travel inside the batch's JSON text, never as a* `::jsonb` bind of a stringified value. A row a fact purge's sweep refuses (it holds the purged claim; page-body/schema.ts)- * is not stored, and the call throws DerivationWriteRefused after storing the others.+ * is not stored, and the call throws DerivationWriteRefused after storing the others. A writer that cannot read the sweep+ * records but whose row RLS accepts meets the AFTER ROW check instead: it raises P0001 derivation_purge_pending and that+ * batch's statement stores nothing.*/export async function upsertSegmentDerivations(exec: SqlExecutor, rows: readonly SegmentDerivationInput[]): Promise<void> {const batches = jsonRowBatches(rows, row => ({diff --git a/src/core/schema-migrations/v276-guard-triggers-security-definer.ts b/src/core/schema-migrations/v276-guard-triggers-security-definer.tsindex 311fd62418..c626cc9cb8 100644--- a/src/core/schema-migrations/v276-guard-triggers-security-definer.ts+++ b/src/core/schema-migrations/v276-guard-triggers-security-definer.ts@@ -78,8 +78,8 @@ export async function hardenGuards(engine: BrainEngine, label: string): Promise<WHERE n.nspname = 'public' AND p.proconfig && $1::text[] ORDER BY 1`, [[...LEGACY_SEARCH_PATH_SETTINGS]]);skipped.push(...unhardened.map(r => r.sig));if (skipped.length > 0) {- process.stderr.write(` ${label}: ${skipped.length} guard function(s) or trigger(s) left as they were (${skipped.join(', ')}): `- + 'the role must own them. Run gbrain doctor for the fix.\n');+ process.stderr.write(` ${label}: ${skipped.length} function(s) or trigger(s) left as they were (${skipped.join(', ')}): `+ + 'the role must own them, and a guard its trigger\'s table. Run gbrain doctor for the fix.\n');}return skipped;}diff --git a/test/doctor-guard-functions.test.ts b/test/doctor-guard-functions.test.tsindex ceb138fc02..1d6d635d30 100644--- a/test/doctor-guard-functions.test.ts+++ b/test/doctor-guard-functions.test.ts@@ -37,4 +37,35 @@ describe('guard_functions doctor check (#7632)', () => {await engine.runMigration(0, fix.join('\n'));expect(await guardFunctionProblems(engine)).toEqual({ problems: [], fix: [] });});++ // Generated by gstack /ship coverage audit (#7642).+ // Value: protects=doctor names a stored-derivation check that fires BEFORE ROW (a definer raising before RLS) and its fix+ // moves it AFTER ROW; fails_when=the trigger probe accepts page_segment_derivations_refuse_stored_purging at any timing;+ // why_new=the drift test above only drops the trigger; seam=none; no_claim=the RLS oracle itself (PGLite has one role;+ // e2e case 8 covers it)+ test('a stored-derivation check that fires BEFORE ROW is named, and the fix moves it AFTER ROW', async () => {+ await engine.runMigration(0, `DROP TRIGGER page_segment_derivations_refuse_stored_purging ON page_segment_derivations;+ CREATE TRIGGER page_segment_derivations_refuse_stored_purging BEFORE INSERT OR UPDATE OF output, receipt ON page_segment_derivations+ FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_stored_purging_derivation();`);+ const { problems, fix } = await guardFunctionProblems(engine);+ expect(problems).toEqual(['page_segment_derivations has no page_segment_derivations_refuse_stored_purging AFTER ROW check']);+ await engine.runMigration(0, fix.join('\n'));+ expect(await guardFunctionProblems(engine)).toEqual({ problems: [], fix: [] });+ });++ // Generated by gstack /ship coverage audit (#7642).+ // Value: protects=doctor asks for the stored-derivation check only where page_segment_derivations exists, so its fix never+ // targets a missing table; fails_when=the to_regclass presence probe is dropped; why_new=every other doctor test has the+ // table; seam=none; no_claim=a real pre-v273 Postgres brain (a dropped table on PGLite stands in)+ test('a brain without page_segment_derivations is not asked for its check', async () => {+ const bare = new PGLiteEngine();+ try {+ await bare.connect({});+ await bare.initSchema();+ await bare.runMigration(0, 'DROP TABLE page_segment_derivations CASCADE');+ expect(await guardFunctionProblems(bare)).toEqual({ problems: [], fix: [] });+ } finally {+ await bare.disconnect();+ }+ }, 120_000);});diff --git a/test/e2e/guard-definer-postgres.test.ts b/test/e2e/guard-definer-postgres.test.tsindex 8a3ffa7043..9488a97b93 100644--- a/test/e2e/guard-definer-postgres.test.ts+++ b/test/e2e/guard-definer-postgres.test.ts@@ -194,6 +194,13 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()expect(failure(await run(held, [ids.derived, 1, heldOutput]))).toMatchObject({ code: 'P0001', message: expect.stringContaining('derivation_purge_pending:') });const [other, otherOutput] = insertDerivation(JSON.stringify({ text: 'an unrelated link context' }));expect(rowsOf(await run(other, [ids.derived, 2, otherOutput]))).toEqual([{ stored: 1 }]);+ // Generated by gstack /ship coverage audit (#7642).+ // Value: protects=the AFTER ROW stored check refuses an UPDATE that rewrites a stored derivation into a purged claim+ // during its sweep; fails_when=the stored trigger stops firing on UPDATE OF output, receipt (INSERT only);+ // why_new=case 4 inserted only, and the catalog goldens are regenerated with each schema change; seam=none;+ // no_claim=an UPDATE of receipt alone (same trigger column list, not exercised)+ expect(failure(await run('UPDATE page_segment_derivations SET output = $1::jsonb WHERE page_id = $2 AND occurrence_id = 2', [heldOutput, ids.derived])))+ .toMatchObject({ code: 'P0001', message: expect.stringContaining('derivation_purge_pending:') });});});@@ -424,7 +431,7 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()await engine.connect({ database_url: url });expect(await guardFunctionProblems(engine)).toEqual({problems: [`gbrain_refuse_purged_page()'s owner ${weakOwner} neither bypasses RLS nor owns page_purges unforced, so the guard reads them filtered`],- fix: [`-- give gbrain_refuse_purged_page() an owner that bypasses RLS (ALTER FUNCTION gbrain_refuse_purged_page() OWNER TO <owner of the tables>), or ALTER ROLE ${weakOwner} BYPASSRLS;`],+ fix: [`/* give gbrain_refuse_purged_page() an owner that bypasses RLS (ALTER FUNCTION gbrain_refuse_purged_page() OWNER TO <owner of the tables>), or ALTER ROLE ${weakOwner} BYPASSRLS; */`],});await as(conn, WRITER, async run => {expect(rowsOf(await run(insertPurgedPage, [PURGED_HASH]))).toEqual([{ stored: 1 }]);