Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(review): accept-all skips a summary too long to show instead of truncating it; doctor function_search_path names types only, no psql fix; guard covers templated names (#7820, #7688)

garrytanfc790d8fc665
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 74502add22..bc221f067d 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -29,8 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. Each `GraphPath` carries `from_source_id`/`to_source_id` and the edge dedup keys on page ids; each `traverseGraph` `GraphNode` carries `source_id` (DISTINCT per page), so the same slug in two sources stays two edges or nodes. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunkPage(slug, {fromIndex, limit, ...scope})` is get_chunks' paged read: the same predicate as `getChunks`, one count/max query plus the chunk_index range [fromIndex, fromIndex + limit) (a range, so a slug matching a page in two federated sources never splits an index across calls); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`; `getHealth` is a one-line delegation to `src/core/engine-sql/health.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
- `src/core/migrate-pending.ts` — `hasPendingMigrations` (re-exported by `migrate.ts`): one `version` read against the generated `schema-migrations/latest.generated.ts`, so a connect never loads the migration registry.
-- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, `buildIndexOnline` with its best-effort `analyzeAfterIndexBuild` (a failed ANALYZE warns with the repair command and never fails the build of a valid index), the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (`gbrain.write_sources`, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so `gbrain apply-migrations --force-schema` (`REVISION_BACKFILL_RESUME_COMMAND`) resumes it; `readRevisionBackfillStatus` feeds doctor `revision_backfill` (`src/commands/doctor/checks/revision-backfill.ts`: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the `repair orphan-children` preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`). Every pass also ends by putting `pg_temp` back on gbrain functions' search_path (`hardenFunctionSearchPaths`, best-effort; skipped after a lock refusal so the run does not wait a second `lock_timeout`; functions another role owns are named only on passes that applied migrations, #7688).
-- `src/core/function-search-path.ts` — #7632 search_path hardening: `PINNED_FUNCTION_NAMES` (every gbrain function with a pinned search_path; `scripts/check-search-path.sh` fails one missing from it or a pinned path not ending in `pg_temp`), `FUNCTION_SEARCH_PATH_HARDENING_SQL` (the schema blob's last statement), and `hardenFunctionSearchPaths` (v277 and the end of every migration run: one transaction under the migration timeouts, a pg_proc row lock it cannot take becomes `schema_lock_blocked`, a concurrent pg_proc update is retried, returns the functions left or null when listing them failed). Doctor check: `src/commands/doctor/checks/function-search-path.ts` (`function_search_path`: names any pinned function whose path does not end in `pg_temp`, a missing path included; the fix is `gbrain apply-migrations --yes` below v277, else a host-admin schema-qualified `ALTER FUNCTION`).
+- `src/core/migrate.ts` — schema-migration runner. Re-exports `MIGRATIONS` from the generated registry `src/core/schema-migrations/registry.generated.ts`; each migration is one file `src/core/schema-migrations/v<NNN>-<name>.ts` (the source of truth for schema DDL history), with the `Migration` type in `schema-migrations/types.ts` and shared handler helpers (`migrationNotice`, `dropInvalidConcurrentIndex`, `buildIndexOnline` with its best-effort `analyzeAfterIndexBuild` (a failed ANALYZE warns with the repair command and never fails the build of a valid index), the fresh-install quiet flag) in `schema-migrations/helpers.ts`, a leaf that never imports `migrate.ts`. `Migration` carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; fresh-install column in `src/schema.sql`, generated into both blobs, plus a bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — a NULL never matches a scoped `AND source_id = …` filter, so scoped `code-callers`/`code-callees` would return 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). Three shape-keyed self-heals run on EVERY `runMigrations` pass, including the no-pending early-return path, because a merge-renumbered migration or a drifted restore can leave the version counter past a schema change while the live shape stays old: `repairTimelineDedupIndex` (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) and `repairPagesUpsertArbiter` (`pages_source_slug_key`, see `pages-upsert-arbiter.ts`) are not version-gated at all; `repairLinkSourceCheck` (`links_link_source_check`, see `link-source-check-repair.ts`) runs only when the ledger is already >= `LINK_SOURCE_GATE_MIGRATION_VERSION` (114), because below it the pending loop replays v114 itself (running the repair first would rewrite the constraint twice, and a pre-v11 brain has no `link_source` column). All three are best-effort + idempotent; `doctor` surfaces each drift independently. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice). Every pass (including one with nothing pending) ends with `page-state/revision-backfill-schema.ts:resumePageRevisionBackfill` while `pages.knowledge_revision` is nullable (#5216): the page-state schema adds `sources.incarnation` and `pages.knowledge_revision` nullable with a separate default (no volatile-default table rewrite on replay; an empty `pages` is constrained at once), rows are backfilled in committed id batches with a config cursor (`page_state.revision_backfill`), a failing row is isolated and retried at most three passes, each update grants only its rows' sources to the managed writer guard (`gbrain.write_sources`, transaction-local), and the column becomes NOT NULL via CHECK NOT VALID → VALIDATE → SET NOT NULL. With the schema version current no ordinary command runs a pass, so `gbrain apply-migrations --force-schema` (`REVISION_BACKFILL_RESUME_COMMAND`) resumes it; `readRevisionBackfillStatus` feeds doctor `revision_backfill` (`src/commands/doctor/checks/revision-backfill.ts`: ok when NOT NULL, warn with the pending count, the failed rows by page and the resume command, or the `repair orphan-children` preview when only spent rows remain). The revision trigger handles a NULL old revision without reading bodies; snapshots report such a row's revision as `backfill_pending` and `assertPageRevision` refuses revision-bound writes with `revision_backfill_pending` (`page-revision-backfill-5216.test.ts`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The runner (ordering, retry, verify, repair-handler hooks and the static helper imports engine-live paths require) has a plain ratchet ceiling; migrations no longer live in this file.
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary falls into the Bun-vfs ENOENT failure. `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver: tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the squatted npm name; README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + `vector`/`pg_trgm` extensions via `PGliteOptions` (the tarballs are gunzipped and untarred in memory, and `lazyExtension` writes their files into PGLite's filesystem in the extension's `init`, after the backend starts, so postgres loads each `.so` on first use instead of PGLite preloading both on every open, about 30 ms; `readExtensionFiles` refuses any entry that is not a file or directory), plus `startParams` = PGLite's defaults then `PGLITE_START_PARAM_OVERRIDES` (no parallel maintenance workers, `max_wal_size=8GB`: an HNSW build fits the WASM heap, its WAL under the checkpoint trigger). `withSharedBuffers` appends `-c shared_buffers=<size>` when `EngineConfig.pglite_shared_buffers` is set: `connectEngineForServe` sets `ONE_SHOT_READ_SHARED_BUFFERS` (32MB) for a one-shot read-scope CLI process (shared op path, `gbrain call <read op>`, `search`, `sources list`), because the backend zero-fills the whole pool at start (about 55 ms for the 128MB default) and one read never fills it; serve and writes keep the default. The package itself is a type-only import plus one lazy `await import('@electric-sql/pglite')` inside `build()` after the resolver ran: the module must load without the package, or a missing install dies with the raw "Cannot find module" before the tier-3 sentence (#6512). Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.test.ts` (`bun add -g`-shaped hoisted layout, spawned with `bun --no-install` so script auto-install cannot mask a missing package).
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index f2987d2be1..b04cd306b1 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -43,3 +43,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/git-env.ts` + `src/core/hardened-git.ts` — #7584, the operator's `safe.directory` in scrubbed Git environments: `hardenedGitEnvironment` still drops system and global config and every `GIT_*` variable, but carries the operator's `safe.directory` entries (system and global, read from `/` with `git config --includes --show-scope` and cached for 30 s, then `GIT_CONFIG_*`) as environment config, so a source repository owned by another user reads once the operator allows it. `gitChildEnv` carries the environment entries the same way (`envSafeDirectories`, `safeDirectoryEnv`). Every other key in those places stays out. `gitChildEnv` also drops Git's global pathspec switches (`GIT_PATHSPEC_ENV_VARS`: `GIT_LITERAL_PATHSPECS`, `GIT_GLOB_PATHSPECS`, `GIT_NOGLOB_PATHSPECS`, `GIT_ICASE_PATHSPECS`; `extra` can still set one). gbrain's writers mark each path literal with `literalPathspecs` (`:(literal)<path>`), never `git --literal-pathspecs`, which Git exports to every hook and child as `GIT_LITERAL_PATHSPECS=1`, where a hook's glob pathspec then matches nothing. Tests: `test/hardened-git-safe-directory-7584.test.ts` (ownership forced with `GIT_TEST_ASSUME_DIFFERENT_OWNER` through a `git` wrapper on PATH), `test/git-literal-pathspec-hooks-7759.test.ts`.
- `src/core/outside-content.ts` — GBRA-221: `neutralizeOutsideText(text)`, the one neutralizer for text a third party wrote before it lands in a page body (Gmail/Calendar/Contacts renders in `google-render.ts`, GitHub `renderItemPage`/`renderRepoCard`, chat transcripts in `transcripts/render.ts`, `book-mirror` chapter output). It escapes every `gbrain<ws>:<ws><name>` marker token to `gbrain\:<name>` (case-insensitive), `[Source:` to `[Source\:`, and backslash-prefixes each timeline sentinel, bare `## Timeline`/`## History` heading, dated timeline row or heading, transcript message anchor and date heading, using the parsers' own predicates. Idempotent and readable; apply it per outside field (or a composed line holding one), never to a whole page that may hold gbrain's own fences or citations. Also owns `escapeAnchorLines` and `MESSAGE_ANCHOR_RE` (re-exported by `transcripts/render.ts`). New connectors use it.
+- `src/core/function-search-path.ts` — #7632 search_path hardening (#7688, #7785): `PINNED_FUNCTION_NAMES` (every gbrain function with a pinned search_path; `scripts/check-search-path.sh` fails one missing from it or a pinned path not ending in `pg_temp`), `FUNCTION_SEARCH_PATH_HARDENING_SQL` (the schema blob's last statement), and `hardenFunctionSearchPaths` (v277 and the end of every migration run: one transaction under the migration timeouts, a pg_proc row lock it cannot take becomes `schema_lock_blocked`, a concurrent pg_proc update is retried, returns the functions left or null when listing them failed). Doctor check: `src/commands/doctor/checks/function-search-path.ts` (`function_search_path`: names any pinned function whose path does not end in `pg_temp`; the fix is `gbrain apply-migrations --yes` below v277, else the schema-qualified `ALTER FUNCTION` SQL (argument types only) in `details.sql` to run as the owner, with no runnable fix).
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 49cf42ae87..8eb0adee00 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -904,14 +904,14 @@ Verify with `gbrain sources status <id> --json` and
Every gbrain function that pins a `search_path` ends it with `pg_temp`, so a session's temporary table or view named
like a purge or withdrawal ledger cannot hide that ledger from the guard that reads it (#7632). Migration v277 and the
end of every migration run append it to each function the migrating role owns; doctor's `function_search_path` check
-names any function still without it, including one re-created by hand without its `SET search_path` clause.
+names any function whose pinned path still lacks it.
- **Below schema v277**, the check's fix is `gbrain apply-migrations --yes`, which runs v277. Check again afterwards:
what is left is owned by another role.
- **A function another role owns** cannot be altered by the migrating role, so the migration leaves it and names it
- on stderr during runs that apply migrations. Run the `ALTER FUNCTION public.<function>(<args>) SET search_path = …,
- pg_temp;` statements the check prints (also in its `details.sql`) on the database host as the role that owns each
- function, for example with `psql -c "…"` connected as that role. `ALTER FUNCTION … SET` changes neither the owner
- nor the body, so the next boot's `CREATE OR REPLACE` still succeeds.
+ on stderr during runs that apply migrations. Run the `ALTER FUNCTION public.<function>(<argument types>) SET
+ search_path = …, pg_temp;` statements the check prints (also in its `details.sql`) on the database host, connected
+ to this brain's database as the role that owns each function. `ALTER FUNCTION … SET` changes neither the owner nor
+ the body, so the next boot's `CREATE OR REPLACE` still succeeds.
Verify with `gbrain doctor --only function_search_path --json`.
diff --git a/llms-full.txt b/llms-full.txt
index f637feb59f..0531ba730e 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10928,15 +10928,15 @@ Verify with `gbrain sources status <id> --json` and
Every gbrain function that pins a `search_path` ends it with `pg_temp`, so a session's temporary table or view named
like a purge or withdrawal ledger cannot hide that ledger from the guard that reads it (#7632). Migration v277 and the
end of every migration run append it to each function the migrating role owns; doctor's `function_search_path` check
-names any function still without it, including one re-created by hand without its `SET search_path` clause.
+names any function whose pinned path still lacks it.
- **Below schema v277**, the check's fix is `gbrain apply-migrations --yes`, which runs v277. Check again afterwards:
what is left is owned by another role.
- **A function another role owns** cannot be altered by the migrating role, so the migration leaves it and names it
- on stderr during runs that apply migrations. Run the `ALTER FUNCTION public.<function>(<args>) SET search_path = …,
- pg_temp;` statements the check prints (also in its `details.sql`) on the database host as the role that owns each
- function, for example with `psql -c "…"` connected as that role. `ALTER FUNCTION … SET` changes neither the owner
- nor the body, so the next boot's `CREATE OR REPLACE` still succeeds.
+ on stderr during runs that apply migrations. Run the `ALTER FUNCTION public.<function>(<argument types>) SET
+ search_path = …, pg_temp;` statements the check prints (also in its `details.sql`) on the database host, connected
+ to this brain's database as the role that owns each function. `ALTER FUNCTION … SET` changes neither the owner nor
+ the body, so the next boot's `CREATE OR REPLACE` still succeeds.
Verify with `gbrain doctor --only function_search_path --json`.
diff --git a/scripts/check-search-path.sh b/scripts/check-search-path.sh
index 5488b6b8c1..61176c3080 100755
--- a/scripts/check-search-path.sh
+++ b/scripts/check-search-path.sh
@@ -36,7 +36,7 @@ FILES="$(find src -type f \( -name '*.ts' -o -name '*.sql' \) -not -path 'src/co
# perl reads each file whole, finds every CREATE [OR REPLACE] FUNCTION header up
# to its AS $tag$, skips LANGUAGE sql, and reports headers with no search_path.
BAD="$(printf '%s\n' "$FILES" | xargs perl -0777 -ne '
- while (/CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+([\w."]+)\s*\((.*?)\)\s+RETURNS\s+(.*?)\bAS\s+\$(\w*)\$/gis) {
+ while (/CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+([\w."]+|\$\{\w+\})\s*\((.*?)\)\s+RETURNS\s+(.*?)\bAS\s+\$(\w*)\$/gis) {
my ($name, $rest, $start) = ($1, $3, $-[0]);
next if $rest =~ /\bLANGUAGE\s+sql\b/i;
next if $rest =~ /search_path/i;
@@ -63,17 +63,22 @@ ALLOWLIST_FILE="src/core/function-search-path.ts"
ALLOWED=""
if [ -f "$ALLOWLIST_FILE" ]; then
ALLOWED="$(perl -0777 -ne 'print join(" ", /'"'"'(\w+)'"'"'/g) if /PINNED_FUNCTION_NAMES\s*=\s*\[(.*?)\]/s && ($_ = $1)' "$ALLOWLIST_FILE")"
+ if [ -z "$ALLOWED" ]; then
+ echo "ERROR: could not read PINNED_FUNCTION_NAMES from $ALLOWLIST_FILE (expected: export const PINNED_FUNCTION_NAMES = [ 'name', ... ])."
+ exit 1
+ fi
fi
PATH_BAD="$(printf '%s\n' "$FILES" | GBRAIN_ALLOWED="$ALLOWED" xargs perl -0777 -ne '
BEGIN { %allowed = map { $_ => 1 } split / /, ($ENV{GBRAIN_ALLOWED} // ""); $check = length($ENV{GBRAIN_ALLOWED} // ""); }
- while (/CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+([\w."]+)\s*\((.*?)\)\s+RETURNS\s+(.*?)\bAS\s+\$(\w*)\$/gis) {
+ while (/CREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+([\w."]+|\$\{\w+\})\s*\((.*?)\)\s+RETURNS\s+(.*?)\bAS\s+\$(\w*)\$/gis) {
my ($name, $rest, $start) = ($1, $3, $-[0]);
- next unless $rest =~ /search_path\s*(?:=|TO)\s*((?:[\w"]+\s*,\s*)*[\w"]+)/i;
- my $path = $1;
- (my $bare = $name) =~ s/^(?:"?public"?\.)?"?([^"]+)"?$/$1/;
+ next unless $rest =~ /search_path/i;
my $line = 1 + (substr($_, 0, $start) =~ tr/\n//);
+ my $path = $rest =~ /search_path\s*(?:=|TO)\s*((?:[\w"]+\s*,\s*)*[\w"]+)/i ? $1 : "(not a fixed list)";
+ (my $bare = $name) =~ s/^(?:"?public"?\.)?"?([^"]+)"?$/$1/;
+ my $templated = $name =~ /^\$\{/;
print "$ARGV:$line: $bare (search_path = $path does not end in pg_temp)\n" unless $path =~ /(?:^|,)\s*pg_temp$/i;
- print "$ARGV:$line: $bare (not in PINNED_FUNCTION_NAMES)\n" if $check && !$allowed{$bare};
+ print "$ARGV:$line: $bare (not in PINNED_FUNCTION_NAMES)\n" if $check && !$templated && !$allowed{$bare};
}
' 2>/dev/null || true)"
diff --git a/src/commands/doctor/checks/function-search-path.ts b/src/commands/doctor/checks/function-search-path.ts
index 718afbfa24..199e72b37b 100644
--- a/src/commands/doctor/checks/function-search-path.ts
+++ b/src/commands/doctor/checks/function-search-path.ts
@@ -3,68 +3,68 @@
* with pg_temp.
*
* Without it, a session's temp table or view named like a ledger (fact_purges, page_purges, take_purges,
- * fact_withdrawals) hides that ledger from the guard that reads it, and a purged or withdrawn write goes through. A
- * function with no search_path at all (re-created by hand without its SET clause) is named too. Below migration v277
- * the fix is the migration; at or past it, the fix is one schema-qualified ALTER FUNCTION per function, run as the role
- * that owns it. ALTER FUNCTION ... SET changes neither the owner nor the body, so the next boot's CREATE OR REPLACE still
+ * fact_withdrawals) hides that ledger from the guard that reads it, and a purged or withdrawn write goes through. Below
+ * migration v277 the fix is the migration; at or past it, the fix is one schema-qualified ALTER FUNCTION per function
+ * (argument types only, so no caller-chosen argument name reaches the printed SQL), run on the database host as the
+ * role that owns it, so the check carries the SQL in details and no runnable fix. ALTER FUNCTION ... SET changes neither the owner nor the body, so the next boot's CREATE OR REPLACE still
* succeeds. Read-only.
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
-import { agentFix, checkError, doctorVerify } from '../check-fix.ts';
+import { agentFix, checkError } from '../check-fix.ts';
import { PINNED_FUNCTION_NAMES, PINNED_PATH_SQL } from '../../../core/function-search-path.ts';
import { v277 } from '../../../core/schema-migrations/v277-function-search-path-pg-temp.ts';
-const NAME = 'function_search_path';
const DOCS = 'docs/guides/troubleshooting.md#function-search-path';
-/** The gbrain functions whose search_path does not end in pg_temp, and the schema-qualified ALTER that fixes each. */
+/** The gbrain functions whose pinned search_path does not end in pg_temp, and the schema-qualified ALTER that fixes each. */
export async function functionSearchPathProblems(engine: BrainEngine): Promise<{ functions: string[]; fix: string[] }> {
- const rows = await engine.executeRaw<{ sig: string; qualified: string; path: string | null }>(
+ const rows = await engine.executeRaw<{ sig: string; qualified: string; path: string }>(
`SELECT p.oid::regprocedure::text AS sig,
- quote_ident(n.nspname) || '.' || quote_ident(p.proname) || '(' || pg_get_function_identity_arguments(p.oid) || ')' AS qualified,
- (SELECT ${PINNED_PATH_SQL} FROM unnest(p.proconfig) AS c(setting) WHERE c.setting LIKE 'search_path=%' LIMIT 1) AS path
- FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
- WHERE n.nspname = 'public' AND p.prokind = 'f' AND p.proname = ANY($1::text[]) ORDER BY 1`,
+ quote_ident(n.nspname) || '.' || quote_ident(p.proname) || '(' || oidvectortypes(p.proargtypes) || ')' AS qualified,
+ ${PINNED_PATH_SQL} AS path
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace CROSS JOIN LATERAL unnest(p.proconfig) AS c(setting)
+ WHERE n.nspname = 'public' AND p.prokind = 'f' AND p.proname = ANY($1::text[]) AND c.setting LIKE 'search_path=%' ORDER BY 1`,
[[...PINNED_FUNCTION_NAMES]]);
- const bad = rows.filter(r => r.path === null || !/(^|,)\s*pg_temp$/i.test(r.path));
+ const bad = rows.filter(r => !/(^|,)\s*pg_temp$/i.test(r.path));
return {
functions: bad.map(r => r.sig),
- fix: bad.map(r => `ALTER FUNCTION ${r.qualified} SET search_path = ${r.path ?? 'pg_catalog, public'}, pg_temp;`),
+ fix: bad.map(r => `ALTER FUNCTION ${r.qualified} SET search_path = ${r.path}, pg_temp;`),
};
}
async function runFunctionSearchPath(ctx: DoctorContext): Promise<Check[]> {
const engine = connectedEngine(ctx);
- ctx.progress.heartbeat(NAME);
+ const checks: Check[] = [];
+ ctx.progress.heartbeat('function_search_path');
try {
const { functions, fix } = await functionSearchPathProblems(engine);
- if (functions.length === 0) {
- return [{ name: NAME, status: 'ok', message: 'Every gbrain function that pins a search_path ends it with pg_temp' }];
- }
const risk = `${functions.length} function(s) do not end their search_path with pg_temp (${functions.join(', ')}), so a temp table or view named like a purge or withdrawal ledger hides it from the guard that reads it.`;
- const version = parseInt(await engine.getConfig('version') || '0', 10);
- if (version < v277.version) {
- return [{
- name: NAME, status: 'fail',
+ const version = functions.length === 0 ? v277.version : parseInt(await engine.getConfig('version') || '0', 10);
+ if (functions.length === 0) {
+ checks.push({ name: 'function_search_path', status: 'ok', message: 'Every gbrain function that pins a search_path ends it with pg_temp' });
+ } else if (version < v277.version) {
+ checks.push({
+ name: 'function_search_path', status: 'fail',
message: `${risk} This brain is at schema v${version}, below migration v${v277.version}, which appends pg_temp to every one its role owns: run gbrain apply-migrations --yes first, then check again.`,
fix: agentFix(['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'],
- `Runs the pending schema migrations, v${v277.version} among them, on the brain host; this check then names only the functions another role owns.`, NAME, { requires_exclusive: true, docs: DOCS }),
+ `Runs the pending schema migrations, v${v277.version} among them, on the brain host; this check then names only the functions another role owns.`, 'function_search_path', { requires_exclusive: true, docs: DOCS }),
details: { functions, schema_version: version },
- }];
+ });
+ } else {
+ checks.push({
+ name: 'function_search_path', status: 'fail',
+ message: `${risk} Fix: run this SQL on the database host, connected to this brain's database as the role that owns each function (migration v${v277.version} and every migration run already did the ones the migrating role owns): ${fix.join(' ')} See ${DOCS}.`,
+ fix_unavailable_reason: 'no_safe_automatic_fix',
+ details: { functions, sql: fix, docs: DOCS },
+ });
}
- return [{
- name: NAME, status: 'fail',
- message: `${risk} Fix, as the role that owns each function (migration v${v277.version} and every migration run already did the ones the migrating role owns): ${fix.join(' ')}`,
- fix: { argv: ['psql', '-c', fix.join(' ')], consent: [], actor: 'host_admin', requires_exclusive: false, docs: DOCS, verify: doctorVerify(NAME),
- why: 'ALTER FUNCTION needs the role that owns each function, so it runs on the database host as that role; it changes neither the owner nor the body.' },
- details: { functions, sql: fix },
- }];
} catch (e) {
- return [checkError(NAME, 'check function search paths', e)];
+ checks.push(checkError('function_search_path', 'check function search paths', e));
}
+ return checks;
}
-export const functionSearchPathEntry: DoctorEntry = { name: NAME, emits: [NAME], run: runFunctionSearchPath };
+export const functionSearchPathEntry: DoctorEntry = { name: 'function_search_path', emits: ['function_search_path'], run: runFunctionSearchPath };
diff --git a/src/commands/trust.ts b/src/commands/trust.ts
index af4e77b040..7e44f3dcde 100644
--- a/src/commands/trust.ts
+++ b/src/commands/trust.ts
@@ -144,12 +144,15 @@ function resultLine(r: OwnerActionResult): string {
return `${r.ref}: ${r.status}${tier}`;
}
-/** The longest line one item gets in the accept-all confirmation; `gbrain trust explain <ref>` shows it in full. */
-const ACCEPT_ALL_ITEM_MAX = 240;
+/**
+ * The longest summary one item may have in the accept-all confirmation. A longer item is skipped, never shortened: the
+ * owner confirms only text they were shown in full, and the item is released or confirmed on its own (#7820).
+ */
+const ACCEPT_ALL_ITEM_MAX = 1_000;
/**
- * DX-15: accept every matching item after one typed confirmation. An item whose preview fails is listed as skipped:
- * it is not in the confirmation and is never applied (#7820).
+ * DX-15: accept every matching item after one typed confirmation. An item whose preview fails, or whose summary is too
+ * long to show in one list, is listed as skipped: it is not in the confirmation and is never applied (#7820).
*/
async function acceptAll(backend: TrustBackend, args: string[], json: boolean): Promise<void> {
const filter = reviewFilter(args);
@@ -169,16 +172,18 @@ async function acceptAll(backend: TrustBackend, args: string[], json: boolean):
return;
}
const settled = await Promise.allSettled(inputs.map(input => backend.preview(input)));
- const skipped = settled.flatMap((s, i) => s.status === 'rejected' ? [{ ref: inputs[i]!.ref!, reason: 'preview_failed',
- error: s.reason instanceof OperationError ? s.reason.toJSON() : String(s.reason), next: `gbrain trust ${inputs[i]!.action} ${inputs[i]!.ref}` }] : []);
- const previewed = settled.flatMap((s, i) => s.status === 'fulfilled' ? [{ input: inputs[i]!, preview: s.value }] : []);
+ const skipped = settled.flatMap((s, i) => {
+ const next = `gbrain trust ${inputs[i]!.action} ${inputs[i]!.ref}`;
+ if (s.status === 'rejected') return [{ ref: inputs[i]!.ref!, reason: 'preview_failed', error: s.reason instanceof OperationError ? s.reason.toJSON() : String(s.reason), next }];
+ return s.value.summary.length > ACCEPT_ALL_ITEM_MAX ? [{ ref: inputs[i]!.ref!, reason: 'summary_too_long', next }] : [];
+ });
+ const previewed = settled.flatMap((s, i) => s.status === 'fulfilled' && s.value.summary.length <= ACCEPT_ALL_ITEM_MAX ? [{ input: inputs[i]!, preview: s.value }] : []);
const previews = previewed.map(p => p.preview);
const command = ['gbrain', 'trust', 'review', '--accept-all', ...args.filter(a => a !== '--accept-all' && a !== '--json')];
const token = `all-${createHash('sha256').update(previews.map(p => `${p.ref}:${p.binding}`).join('\n')).digest('hex').slice(0, 8)}`;
- const line = (p: OwnerActionPreview) => p.summary.length > ACCEPT_ALL_ITEM_MAX ? `${p.summary.slice(0, ACCEPT_ALL_ITEM_MAX - 3)}...` : p.summary;
- const summary = [`Accept ${previews.length} item(s):`, ...previews.map(p => ` ${p.ref.padEnd(6)} ${line(p)}`),
- ...skipped.map(s => ` ${s.ref.padEnd(6)} skipped: its preview failed, so it is not accepted (run ${s.next} on its own)`),
- ...(previews.some(p => p.summary.length > ACCEPT_ALL_ITEM_MAX) ? [' A line ending in ... is shortened; gbrain trust explain <ref> shows the item in full.'] : [])].join('\n');
+ const why = (reason: string) => reason === 'preview_failed' ? 'its preview failed' : 'it is too long to confirm in one list';
+ const summary = [`Accept ${previews.length} item(s):`, ...previews.map(p => ` ${p.ref.padEnd(6)} ${p.summary}`),
+ ...skipped.map(s => ` ${s.ref.padEnd(6)} skipped: ${why(s.reason)}, so it is not accepted (run ${s.next} on its own)`)].join('\n');
if (previews.length) await requireOwnerConfirmation(LOCAL_CTX, { ref: `${previews.length} items`, token, summary, command });
const accepted: OwnerActionResult[] = [];
const pending: Array<{ ref: string; request_id: string; poll: string }> = [];
@@ -200,7 +205,7 @@ async function acceptAll(backend: TrustBackend, args: string[], json: boolean):
for (const r of accepted) console.log(resultLine(r));
for (const p of pending) console.log(`${p.ref}: accepted, still pending (request ${p.request_id}; check with ${p.poll})`);
for (const f of failed) console.log(`${f.ref}: not applied (${(f.error as { message?: string }).message ?? String(f.error)})`);
- for (const s of skipped) console.log(`${s.ref}: skipped, its preview failed (${(s.error as { message?: string }).message ?? String(s.error)}); run ${s.next} on its own`);
+ for (const s of skipped) console.log(`${s.ref}: skipped, ${why(s.reason)}${'error' in s ? ` (${(s.error as { message?: string }).message ?? String(s.error)})` : ''}; run ${s.next} on its own`);
}
if (failed.length || skipped.length) setCliExitVerdict(1);
else if (pending.length && (!acceptPendingRequested(getCliOptions().acceptPending) || uncovered > 0)) setCliExitVerdict(PENDING_WRITE_EXIT_CODE);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d3fb4797ee..57e85afa86 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1380,7 +1380,6 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.582.0', id: 'frontmatter_drift_write_8109', text: 'A write that leaves a page\'s frontmatter unchanged (`remember`, a fact or timeline write, a `put_page` of the stored frontmatter) is no longer refused `source_changed` (`file_database_drift`) when the page\'s canonical file differs from the database only in ordinary frontmatter keys (for example a contact row\'s `last_used` moved forward in the file): the write lands in the database and the file keeps its own frontmatter with the new body, so the frontmatter drift stays for `gbrain sources reconcile <source> <slug> --preview --auto-additive`. Drift in the body, timeline, title, type, tags or a policy, privacy, lineage or trust key (`access`, `visibility`, `readable_by`, `derived_from`, `trust_tier`, `aliases`, ...) refuses as before, and so does a write that changes frontmatter (#8109).' },
{ since: '0.60.582.0', id: 'contacts_activity_advance_8109', text: '`gbrain sources reconcile --auto-additive` now decides a `contacts` row whose only change is an activity date (`last_used`, `last_*`, `*_last_used`, `updated`) moving forward as structurally additive (rule `contacts_activity_advance`) instead of `review` (`list_entries_changed_or_reordered`); a row that changed in any other way, moved, was removed or moved a date backward or into the future still needs review. Unquoted YAML dates compare as the instants they are instead of `date_not_text` (#8109).' },
{ since: '0.60.582.0', id: 'contact_rows_dedupe_8109', text: 'New explicit repair `gbrain repair contact-rows [--source <id>] [--slug <slug>]...` collapses duplicated frontmatter `contacts` rows: one row per (type, value), in first-seen order with the newest `last_used`; a row that differs in another field and every distinct value are kept. the preview writes nothing and prints a hash, `--apply --expect <hash> --yes` rewrites exactly the previewed pages through revision-bound `put_page` (the canonical file on sources with a checkout, the database on repo-less ones), and a page whose file drifted is listed `needs_reconcile`. Nothing runs on upgrade (#8109).' },
- // #7785: the #7636 fence change (v278, 0.60.474.0) shipped without a row; disclosed at the release that adds it.
{ since: 'TBD', id: 'writer_fence_fail_closed_7636', text: 'Since v0.60.474.0 (#7636, migration v278), a Postgres role that row-level security hides gbrain\'s writer state from (the `persistence_brain` row; on a managed brain also the `git_canonical_brain` row, a source row while any source is Git-canonical, or the page behind a tag, timeline entry or take) is refused with `writer_coordinator_required` (relationship `unreadable_state`) on every guarded write, unmanaged brains included, where such writes used to pass as unmanaged. Run gbrain as the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows (docs/ENGINES.md#writer-protocol-fences).' },
{ since: '0.60.525.0', id: 'refresh_sync_budget_8072', text: 'The member syncs of one `gbrain sources refresh` run stop starting work after `sources.refresh_sync_budget_ms` (default 5 minutes; `GBRAIN_REFRESH_SYNC_BUDGET_MS`). Each member gets an equal share of what is left. A run past it reports `sync_deferred` with the members it left `deferred` and still completes the refresh, so writes to the checkout are admitted again and the next `gbrain sources refresh <source>` continues them; a member that committed nothing in its share is reported `refresh_sync_timeout` in `sync_blocked`. A stalled sync no longer holds the refresh lock across scheduled runs or starves the other members.' },
{ since: '0.60.543.0', id: 'member_read_access_gbra218', text: 'A page whose frontmatter names readers (`readable_by: [alice-example, group:team-a]`) is now read remotely only by a token, OAuth client or stdio server bound to a listed member (`gbrain access member add`, `gbrain auth rescope --token <name> --member <id>`, config `mcp.stdio_member`). Every other remote caller gets the same `not_found` as for a missing page, including unbound credentials, a `--private-pages granted-sources` bot and both escape hatches (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), which relax only `visibility: private`. A malformed `readable_by` reads as nobody, and a page derived from a restricted page reads as nobody remotely. Pages that already named `readable_by` before this upgrade read as nobody remotely until `gbrain repair access` (preview, then `--apply`). The local CLI is unchanged; `--as <member>` previews one member\'s view.' },
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 319664b80f..d0b1e2c078 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -502,13 +502,15 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
// #7108: apply-migrations and doctor read this to name the migration and the step that helps.
const timedOut = err instanceof MigrationRetryExhausted ? isStatementTimeoutError(err.lastError) : isStatementTimeoutError(err);
if (timedOut) await recordMigrationTimeout(engine, m, MIGRATION_PRELUDES.has(m.version), err instanceof MigrationRetryExhausted ? err.lastBlockers.map(b => b.pid) : []);
- lockRefused = (err as { code?: unknown }).code === 'schema_lock_blocked' || isLockTimeoutError(err);
throw err;
}
if (!quietReplay) process.stderr.write(` [${m.version}] ✓ ${m.name}\n`);
applied++;
}
+ } catch (err) {
+ lockRefused = (err as { code?: unknown }).code === 'schema_lock_blocked' || isLockTimeoutError(err);
+ throw err;
} finally {
// Never leak the fresh-install quiet flag into a later in-process run —
// covers every exit path from here on (incl. the pre-flight probe).
diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.ts
index 5263328e44..99180686f4 100644
--- a/src/core/trust/owner-actions.ts
+++ b/src/core/trust/owner-actions.ts
@@ -233,7 +233,7 @@ function releasedFields(hold: HoldRow, cell: ParsedFact | null): string {
: [['kind', typeof p.kind === 'string' && p.kind ? p.kind : 'fact'], ['visibility', p.visibility === 'world' ? 'world' : 'private'], ['valid from', date(p.valid_from)],
['valid until', date(p.valid_until)], ['source', p.source], ['context', p.context]];
const shown = entries.filter(([, v]) => v !== undefined && v !== null && v !== '')
- .map(([k, v]) => `${k} ${k === 'context' || typeof v === 'string' ? quoted(v) : printable(v)}`).join(', ');
+ .map(([k, v]) => `${k} ${typeof v === 'number' && Number.isFinite(v) ? printable(v) : quoted(v)}`).join(', ');
return cell ? ` with fence row ${cell.rowNum} as it stands: ${shown}` : ` with ${shown}`;
}
/**
diff --git a/test/doctor-function-search-path.test.ts b/test/doctor-function-search-path.test.ts
index 243cbaa4e7..9ee35b90e3 100644
--- a/test/doctor-function-search-path.test.ts
+++ b/test/doctor-function-search-path.test.ts
@@ -34,7 +34,7 @@ describe('function_search_path doctor check (#7632)', () => {
expect({ functions, fix }).toEqual({
functions: ['gbrain_fts_input(text)', 'gbrain_refuse_purged_page()'],
fix: [
- 'ALTER FUNCTION public.gbrain_fts_input(t text) SET search_path = pg_catalog, pg_temp;',
+ 'ALTER FUNCTION public.gbrain_fts_input(text) SET search_path = pg_catalog, pg_temp;',
'ALTER FUNCTION public.gbrain_refuse_purged_page() SET search_path = pg_catalog, public, pg_temp;',
],
});
@@ -54,29 +54,29 @@ describe('function_search_path doctor check (#7632)', () => {
expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });
}, 120_000);
- test('a gbrain function re-created without any search_path is named, with a fix that pins one (#7688)', async () => {
- await engine.runMigration(0, `ALTER FUNCTION gbrain_try_jsonb(text) RESET search_path`);
- expect(await functionSearchPathProblems(engine)).toEqual({
- functions: ['gbrain_try_jsonb(text)'],
- fix: ['ALTER FUNCTION public.gbrain_try_jsonb(input text) SET search_path = pg_catalog, public, pg_temp;'],
- });
- await engine.runMigration(0, (await functionSearchPathProblems(engine)).fix.join('\n'));
- expect(await functionSearchPathProblems(engine)).toEqual({ functions: [], fix: [] });
- }, 120_000);
-
- test('at or past v277 the check fails with the ALTER as a host-admin psql fix and the SQL in details (#7688)', async () => {
+ test('at or past v277 the check fails with the ALTER in its message and details, and no runnable fix (#7688)', async () => {
await engine.runMigration(0, `ALTER FUNCTION gbrain_refuse_purged_take() SET search_path = pg_catalog, public`);
+ const sql = 'ALTER FUNCTION public.gbrain_refuse_purged_take() SET search_path = pg_catalog, public, pg_temp;';
const [check] = await run(engine);
expect(check).toMatchObject({
- name: 'function_search_path', status: 'fail',
- fix: { argv: ['psql', '-c', 'ALTER FUNCTION public.gbrain_refuse_purged_take() SET search_path = pg_catalog, public, pg_temp;'], actor: 'host_admin', consent: [],
- verify: { argv: ['gbrain', 'doctor', '--only', 'function_search_path', '--json'] }, docs: 'docs/guides/troubleshooting.md#function-search-path' },
- details: { functions: ['gbrain_refuse_purged_take()'], sql: ['ALTER FUNCTION public.gbrain_refuse_purged_take() SET search_path = pg_catalog, public, pg_temp;'] },
+ name: 'function_search_path', status: 'fail', fix_unavailable_reason: 'no_safe_automatic_fix',
+ details: { functions: ['gbrain_refuse_purged_take()'], sql: [sql], docs: 'docs/guides/troubleshooting.md#function-search-path' },
});
- expect(check!.message).toContain('as the role that owns each function');
+ expect(check!.fix).toBeUndefined();
+ expect(check!.message).toContain(`as the role that owns each function (migration v277 and every migration run already did the ones the migrating role owns): ${sql}`);
await engine.runMigration(0, `ALTER FUNCTION gbrain_refuse_purged_take() SET search_path = pg_catalog, public, pg_temp`);
}, 120_000);
+ test('the printed ALTER names argument types only, never a caller-chosen argument name (#7688)', async () => {
+ await engine.runMigration(0, `CREATE FUNCTION public.gbrain_try_jsonb("$(touch x)" int) RETURNS jsonb LANGUAGE plpgsql SET search_path = pg_catalog, public AS $f$ BEGIN RETURN NULL; END $f$`);
+ try {
+ const { fix } = await functionSearchPathProblems(engine);
+ expect(fix).toEqual(['ALTER FUNCTION public.gbrain_try_jsonb(integer) SET search_path = pg_catalog, public, pg_temp;']);
+ } finally {
+ await engine.runMigration(0, 'DROP FUNCTION public.gbrain_try_jsonb(int)');
+ }
+ }, 120_000);
+
test('below v277 the check points at gbrain apply-migrations --yes instead of hand-written ALTERs (#7688)', async () => {
await engine.runMigration(0, `ALTER FUNCTION gbrain_refuse_purged_take() SET search_path = pg_catalog, public`);
const latest = await engine.getConfig('version');
diff --git a/test/scripts/check-search-path.test.ts b/test/scripts/check-search-path.test.ts
index 82b1ab3fe4..2fd9c661db 100644
--- a/test/scripts/check-search-path.test.ts
+++ b/test/scripts/check-search-path.test.ts
@@ -81,6 +81,19 @@ describe('check-search-path.sh', () => {
expect(run.out).not.toContain('src/schema.sql:1:');
});
+ it('checks a templated function name and a FROM CURRENT path, and refuses an allowlist it cannot read (#7688)', () => {
+ write('src/a.ts', 'const s = `CREATE OR REPLACE FUNCTION ${FN}() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$ BEGIN RETURN NEW; END $fn$`;\n');
+ write('src/b.sql', 'CREATE OR REPLACE FUNCTION current_path() RETURNS trigger LANGUAGE plpgsql SET search_path FROM CURRENT AS $fn$ BEGIN RETURN NEW; END $fn$;\n');
+ const run = guard();
+ expect(run.code).toBe(1);
+ expect(run.out).toContain('src/a.ts:1: ${FN} (search_path = pg_catalog, public does not end in pg_temp)');
+ expect(run.out).toContain('src/b.sql:1: current_path (search_path = (not a fixed list) does not end in pg_temp)');
+ write('src/core/function-search-path.ts', 'export const PINNED_FUNCTION_NAMES = Object.freeze(new Set());\n');
+ const unreadable = guard();
+ expect(unreadable.code).toBe(1);
+ expect(unreadable.out).toContain('could not read PINNED_FUNCTION_NAMES');
+ });
+
it('exempts LANGUAGE sql functions and historical migration bodies', () => {
write('src/core/facts/fn.ts', 'const s = `CREATE OR REPLACE FUNCTION inlinable(claim TEXT) RETURNS TEXT\n LANGUAGE SQL IMMUTABLE STRICT AS $fn$ SELECT pg_catalog.lower(claim) $fn$`;\n');
write('src/core/schema-migrations/v001-old.ts', 'const s = `CREATE OR REPLACE FUNCTION old_fn() RETURNS trigger AS $$ BEGIN RETURN NEW; END $$`;\n');
diff --git a/test/trust-owner-actions.test.ts b/test/trust-owner-actions.test.ts
index 81567135d1..9f9c2ed07f 100644
--- a/test/trust-owner-actions.test.ts
+++ b/test/trust-owner-actions.test.ts
@@ -733,10 +733,11 @@ describe('#7820: the release, drop and accept-all previews', () => {
}), 60_000);
// Value: protects=one item whose preview fails no longer aborts accept-all, is listed as skipped, is not in the typed confirmation and is
- // never applied; a long item is shortened in the one confirmation; fails_when=previews go back to Promise.all or a skipped item is applied;
+ // never applied; a summary too long to show in full is skipped the same way, never shortened; fails_when=previews go back to Promise.all,
+ // a long summary is truncated in the confirmation, or a skipped item is applied;
// why_new=index-existing previews now materialize the page and can throw; seam=a stub TrustBackend; no_claim=a real corrupt page
- test('accept-all skips an item whose preview fails, never applies it, and shortens a long item in the confirmation', async () => {
- const long = `Release held fact h9 ("${'a long claim '.repeat(40)}", override) into memory as "confirmed by you"`;
+ test('accept-all skips an item whose preview fails or whose summary is too long to show, and never applies either', async () => {
+ const long = `Release held fact h9 ("${'a long claim '.repeat(80)}", override) into memory as "confirmed by you" with visibility "world"`;
for (const json of [false, true]) {
const applied: string[] = [];
const backend = {
@@ -760,18 +761,19 @@ describe('#7820: the release, drop and accept-all previews', () => {
try { await runTrustOwnerCommand(backend, 'review', ['--accept-all', '--from', 'default', ...(json ? ['--json'] : [])]); return currentExitCode(); }
finally { prompt = io.prompt(); final.mockRestore(); console.log = original; process.exitCode = 0; _resetCliExitVerdictForTests(); }
});
- expect({ json, exit, applied }).toEqual({ json, exit: 1, applied: ['h7', 'h9'] });
- expect(prompt).toContain('Accept 2 item(s)');
+ expect({ json, exit, applied }).toEqual({ json, exit: 1, applied: ['h7'] });
+ expect(prompt).toContain('Accept 1 item(s)');
expect(prompt).toContain('h8 skipped: its preview failed, so it is not accepted (run gbrain trust release h8 on its own)');
- expect(prompt).toContain(`h9 ${long.slice(0, 237)}...\n`);
- expect(prompt).not.toContain(long);
+ expect(prompt).toContain('h9 skipped: it is too long to confirm in one list, so it is not accepted (run gbrain trust release h9 on its own)');
+ expect(prompt).not.toContain('a long claim');
if (json) {
const doc = JSON.parse(docs[0]!);
expect({ accepted: doc.accepted.map((a: { ref: string }) => a.ref), skipped: doc.skipped.map((s: { ref: string; reason: string; next: string }) => [s.ref, s.reason, s.next]) })
- .toEqual({ accepted: ['h7', 'h9'], skipped: [['h8', 'preview_failed', 'gbrain trust release h8']] });
+ .toEqual({ accepted: ['h7'], skipped: [['h8', 'preview_failed', 'gbrain trust release h8'], ['h9', 'summary_too_long', 'gbrain trust release h9']] });
expect(doc.skipped[0].error.code).toBe('invalid_params');
} else {
expect(lines).toContain('h8: skipped, its preview failed (The facts fence of the page could not be read.); run gbrain trust release h8 on its own');
+ expect(lines).toContain('h9: skipped, it is too long to confirm in one list; run gbrain trust release h9 on its own');
}
}
}, 60_000);