Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
58.5 KB
Raw Blame

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), plus oauthClientCount — OAuth clients whose source_id references it. checkDestructiveConfirmation(impact, opts) is the fail-closed gate (--confirm-destructive required when data is present; --yes alone is rejected). FK-RESTRICT lifecycle: clientsReferencingSource(engine, sourceId) lists ALL physical OAuth-client rows referencing a source via oauth_clients.source_id — the FK is PHYSICAL (ON DELETE RESTRICT ignores deleted_at), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back tagged deleted; pre-migration brains without deleted_at fall back to untagged referents (42703-retry idiom) and brains without the table have none by construction. formatClientReferentsBlock renders the shared refusal sources remove/sources purge print (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 / purgeExpiredSources drive the source-level archive lifecycle via sources.archived BOOLEAN, archived_at TIMESTAMPTZ, archive_expires_at TIMESTAMPTZ; purgeExpiredSources SKIPS client-referenced sources via a physical NOT EXISTS (soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting; an archive with a missing or epoch archived_at/archive_expires_at is never treated as expired and is reported in blocked. On an unmanaged brain any other failure of one source's delete is classified (ItemRun site retention.expired_sources): an item-scoped one (a statement timeout on a large cascade, a lock timeout) is reported in blocked with its code and a rendered fix (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 / purgeDeletedPages plus pages.deleted_at TIMESTAMPTZ and a partial purge index. The MCP delete_page op rewires to softDeletePage; ops restore_page (scope: write) and purge_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-call source_id that is honored or rejected loudly, never silently dropped: get_page resolves it through the caller's read grant ('__all__' spans every source for trusted local callers, the granted sources for remote callers), while delete_page/restore_page reject '__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 to ctx.sourceId for legacy tokens and unauthenticated transports; the federated read grant allowedSources confers no delete/restore access), echoing the targeted source_id in the response. Pinned by test/pages-source-scoping-4329.test.ts. Search visibility (buildVisibilityClause in src/core/search/sql-ranking.ts) hides soft-deleted pages and archived sources from searchKeyword / searchKeywordChunks / searchVector in both engines. The autopilot cycle's purge phase calls purgeExpiredSources + 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 .env family. CWD_DOTENV_FILES (the eight names Bun auto-loads across NODE_ENV values), splitDotenvLines (Bun's line grammar: \n, \r\n AND a bare \r terminate a line, leading BOM stripped — shared with gbrain-env-file.ts), dotenvValuesForKey(key, dir) (value set across all assignments; the #427 DATABASE_URL value-match guard in config.ts, which re-exports both), cwdDotenvAssignsKey(key, dir | assignments) (KEY-PRESENCE predicate; an empty assignment counts) and parseCwdDotenv(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 bare DATABASE_URL), GBRAIN_DIRECT_DATABASE_URL, GBRAIN_REMOTE_MCP_URL, GBRAIN_REMOTE_ISSUER_URL, GBRAIN_OAUTH_RELAY_URL / posture-widening GBRAIN_*, plus the re-run marker GBRAIN_CWD_ENV_QUARANTINED; one why-comment per key, plus the deliberate exclusions and deferrals) PLUS CWD_DOTENV_PROTECTED_PREFIXES (LD_, DYLD_, GIT_, BUN_, NPM_CONFIG_, npm_config_, BASH_FUNC_, OPENCLAW_) and CWD_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/ksh ENV deliberately 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 in env, prints ONE stderr line (formatQuarantineWarning, composed from the exported CWD_DOTENV_REMEDIATION that 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 explicit env see Bun's startup snapshot, which is why cli-preflight.ts re-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned by test/env-trust.test.ts; the GBRAIN list is guarded against rot by the structural test/env-trust-protected-keys.test.ts (every process.env.GBRAIN_* / Bun.env.GBRAIN_* / env.GBRAIN_* read in src/ whose name matches _BIN|_CLI|_MODULE|_PATH|_HOME|_URL suffix or GBRAIN_ALLOW_ prefix must be on the list or carry a cwd-dotenv-ok: <why> annotation).

  • src/core/grants/ — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. model.ts validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; host/current brain aliases normalize to the serving brain (null), while other IDs need independently verified host identity. profiles.ts snapshots 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-set full surface for every profile except delegating-agent (starter); only an explicit profile application changes an existing client's surface. catalogProvenance() is the operation catalog a snapshot is written against: service.ts adds it as catalogProvenance to the audit document of every write that sets a new snapshot (registration included), and readClientCatalogProvenance returns it only while that audit row's snapshot is still the client's snapshot (null for grants written without it; never synthesized). allowed_operations = NULL preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. service.ts locks the client, checks grant_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.ts splits legacy fences and removes only invalid agent grants 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.ts also holds PrincipalGrant (GrantSources = default | scalar | federated | none), grantFromTokenRow (unified rows read the access_tokens grant columns and any axis whose permissions mirror disagrees evaluates deny-all and is listed in drift; an unconverted source_grant IS NULL row reads as the conversion migrateLegacyTokens would write, and a malformed permissions value denies every axis), GRANT_MIRROR_WINDOW_ENDS (the date until which the permissions mirror is written and drift is enforced; doctor reports it), authSourcesFromGrant (the AuthInfo source fields every token reader uses: both HTTP transports, publication authority.ts, job admission, shared-skill membership and policy), grantFromClient, validatePrincipalGrant (tokens and clients may hold none); ClientGrant.sourcesNone (oauth_clients.source_grant = 'none': NULL source_id, empty federated_read, verified as NO_SOURCES) and ClientGrant.takesHolders (oauth_clients.takes_holders, NULL = ['world']; read by verifyAccessToken and authorizeTakeHolder), both added by migration v203 (fragment oauth-client-axes-schema.ts) and set through auth rescope --client --sources none|--takes-holders and permissionsMirror. access-token-schema.ts is the column fragment (migration f3_access_token_grants); v202 (legacy_token_grant_conversion) converts every legacy grant in bulk. Tests: test/legacy-token-grant-conversion.test.ts. legacy-token.ts is the token grant editor behind gbrain auth rescope --token (aliases rescope-token, permissions set-takes-holders): one FOR UPDATE transaction that writes the columns, bumps grant_revision (--if-version compare-and-set) and rewrites permissions as 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-permissions or --adopt-columns; migrateLegacyTokens (--migrate-legacy and schema migration v202) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; resolveTokenGrant is the HTTP auth read (both transports): a legacy-shape row converts on that read with one source_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); resolveRescopeTarget refuses a bare name that matches a token and a client. cli.ts splits auth rescope targets and maps the unified client flags onto auth rescope-client's patch. An explicit empty permissions.source_id decodes (parseLegacyTokenScope in src/core/legacy-token-scope.ts) to the NO_SOURCES sentinel, which sourceScopeOpts, the dispatch fence (enforceBoundClientOpAllowList, fence=no_source_grant), submissionAuthority and POST /ingest refuse and publication reauthorization rejects; it never regains the default floor. schema.ts supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through text::jsonb for driver parity. Tests: test/client-grants.test.ts, OAuth compatibility suites, and test/e2e/client-grants.test.ts (Postgres CAS, job ceilings, and actual HTTP preview/edit). GBRA-156 private-pages axis: PrivatePagesGrant (none | granted_sources) lives in access_tokens.private_pages and oauth_clients.private_pages (migration v280, never in the legacy permissions mirror); privatePagesSources counts only explicitly named sources (scalar write source, federated write plus read sources; never the default floor), and privatePagesAuth builds AuthInfo.privatePages for HTTP and OAuth verification; MCP dispatch runs a remote read under withPrivateReadableSources (src/core/search/private-visibility.ts, an AsyncLocalStorage), whose *ForCaller predicate twins and orPrivateReadableSource OR 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 holding may_act_for is skipped (auth create, register-client and the doctor check). Signals: a bot harness (BOT_HARNESSES), a Claude Code chat-channel plugin (settings.json enabledPlugins; read with the bot-workspace test in shared-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. pageTypesForAllowed slack/iMessage aliases; channel = frontmatter channel/chat/conversation, else a #name title, else the source; each DM page alone; private pages hidden unless the remote-private hatch is on). credentialReadSources mirrors dispatch: an unscoped legacy token reads default plus federated sources, an unscoped OAuth client default, scalar and federated grants what they name; stdioReadSources resolves like the stdio server. sharedTokenNotice builds the unscoped_multi_user_token safety notice, silent when exposureServes / brainServes (src/core/access/serves.ts) says the brain serves one person (fixes lead with binding: bindArgv, auth rescope --member or --may-act-for, setup <harness> --serves several; a source rescope is named as a narrowing that leaves the credential unbound); writeExposureNotice prints 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 through mintLegacyToken, so keys are born on the unified grant columns; omitted fields take the gbrain auth create defaults (scopes read,write, never admin unless listed; no source grant; holders ['world']), reported in defaults_applied beside the effective grant. Refusals are invalid_params agent envelopes with why and a fix; nothing is minted. The token appears only in the mint response, never in logs or SSE. The list returns ids, scopes, sources and holders through grantFromTokenRow; revoke takes the row id (revokeLegacyTokenById) and refuses a name. Pinned by test/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 for GBRAIN_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's node_modules/<name>/ would load) throw GuardrailLoadError before any import, and when env is process.env (or opts.cwd is given) a spec that a cwd .env file assigns is refused via cwdDotenvAssignsKey (message composed from env-trust's CWD_DOTENV_REMEDIATION) unless opts.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 by test/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 (positive oauth_clients.token_ttl override, else the server default) at TOKEN_TTL_MAX_SECONDS from src/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's resourceUrl (serve-http passes the /mcp URL derived from the configured public URL, never Host), 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 with invalid_target naming 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_TOTAL server-wide, MAX_PENDING_PER_CLIENT = 10 awaiting-decision requests per client_id; assertCapacity prunes expired entries and enforces both ceilings synchronously at the start of begin() 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 request sourceChoice.editable only for a self-registered client's first consent (registered_via='dcr', set by the DCR insert and by migration oauth_client_registered_via as a nullable column; grant_revision = 0; no client_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 calls recordFirstConsentInTransaction (grants/service.ts) inside the locked transaction before the code insert: revision 0 → 1 with an action='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 (a GrantError maps to 409 client_policy_changed, request terminal). registered_via is part of policyDigest. src/commands/serve-http-oauth.ts authenticates request details, enforces session-bound CSRF decisions (the POST body allows source_id only as a string on approve; any other key or shape is 403 invalid_consent), and adds a read write bootstrap scope hint to scope-less /mcp Bearer challenges without changing token authority (grantScopes caps every request to the client row's scope, so a read-only row still yields a read-only token); admin/src/pages/OAuthConsent.tsx renders 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) and source_id is posted only when it differs from the current source. GST-2260: locked() runs its transaction once more when a stale plan (isStalePlanError in retry-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 — GBrainOAuthProvider implementing the MCP SDK's OAuthServerProvider + OAuthRegisteredClientsStore. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: authorize + exchangeAuthorizationCode with PKCE, client_credentials, refresh_token with rotation, revokeToken, registerClient (DCR validates redirect_uri is https:// 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=true prevents 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. Legacy access_tokens fallback in verifyAccessToken honors the original-schema scopes TEXT[] column via normalizeTokenScopes (NULL = grandfathered read+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 through resolveTokenGrant (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 /mcp dispatch site's fail-closed ['world']). sweepExpiredTokens() runs on startup in try/catch and returns the count via RETURNING 1 + array length. RFC hardening: client_id folded atomically into the DELETE WHERE for 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_id bound on revokeToken (RFC 7009 §2.1); /token redirect_uri validated against the /authorize value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); verifyAccessToken/getClient catch only isUndefinedColumnError from src/core/utils.ts (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); dcrDisabled constructor option lets serve-http.ts disable /register without monkey-patching the router. Module-private coerceTimestamp() normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (getClient for RFC 7591 §3.2.1 numeric timestamps, exchangeRefreshToken + verifyAccessToken for the SDK's typeof === 'number' check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to utils.ts — generic BIGINT precision-loss risk. registerClient honors token_endpoint_auth_method: "none" (RFC 7591 §3.2.1): public PKCE clients store client_secret_hash = NULL and the response omits client_secret; confidential clients (client_secret_post / client_secret_basic) keep their one-time-reveal shape; getClient normalizes NULL client_secret_hash to JS undefined so the SDK's clientAuth path accepts public clients. verifyAccessToken JOINs oauth_clients.source_id (write scope, scalar) + oauth_clients.federated_read (read scope, TEXT[]) + oauth_clients.bound_slug_prefixes (write fence, TEXT[] — consumed by enforceClientSlugFence in operations.ts) onto the returned AuthInfo; legacy brains degrade via isUndefinedColumnError fallback, dropping the newest projection first. rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?}) is the trusted-operator rescope (CLI gbrain auth rescope-client, admin POST /admin/api/rescope-client); boundSlugPrefixes is tri-state — undefined leaves the binding untouched, null clears 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. with src/commands/serve-http.ts: custom /token middleware that runs BEFORE the MCP SDK's clientAuth. The SDK does plaintext compare against the request's client_secret; gbrain stores SHA-256 hashes only, so every confidential-client /token request would fail. The middleware detects confidential auth via Authorization: Basic header OR client_secret_post form body (both shapes per RFC 6749 §2.3.1), verifies via verifyClient(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_hash normalization). Pinned by test/oauth-confidential-client.test.ts (both client_secret_basic and client_secret_post). authorize() only calls grants.begin() and redirects to /admin/?oauth_request=<id>#oauth-consent; codes are minted solely in OAuthGrants.decide() behind the admin cookie session and session-bound CSRF. registerClient (the unauthenticated DCR store method) computes the grant_types default (authorization_code) BEFORE the scope block, then calls dcrScopeViolation once and throws InvalidClientMetadataError (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits scope registers an empty scope (no default scope) and its consent request carries scopes: []. allowClientCredentialsDcr (--enable-dcr-insecure) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE dcrScopeViolation, so a client_credentials request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to read' ceiling message (pinned in test/oauth-dcr-scope-ceiling.test.ts). Downstream is already bounded: OAuthGrants.begin() snapshots the intersected grant, exchangeCode and verifyAccessToken re-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 by test/oauth-consent-security.test.ts (live SDK /register with a foreign redirect_uri), against the real server by test/e2e/serve-http-consent.test.ts, and for the ceiling by test/oauth-dcr-scope-ceiling.test.ts + test/oauth-authorize-scope-default.test.ts (DCR client: /authorize read write admin -> code ['read','write'], admin alone -> []).

  • src/core/pg-tls.ts — the one TLS resolver every postgres() pool in src/ builds its options through (withPgTls(url, opts); test/pg-tls.test.ts fails a call site that skips it). An explicit ssl option, URL sslmode / ssl / sslrootcert=system, or the driver's PGSSL wins 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, gets ssl: 'require'. sslmode=disable in the URL is the opt-out. tlsRequiredDefaultError runs after a failed default-required connect (module pool, instance pool, direct pool): it sends the SSLRequest and turns a server's "no" into postgres_tls_required (classifier reason tls_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 by protectedRegions (src/core/fence-scan.ts), shared with the strip functions, preserveProtectedTakes and 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 by test/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) and dcrScopeViolation(requested, grantTypes) — returns null when the requested scopes fit the Dynamic Client Registration ceiling, otherwise the invalid_client_metadata message naming the offending scopes and the operator remedy (gbrain auth register-client / admin API / gbrain auth rescope-client <client_id> --scopes ...). agent keeps its own "operator-approved grant with explicit delegation bindings" wording; when grantTypes includes client_credentials (only reachable under --enable-dcr-insecure) the ceiling is read alone; unknown scope strings are ignored here (the unknown-filter drops them). scopesSupportedForDiscovery({ enableDcr }) is the scopes_supported list for OAuth discovery (consumed by serve-http.ts's authRouterOptions): the DCR-registrable subset (read write, canonical order) while DCR is enabled — so a client that copies discovery into its registration passes dcrScopeViolation — and every scope except agent otherwise; it never narrows an operator-registered client, because a client that omits scope at /authorize receives its full registered set via grantScopes (oauth-grants.ts) and an explicit request is intersected with the registration. The DCR constants and the helper sit BELOW ALLOWED_SCOPES_LIST, and no comment line pairs that identifier with [, because scripts/check-admin-scope-drift.sh extracts the allowlist block with an awk match on exactly that pair. Pinned by test/scope.test.ts + test/oauth-dcr-scope-ceiling.test.ts + the discovery test in test/e2e/serve-http-consent.test.ts.

  • src/core/secret-scan-labeled.ts — the transcript-lane labeled_credential detector (#6147 idea, widened), compiled by secret-scan.ts only under ScanOpts.labeledCredentials (transcript pages, the recent-transcripts read and transcripts 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 then user / pass or user: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 to validate) 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=, and LABELED_STOPLIST words; 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-file are not labels), an env-name suffix after the label (PASSWORD_DB=; a setting suffix such as _FILE/_MIN_LENGTH/_HINT rejects via settingSuffix), a cli form (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-scan TableScanState: 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). danglingLabel gates the next-line continuation patterns per form: pair after 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 at ECHO_MIN_CHARS_LABELED = 8 when labeledEchoEligible. Every quantifier is bounded (perf-pinned in test/secret-scan-perf.test.ts); acceptance table in test/transcript-labeled-credential.test.ts; user doc docs/guides/data-ingestion.md#credential-redaction. GST-2768: TRANSCRIPT_LABELED_PATTERNS (compiled only under ScanOpts.transcriptRules) adds the .netrc password form (one line, or a password line inside a multi-line stanza that netrcStanzaOpen tracks from a machine/default line through login/account/password, blank and # comment lines, the netrc continuation form) and the key continuation after danglingKeyLabel (a key or token label ending its line), validated by keyLabelValueIsCredential (12+ chars, one token, a letter and a digit).

  • src/core/ssrf-validate.ts — DNS-rebinding-defended URL validation. validateAndResolveUrl(url) resolves the hostname via dns.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 __setDnsLookupForTests for 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 an agent_written row whose write_origin.content_origin is user_said; the tier never rises, the eval harness reads the constant), minTrust/maxTrust/admitsTrust/tiersAtOrAbove, contentOriginTier (tool_output lowers to external), storedMinTrust (a damaged token floor fails closed to the strictest), and effectiveWriteTrust, which computes a write's tier once (derived writes capped at agent_written and their least trusted input; write_origin.taint_inputs keeps the 32 least trusted with taint_inputs_truncated/taint_input_count). schema.ts (migration only, like attribution): trust_tier + write_origin on facts, takes, timeline_entries and pages, the page_versions snapshot, min_trust on oauth_clients/access_tokens, trust_proposals, and the BEFORE ROW trust_tier_stamp trigger (fires last: INSERT gets the writer's tier from gbrain.write_trust_tier or unknown; a TRUST_CONTENT_COLUMNS change restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needs gbrain.write_trust_promotion covering it, or gbrain.write_trust_backfill from unknown to below user_confirmed, else trust_raise_refused). Writers declare through WriteAttribution.trust, withWriteTrust and maintenanceTransaction(…, trust) (persistence/context.ts; nested declarations combine as min, a group member resets). confirm.ts: requireOwnerConfirmation (a remote caller needs memory_confirm; the local CLI needs a TTY where the user types the target token; --yes never confirms), tierRaiseFix, trustRaiseRefusal, test seam __setConfirmationIoForTests. min-trust.ts: the local-only floor writes behind gbrain auth create --min-trust and gbrain auth set-min-trust. backfill.ts: gbrain trust backfill (deterministic signals, read-only dry run that works before the migration, resumable batches inside withCoordinatedWrite on managed brains) and the doctor trust_tiers counts. Tests: test/trust-tier.test.ts, test/trust-tier-schema.test.ts and test/trust-backfill.test.ts (PGLite and Postgres), test/trust-confirm-scope.test.ts. Write side (lane L1a): channel.ts computes the tier once per write from the channel (requestChannelTrust: agent verbs agent_written, content_origin: tool_output external_untrusted, connector jobs external_untrusted; owner sync/import ownerImportTrust: operator_curated or the sources set-trust default, lowered by frontmatter markers frontmatterTrustCaps) and stampTrustMarker (the lower-only trust_tier marker, CEO-21); page-write.ts wires it into page-prepare (marker stamp, fence edits keep the page tier via withTrustKeep, lower_page proposals on agent rewrites, the page gate tier; on an unclassified page stampPageTrustMarker also caps the marker by the stored frontmatter's own lowering markers, so a write that removes one cannot raise the page, #7873; a derived submit_job page with a derivation declaration stamps the marker too, #7905); proposals.ts is the trust_proposals store and handler dispatch (decide.ts loads every handler); supersede-handlers.ts is guarded supersession (supersessionGuarded, contested fact/take/ontology proposals, remote forget_requires_owner, the trust store for the checked decide_proposals supersede); fence-guard.ts guards 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 in operation-load.ts) drops a privacy-hold contested.proposal_ref from the reply for a world-only caller who cannot read the private fact, failing closed; held-removals.ts is the owner's accept of those forget proposals (the page's text rules the row; a refused takes_remove reruns as an owner takes_remove bound by a nonce); propagation.ts lowers rows derived from a lowered input through derivation_inputs and never promotes (propagateTierLowering, §12 (b)); tests test/trust-held-removals.test.ts (PGLite and Postgres); gate-outcomes.ts is the DX-1 gate field 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 / applyOwnerAction for 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 a binding of the target's exact state (row content and tier, page revision, proposal status); apply re-previews, refuses a moved binding with preview_changed and a raising action without a confirmation with confirmation_required (ownerActionFix is the DX-3 tell_user_to_run fix). Fact and take confirms are tier-only updates under withTrustPromotion (inside withCoordinatedWrite on a managed brain); the hold store is an isolated adapter over write_gate_holds (__setHoldStoreForTests, TODO(L2a-merge)); on a managed brain its publish (release-publish.ts) releases a held fact whose page exists as a journaled trust_release request: prepareTrustReleaseMutation appends the fact to its entity page's facts fence with prepareFenceFactAppend (or, for a hold naming payload.row_num, indexes the row its file already holds), flips the hold and writes the row at user_confirmed (origin trust_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 refuses preview_changed when the cell no longer matches (releaseCell, releaseCellFields, origin fields_previewed; #7656; doctor trust_release_unpreviewed_fields lists 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): there submitTrustRelease refuses through refuseUnheldFact (git_home_required / access_policy_pending) with the hold kept and nothing written (GST-2676, test/trust-release-strict-home-gst2676.test.ts); disable --all writes write_gate.external_mode=off, write_gate.agent_mode=off, trust.agent_activation=allow with the trust.kill_switch receipt that --undo restores from. page-handlers.ts: confirmPage (removes the CEO-21 trust_tier marker through a journaled trust_owner_page mutation on a managed brain, importFromContent otherwise; tier only when no marker), revertPageToVersion (the version's content and its snapshot tier, unknown for legacy versions), the coordinator preparer prepareTrustOwnerPageMutation (dispatched from persistence/service.ts; re-checks the approved revision and refuses a remote request without memory_confirm), and the lower_page handler (accept = confirm, reject = dismiss, revertLoweredPage = restore the prior owner version). refs.ts: typed refs f<id>, t<id>, h<id>, tp<id>, a<id>, p:<source>/<slug>, bare slugs resolved by --source or 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: the activationSuppressedSql predicate, 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) and explainTrust. allow-rules.ts: the trust_allow_rules table (migration v229, receipted, removal keeps the row) and the pure matchTrustAllowRule over server-stamped fields. owner-ipc.ts: the trust_read / trust_preview / trust_apply administration 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: resolveReadEligibility returns the effective floor (the strictest of AuthInfo.minTrust, the caller's min_trust and trust.read_policy=filter's own unknown floor; label mode adds nothing, so ordering is byte-identical) and, for proactive reads, suppressFlagged unless trust.agent_activation=allow. sql.ts: vetted predicates over a caller alias (closed vocabularies only): trustFloorSql, pageEligibleSql (spliced by buildVisibilityClause and pageReadFilter, 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, by source_markdown_slug or entity_slug in its own source, and the page's takes and timeline rows, back on restore_page), a quarantined page's projections and needs_rederive rows are hidden, never expired) and activationSuppressedSql (tier at or below agent_written plus an instruction-family write_gate_receipts flag). labels.ts: trust_tier + a short server-stamped origin (trustFields appends :user_said for a relayed user statement, which trustLabelWords reads as USER_SAID_TRUST_LABEL unless the row is flagged unconfirmed); compact per-item text labels with the fixed words, unknown as a short origin line, and the <external-data> envelope only below unknown. registry.ts: OP_READ_TRUST classifies every read-scope op filtered | labeled | text_free (the dispatcher refuses a labeled op for a floored token) and PROACTIVE_SURFACES lists the injecting surfaces, each calling proactiveEligibility(ctx, id); drift-tested by test/eligibility-registry.test.ts. stamp.ts labels rows after ranking and backstops the floor for rows a stage adds by slug; explicit reads mark flagged rows unconfirmed. activation.ts partitions proactive candidates (partitionForActivation, pageActivationVerdicts) and builds the memory_suppressed notice (count + gbrain trust review, never content). scan.ts (gbrain trust scan, doctor trust_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.ts is the gbrain trust explain data 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 of src/core/trust/ is above): taint.ts (I2, ENG-3/ENG-7): readTaintInputs/deriveTrust read the stored tiers of every row a deriver placed in its prompt (a vanished input reads unknown); derivedWriteTrust caps model output at agent_written and a deterministic projection (fence or timeline parse) at operator_curated; recordTaintEdges writes the complete derivation_inputs edges; lowerToDerivedTier/lowerDerivedPage (and lowerDerivedPageIn, the same inside a caller's coordinated transaction) lower a derived row whose republish changed no content column; derivedMaintenanceTransaction is the unmanaged deriver seam; declareDerivation/declaredWriteTrust carry a derivation in a maintenance or facts intent (the preparer stamps it, never above agent_written); readDerivedTaintShare is 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 extract timeline walks stamped per page tier and gated; addProjectedPageTimeline writes 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, --yes never counts, non-TTY refuses confirmation_required with a tell_user_to_run fix) records a claim in sources.config (trust_tier: operator_curated, trust_claimed_at, trust_claim_lifted_at) and lifts the source's legacy unknown rows (ids at or below write_gate.scan_baseline) through trust/backfill.ts scoped to the claimed sources (own cursor, write_origin.channel trust_claim), lowered by frontmatterTrustCapsSql (channel.ts, pinned to frontmatterTrustCaps) and every backfill signal, never above operator_curated; connector sources refuse. Doctor trust_sources_unclaimed, gbrain post-upgrade and the behavior-change notice name the claim (actor: user, tell_user_to_run); doctor trust_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_claim rows whose page rule now ranks below their stored tier (legacy extracted_by: extract_atoms-* atoms) drop to it, pages first with child rows following through the relower-mode page taint, receipt write_origin.channel trust_relower; the dry run reports the same rows; doctor trust_sources_unclaimed names 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: #6550 gbrain trust backfill --repair-unknown-markers (local CLI, src/cli/commands/trust.ts). previewMarkerRepair lists live pages whose frontmatter trust_tier is unknown while the row is higher, with evidence (first page_versions snapshot showing the marker vs the fixed release UNKNOWN_MARKER_FIX_RELEASE: its commit time bounds the first run, upgrade-state.json can name it; whether the oldest kept version had the marker), an assessment (consistent_with_6550 only when a pre-fix snapshot shows it and the first import did not, else ambiguous), pages already lowered through the marker (with their revert command), a preview_hash and the apply argv naming only the consistent pages. applyMarkerRepair refuses preview_changed unless the fresh preview hashes to --expect, then calls page-handlers.ts repairPageMarker per named slug: the trust_owner_page mode repair_marker (refused for remote requests) rewrites the marker to repairedMarker(stored tier) (none at owner tiers) at the previewed revision and keeps the tier. review.ts adds a repair command to lower_page items an unknown marker caused. Pinned by test/trust-channel-writes.test.ts (#6550 repair) and test/trust-cli.test.ts.

  • src/core/trust/label-lowerings.ts: GST-2468 gbrain trust backfill --label-lowerings (local CLI, src/cli/commands/trust.ts), read-only. listLabelLowerings reads every lower_page proposal with the page_versions row its before_state.version_id names and the live page, and classes it label_only (only LABEL_KEYS and the stamp keys differ, a label among them), content or unreadable, counted by proposer; changed_since when 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's page_versions plus its live row; each transition's writer is the older snapshot's archived_write_request_id (joined to persistence_requests.id for authority.remote, else the principal kind; none: unattributed). Verdicts: remote, ambiguous, local, needs_review (a later local write changed the same stamp) and restamp (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) with stampTrustMarker, so it only lowers. scanProvenanceDrift is bounded (DRIFT_SCAN_LIMIT per source) and degrades to pre_trust / pre_attribution. The doctor check is read-only; the repair kind is explicit-only and preview-bound (provenance-v1 hash, approved set) and writes through trust_owner_page mode restore_provenance (restorePageProvenance in page-handlers.ts, local CLI only, re-checked against plannedDigest, files lower_page with proposer provenance_repair) or repair_marker for restamp. A page sync holds is listed held by the preview and skipped held by the apply, both through pageHolds (#8009), so the apply writes what the preview counted. Both repair modes render the page to its file on a classic checkout (writePageThrough with the preimage bytes); #7960: when the database transaction then fails, restoreOwnerRepairFile puts 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: recordAgentPageLowering also files for derived publications and for callers that name a proposer; prepareMaintenanceMutation and derivedMaintenanceTransaction (rows carrying prior) call it. #7918: derivationWriteTrust rates a present but unreadable declaration unknown.

  • src/core/write-gate.ts + src/core/write-gate-patterns.ts — the #5575 blocking write gate, separate from observe-only guardrails.ts (never imported). Deterministic and model-free (P8): WRITE_GATE_PATTERNS (bounded clones of the detection-grade think/sanitize.ts INJECTION_DETECTION_PATTERNS, the exported transcript IMPERATIVE_RES, plus standing-instruction (incl. agent-addressed rules with long run-ups, concealment and act-without-asking clauses), exfiltration (incl. passive "must be emailed to

    " rules and direct cc/bcc) and credential patterns; families override, standing_instruction, exfiltration, credential). detectInstructionLike decodes 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 (overlap MAX_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, except WHOLE_WINDOW_PATTERNS; preceded regexes check context before a rare-token match, a neg group rejects negated matches. assessPageForGate (title, body minus managed fence table rows, frontmatter strings), assessFactForGate (fact, context, value, provenance, pre-sanitized source_text), assessTakeForGate and assessTimelineForGate scan every attacker-controllable field plus origin strings. Verdicts by tier: owner tiers never assessed; external_untrusted -> write_gate.external_mode (flag default per the paid eval, quarantine opt-in, reject, off), detector error -> quarantine; agent_written/unknown -> flag (write_gate.agent_mode=off), detector error -> allow. writeGateOutcome is the DX-1 gate shape; writeHeldError / writeGateRejectedError build the write_held / write_gate_rejected refusals (families only, no pattern names). scripts/check-write-gate-regex.ts (in verify) proves every pattern bounded. assessPageForGate / assessWriteGate take an optional WriteGateWork accumulator (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 on the), test/write-gate-anchor-ranges.test.ts (sampled matches of every narrowed pattern hold an anchor word within its longest match), and test/write-gate-detector-differential.test.ts (identical hits to the pre-optimization detector v2 kept as test/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) and write_gate_holds (quarantined facts/takes kept out of facts/takes, unique on source, slug, fingerprint and detector version; re-arrival re-opens a decided hold). Writers record inside their publication transaction: recordPageGateReceipt resolves the live page row, recordWriteGateReceipt, recordWriteGateHold; decideFactWrite / decideTakeWrite return insert/hold/reject per row and recordFlaggedRow receipts an inserted flagged row. Owner review: listWriteGateHolds, getWriteGateHold, releaseWriteGateHold (returns the payload for the confirm path; authorization is the caller's), dropWriteGateHold; pruneWriteGateReceipts drops receipts unseen for 365 days except a pending hold's. Tests: test/write-gate-store.test.ts (+ Postgres arm test/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_requests operation 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.

Continue this subsystem.