Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(pages): gbrain pages status answers whether each page is searchable and why (#7179)

garrytan3e05a01fc4cc
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 6d2be191de..421cd371de 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -32,8 +32,8 @@ link it here rather than raising the cap.
| [Commands (2/6, continued)](key-files/commands-2-continued.md) | `doctor/checks/routing-federation.ts`, `git-convergence.ts`, `keyword-plan.ts`, `dream-retriage.ts` to `embed.ts` |
| [Commands (3/6)](key-files/commands-3.md) | `src/commands/engine-status.ts` through `src/commands/extract.ts` |
| [Commands (3/6, continued)](key-files/commands-3-continued.md) | `src/commands/extract-timeline-db.ts` through `src/commands/frontmatter-install-hook.ts` |
-| [Commands (4/6)](key-files/commands-4.md) | `src/commands/frontmatter.ts` through `persistence-admin.ts` |
-| [Commands (4/6, continued)](key-files/commands-4-continued.md) | `persistence-delegate.ts` to `reindex-search-vector.ts`, `init-mode-picker.ts`, `core/embedding-migration-cli.ts` |
+| [Commands (4/6)](key-files/commands-4.md) | `src/commands/frontmatter.ts` through `pages-status.ts` |
+| [Commands (4/6, continued)](key-files/commands-4-continued.md) | `persistence-admin.ts` to `reindex-search-vector.ts`, `init-mode-picker.ts`, `core/embedding-migration-cli.ts` |
| [Commands (5/6)](key-files/commands-5.md) | `src/commands/reindex.ts` through `src/commands/storage.ts` |
| [Commands (6/6)](key-files/commands-6.md) | `src/commands/sync.ts` through `src/commands/whoknows.ts` |
| [Core Ai](key-files/core-ai.md) | `src/core/ai/` gateway, embedding, dims, errors, fallbacks |
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.md
index c79d2f23e5..7fce7bbdfa 100644
--- a/docs/architecture/key-files/commands-4-continued.md
+++ b/docs/architecture/key-files/commands-4-continued.md
@@ -3,6 +3,7 @@
[Subsystem index](../KEY_FILES.md) · [Previous entries](commands-4.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration,transfer-administration}.ts` — trusted local `sources writer status|failures|claim|transfer` (failures: [Managed sync bookkeeping](managed-sync-bookkeeping.md)) and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts. `transfer-administration.ts` owns `transfer prepare|accept|cancel`: `cancel <source> --expected-epoch <n>` (intent `writer_transfer_cancel`, `--dry-run` previews) runs `cancelWriterTransfer` in `ownership.ts` on the owner host under the coordination lock and `FOR UPDATE`, requires `draining` at that epoch, returns the worktree to `active` and clears the prepared manifest while keeping the epoch, so an accept bound to it refuses `writer_transfer_conflict`. Prepare stamps `prepared_at`. Test: `test/pathological/c5-writer-transfer-cancel.test.ts` (both engines).
- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. `reportPersistenceCliError` owns the write exit verdict (`writeErrorExitCode` in `persistence/write-wait.ts`: pending exits 10 with `poll_command`, 0 with `--accept-pending`); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`. #6255: a pending receipt's envelope carries the receipt fix, and `poll_command` plus the `Poll:` line are that same argv.
- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Consent (C2) is `consentGate` (`src/core/consent-cli.ts`): `destructive`, bound to a `plan_hash` over the data dir, WAL segment names and a stale postmaster.pid (`--dry-run --json` reports it; approval is `--yes --expect <plan_hash>`, a bare `--yes` re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the `.wal-repair-backup-<ts>` folder, `restoreCommand`'s undo) is on stderr, in the payload and the dry run; the receipt adds `restore_command`. Non-TTY without approval exits 3; the TTY prompt is interaction.readLine (EOF = decline). `src/commands/reinit-pglite.ts` asks the same way (destructive, plan bound to the brain path and target model/width, the `.bak` restore command in the risk text; the `.bak` collision is refused before asking). The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`. `--legacy-lock` routes to `src/commands/pglite-repair-legacy-lock.ts` (`runLegacyLockRepair`): `--dry-run` prints `inspectLegacyLock` (`src/core/pglite-legacy-lock.ts`) with `apply_argv`, risk and user_message; apply takes `acquireKernelLockOnly` (5 s; busy → `pglite_busy` reason `timeout`), re-inspects under it, refuses `legacy_lock_removal_refused` (`live_holder` / `network_filesystem` / `filesystem_unverified`, fix = the preview), asks `consentGate` (`destructive`, plan hash bound to the legacy lock; a changed lock refuses `preview_changed`), inspects again after consent (refusal or a changed plan hash refuses; `consentEnv` / `probe` are test seams), then applies and prints the receipt. Pinned by `test/pathological/c3-pglite-legacy-lock.test.ts`.
- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 58a3adf7eb..ce920051be 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -37,7 +37,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.
-- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. `--retry-parked` retries parked tombstones once within `--older-than` and rename holds; the dry run lists `parked`, `retried` and `blocked`, and the consent names the parked count. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. `pages ghosts [--source <id>] [--json]` (#6696 B5, `pages-ghosts.ts`) lists ghost pages read-only through `scanGhostSource`. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).
+- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff in every source (per-source purge is not supported); cascades to content_chunks/page_links/chunk_relations. `parsePurgeArgs` is strict (the `pages purge-deleted` row of `src/cli/strict-args.ts`): `--older-than N` and `--older-than=N` both work, and any other token throws `invalid_params` before the engine is touched. The real purge first previews the count and, when anything would be purged, goes through `consentGate` (destructive): a TTY prompt, `--yes`, or exit 3 with the consent payload whose fix is the exact `--yes` argv and whose preview is `--dry-run --json`. `--retry-parked` retries parked tombstones once within `--older-than` and rename holds; the dry run lists `parked`, `retried` and `blocked`, and the consent names the parked count. The autopilot purge phase calls `purgeDeletedPagesCoordinated` directly and never asks. `pages ghosts [--source <id>] [--json]` (#6696 B5, `pages-ghosts.ts`) lists ghost pages read-only through `scanGhostSource`. `pages status <slug...>` (#7179) lives in `pages-status.ts`. Exports `SUBCOMMANDS` and `printUsage` for the help route. Pinned by `test/pages-purge-deleted-args.test.ts` and the `pages purge-deleted` consent-table row. Its help points soft-delete and restore at `gbrain delete|restore <slug> --force` (page writes are revisioned).
- `src/commands/pages-unsearchable.ts` — `gbrain pages unsearchable --source <id> [--state <state>] [--limit N] [--json]` (#6696 B3, read-only): one row per (page, embedding state) from `listEmbeddingStateRows` with reason, chunks, bytes and the state's rendered fix; every state but `embedded` unless `--state` names one; `--limit` 1-1000 (default 50) with `complete`; an unknown `--state` or bad `--limit` throws `invalid_params` naming the valid values. Test: `test/pages-unsearchable.test.ts`.
-
-- `src/commands/persistence-admin.ts` + `src/core/persistence/{admin-contract,administration,transfer-administration}.ts` — trusted local `sources writer status|failures|claim|transfer` (failures: [Managed sync bookkeeping](managed-sync-bookkeeping.md)) and `auth local-writer list|register|revoke`. Parse and resolve the brain before opening PGLite; an existing owner receives a separate private administration envelope verified against the current CLI registration. These names never enter the public MCP operation registry; stdio, hook credentials, forged trust fields and revoked CLI registrations cannot administer. Transfer requires exact manifest and owner epoch; status `--probe` acquires/releases a real native lock. Explicit credential replacement commits old revocation and new registration together before atomically publishing the private file, preserving old credentials for recovery without keeping their authority. No credential/hash appears in output. `test/persistence-administration.test.ts` covers database rollback, parallel rotations, transfer conflicts, real sockets and real CLI subprocesses. `retry-effects <source> --request-id <original-uuid> --dry-run --json` previews a failed embedding effect without work; applying the same reviewed request requires original/current authority, selected-brain config, source/page/owner CAS and one additional allowance. For a request with parked Git or withdrawal effects the same command previews the parked targets (`--dry-run`) or authorizes one more attempt per parked target, reporting each effect's state and whether it is terminal. It never claims ownership or rewrites canonical receipts. `transfer-administration.ts` owns `transfer prepare|accept|cancel`: `cancel <source> --expected-epoch <n>` (intent `writer_transfer_cancel`, `--dry-run` previews) runs `cancelWriterTransfer` in `ownership.ts` on the owner host under the coordination lock and `FOR UPDATE`, requires `draining` at that epoch, returns the worktree to `active` and clears the prepared manifest while keeping the epoch, so an accept bound to it refuses `writer_transfer_conflict`. Prepare stamps `prepared_at`. Test: `test/pathological/c5-writer-transfer-cancel.test.ts` (both engines).
+- `src/commands/pages-status.ts` — `gbrain pages status <slug...> [--source <id>] [--json]` (#7179, read-only, CLI only): one `PageStatus` per slug (at most 200) in the `sources resolve-path` state vocabulary (`searchable`, `pending_embedding`, `chunkless`, `keyword_only`, `quarantined`, `empty`, `missing`, `page_deleted`) with `searchable` true/'keyword'/false, the page's chunks and `unembedded` (no vector in the active column), `embedding_hold` (a held or capped budget row that applies per `budgetRowAppliesFilter`), `hold` (the Git sync hold on its file from `readGitHold`, keyed by the source-root path under the source's slug mode), `source_path`, `in_synced_commit` (the file is in `sources.last_commit`; null without a Git checkout here) and `why` + `fix`; top level `last_commit`, `head`, `at_head`, `embeddings_enabled`. The state is the worst classifier row from `listEmbeddingStateRows` narrowed by `slugs` (quarantined > chunkless > pending > keyword_only > empty > embedded); a held large page's vector-less chunks read `pending_embedding`, not keyword_only, and its fix is `heldApproveAction` (ask_user, preview first, never a spend). A sync hold's `gitHoldFix` wins over every other fix; otherwise `embeddingStateFix`, none for `searchable`, `missing`, `page_deleted` or pending on a brain keyless by choice. Strict arguments (`invalid_params`, exit 2); a page that is not searchable exits 0. Test: `test/pages-status-7179.test.ts`.
diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.ts
index e530f839c9..70cd31d20c 100644
--- a/scripts/check-agent-contract.ts
+++ b/scripts/check-agent-contract.ts
@@ -275,7 +275,9 @@ const READ_ONLY_SUBCOMMANDS = new Set(['config get', 'sources list', 'sources st
// #6661: [X12] --status takes no lock, makes no home dir and writes no receipt; it probes the serve over HTTP.
'bootstrap harness --status',
// #6803: the stale-extraction preview returns before any write and reports the terminal counts (actionable, mention_due).
- 'extract --stale --dry-run']);
+ 'extract --stale --dry-run',
+ // #7179: per-page search state; reads page, chunk, budget and hold rows plus Git objects, writes nothing.
+ 'pages status']);
function tsFiles(dir: string): string[] {
if (!existsSync(dir)) return [];
diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.ts
index 5e4cb19ac0..02ab3e38fc 100644
--- a/src/cli/subcommands.ts
+++ b/src/cli/subcommands.ts
@@ -17,7 +17,7 @@
* returns before startup side effects, strict argument checks and engine
* access.
*/
-export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge', 'unsearchable', 'ghosts'] as const;
+export const PAGES_SUBCOMMANDS = ['purge-deleted', 'purges', 'unpurge', 'unsearchable', 'ghosts', 'status'] as const;
export const CACHE_SUBCOMMANDS = ['stats', 'clear', 'prune'] as const;
export const INTEGRITY_SUBCOMMANDS = ['check', 'auto', 'review', 'reset-progress'] as const;
export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;
diff --git a/src/commands/pages-status.ts b/src/commands/pages-status.ts
new file mode 100644
index 0000000000..03f63e286d
--- /dev/null
+++ b/src/commands/pages-status.ts
@@ -0,0 +1,240 @@
+/**
+ * `gbrain pages status <slug...> [--source <id>] [--json]` (#7179): read-only,
+ * one answer per page to "is this page searchable, and if not, why?". It joins
+ * what an operator otherwise assembles by hand: the page row (live, deleted or
+ * missing), its embedding state from the engine classifier
+ * (`listEmbeddingStateRows` narrowed by `slugs`; worst state wins), the chunks
+ * without a vector in the active column, an applying large-page embedding hold
+ * (`budgetRowAppliesFilter`), the Git sync hold on its file (`readGitHold`),
+ * and whether the file is in the source's synced commit. States use the
+ * `sources resolve-path` vocabulary. A held large page stays
+ * `pending_embedding`; its fix is the held approval (ask_user, preview first),
+ * never a spend. A sync hold's own fix wins over every other fix.
+ */
+import { realpathSync } from 'node:fs';
+import type { BrainEngine } from '../core/engine.ts';
+import { cliRenderContext, renderAction, type Action } from '../core/agent-output.ts';
+import { opError } from '../core/ops/contract.ts';
+import { resolveSourceId } from '../core/source-resolver.ts';
+import { embeddingsDisabled } from '../core/embedding-disabled.ts';
+import { DELETED_PAGE_PURGE_WINDOW_HOURS, embeddingStateFix, type EmbeddingState, type EmbeddingStateRow } from '../core/embedding-state.ts';
+import { approvalAmount, approvalBasis, heldApproveAction } from '../core/held-embedding-action.ts';
+import { budgetRowAppliesFilter } from '../core/page-size-policy.ts';
+import { chunkGenerationFilter } from '../core/search/safe-chunks.ts';
+import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from '../core/search/embedding-column.ts';
+import { effectiveBytesBlock } from '../core/import-screen.ts';
+import { loadSyncEligibility, syncGit } from '../core/persistence/sync-discovery.ts';
+import { fenceAutoRepairFor, gitHoldFix, readGitHold } from '../core/persistence/sync-holds.ts';
+
+export const PAGES_STATUS_USAGE = 'Usage: gbrain pages status <slug...> [--source <id>] [--json]';
+/** Slugs one call reads. */
+export const PAGES_STATUS_MAX = 200;
+
+export type PageStatusState = 'searchable' | 'pending_embedding' | 'chunkless' | 'keyword_only' | 'quarantined' | 'empty' | 'missing' | 'page_deleted';
+
+export interface PageStatus {
+ slug: string;
+ source_id: string;
+ state: PageStatusState;
+ /** Whether search finds the page now: by keyword and vector (`true`), by keyword only (`'keyword'`), or not at all. */
+ searchable: true | 'keyword' | false;
+ page: { id: number; slug: string; deleted: boolean; chunks: number; unembedded: number } | null;
+ embedding_hold: { state: 'held' | 'capped'; reason: string | null; updated_at: string } | null;
+ hold: { code: string; message: string } | null;
+ source_path: string | null;
+ /** The file is in the source's synced commit (`sources.last_commit`); null without a Git checkout here or a recorded file. */
+ in_synced_commit: boolean | null;
+ why: string;
+ fix: Action | null;
+}
+
+export interface PagesStatus {
+ source_id: string;
+ last_commit: string | null;
+ head: string | null;
+ at_head: boolean | null;
+ embeddings_enabled: boolean;
+ pages: PageStatus[];
+}
+
+export interface PagesStatusArgs { slugs: string[]; source: string | null; json: boolean }
+
+/** Worst first: a page with some chunks embedded and some pending reads as pending. */
+const STATE_ORDER: EmbeddingState[] = ['quarantined', 'chunkless_healable', 'pending', 'keyword_only', 'empty', 'embedded'];
+const PAGE_STATE: Record<Exclude<EmbeddingState, 'deleted_page_chunks'>, PageStatusState> = { embedded: 'searchable', pending: 'pending_embedding',
+ keyword_only: 'keyword_only', quarantined: 'quarantined', empty: 'empty', chunkless_healable: 'chunkless' };
+const SEARCHABLE: Record<PageStatusState, PageStatus['searchable']> = { searchable: true, pending_embedding: 'keyword', keyword_only: 'keyword',
+ quarantined: false, chunkless: false, empty: false, missing: false, page_deleted: false };
+
+/** Positional slugs plus `--source <id>` (or `--source=<id>`) and `--json`; anything else is `invalid_params`. */
+export function parsePagesStatusArgs(args: readonly string[]): PagesStatusArgs {
+ const slugs: string[] = [];
+ let source: string | null = null;
+ let json = false;
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]!;
+ if (arg === '--json') { json = true; continue; }
+ if (arg === '--source' || arg.startsWith('--source=')) {
+ if (source !== null) throw opError('invalid_params', '--source was given more than once.', PAGES_STATUS_USAGE);
+ const value = arg === '--source' ? args[++i] : arg.slice('--source='.length);
+ if (!value || value.startsWith('-')) throw opError('invalid_params', '--source needs a source id.', PAGES_STATUS_USAGE);
+ source = value;
+ continue;
+ }
+ if (arg.startsWith('-')) throw opError('invalid_params', `Unknown option: ${arg}.`, PAGES_STATUS_USAGE);
+ if (!slugs.includes(arg)) slugs.push(arg);
+ }
+ if (!slugs.length) throw opError('invalid_params', 'Name at least one page slug.', PAGES_STATUS_USAGE);
+ if (slugs.length > PAGES_STATUS_MAX) throw opError('invalid_params', `At most ${PAGES_STATUS_MAX} slugs per call (got ${slugs.length}).`, `Split the slugs into batches. ${PAGES_STATUS_USAGE}`);
+ return { slugs, source, json };
+}
+
+interface PageRow {
+ id: number; slug: string; deleted: boolean; source_path: string | null; embed_skip: boolean;
+ hold_state: 'held' | 'capped' | null; hold_reason: string | null; hold_updated_at: Date | string | null;
+ chunks: number | string; unembedded: number | string; unembedded_chars: number | string;
+}
+
+/** The page rows (live or deleted), each with its chunk counts over the active column and its applying embedding budget row. */
+async function readPages(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<Map<string, PageRow>> {
+ const column = `cc.${quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name)}`;
+ const rows = await engine.executeRaw<PageRow>(
+ `SELECT p.id, p.slug, p.deleted_at IS NOT NULL AS deleted, p.source_path, COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip' AS embed_skip,
+ b.state AS hold_state, b.reason AS hold_reason, b.updated_at AS hold_updated_at, w.chunks, w.unembedded, w.unembedded_chars
+ FROM pages p
+ LEFT JOIN page_embedding_budget b ON b.page_id = p.id AND ${budgetRowAppliesFilter('b', 'p')}
+ CROSS JOIN LATERAL (SELECT count(*)::int AS chunks, (count(*) FILTER (WHERE ${column} IS NULL))::int AS unembedded,
+ COALESCE(sum(length(cc.chunk_text)) FILTER (WHERE ${column} IS NULL), 0)::bigint AS unembedded_chars
+ FROM content_chunks cc WHERE cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')}) w
+ WHERE p.source_id = $1 AND p.slug = ANY($2::text[])`, [sourceId, slugs]);
+ return new Map(rows.map(row => [row.slug, row]));
+}
+
+/** The worst classifier row per live slug. */
+async function readEmbeddingStates(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<Map<string, EmbeddingStateRow>> {
+ if (!slugs.length) return new Map();
+ const rows = await engine.listEmbeddingStateRows({ sourceIds: [sourceId], slugs, states: STATE_ORDER, limit: slugs.length * STATE_ORDER.length,
+ purgeWindowHours: DELETED_PAGE_PURGE_WINDOW_HOURS });
+ const worst = new Map<string, EmbeddingStateRow>();
+ for (const row of rows) {
+ const prior = worst.get(row.slug);
+ if (!prior || STATE_ORDER.indexOf(row.state) < STATE_ORDER.indexOf(prior.state)) worst.set(row.slug, row);
+ }
+ return worst;
+}
+
+interface GitView { head: string | null; files: Map<string, { inSynced: boolean | null; holdPath: string | null }> }
+
+/**
+ * HEAD of the source checkout on this host and, per recorded file, whether the synced commit has it and its hold key
+ * (the source-root-relative path) under the source's slug mode. Null when the source has no readable Git checkout here.
+ */
+async function readGitView(engine: BrainEngine, sourceId: string, source: { local_path: string | null; last_commit: string | null; config: Record<string, unknown> | null },
+ sourcePaths: string[]): Promise<GitView | null> {
+ if (!source.local_path) return null;
+ try {
+ const root = realpathSync(source.local_path);
+ const gitRoot = realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim());
+ let head: string | null = null;
+ try { head = syncGit(gitRoot, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']).trim() || null; } catch { /* unborn HEAD */ }
+ const { scope, slugMode } = await loadSyncEligibility(engine, { root, gitRoot, sourceId, source: { last_commit: source.last_commit, config: source.config ?? {} } });
+ const mapped = sourcePaths.map(sourcePath => {
+ if (slugMode === 'source-root' && scope) return { sourcePath, gitPath: `${scope}/${sourcePath}`, holdPath: sourcePath };
+ return { sourcePath, gitPath: sourcePath, holdPath: !scope ? sourcePath : sourcePath.startsWith(`${scope}/`) ? sourcePath.slice(scope.length + 1) : null };
+ });
+ let synced: Set<string> | null = null;
+ if (source.last_commit && mapped.length) {
+ try {
+ const listed = syncGit(gitRoot, ['--literal-pathspecs', 'ls-tree', '-z', '--name-only', source.last_commit, '--', ...mapped.map(m => m.gitPath)]);
+ synced = new Set(listed.split('\0').filter(Boolean));
+ } catch { /* the synced commit is not in this checkout */ }
+ }
+ return { head, files: new Map(mapped.map(m => [m.sourcePath, { inSynced: synced ? synced.has(m.gitPath) : null, holdPath: m.holdPath }])) };
+ } catch {
+ return null;
+ }
+}
+
+function stateWhy(slug: string, state: PageStatusState, ctx: { row?: EmbeddingStateRow; unembedded: number; disabled: boolean; embeddingHold: PageStatus['embedding_hold'] }): string {
+ switch (state) {
+ case 'searchable': return `Page ${slug} is live and every chunk has a vector.`;
+ case 'pending_embedding':
+ if (ctx.embeddingHold) return `Page ${slug} is searchable by keyword; ${ctx.unembedded} chunk(s) of this large page wait for embedding approval (${ctx.embeddingHold.state}${ctx.embeddingHold.reason ? `: ${ctx.embeddingHold.reason}` : ''}), and nothing embeds them until the user approves.`;
+ return ctx.disabled ? `Page ${slug} is searchable by keyword; embeddings are off on this brain, so its chunks carry no vector.`
+ : `Page ${slug} is searchable by keyword; ${ctx.unembedded} chunk(s) still wait for a vector.`;
+ case 'keyword_only': return `Page ${slug} is searchable by keyword only: the import gate marked it embed_skip (${ctx.row?.embed_skip_reason ?? 'embed_skip'}), so it gets no vectors.`;
+ case 'quarantined': return `Page ${slug} is quarantined (${ctx.row?.quarantine_reason ?? 'quarantine'}): the content-quality gate hides it from search.`;
+ case 'chunkless': return `Page ${slug} has body text but no chunk rows, so neither keyword nor vector search can read its body.`;
+ case 'empty': return `Page ${slug} has no body text, so there is nothing to search.`;
+ case 'page_deleted': return `Page ${slug} is soft-deleted, so search never returns it. If it should come back, restore it with gbrain restore ${slug} --force.`;
+ case 'missing': return `No page with slug ${slug} exists in this source, live or deleted.`;
+ }
+}
+
+/** Resolves each slug of one source to its search state, reason and fix. Read-only. */
+export async function readPagesStatus(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<PagesStatus> {
+ const [source] = await engine.executeRaw<{ local_path: string | null; last_commit: string | null; config: Record<string, unknown> | null; incarnation: string | null }>(
+ 'SELECT local_path, last_commit, config, incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const disabled = await embeddingsDisabled(engine);
+ const pages = await readPages(engine, sourceId, slugs);
+ const states = await readEmbeddingStates(engine, sourceId, [...pages.values()].filter(page => !page.deleted).map(page => page.slug));
+ const sourcePaths = [...new Set([...pages.values()].flatMap(page => page.source_path ? [page.source_path] : []))];
+ const git = source ? await readGitView(engine, sourceId, source, sourcePaths) : null;
+ const lastCommit = source?.last_commit ?? null;
+ const head = git?.head ?? null;
+ let blockBytes: number | undefined;
+ let basis: Awaited<ReturnType<typeof approvalBasis>> | undefined;
+ const out: PageStatus[] = [];
+ for (const slug of slugs) {
+ const page = pages.get(slug);
+ if (!page) {
+ out.push({ slug, source_id: sourceId, state: 'missing', searchable: false, page: null, embedding_hold: null, hold: null, source_path: null, in_synced_commit: null,
+ why: stateWhy(slug, 'missing', { unembedded: 0, disabled, embeddingHold: null }), fix: null });
+ continue;
+ }
+ const file = page.source_path ? git?.files.get(page.source_path) : undefined;
+ const record = file?.holdPath && source?.incarnation ? await readGitHold(engine, sourceId, source.incarnation, file.holdPath) : null;
+ const embeddingHold = page.hold_state ? { state: page.hold_state, reason: page.hold_reason, updated_at: new Date(page.hold_updated_at!).toISOString() } : null;
+ const unembedded = Number(page.unembedded);
+ const row = page.deleted ? undefined : states.get(slug);
+ let classifier: EmbeddingState | null = page.deleted ? null : row?.state ?? 'chunkless_healable';
+ if (classifier === 'keyword_only' && embeddingHold && !page.embed_skip) classifier = 'pending';
+ const state: PageStatusState = classifier === null ? 'page_deleted' : PAGE_STATE[classifier as Exclude<EmbeddingState, 'deleted_page_chunks'>] ?? 'searchable';
+ let why = stateWhy(slug, state, { row, unembedded, disabled, embeddingHold });
+ let fix: Action | null = null;
+ if (record) {
+ why = `Sync holds its file ${page.source_path} (${record.code}): ${record.message} Search shows the page as it was before the held change. ${why}`;
+ fix = gitHoldFix(record, await fenceAutoRepairFor(engine, [record]));
+ } else if (state === 'pending_embedding' && embeddingHold) {
+ basis ??= await approvalBasis();
+ fix = heldApproveAction({ source_id: sourceId, slug, pending_chunks: unembedded, ...approvalAmount(Number(page.unembedded_chars), basis) }, basis.free);
+ } else if (classifier && classifier !== 'embedded' && !(disabled && classifier === 'pending')) {
+ if (classifier === 'keyword_only') blockBytes ??= await effectiveBytesBlock(engine);
+ fix = embeddingStateFix(classifier, { sourceId, slug, markerBytes: row?.marker_bytes ?? null, blockBytes, embeddingsEnabled: !disabled,
+ verify: { argv: ['gbrain', 'pages', 'status', slug, '--source', sourceId, '--json'] } });
+ }
+ out.push({ slug, source_id: sourceId, state, searchable: SEARCHABLE[state],
+ page: { id: Number(page.id), slug: page.slug, deleted: page.deleted, chunks: Number(page.chunks), unembedded },
+ embedding_hold: embeddingHold, hold: record ? { code: record.code, message: record.message } : null, source_path: page.source_path,
+ in_synced_commit: file?.inSynced ?? null, why, fix });
+ }
+ return { source_id: sourceId, last_commit: lastCommit, head, at_head: head && lastCommit ? head === lastCommit : null, embeddings_enabled: !disabled, pages: out };
+}
+
+export async function runPagesStatus(engine: BrainEngine, args: string[]): Promise<void> {
+ const parsed = parsePagesStatusArgs(args);
+ const sourceId = await resolveSourceId(engine, parsed.source);
+ const result = await readPagesStatus(engine, sourceId, parsed.slugs);
+ if (parsed.json) { console.log(JSON.stringify(result, null, 2)); return; }
+ const commit = result.last_commit ? `last synced commit ${result.last_commit.slice(0, 12)}` : 'no synced commit';
+ const headNote = result.head && result.at_head === false ? `, checkout HEAD ${result.head.slice(0, 12)} (not synced yet)` : '';
+ console.log(`Source ${result.source_id}, ${commit}${headNote}; embeddings ${result.embeddings_enabled ? 'on' : 'off'}.`);
+ const render = cliRenderContext();
+ for (const p of result.pages) {
+ const reach = p.searchable === true ? 'searchable' : p.searchable === 'keyword' ? 'keyword search only' : 'not searchable';
+ console.log(` ${p.slug}: ${p.state} (${reach})`);
+ console.log(` ${p.why}`);
+ const fix = p.fix ? renderAction(p.fix, render) : null;
+ if (fix?.command) console.log(` fix (${fix.next.replace(/_/g, ' ')}): ${fix.command}`);
+ }
+}
diff --git a/src/commands/pages.ts b/src/commands/pages.ts
index fcc9f9acd8..ececffe8c6 100644
--- a/src/commands/pages.ts
+++ b/src/commands/pages.ts
@@ -4,6 +4,7 @@
* The first subcommand: `pages purge-deleted [--older-than HOURS|Nh|Nd] [--retry-parked] [--dry-run] [--json] [--yes]`.
* `pages unsearchable` (#6696 B3) lists embedding-state rows; its body is pages-unsearchable.ts.
* `pages ghosts [--source <id>] [--json]` (#6696 B5, pages-ghosts.ts) lists ghost pages, read-only.
+ * `pages status <slug...> [--source <id>] [--json]` (#7179, pages-status.ts) says whether each page is searchable and why, read-only.
* Manual escape hatch alongside the autopilot purge phase. Hard-deletes pages
* whose `deleted_at` is older than the cutoff; cascades to content_chunks,
* page_links, chunk_relations via existing FKs.
@@ -123,6 +124,12 @@ Subcommands:
chunkless_healable; embedded only via --state) with
reason, chunks, bytes and each state's fix. --limit
defaults to 50; complete:false means more rows exist.
+ status <slug...> [--source <id>] [--json]
+ Read-only: per page, whether search can find it (state,
+ searchable true|keyword|false), its chunks and vector-less
+ chunks, any large-page embedding hold or sync hold on its
+ file, whether the file is in the synced commit, why, and
+ the fix. A page that is not searchable still exits 0.
Notes:
Soft-delete a page via \`gbrain delete <slug> --force\`; restore via \`gbrain restore <slug> --force\`
@@ -141,6 +148,7 @@ export async function runPages(engine: BrainEngine, args: string[]): Promise<voi
case 'purges': case 'unpurge': return (await import('./pages-purges.ts')).runPagePurges(engine, sub, args.slice(1));
case 'unsearchable': return (await import('./pages-unsearchable.ts')).runPagesUnsearchable(engine, args.slice(1));
case 'ghosts': return (await import('./pages-ghosts.ts')).runPagesGhosts(engine, args.slice(1));
+ case 'status': return (await import('./pages-status.ts')).runPagesStatus(engine, args.slice(1));
case undefined:
printUsage();
return;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index d3a09fecea..d5d69a3489 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -91,7 +91,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'notices': ['--brain', '--help', '--json', '--source'],
'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--retry-parked', '--source', '--state', '--yes'],
+ 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--state', '--verify', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],
'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 3d31990089..0193b97b3d 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -1001,8 +1001,8 @@ const normalizeStateRow = compileRowNormalizer<EmbeddingStateRow>({ chunks: 'big
* prints, to report completeness).
*/
export async function listEmbeddingStateRows(exec: ScopedRead, column: string,
- opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
- const scope = embeddingStateScope(opts.sourceIds);
+ opts: { sourceIds?: string[]; slugs?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ const scope = opts.slugs ? sqlFragment`${embeddingStateScope(opts.sourceIds)} AND p.slug = ANY(${opts.slugs}::text[])` : embeddingStateScope(opts.sourceIds);
const { rows } = await exec.run(sqlFragment`
SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue
FROM (
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 154bd6c9c5..885dc7cd20 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1363,7 +1363,7 @@ export interface BrainEngine {
/** #6696 B3: counts per embedding state over the ACTIVE column (contract and ops/full semantics: src/core/embedding-state.ts). */
readEmbeddingStateCounts(opts: { mode: 'ops' | 'full'; sourceIds?: string[]; purgeWindowHours: number }): Promise<EmbeddingStateCounts>;
/** #6696 B3: one row per (page, state) in `states`, ordered (state, source_id, slug), at most `limit` rows. */
- listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]>;
+ listEmbeddingStateRows(opts: { sourceIds?: string[]; slugs?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]>;
/**
* Delete every chunk for a page. Internal page-id lookup is sourceId-scoped
* when `opts.sourceId` is given; otherwise the bare-slug subquery returns
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 066d197824..2089291c41 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1876,7 +1876,7 @@ export class PGLiteEngine implements BrainEngine {
return chunksImpl.readEmbeddingStateCounts(scopedRead(this.engineSql), column, opts);
}
- async listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ async listEmbeddingStateRows(opts: { sourceIds?: string[]; slugs?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
return chunksImpl.listEmbeddingStateRows(scopedRead(this.engineSql), column, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index af1b260aba..bc1c8940e5 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1637,7 +1637,7 @@ export class PostgresEngine implements BrainEngine {
return this.withScopedReadTransaction(opts.sourceIds, undefined, tx => chunksImpl.readEmbeddingStateCounts(scopedRead(this.engineSqlOn(tx)), column, opts));
}
- async listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ async listEmbeddingStateRows(opts: { sourceIds?: string[]; slugs?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
return this.withScopedReadTransaction(opts.sourceIds, undefined, tx => chunksImpl.listEmbeddingStateRows(scopedRead(this.engineSqlOn(tx)), column, opts));
}
diff --git a/test/pages-status-7179.test.ts b/test/pages-status-7179.test.ts
new file mode 100644
index 0000000000..337c436085
--- /dev/null
+++ b/test/pages-status-7179.test.ts
@@ -0,0 +1,203 @@
+/**
+ * `gbrain pages status <slug...>` (#7179): one read-only answer per page to "is this page searchable, and if not, why?".
+ * Each state of the `sources resolve-path` vocabulary a page can be in, the large-page embedding hold (still
+ * pending_embedding, fixed by the held approval and never a spend), the Git sync hold on the page's file (code exactly
+ * as `readGitHold` returns it, with its own fix), strict arguments, and the `slugs` filter on `listEmbeddingStateRows`.
+ * Red on master: the subcommand, the module and the `slugs` option do not exist there. PGLite, plus the Postgres arm
+ * when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPages } from '../src/commands/pages.ts';
+import { readPagesStatus, type PagesStatus } from '../src/commands/pages-status.ts';
+import { EMBEDDING_STATES } from '../src/core/embedding-state.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { gitHoldFix, readGitHold } from '../src/core/persistence/sync-holds.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { makeDoctorHome, runGbrain } from './helpers/doctor-json-golden.ts';
+
+const backends = testBackends();
+const home = mkdtempSync(join(tmpdir(), 'gbrain-pages-status-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };
+const VECTOR = 'array_fill(0.1::real, ARRAY[1536])::vector';
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function each(run: (engine: BrainEngine) => Promise<void>): Promise<void> {
+ await withEnv(env, async () => {
+ for (const engine of engines) {
+ try { await run(engine); } finally { await disposePersistenceConsumer(engine); }
+ }
+ });
+}
+
+async function newSource(engine: BrainEngine): Promise<string> {
+ const id = `pst-${randomUUID().replace(/-/g, '').slice(0, 20)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
+ return id;
+}
+
+/** A page with chunk rows written directly: `vectors[i]` says whether chunk i has a vector in the active column. */
+async function page(engine: BrainEngine, source: string, slug: string, opts: { body?: string; frontmatter?: Record<string, unknown>; vectors?: boolean[] } = {}): Promise<number> {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: opts.body ?? `${slug} body` }, { sourceId: source });
+ const [row] = await engine.executeRaw<{ id: number }>('UPDATE pages SET frontmatter = $3::text::jsonb WHERE slug = $1 AND source_id = $2 RETURNING id',
+ [slug, source, JSON.stringify(opts.frontmatter ?? {})]);
+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [row!.id]);
+ for (const [i, vector] of (opts.vectors ?? []).entries()) {
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, embedding) VALUES ($1, $2, 'abcd', ${vector ? VECTOR : 'NULL'})`, [row!.id, i]);
+ }
+ return Number(row!.id);
+}
+
+async function cli(engine: BrainEngine, args: string[]): Promise<string> {
+ const lines: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.join(' ')); });
+ try { await runPages(engine as never, ['status', ...args]); } finally { log.mockRestore(); }
+ return lines.join('\n');
+}
+
+describe('gbrain pages status: embedding states', () => {
+ test('embedded, pending (worst chunk wins), chunkless with body, quarantined, missing and soft-deleted pages each read their state and fix', () => each(async engine => {
+ const source = await newSource(engine);
+ await page(engine, source, 'notes/alice-example', { vectors: [true, true] });
+ await page(engine, source, 'notes/acme-example', { vectors: [true, false, false] });
+ await page(engine, source, 'notes/stub-with-body');
+ await page(engine, source, 'notes/junk-example', { vectors: [true], frontmatter: { quarantine: { reason: 'junk_pattern' } } });
+ await page(engine, source, 'notes/gone-example', { vectors: [true] });
+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE slug = $1 AND source_id = $2', ['notes/gone-example', source]);
+ const out = JSON.parse(await cli(engine, ['notes/alice-example', 'notes/acme-example', 'notes/stub-with-body', 'notes/junk-example', 'notes/nobody-example',
+ 'notes/gone-example', '--source', source, '--json'])) as PagesStatus;
+ expect(out).toMatchObject({ source_id: source, last_commit: null, head: null, at_head: null, embeddings_enabled: true });
+ const [alice, acme, stub, junk, nobody, gone] = out.pages;
+ expect(alice).toMatchObject({ slug: 'notes/alice-example', source_id: source, state: 'searchable', searchable: true, embedding_hold: null, hold: null,
+ in_synced_commit: null, fix: null, page: { slug: 'notes/alice-example', deleted: false, chunks: 2, unembedded: 0 } });
+ expect(acme).toMatchObject({ state: 'pending_embedding', searchable: 'keyword', page: { chunks: 3, unembedded: 2 },
+ fix: { argv: ['gbrain', 'embed', '--stale', '--catch-up', '--source', source, '--yes'], consent: ['paid'],
+ verify: { argv: ['gbrain', 'pages', 'status', 'notes/acme-example', '--source', source, '--json'] } } });
+ expect(acme!.why).toContain('2 chunk(s) still wait for a vector');
+ expect(stub).toMatchObject({ state: 'chunkless', searchable: false, page: { chunks: 0, unembedded: 0 }, fix: { argv: ['gbrain', 'embed', '--stale', '--catch-up', '--source', source, '--yes'] } });
+ expect(junk).toMatchObject({ state: 'quarantined', searchable: false, fix: { ask_user: true, argv: ['gbrain', 'quarantine', 'clear', 'notes/junk-example', '--source-id', source, '--force'] } });
+ expect(junk!.why).toContain('junk_pattern');
+ expect(nobody).toMatchObject({ slug: 'notes/nobody-example', state: 'missing', searchable: false, page: null, source_path: null, fix: null });
+ expect(gone).toMatchObject({ state: 'page_deleted', searchable: false, page: { deleted: true, chunks: 1 }, fix: null });
+ }), 120_000);
+
+ test('a held large page stays pending_embedding with the hold set; its fix is the held approval, asked first, and nothing is spent', () => each(async engine => {
+ const source = await newSource(engine);
+ const big = 'x'.repeat(1024 ** 2 + 4096);
+ const held = await page(engine, source, 'notes/large-example', { body: big, vectors: [true, false, false] });
+ const small = await page(engine, source, 'notes/small-example', { vectors: [false] });
+ for (const id of [held, small]) {
+ await engine.executeRaw("INSERT INTO page_embedding_budget (page_id, state, reason) VALUES ($1, 'held', 'upgrade_backfill')", [id]);
+ }
+ const out = await readPagesStatus(engine, source, ['notes/large-example', 'notes/small-example']);
+ const [large, edited] = out.pages;
+ expect(large).toMatchObject({ state: 'pending_embedding', searchable: 'keyword', page: { chunks: 3, unembedded: 2 },
+ embedding_hold: { state: 'held', reason: 'upgrade_backfill', updated_at: expect.any(String) } });
+ expect(large!.fix).toMatchObject({ ask_user: true, consent: ['paid', 'egress'], preview_argv: ['gbrain', 'embed', '--held', '--dry-run', '--source', source, '--json'] });
+ expect(large!.fix!.argv!.slice(0, 5)).toEqual(['gbrain', 'embed', '--slugs', 'notes/large-example', '--source']);
+ expect(large!.fix!.argv).toContain('--max-usd');
+ expect(large!.why).toContain('wait for embedding approval');
+ expect(edited).toMatchObject({ state: 'pending_embedding', embedding_hold: null, fix: { argv: ['gbrain', 'embed', '--stale', '--catch-up', '--source', source, '--yes'] } });
+ const [budget] = await engine.executeRaw<{ state: string; spent_usd: number }>('SELECT state, spent_usd FROM page_embedding_budget WHERE page_id = $1', [held]);
+ expect(budget).toMatchObject({ state: 'held', spent_usd: 0 });
+ const [left] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE page_id = $1 AND embedding IS NULL', [held]);
+ expect(Number(left!.n)).toBe(2);
+ }), 120_000);
+
+ test('the slugs filter narrows both halves of listEmbeddingStateRows', () => each(async engine => {
+ const source = await newSource(engine);
+ await page(engine, source, 'notes/alice-example', { vectors: [true] });
+ await page(engine, source, 'notes/acme-example', { vectors: [false] });
+ await page(engine, source, 'notes/stub-with-body');
+ await page(engine, source, 'notes/other-example');
+ const opts = { sourceIds: [source], states: EMBEDDING_STATES, limit: 100, purgeWindowHours: 72 };
+ const all = await engine.listEmbeddingStateRows(opts);
+ expect(all.map(r => r.slug).sort()).toEqual(['notes/acme-example', 'notes/alice-example', 'notes/other-example', 'notes/stub-with-body']);
+ const some = await engine.listEmbeddingStateRows({ ...opts, slugs: ['notes/acme-example', 'notes/stub-with-body'] });
+ expect(some.map(r => [r.slug, r.state])).toEqual([['notes/stub-with-body', 'chunkless_healable'], ['notes/acme-example', 'pending']]);
+ expect(await engine.listEmbeddingStateRows({ ...opts, slugs: [] })).toEqual([]);
+ }), 120_000);
+});
+
+describe('gbrain pages status: Git', () => {
+ const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ const commit = (root: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'content'); return git(root, 'rev-parse', 'HEAD'); };
+
+ test('a page whose file sync holds names the hold (code exactly as readGitHold returns it) and uses its fix; a synced page reads in_synced_commit', () => each(async engine => {
+ const id = `pst-${randomUUID().replace(/-/g, '').slice(0, 20)}`, repo = join(home, id);
+ const write = (path: string, content: string) => { mkdirSync(join(repo, path, '..'), { recursive: true }); writeFileSync(join(repo, path), content); };
+ mkdirSync(repo, { recursive: true }); git(repo, 'init', '-q');
+ write('notes/alice-example.md', '---\ntitle: Alice Example\n---\nA synthetic observation.\n');
+ write('notes/beta-example.md', '---\ntitle: Beta Example\n---\nAnother synthetic observation.\n');
+ commit(repo);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, repo, '{}']);
+ await claimWorktree(engine, id, repo);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ await sync();
+ write('notes/beta-example.md', '---\ntitle: Beta Example\nslug: notes/acme-example\n---\nAnother synthetic observation, edited.\n');
+ const head = commit(repo);
+ await sync();
+ const [src] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ const record = await readGitHold(engine, id, src!.incarnation, 'notes/beta-example.md');
+ expect(record).toMatchObject({ code: 'frontmatter_slug_conflict', page_id: expect.any(Number) });
+ const out = await readPagesStatus(engine, id, ['notes/alice-example', 'notes/beta-example']);
+ expect(out).toMatchObject({ source_id: id, last_commit: head, head, at_head: true });
+ const [alice, beta] = out.pages;
+ expect(alice).toMatchObject({ source_path: 'notes/alice-example.md', in_synced_commit: true, hold: null });
+ expect(beta).toMatchObject({ source_path: 'notes/beta-example.md', in_synced_commit: true, hold: { code: record!.code, message: record!.message } });
+ expect(beta!.page).toMatchObject({ slug: 'notes/beta-example', deleted: false });
+ expect(beta!.why).toContain(`Sync holds its file notes/beta-example.md (${record!.code})`);
+ expect(beta!.fix).toEqual(gitHoldFix(record!));
+ write('notes/alice-example.md', '---\ntitle: Alice Example\n---\nA synthetic observation, edited after the sync.\n');
+ const ahead = commit(repo);
+ expect(await readPagesStatus(engine, id, ['notes/alice-example'])).toMatchObject({ last_commit: head, head: ahead, at_head: false });
+ }), 240_000);
+});
+
+describe('gbrain pages status: arguments', () => {
+ test('no slug, an unknown option, or --source without a value is invalid_params before any read', async () => {
+ const engine = engines[0]!;
+ await expect(cli(engine, ['--json'])).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(cli(engine, ['notes/alice-example', '--state', 'pending'])).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(cli(engine, ['notes/alice-example', '--source'])).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(cli(engine, ['notes/alice-example', '--source', '--json'])).rejects.toMatchObject({ code: 'invalid_params' });
+ });
+
+ test('CLI: a missing page exits 0 with its state; no slug exits 2 with one invalid_params envelope', async () => {
+ const h = makeDoctorHome('pages-status');
+ try {
+ expect((await runGbrain(h, ['init', '--pglite', '--no-embedding'])).exitCode).toBe(0);
+ const missing = await runGbrain(h, ['pages', 'status', 'notes/nobody-example', '--json']);
+ expect(missing.exitCode).toBe(0);
+ expect(missing.json).toMatchObject({ source_id: 'default', pages: [{ slug: 'notes/nobody-example', state: 'missing', searchable: false }] });
+ const bad = await runGbrain(h, ['pages', 'status', '--json']);
+ expect(bad.exitCode).toBe(2);
+ expect(bad.json).toMatchObject({ code: 'invalid_params' });
+ } finally {
+ h.cleanup();
+ }
+ }, 120_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 8d27e71e5f..a3afc8a3d8 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -236,6 +236,7 @@ test/page-prepare-shared-origin-6517.test.ts
test/page-purge-batch-sweep-6884.test.ts
test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
+test/pages-status-7179.test.ts
test/pathological/a-36-facts-batch-partial-refusal.test.ts
test/pathological/a-42-atom-dot-led-slug.test.ts
test/pathological/a-51-conversation-batch-booking.test.ts