Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Security
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/core/destructive-guard.ts— three-layer protection against accidental data loss.assessDestructiveImpact(engine, sourceId)counts pages/chunks/embeddings/files/facts for a source (a fact-only source — a revoked agent's workspace, since facts are the primary agent write lane — is data at stake, not empty; pre-facts brains degrade to 0), plusoauthClientCount— OAuth clients whosesource_idreferences it.checkDestructiveConfirmation(impact, opts)is the fail-closed gate (--confirm-destructiverequired when data is present;--yesalone is rejected). FK-RESTRICT lifecycle:clientsReferencingSource(engine, sourceId)lists ALL physical OAuth-client rows referencing a source viaoauth_clients.source_id— the FK is PHYSICAL (ON DELETE RESTRICT ignoresdeleted_at), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back taggeddeleted; pre-migration brains withoutdeleted_atfall back to untagged referents (42703-retry idiom) and brains without the table have none by construction.formatClientReferentsBlockrenders the shared refusalsources remove/sources purgeprint (naming each client —[revoked, retained]for soft-deleted rows — + the revoke command) so the raw Postgres FK violation never reaches the operator.softDeleteSource/restoreSource/listArchivedSources/purgeExpiredSourcesdrive the source-level archive lifecycle viasources.archived BOOLEAN,archived_at TIMESTAMPTZ,archive_expires_at TIMESTAMPTZ;purgeExpiredSourcesSKIPS client-referenced sources via a physicalNOT EXISTS(soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting; an archive with a missing or epocharchived_at/archive_expires_atis never treated as expired and is reported inblocked. On an unmanaged brain any other failure of one source's delete is classified (ItemRun siteretention.expired_sources): an item-scoped one (a statement timeout on a large cascade, a lock timeout) is reported inblockedwith itscodeand a renderedfix(tell_user_to_run gbrain sources purge <id> --confirm-destructive) and the sweep continues; a run-scoped one, or a sweep where most sources fail, re-raises (test/pathological/a50-unmanaged-expired-sources.test.ts). Page-level analog:BrainEngine.softDeletePage/restorePage/purgeDeletedPagespluspages.deleted_at TIMESTAMPTZand a partial purge index. The MCPdelete_pageop rewires tosoftDeletePage; opsrestore_page(scope: write) andpurge_deleted_pages(scope: admin,localOnly: true) round out the surface.get_page/delete_page/restore_page(src/core/ops/pages.ts) accept an explicit per-callsource_idthat is honored or rejected loudly, never silently dropped:get_pageresolves it through the caller's read grant ('__all__'spans every source for trusted local callers, the granted sources for remote callers), whiledelete_page/restore_pagereject'__all__', target exactly one source, and — for every caller other than trusted local CLI (ctx.remote === false) — accept only the caller's write authority (ctx.auth.sourceId, falling back toctx.sourceIdfor legacy tokens and unauthenticated transports; the federated read grantallowedSourcesconfers no delete/restore access), echoing the targetedsource_idin the response. Pinned bytest/pages-source-scoping-4329.test.ts. Search visibility (buildVisibilityClauseinsrc/core/search/sql-ranking.ts) hides soft-deleted pages and archived sources fromsearchKeyword/searchKeywordChunks/searchVectorin both engines. The autopilot cycle'spurgephase callspurgeExpiredSources+engine.purgeDeletedPages(72)so the 72h TTL is real.src/core/env-trust.ts— Trust boundary for environment variables Bun auto-loaded from the cwd.envfamily.CWD_DOTENV_FILES(the eight names Bun auto-loads across NODE_ENV values),splitDotenvLines(Bun's line grammar:\n,\r\nAND a bare\rterminate a line, leading BOM stripped — shared with gbrain-env-file.ts),dotenvValuesForKey(key, dir)(value set across all assignments; the #427DATABASE_URLvalue-match guard in config.ts, which re-exports both),cwdDotenvAssignsKey(key, dir | assignments)(KEY-PRESENCE predicate; an empty assignment counts) andparseCwdDotenv(dir)→DotenvAssignment[](one read the two preflight consumers share). The assignment RHS is matched as([^\r\n]*), never.*$. Protection is one predicate,isCwdDotenvProtectedKey(key):CWD_DOTENV_PROTECTED_KEYS(code-loading / exec-target / root- and endpoint-redirect incl.GBRAIN_DATABASE_URL(key-presence; the #427 config.ts VALUE guard is separate and covers only bareDATABASE_URL),GBRAIN_DIRECT_DATABASE_URL,GBRAIN_REMOTE_MCP_URL,GBRAIN_REMOTE_ISSUER_URL,GBRAIN_OAUTH_RELAY_URL/ posture-wideningGBRAIN_*, plus the re-run markerGBRAIN_CWD_ENV_QUARANTINED; one why-comment per key, plus the deliberate exclusions and deferrals) PLUSCWD_DOTENV_PROTECTED_PREFIXES(LD_,DYLD_,GIT_,BUN_,NPM_CONFIG_,npm_config_,BASH_FUNC_,OPENCLAW_) andCWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS(NODE_OPTIONS/NODE_PATH/CA/TLS, SSH_ASKPASS*, XDG_CONFIG/DATA/CACHE_HOME, GNUPGHOME, SSL_CERT_FILE/DIR, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE, OPENSSL_CONF/ENGINES/MODULES, TMPDIR/TMP/TEMP, HOME/USERPROFILE, the shell-startup / interpreter-home group BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH (sh/kshENVdeliberately excluded: interactive-only and a routine project key), EDITOR/VISUAL/PAGER, PYTHON/PERL/RUBY preload, proxy vars both spellings, CLAUDE_CONFIG_DIR, ANTHROPIC_*/OPENAI/OPENROUTER/LITELLM/OLLAMA/LMSTUDIO/LLAMA_SERVER(_RERANKER)_BASE_URL) — the families a cwd .env could plant for the programs gbrain spawns; a denylist that grows as families are identified.quarantineCwdDotenv(env = process.env, dir = process.cwd(), { warn, assignments })iterates the keys the cwd .env files ASSIGN, deletes each protected one present inenv, prints ONE stderr line (formatQuarantineWarning, composed from the exportedCWD_DOTENV_REMEDIATIONthat guardrails.ts reuses) naming them sorted, returns them sorted. INVARIANTS: key presence, never value match; the parser accepts every line shape Bun's loader does; in-process only — children spawned without an explicitenvsee Bun's startup snapshot, which is whycli-preflight.tsre-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned bytest/env-trust.test.ts; the GBRAIN list is guarded against rot by the structuraltest/env-trust-protected-keys.test.ts(everyprocess.env.GBRAIN_*/Bun.env.GBRAIN_*/env.GBRAIN_*read in src/ whose name matches_BIN|_CLI|_MODULE|_PATH|_HOME|_URLsuffix orGBRAIN_ALLOW_prefix must be on the list or carry acwd-dotenv-ok: <why>annotation).src/core/grants/— canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission.model.tsvalidates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL;host/currentbrain aliases normalize to the serving brain (null), while other IDs need independently verified host identity.profiles.tssnapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, unlimited delegated spend, and an operator-setfullsurface for every profile exceptdelegating-agent(starter); only an explicit profile application changes an existing client's surface.catalogProvenance()is the operation catalog a snapshot is written against:service.tsadds it ascatalogProvenanceto the audit document of every write that sets a new snapshot (registration included), andreadClientCatalogProvenancereturns it only while that audit row's snapshot is still the client's snapshot (null for grants written without it; never synthesized).allowed_operations = NULLpreserves legacy scope-based behavior; a new profile missing its snapshot fails closed.service.tslocks the client, checksgrant_revision, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry.migration.tssplits legacy fences and removes only invalidagentgrants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape:model.tsalso holdsPrincipalGrant(GrantSources=default|scalar|federated|none),grantFromTokenRow(unified rows read theaccess_tokensgrant columns and any axis whosepermissionsmirror disagrees evaluates deny-all and is listed indrift; an unconvertedsource_grant IS NULLrow reads as the conversionmigrateLegacyTokenswould write, and a malformedpermissionsvalue denies every axis),GRANT_MIRROR_WINDOW_ENDS(the date until which thepermissionsmirror is written and drift is enforced; doctor reports it),authSourcesFromGrant(the AuthInfo source fields every token reader uses: both HTTP transports, publicationauthority.ts, job admission, shared-skill membership and policy),grantFromClient,validatePrincipalGrant(tokens and clients may holdnone);ClientGrant.sourcesNone(oauth_clients.source_grant = 'none': NULLsource_id, emptyfederated_read, verified asNO_SOURCES) andClientGrant.takesHolders(oauth_clients.takes_holders, NULL =['world']; read byverifyAccessTokenandauthorizeTakeHolder), both added by migration v203 (fragmentoauth-client-axes-schema.ts) and set throughauth rescope --client --sources none|--takes-holdersandpermissionsMirror.access-token-schema.tsis the column fragment (migrationf3_access_token_grants); v202 (legacy_token_grant_conversion) converts every legacy grant in bulk. Tests:test/legacy-token-grant-conversion.test.ts.legacy-token.tsis the token grant editor behindgbrain auth rescope --token(aliasesrescope-token,permissions set-takes-holders): oneFOR UPDATEtransaction that writes the columns, bumpsgrant_revision(--if-versioncompare-and-set) and rewritespermissionsas a mirror with every other key preserved;none= explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until--adopt-permissionsor--adopt-columns;migrateLegacyTokens(--migrate-legacyand schema migration v202) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB;resolveTokenGrantis the HTTP auth read (both transports): a legacy-shape row converts on that read with onesource_grant IS NULL-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion);resolveRescopeTargetrefuses a bare name that matches a token and a client.cli.tssplitsauth rescopetargets and maps the unified client flags ontoauth rescope-client's patch. An explicit emptypermissions.source_iddecodes (parseLegacyTokenScopeinsrc/core/legacy-token-scope.ts) to theNO_SOURCESsentinel, whichsourceScopeOpts, the dispatch fence (enforceBoundClientOpAllowList,fence=no_source_grant),submissionAuthorityandPOST /ingestrefuse and publication reauthorization rejects; it never regains thedefaultfloor.schema.tssupplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes throughtext::jsonbfor driver parity. Tests:test/client-grants.test.ts, OAuth compatibility suites, andtest/e2e/client-grants.test.ts(Postgres CAS, job ceilings, and actual HTTP preview/edit). GBRA-156 private-pages axis:PrivatePagesGrant(none|granted_sources) lives inaccess_tokens.private_pagesandoauth_clients.private_pages(migration v280, never in the legacy permissions mirror);privatePagesSourcescounts only explicitly named sources (scalar write source, federated write plus read sources; never thedefaultfloor), andprivatePagesAuthbuildsAuthInfo.privatePagesfor HTTP and OAuth verification; MCP dispatch runs a remote read underwithPrivateReadableSources(src/core/search/private-visibility.ts, an AsyncLocalStorage), whose*ForCallerpredicate twins andorPrivateReadableSourceOR those sources in at read sites only, never at stored-visibility decisions.src/core/grants/shared-exposure.ts+src/commands/shared-exposure-local.ts+src/commands/doctor/checks/unscoped-multi-user-token.ts— GST-363 warning when one credential that reads the same pages whoever asks (unbound, or bound to one member) serves an agent several people use; a credential holdingmay_act_foris skipped (auth create, register-client and the doctor check). Signals: a bot harness (BOT_HARNESSES), a Claude Code chat-channel plugin (settings.jsonenabledPlugins; read with the bot-workspace test inshared-exposure-local.ts, so the core reads no file or environment), or chat pages from 2+ channels in the read set (chatChannelCensus: chat types incl.pageTypesForAllowedslack/iMessage aliases; channel = frontmatter channel/chat/conversation, else a#nametitle, else the source; each DM page alone; private pages hidden unless the remote-private hatch is on).credentialReadSourcesmirrors dispatch: an unscoped legacy token reads default plus federated sources, an unscoped OAuth clientdefault, scalar and federated grants what they name;stdioReadSourcesresolves like the stdio server.sharedTokenNoticebuilds theunscoped_multi_user_tokensafety notice, silent whenexposureServes/brainServes(src/core/access/serves.ts) says the brain serves one person (fixes lead with binding:bindArgv,auth rescope --memberor--may-act-for,setup <harness> --serves several; a source rescope is named as a narrowing that leaves the credential unbound);writeExposureNoticeprints it on stderr. Routes: setup (bot harnesses, claude-code channel plugin), mcp grant, connect, skillpack scaffold, auth create, auth register-client; none changes a grant or an exit code. The doctor check is not applicable on a one-person brain, warns on credentials or wired local agents with multi-channel chat in reach, reports a bot harness alone as info, and gives a remote caller a count only. Tests:test/shared-exposure.test.ts,test/shared-exposure-routes.test.ts(repo-less PGLite).src/core/grants/lifecycle.ts+src/commands/serve-http-clients.ts— owner-authenticated client inspection, setup, export and lifecycle endpoints. Token invalidation/revoke/delete lock the OAuth client row, require reviewed revisions and explicit application, and commit an audit record atomically. Deletion records a tombstone while preserving request history and spending reservations/settlement; missing clients become terminal delegated denials while transient lookup failures remain retryable.src/commands/serve-http-api-keys.ts— owner-dashboard legacy API keys (/admin/api/api-keys). Mint validates the request (parseApiKeyMintRequest: name 1-128 printable characters, registered scopes, active source ids, holder grammar) and goes throughmintLegacyToken, so keys are born on the unified grant columns; omitted fields take thegbrain auth createdefaults (scopesread,write, neveradminunless listed; no source grant; holders['world']), reported indefaults_appliedbeside the effective grant. Refusals areinvalid_paramsagent envelopes withwhyand afix; nothing is minted. The token appears only in the mint response, never in logs or SSE. The list returns ids, scopes, sources and holders throughgrantFromTokenRow; revoke takes the row id (revokeLegacyTokenById) and refuses a name. Pinned bytest/serve-http-api-keys.test.ts.src/core/guarded-http.ts+src/core/ssrf-validate.ts— DNS answer classification, validated-address connections with original TLS/HTTP hostname and port, shared deadline/redirect policy, header-only probes, and bounded gzip/deflate/Brotli decoding. Ambient proxies fail closed with restart guidance. Consumers: URL reachability, remote images, and HTTP integration checks. Real TLS fixtures run on Bun 1.4.4.src/core/guardrails.ts— vendor-neutral content guardrail seams (registerGuardrailProvider,classify).loadGuardrailProvidersFromEnv(env = process.env, opts?: { cwd, skipCwdCheck })accepts ONLY an absolute path or a~/path forGBRAIN_GUARDRAILS_MODULE; cwd-relative specs (./,../, bare.) and bare package specifiers (pkg,@scope/pkg,pkg/sub— in the compiled binary Bun's module walk-up starts at the cwd, so a hostile checkout'snode_modules/<name>/would load) throwGuardrailLoadErrorbefore any import, and whenenvisprocess.env(oropts.cwdis given) a spec that a cwd .env file assigns is refused viacwdDotenvAssignsKey(message composed from env-trust'sCWD_DOTENV_REMEDIATION) unlessopts.skipCwdCheck(preflight's cwd == config-dir case). node:path/url/os are static imports. Registration is counted by EVENTS against a pre-import baseline so import-time side-effect registration and same-id replacement are accepted (#3688 residual). Pinned bytest/guardrails.test.ts+test/guardrails-env-load.test.ts.src/core/oauth-grants.ts— client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Issuance caps the resolved access-token lifetime (positiveoauth_clients.token_ttloverride, else the server default) atTOKEN_TTL_MAX_SECONDSfromsrc/core/grants/model.ts, so a stored or configured lifetime above 90 days never mints a longer token (test/oauth-token-ttl-clamp.test.ts, both engines).canonicalOAuthResource(requested, canonical)is the one RFC 8707 resource canonicalizer: with the provider'sresourceUrl(serve-http passes the /mcp URL derived from the configured public URL, neverHost),begin(), code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else withinvalid_targetnaming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (MAX_PENDING_TOTALserver-wide,MAX_PENDING_PER_CLIENT= 10 awaiting-decision requests perclient_id;assertCapacityprunes expired entries and enforces both ceilings synchronously at the start ofbegin()and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies.begin()rejects revoked or deleted clients before creating a request. #6202 first-consent source choice:begin()marks a requestsourceChoice.editableonly for a self-registered client's first consent (registered_via='dcr', set by the DCR insert and by migrationoauth_client_registered_viaas a nullable column;grant_revision = 0; noclient_credentials; a source grant) and offers the active sources;decide(id, approve, choice?)refuses a choice on a denial, a read-only request or an unoffered source with 403 before claiming the request, and for an editable request callsrecordFirstConsentInTransaction(grants/service.ts) inside the locked transaction before the code insert: revision 0 → 1 with anaction='consent',actor='owner'audit row even for an unchanged source, the final source share-locked and required active on every first consent, changed or not (aGrantErrormaps to 409client_policy_changed, request terminal).registered_viais part ofpolicyDigest.src/commands/serve-http-oauth.tsauthenticates request details, enforces session-bound CSRF decisions (the POST body allowssource_idonly as a string onapprove; any other key or shape is 403invalid_consent), and adds aread writebootstrap scope hint to scope-less/mcpBearer challenges without changing token authority (grantScopescaps every request to the client row's scope, so a read-only row still yields a read-only token);admin/src/pages/OAuthConsent.tsxrenders the existing admin login/approval flow without exposing protected details in the page shell; for an editable request the write source is a select of the offered sources (read sources mirror it) andsource_idis posted only when it differs from the current source. GST-2260:locked()runs its transaction once more when a stale plan (isStalePlanErrorinretry-matcher.ts) aborted its opening client read, which comes before the callback writes anything, so it is safe even under a non-transactional caller (mcp-provision) (test/stale-plan-heal.test.ts). Tests:test/oauth-owner-consent.test.ts,test/oauth-consent-security.test.ts,test/oauth-client-registered-via-migration.test.ts,test/e2e/oauth-owner-consent-source-postgres.test.ts,test/e2e/oauth-client-registered-via-postgres.test.ts,admin/e2e/admin.pw.ts.src/core/oauth-provider.ts—GBrainOAuthProviderimplementing the MCP SDK'sOAuthServerProvider+OAuthRegisteredClientsStore. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1:authorize+exchangeAuthorizationCodewith PKCE,client_credentials,refresh_tokenwith rotation,revokeToken,registerClient(DCR validates redirect_uri ishttps://or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (skipLocalPkceValidation=trueprevents the SDK from discarding the verifier first). Existing active-client grants remain usable.pgArray()escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacyaccess_tokensfallback inverifyAccessTokenhonors the original-schemascopes TEXT[]column vianormalizeTokenScopes(NULL = grandfatheredread+write+admin, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is,[]/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and reads the token's source, operation and takes-holder grant throughresolveTokenGrant(src/core/grants/legacy-token.ts, shared with the legacy HTTP transport so the two transports cannot drift; a legacy-shape row converts to the grant columns on that read;[]takes-holders preserved as explicit deny-all, NULL → the/mcpdispatch site's fail-closed['world']).sweepExpiredTokens()runs on startup in try/catch and returns the count viaRETURNING 1+ array length. RFC hardening:client_idfolded atomically into theDELETE WHEREfor both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens);client_idbound onrevokeToken(RFC 7009 §2.1);/tokenredirect_urivalidated against the/authorizevalue (RFC 6749 §4.1.3, empty-string treated as missing not wildcard);verifyAccessToken/getClientcatch onlyisUndefinedColumnErrorfromsrc/core/utils.ts(only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw);dcrDisabledconstructor option letsserve-http.tsdisable/registerwithout monkey-patching the router. Module-privatecoerceTimestamp()normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (getClientfor RFC 7591 §3.2.1 numeric timestamps,exchangeRefreshToken+verifyAccessTokenfor the SDK'stypeof === 'number'check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted toutils.ts— generic BIGINT precision-loss risk.registerClienthonorstoken_endpoint_auth_method: "none"(RFC 7591 §3.2.1): public PKCE clients storeclient_secret_hash = NULLand the response omitsclient_secret; confidential clients (client_secret_post/client_secret_basic) keep their one-time-reveal shape;getClientnormalizes NULLclient_secret_hashto JSundefinedso the SDK's clientAuth path accepts public clients.verifyAccessTokenJOINsoauth_clients.source_id(write scope, scalar) +oauth_clients.federated_read(read scope, TEXT[]) +oauth_clients.bound_slug_prefixes(write fence, TEXT[] — consumed byenforceClientSlugFenceinoperations.ts) onto the returnedAuthInfo; legacy brains degrade viaisUndefinedColumnErrorfallback, dropping the newest projection first.rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})is the trusted-operator rescope (CLIgbrain auth rescope-client, adminPOST /admin/api/rescope-client);boundSlugPrefixesis tri-state — undefined leaves the binding untouched,nullclears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. withsrc/commands/serve-http.ts: custom/tokenmiddleware that runs BEFORE the MCP SDK'sclientAuth. The SDK does plaintext compare against the request'sclient_secret; gbrain stores SHA-256 hashes only, so every confidential-client/tokenrequest would fail. The middleware detects confidential auth viaAuthorization: Basicheader ORclient_secret_postform body (both shapes per RFC 6749 §2.3.1), verifies viaverifyClient(client_id, presented_secret)(SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-client_secret_hashnormalization). Pinned bytest/oauth-confidential-client.test.ts(bothclient_secret_basicandclient_secret_post).authorize()only callsgrants.begin()and redirects to/admin/?oauth_request=<id>#oauth-consent; codes are minted solely inOAuthGrants.decide()behind the admin cookie session and session-bound CSRF.registerClient(the unauthenticated DCR store method) computes thegrant_typesdefault (authorization_code) BEFORE the scope block, then callsdcrScopeViolationonce and throwsInvalidClientMetadataError(HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omitsscoperegisters an empty scope (no default scope) and its consent request carriesscopes: [].allowClientCredentialsDcr(--enable-dcr-insecure) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFOREdcrScopeViolation, so aclient_credentialsrequest without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited toread' ceiling message (pinned intest/oauth-dcr-scope-ceiling.test.ts). Downstream is already bounded:OAuthGrants.begin()snapshots the intersected grant,exchangeCodeandverifyAccessTokenre-intersect with the client's current scope. Operator paths (registerClientManual, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process bytest/oauth-consent-security.test.ts(live SDK/registerwith a foreignredirect_uri), against the real server bytest/e2e/serve-http-consent.test.ts, and for the ceiling bytest/oauth-dcr-scope-ceiling.test.ts+test/oauth-authorize-scope-default.test.ts(DCR client:/authorizeread write admin-> code['read','write'],adminalone ->[]).src/core/pg-tls.ts— the one TLS resolver everypostgres()pool insrc/builds its options through (withPgTls(url, opts);test/pg-tls.test.tsfails a call site that skips it). An explicitssloption, URLsslmode/ssl/sslrootcert=system, or the driver'sPGSSLwins unchanged; a loopback host (localhost, 127.0.0.0/8, ::1, a Unix socket) keeps the driver default; any other host, private and Docker service names included, getsssl: 'require'.sslmode=disablein the URL is the opt-out.tlsRequiredDefaultErrorruns after a failed default-required connect (module pool, instance pool, direct pool): it sends the SSLRequest and turns a server's "no" intopostgres_tls_required(classifier reasontls_required_default); DNS, refused and timeout failures are not probed. Docs:docs/ENGINES.md#tls-for-postgres-connections.src/core/remote-body.ts— linear protected-body sanitizer over the existing Facts parser/renderer. Processes every protected fence, retains only world Facts, removes all Takes and drops malformed protected sections. Chunk creation sanitizes full bodies before splitting. Page/history responses apply it whenever trust is not explicitly local, independently of page-visibility opt-outs and holder grants. Fences are located byprotectedRegions(src/core/fence-scan.ts), shared with the strip functions,preserveProtectedTakesand the write projection: every marker token counts as in the lexical scan, and a region readers see runs past end markers quoted in code to the end readers pair with it, so the boundary never hides less than the lexical scan. Readers skip markers in inline code and trusted closed code blocks. Pinned bytest/fence-marker-code-context.test.ts.src/core/scope.ts— OAuth scope hierarchy + allowlist (the 6 scope strings,hasScope,assertAllowedScopes,filterAllowedScopes,parseScopeString,normalizeScopesInput) AND the anonymous-registration policy:DCR_REGISTRABLE_SCOPES(read,write) anddcrScopeViolation(requested, grantTypes)— returnsnullwhen the requested scopes fit the Dynamic Client Registration ceiling, otherwise theinvalid_client_metadatamessage naming the offending scopes and the operator remedy (gbrain auth register-client/ admin API /gbrain auth rescope-client <client_id> --scopes ...).agentkeeps its own "operator-approved grant with explicit delegation bindings" wording; whengrantTypesincludesclient_credentials(only reachable under--enable-dcr-insecure) the ceiling isreadalone; unknown scope strings are ignored here (the unknown-filter drops them).scopesSupportedForDiscovery({ enableDcr })is thescopes_supportedlist for OAuth discovery (consumed byserve-http.ts'sauthRouterOptions): the DCR-registrable subset (read write, canonical order) while DCR is enabled — so a client that copies discovery into its registration passesdcrScopeViolation— and every scope exceptagentotherwise; it never narrows an operator-registered client, because a client that omitsscopeat/authorizereceives its full registered set viagrantScopes(oauth-grants.ts) and an explicit request is intersected with the registration. The DCR constants and the helper sit BELOWALLOWED_SCOPES_LIST, and no comment line pairs that identifier with[, becausescripts/check-admin-scope-drift.shextracts the allowlist block with an awk match on exactly that pair. Pinned bytest/scope.test.ts+test/oauth-dcr-scope-ceiling.test.ts+ the discovery test intest/e2e/serve-http-consent.test.ts.src/core/secret-scan-labeled.ts— the transcript-lanelabeled_credentialdetector (#6147 idea, widened), compiled bysecret-scan.tsonly underScanOpts.labeledCredentials(transcript pages, the recent-transcripts read andtranscripts audit-secrets), after every other rule so a vendor or entropy claim keeps attribution. SINGLE labels (password|passwd|passcode|passphrase|pwd, optional identifier prefix, JSON-key quote, markdown bold) before:/=/:, and PAIR labels (login|log-in|credentials|creds|user/pass|username/password|…) before:/=/:/-/nothing thenuser / passoruser:pass, each in a bare and a quoted/backticked form; only the password half is claimed.labeledValueIsCredential(value, form, head)(the scanner passes the match head tovalidate) rejects placeholders, masks, templating, URLs, paths, calls, dotted references, digitless code identifiers, a backtick that closes a code span holding the label, a meeting link's?pwd=, andLABELED_STOPLISTwords; a pair's password also needs 4+ chars with a letter and a digit or symbol, and its user half must not be a stopword. W4.1 widens it: CLI flags with a separate value (--password X,--pass "a b"; suffixed flags such as--password-fileare not labels), an env-name suffix after the label (PASSWORD_DB=; a setting suffix such as_FILE/_MIN_LENGTH/_HINTrejects viasettingSuffix), acliform (prefixed flags such as--db-password,--pw, openssl-passin pass:) whose value may not start with-(other forms keep--leading passwords), the setting-suffix exemption only for single labels, and Markdown tables (tableCredentialCells,pw/Password (prod)headers,|-|separators, a per-row column Set so a row is linear in cells with per-scanTableScanState: cells under a password-label header column and the value cell of a non-header| password | X |row; escaped pipes, no outer pipes, several columns).danglingLabelgates the next-line continuation patterns per form:pairafter a dangling pair,single(the whole next line is the value, validated as a single label) after a line ending in a single label and delimiter; such a line, and a table row with a claimed cell, is scanned even when shorter than 8 chars. Claimed values join the echo dictionary atECHO_MIN_CHARS_LABELED= 8 whenlabeledEchoEligible. Every quantifier is bounded (perf-pinned intest/secret-scan-perf.test.ts); acceptance table intest/transcript-labeled-credential.test.ts; user docdocs/guides/data-ingestion.md#credential-redaction. GST-2768:TRANSCRIPT_LABELED_PATTERNS(compiled only underScanOpts.transcriptRules) adds the.netrcpasswordform (one line, or apasswordline inside a multi-line stanza thatnetrcStanzaOpentracks from amachine/defaultline throughlogin/account/password, blank and#comment lines, thenetrccontinuation form) and thekeycontinuation afterdanglingKeyLabel(a key or token label ending its line), validated bykeyLabelValueIsCredential(12+ chars, one token, a letter and a digit).src/core/ssrf-validate.ts— DNS-rebinding-defended URL validation.validateAndResolveUrl(url)resolves the hostname viadns.lookup({all: true, family: 0}), checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding).fetchWithSSRFGuard(url, opts)does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam__setDnsLookupForTestsfor hermetic tests.src/core/trust/— memory trust tiers (#5575).tier.ts: the six tiers in filter order (user_confirmed>operator_curated>tool_observed>agent_written>unknown>external_untrusted),TRUST_TIER_LABELS(the fixed user-facing labels; enums only in JSON),USER_SAID_TRUST_LABEL(the label of anagent_writtenrow whosewrite_origin.content_originisuser_said; the tier never rises, the eval harness reads the constant),minTrust/maxTrust/admitsTrust/tiersAtOrAbove,contentOriginTier(tool_outputlowers to external),storedMinTrust(a damaged token floor fails closed to the strictest), andeffectiveWriteTrust, which computes a write's tier once (derived writes capped atagent_writtenand their least trusted input;write_origin.taint_inputskeeps the 32 least trusted withtaint_inputs_truncated/taint_input_count).schema.ts(migration only, like attribution):trust_tier+write_originon facts, takes, timeline_entries and pages, the page_versions snapshot,min_truston oauth_clients/access_tokens,trust_proposals, and the BEFORE ROWtrust_tier_stamptrigger (fires last: INSERT gets the writer's tier fromgbrain.write_trust_tierorunknown; aTRUST_CONTENT_COLUMNSchange restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needsgbrain.write_trust_promotioncovering it, orgbrain.write_trust_backfillfromunknownto belowuser_confirmed, elsetrust_raise_refused). Writers declare throughWriteAttribution.trust,withWriteTrustandmaintenanceTransaction(…, trust)(persistence/context.ts; nested declarations combine as min, a group member resets).confirm.ts:requireOwnerConfirmation(a remote caller needsmemory_confirm; the local CLI needs a TTY where the user types the target token;--yesnever confirms),tierRaiseFix,trustRaiseRefusal, test seam__setConfirmationIoForTests.min-trust.ts: the local-only floor writes behindgbrain auth create --min-trustandgbrain auth set-min-trust.backfill.ts:gbrain trust backfill(deterministic signals, read-only dry run that works before the migration, resumable batches insidewithCoordinatedWriteon managed brains) and the doctortrust_tierscounts. Tests:test/trust-tier.test.ts,test/trust-tier-schema.test.tsandtest/trust-backfill.test.ts(PGLite and Postgres),test/trust-confirm-scope.test.ts. Write side (lane L1a):channel.tscomputes the tier once per write from the channel (requestChannelTrust: agent verbs agent_written,content_origin: tool_outputexternal_untrusted, connector jobs external_untrusted; owner sync/importownerImportTrust: operator_curated or thesources set-trustdefault, lowered by frontmatter markersfrontmatterTrustCaps) andstampTrustMarker(the lower-onlytrust_tiermarker, CEO-21);page-write.tswires it into page-prepare (marker stamp, fence edits keep the page tier viawithTrustKeep,lower_pageproposals on agent rewrites, the page gate tier; on an unclassified pagestampPageTrustMarkeralso caps the marker by the stored frontmatter's own lowering markers, so a write that removes one cannot raise the page, #7873; a derivedsubmit_jobpage with a derivation declaration stamps the marker too, #7905);proposals.tsis thetrust_proposalsstore and handler dispatch (decide.tsloads every handler);supersede-handlers.tsis guarded supersession (supersessionGuarded, contested fact/take/ontology proposals, remoteforget_requires_owner, the trust store for the checked decide_proposals supersede);fence-guard.tsguards the facts-fence re-projection and gates new fence rows, and holds take and timeline rows a lower-tier write would delete, replace or deactivate (guardFenceTakes,heldRows,contestHeldRows; projection,takes_remove, takes reconcile, timeline orphan prune; W1 #6783 §12 (a)); GST-2900: a world fence row restating a more trusted private fact of its own entity kept on another page (or on none) is held like a same-page restatement;privacy-hold-reply.ts(hidePrivacyHoldRefs, wrapped around every mutating op and the write-request receipt reads inoperation-load.ts) drops a privacy-holdcontested.proposal_reffrom the reply for a world-only caller who cannot read the private fact, failing closed;held-removals.tsis the owner's accept of thoseforgetproposals (the page's text rules the row; a refusedtakes_removereruns as an ownertakes_removebound by a nonce);propagation.tslowers rows derived from a lowered input throughderivation_inputsand never promotes (propagateTierLowering, §12 (b)); teststest/trust-held-removals.test.ts(PGLite and Postgres);gate-outcomes.tsis the DX-1gatefield and the held-write verb error. Owner actions: owner actions (#5575 lane L1a-owner: A4, CEO-2, CEO-9, CEO-12, DX-2, DX-7, DX-10, DX-13, DX-14, DX-15, ENG-15).owner-actions.ts:previewOwnerAction/applyOwnerActionfor confirm, drop, release, revert, allow, allow_remove, disable and enable: the preview names the summary, the typed token (the ref, or a hash8 for page refs), the exact command, whether the action raises trust and abindingof the target's exact state (row content and tier, page revision, proposal status); apply re-previews, refuses a moved binding withpreview_changedand a raising action without a confirmation withconfirmation_required(ownerActionFixis the DX-3tell_user_to_runfix). Fact and take confirms are tier-only updates underwithTrustPromotion(insidewithCoordinatedWriteon a managed brain); the hold store is an isolated adapter overwrite_gate_holds(__setHoldStoreForTests,TODO(L2a-merge)); on a managed brain itspublish(release-publish.ts) releases a held fact whose page exists as a journaledtrust_releaserequest:prepareTrustReleaseMutationappends the fact to its entity page's facts fence withprepareFenceFactAppend(or, for a hold namingpayload.row_num, indexes the row its file already holds), flips the hold and writes the row at user_confirmed (origintrust_release, ledger cause{hold}) in one publication, locks and rechecks the hold in validate (preview_changed), previews and binds an index-existing release's cell fields and refusespreview_changedwhen the cell no longer matches (releaseCell,releaseCellFields, originfields_previewed; #7656; doctortrust_release_unpreviewed_fieldslists earlier releases without it), while the database-only fallback re-checks the binding on the locked hold (#7657), keys the request id on the hold and its approved state, and refuses a deleted or private page with the fact still held; a hold with no entity slug or no page keeps the database-only release, except on a git-canonical source where no holding page can carry the entity (an exact page rule, an unreadable access state): theresubmitTrustReleaserefuses throughrefuseUnheldFact(git_home_required/access_policy_pending) with the hold kept and nothing written (GST-2676,test/trust-release-strict-home-gst2676.test.ts);disable --allwriteswrite_gate.external_mode=off,write_gate.agent_mode=off,trust.agent_activation=allowwith thetrust.kill_switchreceipt that--undorestores from.page-handlers.ts:confirmPage(removes the CEO-21trust_tiermarker through a journaledtrust_owner_pagemutation on a managed brain,importFromContentotherwise; tier only when no marker),revertPageToVersion(the version's content and its snapshot tier,unknownfor legacy versions), the coordinator preparerprepareTrustOwnerPageMutation(dispatched frompersistence/service.ts; re-checks the approved revision and refuses a remote request withoutmemory_confirm), and thelower_pagehandler (accept = confirm, reject = dismiss,revertLoweredPage= restore the prior owner version).refs.ts: typed refsf<id>,t<id>,h<id>,tp<id>,a<id>,p:<source>/<slug>, bare slugs resolved by--sourceor a single source (ambiguity refuses).review.ts:buildTrustReview(pending proposals, lowered pages, unconfirmed standing preferences, holds, agent-written pages the write gate flagged as instructions (flagged_page: theactivationSuppressedSqlpredicate, so exactly the pages proactive surfaces withhold, minus quarantined pages and pages a pending proposal already lists), allow rules, kill-switch state, grouped by day and page, complete argv) andexplainTrust.allow-rules.ts: thetrust_allow_rulestable (migration v229, receipted, removal keeps the row) and the purematchTrustAllowRuleover server-stamped fields.owner-ipc.ts: thetrust_read/trust_preview/trust_applyadministration handlers a resident owner serves over its 0600 socket to the verified local CLI only. Tests:test/trust-owner-actions.test.ts(PGLite and Postgres),test/trust-release-fence.test.ts(PGLite and Postgres),test/trust-owner-ipc.test.ts,test/trust-cli.test.ts. Derived-row taint (taint.ts,derived-gate.ts,timeline-projection.ts): see security.src/core/eligibility/{policy,sql,labels,registry,stamp,activation,scan,explain}.ts— the one reversible read eligibility policy for memory trust (#5575 A6, A7, CEO-18, CEO-20, DX-6, DX-10, ENG-8, ENG-14).policy.ts:resolveReadEligibilityreturns the effective floor (the strictest ofAuthInfo.minTrust, the caller'smin_trustandtrust.read_policy=filter's ownunknownfloor; label mode adds nothing, so ordering is byte-identical) and, for proactive reads,suppressFlaggedunlesstrust.agent_activation=allow.sql.ts: vetted predicates over a caller alias (closed vocabularies only):trustFloorSql,pageEligibleSql(spliced bybuildVisibilityClauseandpageReadFilter, so every search arm filters before LIMIT; a chunk's tier is its page's),projectionEligibleSql(facts, takes and timeline reads: a soft-deleted page's projections (deletedPageProjectionHiddenSql: a fact on or about the page, bysource_markdown_slugorentity_slugin its own source, and the page's takes and timeline rows, back onrestore_page), a quarantined page's projections andneeds_rederiverows are hidden, never expired) andactivationSuppressedSql(tier at or belowagent_writtenplus an instruction-familywrite_gate_receiptsflag).labels.ts:trust_tier+ a short server-stampedorigin(trustFieldsappends:user_saidfor a relayed user statement, whichtrustLabelWordsreads asUSER_SAID_TRUST_LABELunless the row is flagged unconfirmed); compact per-item text labels with the fixed words,unknownas a short origin line, and the<external-data>envelope only belowunknown.registry.ts:OP_READ_TRUSTclassifies every read-scope opfiltered | labeled | text_free(the dispatcher refuses alabeledop for a floored token) andPROACTIVE_SURFACESlists the injecting surfaces, each callingproactiveEligibility(ctx, id); drift-tested bytest/eligibility-registry.test.ts.stamp.tslabels rows after ranking and backstops the floor for rows a stage adds by slug; explicit reads mark flagged rowsunconfirmed.activation.tspartitions proactive candidates (partitionForActivation,pageActivationVerdicts) and builds thememory_suppressednotice (count +gbrain trust review, never content).scan.ts(gbrain trust scan, doctortrust_scan) records flag receipts for agent-written-or-lower rows written before the gate, in resumable keyset batches bounded by the id ceiling of its first run (later rows are gated by their writers; a detector bump rescans).explain.tsis thegbrain trust explaindata API: tier, origin, receipts and the per-surface decision for a typed ref. Tests:test/eligibility-{policy,registry,reads}.test.ts.src/core/trust/taint.ts,derived-gate.ts,timeline-projection.ts(#5575 derived rows; the rest ofsrc/core/trust/is above):taint.ts(I2, ENG-3/ENG-7):readTaintInputs/deriveTrustread the stored tiers of every row a deriver placed in its prompt (a vanished input readsunknown);derivedWriteTrustcaps model output atagent_writtenand a deterministic projection (fence or timeline parse) atoperator_curated;recordTaintEdgeswrites the completederivation_inputsedges;lowerToDerivedTier/lowerDerivedPage(andlowerDerivedPageIn, the same inside a caller's coordinated transaction) lower a derived row whose republish changed no content column;derivedMaintenanceTransactionis the unmanaged deriver seam;declareDerivation/declaredWriteTrustcarry a derivation in a maintenance or facts intent (the preparer stamps it, never aboveagent_written);readDerivedTaintShareis the doctor CEO-24 diagnostic.derived-gate.ts: the derivers' row-level write gate at the declared tier (derivedGateConfig,applyGateDecision: insert + flag receipt, hold, or skip a reject;recordTimelineFlag).timeline-projection.ts:gbrain extracttimeline walks stamped per page tier and gated;addProjectedPageTimelinewrites one page's own timeline as one batch that holds the live page FOR SHARE and refuses a missing one (requirePages), falling back row by row when the database refuses the batch (#6805). Tests:test/trust-taint.test.ts,test/trust-taint-origin.test.ts(PGLite and Postgres),test/trust-taint-dream.test.ts.src/core/trust/claim.ts+claim-state.ts+claim-notice.ts,src/commands/trust-claim.ts: #5575 legacy content.gbrain trust claim-sources(local CLI; typed source id on a TTY,--yesnever counts, non-TTY refusesconfirmation_requiredwith a tell_user_to_run fix) records a claim insources.config(trust_tier: operator_curated,trust_claimed_at,trust_claim_lifted_at) and lifts the source's legacyunknownrows (ids at or belowwrite_gate.scan_baseline) throughtrust/backfill.tsscoped to the claimed sources (own cursor,write_origin.channeltrust_claim), lowered byfrontmatterTrustCapsSql(channel.ts, pinned tofrontmatterTrustCaps) and every backfill signal, never above operator_curated; connector sources refuse. Doctortrust_sources_unclaimed,gbrain post-upgradeand the behavior-change notice name the claim (actor: user, tell_user_to_run); doctortrust_scan's fix is the user's to run; the scan refuses while a lift is pending; explain and review show pending rows as owner tier.claim-sources --relower [--dry-run](relowerClaimedRows, backfill.ts) is the lower-only #6533 repair:trust_claimrows whose page rule now ranks below their stored tier (legacyextracted_by: extract_atoms-*atoms) drop to it, pages first with child rows following through the relower-mode page taint, receiptwrite_origin.channeltrust_relower; the dry run reports the same rows; doctortrust_sources_unclaimednames it. Guide:docs/guides/memory-trust.md. Tests:test/trust-claim.test.ts,test/trust-claim-relower.test.ts.src/core/trust/marker-repair.ts: #6550gbrain trust backfill --repair-unknown-markers(local CLI,src/cli/commands/trust.ts).previewMarkerRepairlists live pages whose frontmattertrust_tierisunknownwhile the row is higher, with evidence (firstpage_versionssnapshot showing the marker vs the fixed releaseUNKNOWN_MARKER_FIX_RELEASE: its commit time bounds the first run,upgrade-state.jsoncan name it; whether the oldest kept version had the marker), anassessment(consistent_with_6550only when a pre-fix snapshot shows it and the first import did not, elseambiguous), pages already lowered through the marker (with their revert command), apreview_hashand the apply argv naming only the consistent pages.applyMarkerRepairrefusespreview_changedunless the fresh preview hashes to--expect, then callspage-handlers.tsrepairPageMarkerper named slug: thetrust_owner_pagemoderepair_marker(refused for remote requests) rewrites the marker torepairedMarker(stored tier)(none at owner tiers) at the previewed revision and keeps the tier.review.tsadds arepaircommand tolower_pageitems anunknownmarker caused. Pinned bytest/trust-channel-writes.test.ts(#6550 repair) andtest/trust-cli.test.ts.src/core/trust/label-lowerings.ts: GST-2468gbrain trust backfill --label-lowerings(local CLI,src/cli/commands/trust.ts), read-only.listLabelLoweringsreads everylower_pageproposal with thepage_versionsrow itsbefore_state.version_idnames and the live page, and classes itlabel_only(onlyLABEL_KEYSand the stamp keys differ, a label among them),contentorunreadable, counted by proposer;changed_sincewhen the page moved past the proposal's recorded revision. Writes nothing.src/core/trust/provenance-drift.ts,src/core/repair/provenance.ts,src/commands/doctor/checks/provenance-stamp-drift.ts: #7891 / #7918.analyzePageDrift(pure) walks a page'spage_versionsplus its live row; each transition's writer is the older snapshot'sarchived_write_request_id(joined topersistence_requests.idforauthority.remote, else the principal kind; none:unattributed). Verdicts:remote,ambiguous,local,needs_review(a later local write changed the same stamp) andrestamp(a classified page whose live caps rank above its stored tier). A restore puts each stamp back to the server-written column or the value before the first non-local change, and stamps min(lost cap, live caps, stored tier) withstampTrustMarker, so it only lowers.scanProvenanceDriftis bounded (DRIFT_SCAN_LIMITper source) and degrades topre_trust/pre_attribution. The doctor check is read-only; the repair kind is explicit-only and preview-bound (provenance-v1hash, approved set) and writes throughtrust_owner_pagemoderestore_provenance(restorePageProvenanceinpage-handlers.ts, local CLI only, re-checked againstplannedDigest, fileslower_pagewith proposerprovenance_repair) orrepair_markerforrestamp. A page sync holds is listedheldby the preview and skippedheldby the apply, both throughpageHolds(#8009), so the apply writes what the preview counted. Both repair modes render the page to its file on a classic checkout (writePageThroughwith the preimage bytes); #7960: when the database transaction then fails,restoreOwnerRepairFileputs the prior bytes back while the file still holds what the repair wrote, and commits that restore (restore write-through) when the write was committed. #7917:recordAgentPageLoweringalso files for derived publications and for callers that name a proposer;prepareMaintenanceMutationandderivedMaintenanceTransaction(rows carryingprior) call it. #7918:derivationWriteTrustrates a present but unreadable declarationunknown.
" rules and direct cc/bcc) and credential patterns; familiessrc/core/write-gate.ts+src/core/write-gate-patterns.ts— the #5575 blocking write gate, separate from observe-onlyguardrails.ts(never imported). Deterministic and model-free (P8):WRITE_GATE_PATTERNS(bounded clones of the detection-gradethink/sanitize.tsINJECTION_DETECTION_PATTERNS, the exported transcriptIMPERATIVE_RES, plus standing-instruction (incl. agent-addressed rules with long run-ups, concealment and act-without-asking clauses), exfiltration (incl. passive "must be emailed tooverride,standing_instruction,exfiltration,credential).detectInstructionLikedecodes tag characters, strips invisibles and NFKC-folds compatibility forms only when present, finds anchor words in one allocation-light hash pass (one tight loop per word), then runs each pattern only on 4 KB windows (overlapMAX_MATCH_CHARS+MAX_PRECEDING_CHARS) holding its anchors, tracked as sliding per-window anchor counts, and inside a window only within the pattern's longest match (write-gate-regex.ts, the analysis the regex lint uses) of its own anchor words, exceptWHOLE_WINDOW_PATTERNS;precededregexes check context before a rare-token match, aneggroup rejects negated matches.assessPageForGate(title, body minus managed fence table rows, frontmatter strings),assessFactForGate(fact, context, value, provenance, pre-sanitizedsource_text),assessTakeForGateandassessTimelineForGatescan every attacker-controllable field plus origin strings. Verdicts by tier: owner tiers never assessed;external_untrusted->write_gate.external_mode(flagdefault per the paid eval,quarantineopt-in,reject,off), detector error -> quarantine;agent_written/unknown->flag(write_gate.agent_mode=off), detector error -> allow.writeGateOutcomeis the DX-1gateshape;writeHeldError/writeGateRejectedErrorbuild thewrite_held/write_gate_rejectedrefusals (families only, no pattern names).scripts/check-write-gate-regex.ts(in verify) proves every pattern bounded.assessPageForGate/assessWriteGatetake an optionalWriteGateWorkaccumulator (createWriteGateWork) the detector fills per assessment with the work it did (normalization and anchor-pass input units, windows, pattern checks past the prefilter, regex executions, searched characters); nothing is kept between calls (#6490). Tests:test/write-gate.test.ts,test/write-gate-perf.slow.test.ts(quiet-round absolute p95 with the receipt insert, 5 MB linear bounds),test/write-gate-work-counters-6490.test.ts(the counters pinned per corpus; four mutants fail it: disabled prefilter, REACH x8, a per-window normalization pass, a pattern anchored onthe),test/write-gate-anchor-ranges.test.ts(sampled matches of every narrowed pattern hold an anchor word within its longest match), andtest/write-gate-detector-differential.test.ts(identical hits to the pre-optimization detector v2 kept astest/helpers/write-gate-detector-reference.ts, over the detector corpora, BrainBench fixtures, docs/skills and a seeded random corpus).src/core/write-gate-store.ts+src/core/write-gate-schema.ts—write_gate_receipts(flag/quarantine verdicts per persisted target, unique on target, content hash and detector version; pattern names only) andwrite_gate_holds(quarantined facts/takes kept out offacts/takes, unique on source, slug, fingerprint and detector version; re-arrival re-opens a decided hold). Writers record inside their publication transaction:recordPageGateReceiptresolves the live page row,recordWriteGateReceipt,recordWriteGateHold;decideFactWrite/decideTakeWritereturn insert/hold/reject per row andrecordFlaggedRowreceipts an inserted flagged row. Owner review:listWriteGateHolds,getWriteGateHold,releaseWriteGateHold(returns the payload for the confirm path; authorization is the caller's),dropWriteGateHold;pruneWriteGateReceiptsdrops receipts unseen for 365 days except a pending hold's. Tests:test/write-gate-store.test.ts(+ Postgres armtest/e2e/write-gate-store-postgres.test.ts).src/core/write-gate-scan.ts+scripts/trust-dry-run-scan.ts— read-only exposure scan: keyset batches over pages, facts, takes and timeline entries, tier projected from deterministic signals (connector source, webhook/clipper page,mcp:*/capture/transcript page, agent fact lanes,persistence_requestsoperation and authority; none ->unknown), flag/quarantine counts and families per tier and table, counts and pattern names only. The script runs it in a REPEATABLE READ READ ONLY transaction (PGLite: on a copy of the data directory). Test:test/write-gate-scan.test.ts.