Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W1: register held-removals in the writer inventories; propagation reads managed mode through readManagedMode; regenerate flag registry
garrytan592591cb0508
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 896e61e8a0..73155ce6ca 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -235,6 +235,7 @@ src/core/trust/claim.ts 2 engine_guard gbrain trust claim-sources records the clsrc/core/cycle/dream-taint.ts 1 engine_guard putDerivedPage writes the unmanaged dream summary page inside derivedMaintenanceTransaction (attributed, tier lowered to the derivation's taint); on a managed brain the canonical table trigger refuses the write outside the coordinator.src/core/persistence/derived-facts.ts 1 coordinator insertGatedFacts inserts only gate-allowed conversation fact rows; writeDerivedFacts refuses on a managed brain (writer_coordinator_required) and otherwise runs it inside the attributed maintenance transaction with taint edges.src/core/trust/fence-guard.ts 2 coordinator guardFenceRows detaches and renumbers fence rows more trusted than the writer inside the canonical fence re-projection of the page publication (canonical-projections.ts), in the same journal transaction as the receipt.+src/core/trust/held-removals.ts 3 coordinator The owner accept of a held take or timeline removal deletes or re-projects that one row as the page now says, inside withCoordinatedWrite under the page key on a managed brain (withWriteAttribution otherwise), in the transaction that decides the proposal; a refused takes_remove instead reruns as an owner takes_remove through the takes request preparer.src/core/trust/owner-actions.ts 1 coordinator The owner release of a held fact inserts it at user_confirmed under the promotion capability, inside withCoordinatedWrite on a managed brain (withWriteAttribution otherwise), in the owner action transaction that decides the hold.src/core/trust/page-handlers.ts 1 coordinator Owner page confirm/revert: a managed brain admits a journaled owner page mutation (submitOwnerPage); the unmanaged path runs importFromContent inside one attributed transaction that re-checks the previewed revision.src/core/trust/supersede-handlers.ts 3 filesystem_guard Trust-guard supersession accept/undo raise or restore only trust_tier on the proposal's facts/takes row through the S9 decide_proposals checked accept/undo path (proposal-supersede.ts): source filesystem and page locks unmanaged, the decide_proposal coordinator mutation managed.diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 8b57d2ce33..33389acb26 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -291,6 +291,7 @@ or a physical projection that leaves attribution untouched):- `src/core/timeline-dedup-repair.ts` (1): runs only from schema migration v139, before migration v193 adds the attribution columns, so it has no actor to record.- `src/core/timeline-write-through.ts` (2): the timeline write-through's page row splice and entry insert run in one `maintenanceTransaction`.- `src/core/trust/fence-guard.ts` (2): the guarded fence re-projection detaches or moves higher-tier fact rows inside the page's coordinated publication.+- `src/core/trust/held-removals.ts` (1): an owner accept of a held take or timeline removal re-projects the row as the page says in a coordinated (managed) or attributed (unmanaged) transaction under the page key.- `src/core/trust/owner-actions.ts` (1): an owner release inserts the held fact in a coordinated (managed) or attributed (unmanaged) transaction at user_confirmed.- `src/core/trust/supersede-handlers.ts` (3): owner accept/undo of a trust proposal re-tiers the new fact (or take) inside the checked supersede's (or takes publication's) transaction.<!-- write-attribution-covered:end -->diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 3f4f5581c7..37c9187bda 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--to', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--relower', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--to', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],diff --git a/src/core/trust/propagation.ts b/src/core/trust/propagation.tsindex 57158319d9..baae65dec1 100644--- a/src/core/trust/propagation.ts+++ b/src/core/trust/propagation.ts@@ -16,6 +16,7 @@*/import type { BrainEngine } from '../engine.ts';import { derivedRowsFrom, type DerivationRef } from '../facts/derivation-inputs.ts';+import { readManagedMode } from '../persistence/managed-mode.ts';import { compareTrust, storedTrustTier, trustRankSql, trustTierFromRankSql, type TrustTier } from './tier.ts';const TIERED = ['facts', 'takes', 'pages', 'timeline_entries'] as const;@@ -24,12 +25,11 @@ export interface LoweredRow { table: Tiered; id: number; from: TrustTier; to: Trconst numericId = (column: string) => `(CASE WHEN ${column} ~ '^[0-9]+$' THEN ${column}::bigint END)`;const sourceOf = (table: Tiered) => table === 'facts' || table === 'pages' ? 'x.source_id' : '(SELECT p.source_id FROM pages p WHERE p.id = x.page_id)';-const WRITABLE = (source: string) => `(NOT EXISTS (SELECT 1 FROM persistence_brain WHERE singleton = 1 AND enabled)- OR COALESCE(NULLIF(current_setting('gbrain.write_sources', true), ''), '[]')::jsonb ? ${source})`;+const WRITABLE = (source: string) => `(NOT $3::boolean OR COALESCE(NULLIF(current_setting('gbrain.write_sources', true), ''), '[]')::jsonb ? ${source})`;const INPUT_TIER = 'COALESCE(f.trust_tier, k.trust_tier, p.trust_tier, t.trust_tier)';/** Each derived row of `table` among `ids` whose current inputs are less trusted than it: the tier it lowers to. */-async function lowerable(tx: BrainEngine, table: Tiered, ids: readonly string[]) {+async function lowerable(tx: BrainEngine, table: Tiered, ids: readonly string[], managed: boolean) {return tx.executeRaw<{ id: number; source_id: string | null; from_tier: string; to_tier: string; writable: boolean }>(`WITH low AS (SELECT di.derived_id, min(${trustRankSql(INPUT_TIER)}) AS r FROM derivation_inputs diLEFT JOIN facts f ON di.input_table = 'facts' AND f.id = ${numericId('di.input_id')}@@ -40,7 +40,7 @@ async function lowerable(tx: BrainEngine, table: Tiered, ids: readonly string[])GROUP BY di.derived_id)SELECT x.id, ${sourceOf(table)} AS source_id, x.trust_tier AS from_tier, ${trustTierFromRankSql('low.r')} AS to_tier, ${WRITABLE(sourceOf(table))} AS writableFROM low JOIN ${table} x ON x.id = ${numericId('low.derived_id')} WHERE low.r < ${trustRankSql('x.trust_tier')}- ORDER BY x.id FOR UPDATE OF x`, [table, [...ids]]);+ ORDER BY x.id FOR UPDATE OF x`, [table, [...ids], managed]);}/** Of `before` (fact ids and their tiers before a write), the facts the write lowered, propagated. */@@ -55,13 +55,15 @@ export async function propagateFactLowering(tx: BrainEngine, before: ReadonlyArrexport async function propagateTierLowering(tx: BrainEngine, inputs: readonly DerivationRef[]): Promise<LoweredRow[]> {if (!inputs.length) return [];const { rows } = await derivedRowsFrom(tx, inputs);+ if (!rows.length) return [];+ const managed = await readManagedMode(tx, { refusal: { subject: 'Trust tier propagation' } });const lowered: LoweredRow[] = [];const deferred: Array<{ table: string; id: string; source_id: string | null }> = [];for (const depth of [...new Set(rows.map(r => r.depth))].sort((a, b) => a - b)) {for (const table of TIERED) {const ids = rows.filter(r => r.depth === depth && r.table === table).map(r => r.id);if (!ids.length) continue;- const candidates = await lowerable(tx, table, ids);+ const candidates = await lowerable(tx, table, ids, managed);const writable = candidates.filter(c => c.writable);deferred.push(...candidates.filter(c => !c.writable).map(c => ({ table, id: String(c.id), source_id: c.source_id })));if (!writable.length) continue;diff --git a/test/receipt-coverage.test.ts b/test/receipt-coverage.test.tsindex cf17854e54..156c000d5b 100644--- a/test/receipt-coverage.test.ts+++ b/test/receipt-coverage.test.ts@@ -42,9 +42,10 @@ const RECEIPT_COVERAGE: Record<string, Coverage> = {'src/core/repair/timeline-comments.ts': { sites: 1, tables: ['timeline_entries'], todo: 'TODO(receipts): gbrain repair timeline-comments row cleanup should publish per page as a maintenance intent' },'src/core/mentions/pass.ts': { sites: 1, tables: ['page_aliases'], todo: 'TODO(receipts): derived alias rows should publish per page as a maintenance intent' },'src/core/bootstrap/verify.ts': { sites: 1, tables: ['facts'], todo: 'TODO(receipts): bootstrap verify deletes its own probe facts without a request; publish the cleanup as a maintenance intent' },+ 'src/core/trust/held-removals.ts': { sites: 1, tables: ['takes', 'timeline_entries'], todo: 'TODO(receipts): the owner accept of a held take or timeline removal (W1 #6783 §12 (a)) re-projects that row in withCoordinatedWrite as maintenance without a request when the page no longer carries it as stored; publish the accept as an owner request (a fence-carried take already reruns as a receipted takes_remove)' },'src/core/trust/owner-actions.ts': { sites: 1, tables: ['facts'], todo: 'TODO(receipts): the owner release of a held fact inserts it in withCoordinatedWrite as maintenance without a request; publish the release as an owner request' },'src/core/trust/page-handlers.ts': { sites: 1, tables: ['pages', 'facts', 'takes', 'timeline_entries'], todo: 'TODO(receipts): owner tier decisions (confirm/lower) change only trust_tier/write_origin in withCoordinatedWrite as maintenance without a request; publish them as owner requests' },- 'src/core/trust/backfill.ts': { sites: 2, tables: ['pages', 'facts', 'takes', 'timeline_entries'], todo: 'TODO(receipts): gbrain trust backfill and claim-sources --relower (#6533) set legacy trust_tier/write_origin (no content column) as attributed coordinated maintenance without a request; publish each batch as a maintenance intent' },+ 'src/core/trust/backfill.ts': { sites: 3, tables: ['pages', 'facts', 'takes', 'timeline_entries'], todo: 'TODO(receipts): gbrain trust backfill and claim-sources --relower (#6533) set legacy trust_tier/write_origin (no content column) as attributed coordinated maintenance without a request; publish each batch as a maintenance intent' },'src/core/repair/frontmatter-keys.ts': { sites: 1, tables: ['pages'], todo: 'TODO(receipts): gbrain repair frontmatter-keys (#6454) strips the four parser-reserved keys from pages.frontmatter (no content column) in withCoordinatedWrite batches as explicit-only maintenance without a request; publish each batch as a maintenance intent' },'src/core/cycle/concept-publication.ts': { sites: 1, tables: [], other: 'concept provenance links (links is not a guarded table)' },'src/core/persistence/links-maintenance.ts': { sites: 1, tables: [], other: 'derived links and the pages attendance-blocked stamp (a physical column the guard exempts)' },@@ -56,7 +57,7 @@ const RECEIPT_COVERAGE: Record<string, Coverage> = {};/** Facts/takes writers allowed without a receipt this wave, each with its TODO above. */-const RECEIPT_EXCEPTIONS = new Set(['src/core/bootstrap/verify.ts', 'src/core/trust/backfill.ts', 'src/core/trust/owner-actions.ts', 'src/core/trust/page-handlers.ts']);+const RECEIPT_EXCEPTIONS = new Set(['src/core/bootstrap/verify.ts', 'src/core/trust/backfill.ts', 'src/core/trust/held-removals.ts', 'src/core/trust/owner-actions.ts', 'src/core/trust/page-handlers.ts']);const ROOT = join(import.meta.dir, '..');