Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Setup imports call transcripts into a company brain, with credentials removed (GST-2731) (#9440)
Garry Tan26607552a105
diff --git a/changelog.d/setup-call-transcripts.md b/changelog.d/setup-call-transcripts.mdnew file mode 100644index 0000000000..cbcfa04215--- /dev/null+++ b/changelog.d/setup-call-transcripts.md@@ -0,0 +1,11 @@+**`gbrain setup --transcripts DIR` imports your exported call transcripts into the company brain with credentials removed, `me/facts` and `company/facts` become quotable facts pages, and setup says what the conversation archive is doing (GST-2731).**++### Added+- `gbrain setup claude-code|codex --shape company|both --transcripts DIR` (also asked at a terminal, after the docs folder) imports `.txt` and `.md` call or meeting transcripts from any recorder into the `company` source, one page per file at `company/calls/<date>-<title>`. Every credential in the text (API keys, tokens, passwords, plus your own redaction patterns) is replaced by a `<REDACTED:…>` marker before anything is stored, with the same redaction the conversation archive uses, and the file's path is redacted the same way. Pages are keyword-only: embedding them waits for your approval, with the conversation archive's hold. The facts backstop skips them; with a chat model key set, scheduled atom and event extraction can still read them within their budgets, and setup prints a `what leaves this machine` line saying which is on, or that nothing leaves. Each file is imported once. A rerun reports it unchanged, and a file changed since keeps its first page. Above 500 files setup prints the import command instead. `--transcripts` needs the company part on this brain, so it is refused with `--team`.+- Setup prints who can read the call pages. That is everyone who can read the `company` source on a brain that serves one person, or the members the source's access rules allow on a brain that serves several. The pages carry no readers of their own.+- `gbrain import DIR --calls [--prefix company/calls] [--source company]`, the same import on its own (implies `--no-embed`).+- Page type `facts` (base packs; gbrain-base-v2 is now 1.7.0). `me/facts` and `company/facts` are created with `type: facts`, and the instructions setup writes for the agent say to quote only a facts page's dated lines and to add a new fact as a new dated line.+- Doctor check `facts_undated_lines`: warns about a facts page with a fact line that has no date, naming the page and the line numbers (never the text), and asks you for the dates. It changes nothing.+- Setup's report ends with one line on the conversation archive: on, off, or offered (a brain that may serve several people is only offered it).+- Docs: `docs/guides/brain-layout.md`.+- Tests: `test/import-calls.test.ts`, `test/doctor-facts-undated-lines.test.ts`, and the transcripts cases in `test/setup-brain-layout.test.ts`.diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex 80318c372c..521dd6fe2d 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -29,7 +29,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.- `src/commands/setup.ts` + `src/cli/commands/setup.ts` — `gbrain setup <harness>` (D8), pre-connect and engine-free (`thinClient: 'none'`, `json: 'document'`): an orchestrator over the existing wiring, not a new installation system. Target first: it resolves the brain (`loadConfig`; none → a `gbrain init --pglite --no-embedding --json` child, `--providers` drops `--no-embedding`; setup prints `Brain ready at <path>` and never init's standalone quickstart or `[AGENT]` banners; on the brain it just created it runs the setup migrations init left pending (`finishFreshSetupMigrations`, `src/commands/setup-migrations.ts`: one `apply-migrations --yes --no-autopilot-install --json` child built by `setupMigrationsArgv` in `migrations/fresh-install.ts`, 60 s bound, offline; v0.11.0 is held back when its host phase would edit an existing `~/.claude/AGENTS.md`, `~/.openclaw/AGENTS.md` or OpenClaw cron manifest (`hostRewriteTargets`)) and replaces init's `[init] Migrations:` line with `[setup] Migrations: …` (a failure keeps init's hand-off plus the error code; an existing brain is not touched), and renders a `Memory:` line naming `remember` (#6606: world facts are pushed, private ones are recall-only, capture writes a page) and then `setupFirstRunNotices` once after `Next:` in human output, or under `notices` in `--json`), the source (`--source` > `GBRAIN_SOURCE` > unpinned), the launcher (`--gbrain-bin` > `resolveGbrainBin`), the surface (`--surface` > `GBRAIN_SURFACE` > the receipt's > `REGISTRATION_SURFACE`) and the registration owner, prints them, then refuses before any write with `setup_hosted_connection` (thin-client config, hosted connection receipt or remote entry: never a second, local brain) or `setup_owner_conflict` (`live_serve` from `peekLock` unless the live stdio serve is this registration's own, `unowned_entry`, `other_install` by receipt `gbrain_home`, `harness_lane` for a bootstrap harness receipt that wired the configuration setup would write (a target in that config directory, compared after symlink resolution; project-scoped hooks; or a receipt recording no paths for the host) or another gbrain marker on a wanted event; #7771, `test/setup-harness-lane-scope-7771.test.ts`). Consent is three recorded decisions (`resolveConsent`): wiring scope (`--scope`, `--no-hooks`, `GBRAIN_HOOKS=0`), capture (`--capture`/`--no-capture`; a file-config `memory.auto_writeback: off` wins) and providers; read-context events come from the capability row, capture events only when accepted. Verify reuses `smokeStdioRegistration` from `doctor/checks/harness-wiring.ts`; states are `configured` → `connection-verified` → `native-pending` (`native-verified` is never claimed). `gbrain setup codex` (`runCodexSetup`/`runCodexRemove`, writer in `src/core/setup/codex.ts`) shares the target, consent, refusal and verify steps: user scope only (`--scope project` exits 2), the codex plugin (`codexPluginProvidesName`) skips the MCP table, `harness_lane` also covers a bootstrap harness receipt targeting codex (in the same scoped sense) or a bootstrap-lane group on a wanted event, the dry run adds a `trust` step, and the final state is `native-verified` when the codex row's push is verified and the receipt owns the trusted UserPromptSubmit hook. Unsupported harness ids (`openclaw`, `hermes`, unknown) refuse with `setup_harness_unsupported` naming the row's guide (exit 2). `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks` is the crash-injection seam. `--serves one|several` (GST-363, `src/commands/setup-serves.ts`; tests `test/setup-serves-several.test.ts`, `test/setup-serves-stdio-member.test.ts`, `test/setup-serves-upgrade.test.ts`): `several` runs `gbrain access serves several --yes --json` and one `gbrain find people/ --as <member> --json` per member as children and prints the receipt (paths, never keys); a one-person setup on a several-person brain refuses `setup_serves_several` unless the owner (written as `mcp.stdio_member`) or `mcp.stdio_member` binds the connection; the brain-first access then carries `serves: 'several'`. Pinned by `test/setup.test.ts` and `test/setup-serves-several.test.ts`.-- `src/commands/setup-brain-layout.ts` — `gbrain setup claude-code|codex --shape personal|company|both [--notes DIR] [--docs DIR] [--team|--solo]` (GST-2731; guide `docs/guides/brain-layout.md`). Every page is written create-only through `gbrain get` then `gbrain put` children, and only when `get` reports `page_not_found` (empty forms, `status: stub`, one "Example (delete me)" line each): `me/facts`, `me/voice`, `me/how-i-decide` in the run's source, and `COMPANY_PAGES` (`company/facts`, `company/decisions`, `company/pricing`, `company/customers`, `company/calls`, `company/playbooks`) in the `company` source. The company source is kept when it exists, else added with `gbrain sources add company --path <dir>` on a gbrain-owned folder beside the default source's content root (never the person's docs folder; a path there that is not an empty folder fails the company part with an `ask_user` `brain_layout_pages_pending` and the block is written without company lines) with no federation flag, so `sources add` federates it only on a one-person brain (#9396); when it reads back unfederated, setup returns `source_not_in_default_search` with `ask_user`. `--notes` and `--docs` import read only with one `gbrain import DIR --no-embed --json` child each (GBRAIN_SOURCE pins the source; over `IMPORT_INLINE_MAX` = 500 markdown files it returns `brain_layout_import_pending` instead), then check keyless search finds the first file's title in the top 5 (company docs through default search when federated). `--team` creates nothing for the company part and returns `brain_layout_team_next`. A `<!-- gbrain:brain-layout:begin/end -->` block (lines per part) goes into the brain-first target only when the brain-first decision is accepted; `--no-instructions` removes it, `--shape none` removes it and keeps pages and source. A brand-new brain set up without `--shape` asks inline only when `isInteractive()`, otherwise `brain_shape` joins the `first_run_decisions` bundle (default none, nothing written). The flag is `--shape` because `--brain` is the global brain-id flag (`cli-options.ts`). Pinned by `test/setup-brain-layout.test.ts`.+- `src/commands/setup-brain-layout.ts` — `gbrain setup claude-code|codex --shape personal|company|both [--notes DIR] [--docs DIR] [--transcripts DIR] [--team|--solo]` (GST-2731; guide `docs/guides/brain-layout.md`). Every page is written create-only through `gbrain get` then `gbrain put` children, and only when `get` reports `page_not_found` (empty forms, `status: stub`, one "Example (delete me)" line each): `me/facts`, `me/voice`, `me/how-i-decide` in the run's source, and `COMPANY_PAGES` (`company/facts`, `company/decisions`, `company/pricing`, `company/customers`, `company/calls`, `company/playbooks`) in the `company` source. The company source is kept when it exists, else added with `gbrain sources add company --path <dir>` on a gbrain-owned folder beside the default source's content root (never the person's docs folder; a path there that is not an empty folder fails the company part with an `ask_user` `brain_layout_pages_pending` and the block is written without company lines) with no federation flag, so `sources add` federates it only on a one-person brain (#9396); when it reads back unfederated, setup returns `source_not_in_default_search` with `ask_user`. `--notes` and `--docs` import read only with one `gbrain import DIR --no-embed --json` child each (GBRAIN_SOURCE pins the source; over `IMPORT_INLINE_MAX` = 500 markdown files it returns `brain_layout_import_pending` instead), then check keyless search finds the first file's title in the top 5 (company docs through default search when federated). `--team` creates nothing for the company part and returns `brain_layout_team_next`. A `<!-- gbrain:brain-layout:begin/end -->` block (lines per part) goes into the brain-first target only when the brain-first decision is accepted; `--no-instructions` removes it, `--shape none` removes it and keeps pages and source. A brand-new brain set up without `--shape` asks inline only when `isInteractive()`, otherwise `brain_shape` joins the `first_run_decisions` bundle (default none, nothing written). `me/facts` and `company/facts` carry `type: facts` (declared in both base packs; gbrain-base-v2 1.7.0), and the block's facts line tells the agent to quote only their dated lines. `--transcripts DIR` (company shape, not `--team`; refused otherwise before anything is written) runs one `gbrain import DIR --calls --prefix company/calls --no-embed --json` child pinned to the company source (over `IMPORT_INLINE_MAX` .txt/.md files it returns `brain_layout_import_pending` with that argv), then reads who can read the first call page with `gbrain access who-can-read <slug> --source company --json` and `gbrain access serves --json --no-open-pages` (`transcripts.readers`: `every_source_reader` or the members the source's rules allow, plus one or several). Every applied shape (not dry run) ends with `archive` (on, off, offered or unknown), read from `gbrain doctor --only transcript_archive_freshness --json` details, never the archive's first-run notice. At a terminal `askBrainShape(folders, read)` asks for the transcripts folder after the docs folder (solo only). The flag is `--shape` because `--brain` is the global brain-id flag (`cli-options.ts`). Pinned by `test/setup-brain-layout.test.ts`.+- `src/commands/import-calls.ts` — `gbrain import <dir> --calls [--prefix <slug prefix>] [--source <id>] [--json]` (GST-2731), dispatched from `runImport` once the folder resolves (`--calls` also implies `--no-embed`; a `--prefix` value is never read as the folder). `listCallFiles` walks .txt/.md files (dot entries and symlinks skipped); `callPageFor` names each `<prefix>/<date>-<title slug>` (date: dated file name, else first line, else modified day; title: rest of a dated file name, else first line, both read after redaction so a credential in either never reaches the title or slug), redacts the whole text with `redactSession` and the user's patterns (`loadImportRedactionPatterns`), redacts the relative path the same way (`redactCallPath`), neutralizes structure lines (`neutralizeOutsideText`) and writes frontmatter `type: meeting`, `facts_backstop: false` and `call_import: {file (redacted), root, hash, redactions, embedding_hold: call_import}` (root and hash JSON-quoted so they read back as strings), with no `readable_by`. `root` is `callRootId(dir)` (a hash of the folder path) and the hash covers title and body, not the date. `call_import` is one of `ANY_SIZE_HOLD_REASONS` in `src/core/page-embedding-budget.ts`, so embed paths skip the page at any size until the owner approves it. `--prefix` is slugified per segment. Each new page goes through the `put_page` handler (trusted local context); a rerun finds the earlier page by `call_import.root` and `file` under the prefix (not the computed slug, which a new modified day can move) and reports it `unchanged` (same hash) or `kept` (never overwritten); a slug held by another page or file gets a hash suffix of root and path. Pinned by `test/import-calls.test.ts`.+- `src/commands/doctor/checks/facts-pages.ts` — `facts_undated_lines` (GST-2731, brain category): each `type: facts` page with list lines carrying no YYYY-MM-DD date is a warn naming source, slug and line numbers (never the line text); the fix is `gbrain get <slug> --source <id>` with `ask_user` for the dates; segmented pages are skipped and counted. Read-only. Pinned by `test/doctor-facts-undated-lines.test.ts`.- `src/core/setup/brain-first.ts` + `src/core/managed-block.ts` — the brain-first instruction block every harness install writes by default (`<!-- gbrain:brain-first:begin/end -->`, `BRAIN_FIRST_VERSION`). `brainFirstTarget` names each harness's own instruction file (Claude Code `~/.claude/CLAUDE.md` or `./CLAUDE.local.md`, Codex `AGENTS.md` or an existing `AGENTS.override.md`, opencode global `AGENTS.md`, OpenClaw `<workspace>/AGENTS.md` from JSON5 `agents.defaults.workspace` (several agents need `--workspace`), Hermes `SOUL.md` after the identity text, Cursor `.cursor/rules/gbrain-brain-first.mdc`); other clients get the block printed to paste. `syncBrainFirst` splices only between the markers (idempotent, upgrades in place, preserves a damaged block and reports it), and the decision (`--no-instructions` / `GBRAIN_AGENT_INSTRUCTIONS=0`, `--instructions`, prior) is remembered in `<configDir>/agent-instructions.json` with the writer (`underInstructionLedgerLock` holds one lock, `<configDir>/agent-instructions.lock`, shared with `skill-loading.json`, across the ledger read, the file and permission edits and the ledger write, re-reads a recorded decision under it, reports a lock it cannot take within 10 seconds as `preserve`, and a dry run takes none; `test/instruction-ledger-lock.test.ts`, `test/instruction-ledger-lock-timeout.slow.test.ts`), so `--remove` on setup, `connect --install` and `bootstrap harness` (lane in `bootstrap/harness-brain-first.ts`) strips only its own blocks. Text varies by access: MCP search surface, verbs surface, or the thin-client CLI launcher (`GBRAIN-INSTRUCTIONS.md` starts with it). doctor `harness_wiring` reads the ledger plus each registered or plugin-served harness's default file and warns on a missing, stale or damaged block with a fix that rewrites only the block (`instructionBlockViews`, `withInstructionBlocks`); `gbrain post-upgrade` prints the same command (`brain-first-upgrade-notice.ts`, `instructionBlockUpgradeHints`). The Claude Code and Codex plugin manifests declare setup's UserPromptSubmit hook with `GBRAIN_HOOK_LANE=plugin`; it yields when another gbrain lane wires the event (`bootstrap/plugin-lanes.ts` `pluginHookYields`; `test/plugin-turn-hook.test.ts`). `managed-block.ts` is the shared marker splice/probe/remove that `bootstrap/instructions-block.ts` also uses (`test/setup-brain-first.test.ts`).- `src/core/setup/turn-hook.ts` + `src/core/setup/turn-hook-check.ts` — the per-turn rule hook for installs whose MCP came from a plain `mcp add` or another installer: a `turn-rule-v1` Claude Code UserPromptSubmit entry or a Codex `hooks.json` group plus its `config.toml` trust entry, running `GBRAIN_HOOK_LANE=turn-rule <hook launcher> gbrain hook user-prompt` (rule only, no local context; it yields to setup, bootstrap and plugin lanes). Written by `setup <claude-code|codex> --instructions-only`, `connect --install`, the hosted `harness connect --install` and `bootstrap harness` (not in registrar mode); with no absolute binary the outcome is `print` with the one-line next step. `inspectTurnHook` (files only; it also reads Claude Code's managed `managed-settings.json` and `managed-settings.d/*.json`, and `turnRuleHookYields` counts a managed gbrain hook, #8057) feeds doctor `harness_wiring` (`turnHookViews`, `withTurnHooks`: untrusted, or missing beside a ledger block, warns with code `turn_hook_not_loaded`); `verifyTurnHook` runs the hook (Claude Code, Codex), `openclaw plugins inspect gbrain-turn-rule --runtime --json` or `hermes hooks doctor`, and every install path exits non-zero with `turn_hook_not_loaded` when it fails (`docs/guides/repair.md#turn-hook-not-loaded`). OpenClaw and Hermes rules name the gbrain tools and the `tool_search` route (`renderBrainFirstTurnRule(access, harness)`; `test/brain-first-turn-rule.test.ts`, `test/setup-brain-first.test.ts`).- `src/core/setup/hook-launcher.ts` + `src/core/setup/hook-launcher-refresh.ts` — the trusted-directory hook launcher (#8424): `<config dir>/hook-launcher/gbrain-hook`, a POSIX sh script that records the session directory in `GBRAIN_HOOK_CWD`, changes into its own directory and execs gbrain there, so a script-mode install never lets the session directory's `bunfig.toml` preload or `.env` load; it refuses (exit 1, one stderr line) when its directory holds anything else. A script-mode install's launcher also records the directory of the Bun that wrote it (`launcherRuntimeDir`, preferring the bun on PATH when it is the same file; `hookLauncherScript(dir)`) and puts it first on PATH, so a harness started without bun on PATH still starts gbrain (GST-2784); a compiled gbrain gets the plain launcher (`isScriptRuntime`, exported from cli-preflight.ts). `hookLauncherState` calls a launcher `stale` when it records no Bun that a script install needs, or a Bun that is gone, and `ensureHookLauncher` moves a launcher that records another Bun. Every setup-lane and turn-rule hook command names it (`buildClaudeHookCommand(…, launcher)`, `codexSetupHookGroup(…, launcher)`, `buildCodexSessionEndCommand(bin, launcher)`); `ensureHookLauncher` writes it before any hook that names it, and `gbrain hook` reads the session directory through `hookSessionCwd()`. `hookLauncherProblem` (turn-hook-check.ts) feeds doctor `harness_wiring` (`withHookLaunchers`, code `hook_session_cwd`, reasons `session_cwd|missing|stale|foreign`); `refreshHookLaunchers` runs in `gbrain post-upgrade`, rewrites this install's stale launcher file in place (no entry changes, so no Codex trust moves) and moves the turn-rule entries and each installed user-scope setup receipt's hooks onto the launcher through their own writers. The stdio MCP entries (`desiredMcpEntry`, `desiredCodexMcpEntry`, `registerClaudeMcp`/`registerCodexMcp` with `hookLauncher`) and the bootstrap, harness and Codex SessionEnd lanes use it too (#8426, #8428); `gbrain serve` captures `GBRAIN_HOOK_CWD` through `src/core/session-cwd.ts` and never changes directory. `src/core/setup/launcher-lanes.ts` (`launcherLaneFindings`) finds those entries for doctor and post-upgrade; post-upgrade rewrites only a Claude Code setup MCP entry setup still owns, under the setup lock, and names every Codex and bootstrap entry. Tests: `test/launcher-lanes-bunfig.serial.test.ts`. Tests: `test/hook-launcher-bunfig.test.ts` (a hostile checkout's preload never runs from any shape), `test/setup.test.ts` (#8424 block), `test/setup-codex-bare-path.test.ts` (setup codex's entries start under a PATH with no bun).diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 295cccf34b..c0e2733582 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -39,7 +39,7 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.-- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. `largePageBodyFilter(alias)` is its SQL twin (`body_bytes` of a segmented page, else the body columns' `octet_length`) and `pageBudgetLimitedFilter(alias)` the held-or-capped budget predicate built on it, so a budget row on a page edited down to 1 MiB or under stops applying (PR 2 fix lane J2; test `test/large-pages/held-budget-shrink.test.ts`). The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.+- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. `largePageBodyFilter(alias)` is its SQL twin (`body_bytes` of a segmented page, else the body columns' `octet_length`) and `pageBudgetLimitedFilter(alias)` the held-or-capped budget predicate built on it, so a budget row on a page edited down to 1 MiB or under stops applying, except a conversation-archive hold (`archive_backfill`, `archive_open_day`) or an imported call's hold (`call_import`), which `budgetRowAppliesFilter` applies at any size (PR 2 fix lane J2; test `test/large-pages/held-budget-shrink.test.ts`). The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation) while they are large (`pageBudgetLimitedFilter`); a page edited down to 1 MiB or under is unmetered and its row is ignored there, in `listBudgetLimitedPages` and in `pageSizeState`, and applies again if the page grows back. `listBudgetLimitedPages` (no row cap with `limit: null`) feeds `gbrain embed --held`; the hold and cap lines `meterPageBatch` prints name a per-page approve with a concrete N (held-embedding-action.ts), and `sizeStateLines` names `gbrain embed --held --dry-run --source <id>`. Its ledger prices a free local recipe at $0 (#6847). #6722 receipts: `pageSizeState` / `readPageSizeStates` / `sizeStateField` give the one `size_state` shape (`deferred` / `partial` / `held` / `skipped`, with reason and bytes) that `put_page` (page-prepare), managed sync (sync-prepare) and `remember` (memory-prepare) receipts carry for a large or embed_skip page; `addSizeState` / `sizeStateLines` build the sync tally `size_states` (managed cursor counts, legacy incremental and full sync) and its output lines. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`, `test/size-state-receipts-6722.test.ts`.- `src/core/oversized-backfill.ts` — large pages upgrade: `runOversizedBackfill` (`gbrain reindex --oversized`, and a two-minute pass in `gbrain post-upgrade` via `printOversizedBackfillUpgradeNotice`) rewrites pages an older gbrain stored chunkless for size (gate-written `embed_skip.reason = oversized`) through the normal write path (canonical owner on a managed brain, as `quarantine clear` does) with `forceRechunk` and no embedding: under the effective `bytes_block` the marker and `content_flag: oversized` are removed; over it (and under the ceiling) a chunkless page keeps both and is only re-chunked for keyword search (`rechunked_over_block`, #6722). A segmented page is sized by `body_bytes` and re-indexed from its materialized snapshot (`materializedSnapshot`, Wave B PR 2; `test/large-pages/oversized-backfill-segmented.test.ts`). CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (`upgrade_backfill`) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview commands; after a run that held pages, `approvals` carries one approve per source with a concrete N (`budgetLimitedReport`).- `src/core/held-embedding.ts` — held embedding budgets surfaced (#6803 part 3) and approvable on every provider (#6847). `readBudgetLimited` counts held and capped large pages with chunks still waiting (active vector column, `embedded_at`, signature drift; no row cap), by source; `budgetLimitedReport` renders the one phrase plus one approve Action per source (most pending chunks first). Consumers: `gbrain embed --stale` (`noteBudgetLimited`, a `budget_limited` field and one line), the embed-backfill job (`budgetLimitedField`; never a failure or stall input), doctor `partial_embedding` (`budgetLimitedFinding`, its own registry entry), the oversized backfill receipt. `heldEmbedArgv`: `--held --dry-run` lists every source (exit 0); `--max-usd` across several sources without `--source` refuses `invalid_params`. `heldApprovalUsd`: an explicit `--max-usd N` on `--slugs`/`--held` is the hold approval on any provider, refused before release with `embedding_unavailable` or `no_pricing`; `--yes` never approves. Tests: `test/held-embedding-budgets.test.ts` (+ Postgres wrapper), `test/held-embedding-approval.test.ts`, `test/held-embedding-printed-commands.serial.test.ts`.diff --git a/docs/architecture/type-taxonomy.md b/docs/architecture/type-taxonomy.mdindex c7b9da58fe..38e66b5ce3 100644--- a/docs/architecture/type-taxonomy.md+++ b/docs/architecture/type-taxonomy.md@@ -60,7 +60,9 @@ writer's page type under `extracts/`, a non-extractable annotation), soimported code and extraction receipts never read as undeclared types andthe catch-all retype leaves them alone. Since 1.6.0 it declares`stored-object` (a storage shelf card, a non-extractable annotation with no-folder prefix) for the same reason.+folder prefix) for the same reason, and since 1.7.0 `facts` (the type gbrain+setup stamps on the me/facts and company/facts starter pages: one dated line+per fact; a non-extractable annotation with no folder prefix).## Subtypes (declared in frontmatter post-unify)diff --git a/docs/guides/brain-layout.md b/docs/guides/brain-layout.mdindex d404df7b0b..19b36c6af7 100644--- a/docs/guides/brain-layout.md+++ b/docs/guides/brain-layout.md@@ -6,7 +6,7 @@ first session.```bashgbrain setup claude-code --shape personal --notes ~/notes-gbrain setup claude-code --shape company --docs ~/acme-example/docs+gbrain setup claude-code --shape company --docs ~/acme-example/docs --transcripts ~/acme-example/callsgbrain setup claude-code --shape both --notes ~/notes --docs ~/acme-example/docs# Codex: the same with gbrain setup codex```@@ -40,6 +40,33 @@ gbrain setup claude-code --shape both --notes ~/notes --docs ~/acme-example/docsempty form marked `status: stub`.- **Your company docs, read only.** `--docs DIR` imports that folder into the `company`source the same way `--notes` does, with the same 500-file limit.+- **Your call transcripts, read only.** `--transcripts DIR` imports exported call and+ meeting transcripts (`.txt` and `.md` files, from any recorder) into the `company`+ source, one page per file: `company/calls/<date>-<title>`. The date comes from a+ `YYYY-MM-DD` at the start of the file name, else from the first line, else from the+ file's modified day; the title is the rest of a dated file name, else the first line.+ The words are kept as written, except that every credential (API keys, tokens,+ passwords) is replaced by a `<REDACTED:…>` marker before anything is stored, with the+ same redaction the conversation archive uses; the file's path is redacted the same way+ before it is stored or printed. A line that would read as page structure gets a+ leading backslash. The pages are keyword-only (no embedding cost): embedding them waits+ for your approval, with the same hold the conversation archive uses. The facts+ backstop skips them; the scheduled atom extraction still reads them when a model key+ is set, within `cycle.extract_atoms.budget_usd`, and so does event extraction+ (`auto_chronicle`) within its daily limit. Setup's `what leaves this machine` line says+ which of these is on for your brain, or that nothing leaves. Each file is imported once: a re-run from the same folder reports it+ unchanged, and a file you changed since keeps its first page (delete the page to+ import it again). Above 500+ files setup prints the import command instead (`gbrain import DIR --calls --prefix+ company/calls --no-embed --source company`). It needs the company part on this brain,+ so it does not go with `--team`.+- **Who reads the call pages.** They carry no readers of their own, so whoever can read+ the `company` source reads them, and no one else. Setup prints who that is, for example+ `readable by: everyone who can read source company (this brain serves one person)`, or+ on a brain that serves several people, the members the source's access rules allow+ (`gbrain access who-can-read <slug> --source company` shows the same). These are not+ your agent conversations: those go to `conversations/` through the+ [conversation archive](conversation-archive.md), which `--transcripts` never touches.`--shape both` does both parts.@@ -49,14 +76,21 @@ A short block in the agent's instruction file, next to the brain-first block(`~/.claude/CLAUDE.md` for Claude Code, `$CODEX_HOME/AGENTS.md` for Codex). It names thepages to read for the parts you chose, says to state facts about you only from `me/facts`and company numbers only from `company/facts`, to add decisions to `company/decisions` as-dated entries, to save company facts with `--source company`, and that a `status: stub`-page holds no facts yet. `--no-instructions` skips it, and takes it out again if an+dated entries, to save company facts with `--source company`, to quote only the dated+lines of a page whose frontmatter says `type: facts` (`me/facts` and `company/facts` do),+and that a `status: stub` page holds no facts yet. `--no-instructions` skips it, and takes it out again if anearlier run wrote it.Then setup checks that keyless search finds one of your notes or docs by its title (forcompany docs, through default search when the source is in it) and prints a question totry in a new session. With no docs folder, it suggests `gbrain sources demo company-brain`-to see how a company brain answers.+to see how a company brain answers. The report also says what the conversation archive is+doing on this brain: on, off, or offered (a brain that may serve several people is only+offered it).++`gbrain doctor` notes a facts page with a fact line that has no date+(`facts_undated_lines`). It names the page and the line numbers, changes nothing, and+asks you for the dates.## A team company brain@@ -78,7 +112,8 @@ this brain; moving it to a shared brain later is a separate step.## Without the flagA brand-new brain set up without `--shape` asks once when a person is at the terminal:-personal, company, both or skip, then the folders, then just you or a team. When an agent+personal, company, both or skip, then the folders, then just you or a team, then (for a+company brain on this machine) a folder of call transcripts. When an agentruns setup (`--json`, or no terminal), the question comes back as the `brain_shape`decision in the `first_run_decisions` notice, with the exact command for each answer.Nothing is written until it is answered, `--yes` included.@@ -93,5 +128,5 @@ source stay; delete pages with `gbrain delete <slug>` (company ones with> Install gbrain and give it a shape: run `gbrain setup claude-code --shape personal`> (or `company`, or `both`). If I have a notes folder, add `--notes <that folder>`; for-> company docs, add `--docs <that folder>`; if my team will share the company brain, add-> `--team`. Then tell me what it wrote and the question to try.+> company docs, add `--docs <that folder>`; for exported call transcripts, add+> `--transcripts <that folder>`; if my team will share the company brain, add `--team`. Then tell me what it wrote and the question to try.diff --git a/scripts/check-operations-filter-bypass.sh b/scripts/check-operations-filter-bypass.shindex 35965b387d..9fad38144e 100755--- a/scripts/check-operations-filter-bypass.sh+++ b/scripts/check-operations-filter-bypass.sh@@ -62,6 +62,7 @@ ALLOWED=("src/core/persistence/administration.ts" # trusted-admin grant diagnostics; does not expose an operation transport"src/core/persistence/provider.ts" # authenticated local registrations; shared dispatch enforces localOnly and the immutable trust lane"src/commands/enrich.ts" # local CLI tool; calls put_page handler with remote=false, not network-exposed+ "src/commands/import-calls.ts" # local CLI import --calls; calls the put_page handler with remote=false, not network-exposed"src/core/extract-takes-from-pages.ts" # local CLI extraction calls put_page with remote=false; it does not expose operations to a transport"src/commands/book-mirror.ts" # local CLI tool; not network-exposed"src/commands/edge-proposals.ts" # local CLI review of edge proposals; calls trusted handlers with remote=false, not network-exposeddiff --git a/scripts/stress/iteration-weights.json b/scripts/stress/iteration-weights.jsonindex 4de39e242a..43b6ac5ba1 100644--- a/scripts/stress/iteration-weights.json+++ b/scripts/stress/iteration-weights.json@@ -691,7 +691,7 @@"test/serve-status-mode.serial.test.ts": 68700,"test/serve-sync-handoff.serial.test.ts": 4100,"test/setup-brain-first.test.ts": 62000,- "test/setup-brain-layout.test.ts": 131300,+ "test/setup-brain-layout.test.ts": 236100,"test/setup-codex-bare-path.test.ts": 90000,"test/setup-serves-several.test.ts": 134100,"test/setup.test.ts": 507300,diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex d1d5cdbe65..1387019f3c 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -215,6 +215,7 @@ test/harness-onboarding.test.ts harness identity and private handoff 6 readFileStest/hook-command.serial.test.ts user-prompt 18 source-surface-helpertest/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSynctest/hook-push-spawn-env.test.ts tryExecAsync env handoff 1 readFileSync+test/import-calls.test.ts operations filter guard 1 exec-scantest/import-private-hold-callers-7897.test.ts import entry points hold a non-canonical private request (#7897) 2 readFileSynctest/init-mode-picker.test.ts cost matrix: newest models, priced from model-pricing 6 readFileSynctest/install-no-postinstall.test.ts GST-2732: installing gbrain runs no lifecycle script 2 readFileSyncdiff --git a/src/cli/help/import.ts b/src/cli/help/import.tsindex 15cae21537..efd11a864d 100644--- a/src/cli/help/import.ts+++ b/src/cli/help/import.ts@@ -3,7 +3,7 @@ import type { CliHelpSpec } from '../command-table.ts';export const help: CliHelpSpec = {summary: 'Import a directory (or one file) of markdown into the brain.',- usage: 'gbrain import <dir> [--source <id> | --source-id <id>] [--no-embed] [--workers <n>] [--fresh] [--include-gitignored] [--allow-noncanonical-root] [--log-noop] [--json]',+ usage: 'gbrain import <dir> [--source <id> | --source-id <id>] [--no-embed] [--workers <n>] [--fresh] [--include-gitignored] [--allow-noncanonical-root] [--log-noop] [--calls [--prefix <slug prefix>]] [--json]',flags: [{ name: '--source', type: 'string', desc: 'Write into this source id (must already exist; see `gbrain sources list`).' },{ name: '--source-id', type: 'string', desc: 'Same as --source; pass one or the other.' },@@ -13,11 +13,14 @@ export const help: CliHelpSpec = {{ name: '--include-gitignored', type: 'boolean', desc: 'Also import files git ignores.' },{ name: '--allow-noncanonical-root', type: 'boolean', desc: 'Import even when the directory is not the source\'s configured root.' },{ name: '--log-noop', type: 'boolean', desc: 'Write an ingest_log row even when nothing changed.' },+ { name: '--calls', type: 'boolean', desc: 'Import .txt and .md call or meeting transcripts once each as <prefix>/<date>-<title> pages, credentials redacted, keyword-only.' },+ { name: '--prefix', type: 'string', desc: 'With --calls: the slug folder for the call pages (default calls).' },{ name: '--json', type: 'boolean', desc: 'Print the import summary as JSON on stdout (progress stays on stderr).' },],examples: ['gbrain import ~/notes','gbrain import ~/notes --source notes --no-embed','gbrain import ./brain --workers 4 --json',+ 'gbrain import ~/call-exports --calls --prefix company/calls --source company --no-embed',],};diff --git a/src/commands/doctor/checks/facts-pages.ts b/src/commands/doctor/checks/facts-pages.tsnew file mode 100644index 0000000000..26c30e1fac--- /dev/null+++ b/src/commands/doctor/checks/facts-pages.ts@@ -0,0 +1,62 @@+/**+ * facts_undated_lines doctor check (GST-2731): a facts page (type: facts, such as me/facts or company/facts, the+ * starter pages gbrain setup --shape writes) holds one dated line per fact, so an agent quoting it can say when the+ * fact was true. This notes each facts page with list lines that carry no YYYY-MM-DD date, by page and line number,+ * never the line's text. Read-only; a warn whose fix reads the page and asks the user for the dates. It reads each+ * page's bounded prefix (the first 64 KiB, far more than a facts page holds); a page stored in segments is skipped+ * and counted.+ */+import type { Check } from '../../doctor.ts';+import type { BrainEngine } from '../../../core/engine.ts';+import { agentFix, checkError, withSkippedSegmented } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { boundedBodyPrefixSql } from '../../../core/page-window/bounded-lead.ts';++const DATE_RE = /\b\d{4}-\d{2}-\d{2}\b/;+const LIST_LINE_RE = /^\s*(?:[-*+]|\d+[.)])\s+\S/;++/** 1-based numbers of the list lines in a facts page body that carry no date. */+export function undatedFactLines(body: string): number[] {+ return body.split('\n').flatMap((line, i) => (LIST_LINE_RE.test(line) && !DATE_RE.test(line) ? [i + 1] : []));+}++export async function factsUndatedLines(engine: BrainEngine): Promise<Omit<Check, 'name'>> {+ try {+ const rows = await engine.executeRaw<{ slug: string; source_id: string; segmented: boolean; body: string | null }>(+ `SELECT p.slug, p.source_id, p.body_storage = 'segmented' AS segmented, ${boundedBodyPrefixSql('p')} AS body+ FROM pages p WHERE p.type = 'facts' AND p.deleted_at IS NULL ORDER BY p.source_id, p.slug`);+ const segmented = rows.filter(r => r.segmented).length;+ const pages = rows.flatMap(r => {+ const lines = r.segmented || r.body == null ? [] : undatedFactLines(r.body);+ return lines.length ? [{ source_id: r.source_id, slug: r.slug, lines }] : [];+ });+ if (!pages.length) {+ return withSkippedSegmented({ status: 'ok' as const, message: `Every fact line on ${rows.length} facts page(s) carries a date.` }, segmented);+ }+ const first = pages[0]!;+ const named = pages.slice(0, 5).map(p => `${p.source_id}:${p.slug} (line${p.lines.length > 1 ? 's' : ''} ${p.lines.slice(0, 10).join(', ')}${p.lines.length > 10 ? ', ...' : ''})`).join('; ');+ return withSkippedSegmented({+ status: 'warn' as const,+ message: `${pages.length} facts page(s) have fact lines with no date, so an agent cannot say when they were true: ${named}${pages.length > 5 ? '; ...' : ''}.`,+ details: { pages },+ fix: agentFix(['gbrain', 'get', first.slug, '--source', first.source_id],+ 'Reads the page. Each undated line needs the date it became true, which only the user knows; add it as a new dated line rather than rewriting the old one.',+ 'facts_undated_lines', { ask_user: true, user_message: `${first.slug} (source ${first.source_id}) has ${first.lines.length} fact line(s) with no date. When did each become true? I can add the dates.` }),+ }, segmented);+ } catch (error) {+ const { name: _name, ...rest } = checkError('facts_undated_lines', 'read the facts pages', error);+ return rest;+ }+}++async function runFactsPages(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ checks.push({ name: 'facts_undated_lines', ...(await factsUndatedLines(connectedEngine(ctx))) });+ return checks;+}++export const factsPagesEntry: DoctorEntry = {+ name: 'facts_undated_lines',+ emits: ['facts_undated_lines'],+ run: runFactsPages,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex b40f782b85..204f14bf1c 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -95,6 +95,7 @@ import { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeimport { globalMaintenanceStalledEntry } from './checks/global-maintenance-stalled.ts';import { unattendedMaintenanceEntry } from './checks/unattended-maintenance.ts';import { transcriptArchiveEntry } from './checks/transcript-archive.ts';+import { factsPagesEntry } from './checks/facts-pages.ts';import { embedBackfillStalledEntry } from './checks/embed-backfill-stalled.ts';import { contentDriftSweepEntry } from './checks/content-drift-sweep.ts';import { connectorAccountMismatchEntry } from './checks/connector-account-mismatch.ts';@@ -375,6 +376,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [mcpRequestLogRetentionEntry,// GST-1943: the storage shelf: cards failing the card schema, interim records not adopted, a hosted shelf directory gone.storageManifestEntry,+ // GST-2731: facts pages (type: facts) with fact lines that carry no date (read-only; the fix asks the user for the dates).+ factsPagesEntry,fenceIntegrityEntry,searchModeEntry,];diff --git a/src/commands/import-calls.ts b/src/commands/import-calls.tsnew file mode 100644index 0000000000..e762fb5b67--- /dev/null+++ b/src/commands/import-calls.ts@@ -0,0 +1,226 @@+/**+ * GST-2731 (GBRA-529 PR 3): `gbrain import <dir> --calls [--prefix <slug prefix>] [--source <id>] [--json]`.+ *+ * An opt-in text mode of the importer for exported call and meeting transcripts (saved as .txt or .md). Each file+ * becomes one page, <prefix>/<date>-<title slug> (prefix `calls` unless given):+ *+ * - the date is the file name's leading YYYY-MM-DD, else the first date on the first line, else the file's+ * modified day; the title is the rest of a dated file name, else the first line, else the file name;+ * - the words are kept: the text is stored as written, after the same credential redaction the conversation+ * archive uses (redactSession over the file as one message, with the user's redaction patterns), and a line that+ * would read as page structure (a timeline split, a gbrain marker) gets a leading backslash (neutralizeOutsideText);+ * - the page is written through put_page, the one writer door (a working tree gets the file and a queued commit,+ * a repo-less brain gets the database row), with no readable_by of its own, so it has exactly the readers of+ * the source it lands in. It is keyword-only (no embedding at write time) and opts out of the facts backstop+ * (facts_backstop: false), so nothing paid runs;+ * - the file path is redacted like the title (call_import.file), and the page waits for the owner's approval before+ * anything embeds it (call_import.embedding_hold, the conversation archive's any-size hold);+ * - each file imports once: a rerun finds the page its file made by its folder and path (call_import.root and file+ * under the prefix, not the computed slug, which a new modified day can move) and reports it unchanged, or kept when the file+ * changed since, and never writes it again. The prefix is slugified per segment, as stored slugs are. Two files that map to one slug get a short hash+ * of their path on the second.+ *+ * These are not agent sessions: nothing here touches conversations/ or the conversation archive switch.+ */+import { createHash, randomUUID } from 'node:crypto';+import { lstatSync, readdirSync, readFileSync } from 'node:fs';+import { basename, join, relative } from 'node:path';+import type { BrainEngine } from '../core/engine.ts';+import type { RunImportResult } from './import.ts';+import { writeJsonDocument } from '../core/cli-force-exit.ts';+import { loadConfig } from '../core/config.ts';+import { getCliOptions } from '../core/cli-options.ts';+import { slugifySegment } from '../core/sync.ts';+import { neutralizeOutsideText } from '../core/outside-content.ts';+import { loadImportRedactionPatterns, redactSession, type ImportRedactionPattern } from '../core/transcripts/render.ts';+import { CLI_WRITE_WAIT_MS } from '../core/persistence/write-wait.ts';++export const CALL_FILE_RE = /\.(txt|md)$/i;+export const DEFAULT_CALL_PREFIX = 'calls';+const LEADING_DATE_RE = /^(\d{4}-\d{2}-\d{2})(?:[\s_.-]+|$)(.*)$/;+const ANY_DATE_RE = /\b(\d{4}-\d{2}-\d{2})\b/;++export interface CallPage {+ rel: string;+ /** The relative path as stored and printed: redacted like the title and body. */+ file: string;+ slug: string;+ title: string;+ date: string;+ date_from: 'file_name' | 'first_line' | 'modified';+ content: string;+ redactions: number;+ hash: string;+}++export interface CallFileResult {+ file: string;+ slug: string;+ status: 'imported' | 'unchanged' | 'kept' | 'error';+ date_from?: CallPage['date_from'];+ redactions?: number;+ git_state?: string;+ error?: string;+}++/** .txt and .md files under `dir`, sorted; dot entries and symlinks are skipped. */+export function listCallFiles(dir: string): string[] {+ const out: string[] = [];+ const walk = (d: string): void => {+ let names: string[];+ try { names = readdirSync(d).sort(); } catch { return; }+ for (const name of names) {+ if (name.startsWith('.')) continue;+ const p = join(d, name);+ let st;+ try { st = lstatSync(p); } catch { continue; }+ if (st.isSymbolicLink()) continue;+ if (st.isDirectory()) walk(p);+ else if (st.isFile() && CALL_FILE_RE.test(name)) out.push(p);+ }+ };+ walk(dir);+ return out;+}++const validDay = (day: string | undefined): string | null => {+ if (!day) return null;+ const t = Date.parse(`${day}T00:00:00Z`);+ return Number.isNaN(t) || new Date(t).toISOString().slice(0, 10) !== day ? null : day;+};++const localDay = (ms: number): string => {+ const d = new Date(ms);+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;+};++/** The first non-empty line of the text, past a leading frontmatter block, without heading marks. */+function firstLine(text: string): string {+ let lines = text.replace(/^\uFEFF/, '').split(/\r?\n/);+ if (lines[0]?.trim() === '---') {+ const end = lines.findIndex((l, i) => i > 0 && l.trim() === '---');+ if (end > 0) lines = lines.slice(end + 1);+ }+ return (lines.find(l => l.trim()) ?? '').trim().replace(/^#+\s*/, '');+}++/** The page one call file becomes: slug, title, date, and the redacted, structure-neutral content. */+export function callPageFor(rel: string, text: string, mtimeMs: number, prefix: string, patterns: ImportRedactionPattern[], root?: string): CallPage {+ const redact = (s: string): string => redactCallPath(s, patterns).file;+ const name = redact(basename(rel).replace(CALL_FILE_RE, ''));+ const lead = LEADING_DATE_RE.exec(name);+ const line = redact(firstLine(text));+ const fromName = validDay(lead?.[1]);+ const fromLine = fromName ? null : validDay(ANY_DATE_RE.exec(line)?.[1]);+ const date = fromName ?? fromLine ?? localDay(mtimeMs);+ const nameTitle = (fromName ? lead![2]! : name).split(/(<REDACTED:[^>]*>)/).map((part, i) => i % 2 ? part : part.replace(/[_-]+/g, ' ')).join('').trim();+ const lineTitle = line.replace(ANY_DATE_RE, '').replace(/^[\s:|,.-]+|[\s:|,.-]+$/g, '').trim();+ const rawTitle = ((fromName ? nameTitle || lineTitle : lineTitle || nameTitle) || 'call').slice(0, 120);+ const path = redactCallPath(rel, patterns);+ const redacted = redactSession({ meta: { harness: 'claude-export', sessionId: path.file, title: rawTitle }, messages: [{ role: 'user', timestamp: '', text }] }, { patterns });+ const title = redacted.session.meta.title ?? rawTitle;+ const body = neutralizeOutsideText(redacted.session.messages[0]!.text).replace(/\s+$/, '');+ const slugTitle = slugifySegment(title).slice(0, 80).replace(/-+$/, '') || 'call';+ const hash = createHash('sha256').update(`${title}\u0000${body}`).digest('hex').slice(0, 16);+ const frontmatter = [+ '---',+ `title: ${JSON.stringify(title)}`,+ 'type: meeting',+ `date: ${date}`,+ 'facts_backstop: false',+ 'call_import:',+ ` file: ${JSON.stringify(path.file)}`,+ ...(root ? [` root: ${JSON.stringify(root)}`] : []),+ ` hash: ${JSON.stringify(hash)}`,+ ` redactions: ${redacted.redactionCount + path.redactions}`,+ ' embedding_hold: call_import',+ '---',+ ].join('\n');+ return { rel, file: path.file, slug: `${prefix}/${date}-${slugTitle}`, title, date, date_from: fromName ? 'file_name' : fromLine ? 'first_line' : 'modified', content: `${frontmatter}\n${body}\n`, redactions: redacted.redactionCount + path.redactions, hash };+}++const callImportOf = (frontmatter: unknown): { file?: unknown; root?: unknown; hash?: unknown } | null => {+ const ci = (frontmatter as { call_import?: unknown } | null)?.call_import;+ return ci && typeof ci === 'object' ? ci as { file?: unknown; root?: unknown; hash?: unknown } : null;+};++/** A file path with the same credential redaction as the call's title, so a secret in a file name is never stored or printed. */+export function redactCallPath(rel: string, patterns: ImportRedactionPattern[]): { file: string; redactions: number } {+ const r = redactSession({ meta: { harness: 'claude-export', sessionId: '', title: rel }, messages: [] }, { patterns });+ return { file: r.session.meta.title ?? rel, redactions: r.redactionCount };+}++/** The import folder's identity in a page: a short hash of its real path, so two folders holding the same file name stay apart. */+export const callRootId = (dir: string): string => createHash('sha256').update(dir).digest('hex').slice(0, 12);++function flagValue(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+}++/** Import every call file under `dir` once, into `sourceId` (default when unset). */+export async function runCallImport(engine: BrainEngine, dir: string, args: string[], opts: { sourceId?: string; json: boolean }): Promise<RunImportResult> {+ const prefix = (flagValue(args, '--prefix') ?? DEFAULT_CALL_PREFIX).split('/').map(slugifySegment).filter(Boolean).join('/') || DEFAULT_CALL_PREFIX;+ const sourceId = opts.sourceId ?? 'default';+ const patterns = loadImportRedactionPatterns();+ const { operations } = await import('../core/operations.ts');+ const putPage = operations.find(op => op.name === 'put_page')!;+ const ctx = { engine, config: loadConfig() ?? { engine: engine.kind }, logger: { info() {}, warn: (m: string) => process.stderr.write(`${m}\n`), error: (m: string) => process.stderr.write(`${m}\n`) },+ dryRun: false, remote: false, cliOpts: getCliOptions(), sourceId, writeWaitMs: CLI_WRITE_WAIT_MS } as Parameters<typeof putPage.handler>[0];+ const files = listCallFiles(dir);+ const root = callRootId(dir);+ const priorSlugs = new Map((await engine.executeRaw<{ slug: string; file: string }>(+ `SELECT slug, frontmatter->'call_import'->>'file' AS file FROM pages+ WHERE source_id = $1 AND deleted_at IS NULL AND starts_with(slug, $2) AND frontmatter->'call_import'->>'root' = $3+ AND frontmatter->'call_import'->>'file' IS NOT NULL`,+ [sourceId, `${prefix}/`, root])).map(r => [r.file, r.slug]));+ const sameImport = (frontmatter: unknown, file: string): boolean => { const ci = callImportOf(frontmatter); return ci?.file === file && ci.root === root; };+ const results: CallFileResult[] = [];+ const used = new Set<string>();+ for (const path of files) {+ const rel = relative(dir, path);+ let page: CallPage;+ try {+ page = callPageFor(rel, readFileSync(path, 'utf8'), lstatSync(path).mtimeMs, prefix, patterns, root);+ } catch (e) {+ results.push({ file: redactCallPath(rel, patterns).file, slug: '', status: 'error', error: e instanceof Error ? e.message : String(e) });+ continue;+ }+ const suffixed = `${page.slug}-${createHash('sha256').update(`${root}/${rel}`).digest('hex').slice(0, 6)}`;+ const priorSlug = priorSlugs.get(page.file);+ let slug = priorSlug ?? (used.has(page.slug) ? suffixed : page.slug);+ let existing = await engine.readPageSnapshot(slug, { sourceId });+ if (!priorSlug && existing && !sameImport(existing.page.frontmatter, page.file) && slug !== suffixed) {+ slug = suffixed;+ existing = await engine.readPageSnapshot(slug, { sourceId });+ }+ used.add(slug);+ const base = { file: page.file, slug, date_from: page.date_from, redactions: page.redactions };+ if (existing) {+ if (!sameImport(existing.page.frontmatter, page.file)) results.push({ ...base, status: 'error', error: `${slug} already holds another page; rename the file to import it` });+ else results.push({ ...base, status: callImportOf(existing.page.frontmatter)?.hash === page.hash ? 'unchanged' : 'kept' });+ continue;+ }+ try {+ const receipt = await putPage.handler(ctx, { slug, content: page.content, request_id: randomUUID() }) as { persistence?: { git_state?: string } } | null;+ results.push({ ...base, status: 'imported', ...(receipt?.persistence?.git_state ? { git_state: receipt.persistence.git_state } : {}) });+ } catch (e) {+ results.push({ ...base, status: 'error', error: e instanceof Error ? e.message : String(e) });+ }+ }+ const count = (s: CallFileResult['status']) => results.filter(r => r.status === s).length;+ const imported = count('imported');+ const errors = count('error');+ const redactions = results.filter(r => r.status === 'imported').reduce((n, r) => n + (r.redactions ?? 0), 0);+ const failures = results.filter(r => r.status === 'error').map(r => ({ path: r.file, error: r.error ?? 'unknown error' }));+ if (opts.json) {+ await writeJsonDocument(JSON.stringify({+ status: errors > 0 ? 'partial' : 'success', mode: 'calls', source_id: sourceId, prefix, total_files: files.length,+ imported, unchanged: count('unchanged'), kept: count('kept'), errors, redactions, pages: results, failures,+ }));+ } else {+ console.log(`Call import into source ${sourceId} under ${prefix}/: ${imported} imported, ${count('unchanged')} unchanged, ${count('kept')} kept (changed since import, not overwritten), ${errors} error(s); ${redactions} credential(s) redacted.`);+ for (const r of results) console.log(` ${r.status.padEnd(9)} ${r.slug || '-'} <- ${r.file}${r.error ? ` (${r.error})` : ''}`);+ }+ return { imported, skipped: results.length - imported, errors, chunksCreated: 0, failures };+}diff --git a/src/commands/import.ts b/src/commands/import.tsindex 1943780ffb..a0a50d351f 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -310,7 +310,7 @@ export async function runImport(const inheritedSignal = currentSourceFilesystemSignal();const signal = opts.signal && inheritedSignal ? AbortSignal.any([opts.signal, inheritedSignal]) : opts.signal ?? inheritedSignal;signal?.throwIfAborted();- const noEmbed = args.includes('--no-embed');+ const noEmbed = args.includes('--no-embed') || args.includes('--calls');const allowNoncanonicalRoot = args.includes('--allow-noncanonical-root');const fresh = args.includes('--fresh');const jsonOutput = args.includes('--json');@@ -498,10 +498,10 @@ export async function runImport(if (workersIdx !== -1) flagValues.add(workersIdx + 1);if (sourceIdIdx !== -1) flagValues.add(sourceIdIdx + 1);if (sourceIdx !== -1) flagValues.add(sourceIdx + 1);- const dirArg = args.find((a, i) => !a.startsWith('--') && !flagValues.has(i) && args[i - 1] !== '--access-policy');+ const dirArg = args.find((a, i) => !a.startsWith('--') && !flagValues.has(i) && args[i - 1] !== '--access-policy' && args[i - 1] !== '--prefix');if (!dirArg) {- console.error('Usage: gbrain import <dir> [--no-embed] [--workers N] [--fresh] [--source <id> | --source-id <id>] [--access-policy <exported-source>|none] [--include-gitignored] [--allow-noncanonical-root] [--json]');+ console.error('Usage: gbrain import <dir> [--no-embed] [--workers N] [--fresh] [--source <id> | --source-id <id>] [--access-policy <exported-source>|none] [--include-gitignored] [--allow-noncanonical-root] [--calls [--prefix <slug prefix>]] [--json]');throw new ImportAbortError('no import directory given');}// #1728: capture the import target ONCE as an absolute real path. Every@@ -516,6 +516,7 @@ export async function runImport(console.error(`Import target is not readable: ${dirArg} (${e instanceof Error ? e.message : String(e)})`);throw new ImportAbortError(`import target not readable: ${dirArg}`);}+ if (args.includes('--calls')) return (await import('./import-calls.ts')).runCallImport(engine, dir, args, { sourceId, json: jsonOutput });const managedImport = await readManagedMode(engine);if (managedImport && dir !== resolve(dirArg)) throw symlinkedRootAbort(dirArg, dir);diff --git a/src/commands/setup-brain-layout.ts b/src/commands/setup-brain-layout.tsindex 7f26a14b60..ef402a1d9c 100644--- a/src/commands/setup-brain-layout.ts+++ b/src/commands/setup-brain-layout.ts@@ -12,6 +12,11 @@* when the brain serves one person; otherwise its `source_not_in_default_search` notice asks the user;* - a one-shot import of the notes folder (personal) and the docs folder (company), read only, never written.* Over IMPORT_INLINE_MAX markdown files setup hands the agent the import command instead;+ * - with --transcripts, a one-shot import of exported call transcripts (.txt, .md) as company/calls/<date>-<title>+ * pages in the company source (gbrain import --calls: credentials redacted, keyword-only, each file once), and a+ * line naming who can read them, read from gbrain access who-can-read; the pages carry no readers of their own;+ * - me/facts and company/facts carry type: facts, and the block tells the agent to quote only their dated lines;+ * - one line saying what the conversation archive is doing on this brain (on, off or offered), read from doctor;* - a managed layout block beside the brain-first block, telling the agent which pages to read and to quote* facts and numbers only from the facts pages. `--shape none` removes the block and keeps the pages;* - a keyless check that default search finds an imported file, and one question to ask in a new session.@@ -40,16 +45,20 @@ export interface LayoutFlags {notes?: string | null;/** An absolute company docs folder; null for an explicit `--docs none`. */docs?: string | null;+ /** An absolute folder of exported call transcripts; null for an explicit `--transcripts none`. */+ transcripts?: string | null;/** --team: the company part belongs on a shared brain, so setup prints the route and creates nothing for it. */team?: boolean;dryRun: boolean;}export const IMPORT_INLINE_MAX = 500;-export const LAYOUT_VERSION = 2;+export const LAYOUT_VERSION = 3;export const LAYOUT_BEGIN = '<!-- gbrain:brain-layout:begin -->';export const LAYOUT_END = '<!-- gbrain:brain-layout:end -->';export const COMPANY_SOURCE = 'company';+export const CALLS_PREFIX = `${COMPANY_SOURCE}/calls`;+const CALL_FILES = /\.(txt|md)$/i;export type LayoutScope = 'user' | 'project';@@ -62,13 +71,14 @@ export const setupArgv = (harness: string, scope: LayoutScope = 'user', source:const markers = (harness: string, scope: LayoutScope, source: string | null, shape: BrainShape): BlockMarkers => ({ begin: LAYOUT_BEGIN, end: LAYOUT_END, label: 'brain-layout', rerun: [...setupArgv(harness, scope, source), '--shape', shape === 'none' ? 'personal' : shape].join(' ') });-export interface StarterPage { slug: string; title: string; body: string }+export interface StarterPage { slug: string; title: string; body: string; type?: string }/** The personal starter pages: empty forms with one marked example line each. */export const PERSONAL_PAGES: readonly StarterPage[] = [{slug: 'me/facts',title: 'Facts about me',+ type: 'facts',body: 'True things about me that agents may say. One dated line per fact, with where it came from. '+ 'Never overwrite a line: when something changes, add a new dated line.\n\n'+ '- Example (delete me): 2026-01-01: I live in example-city. Source: I said so.',@@ -94,6 +104,7 @@ export const COMPANY_PAGES: readonly StarterPage[] = [{slug: 'company/facts',title: 'Company facts',+ type: 'facts',body: 'Numbers and facts agents may quote. One line each, with a date and where it came from. '+ 'Never overwrite a line: when a number changes, add a new dated line.\n\n'+ '- Example (delete me): 2026-01-01: 12 paying customers. Source: billing export.',@@ -132,7 +143,7 @@ export const COMPANY_PAGES: readonly StarterPage[] = [];export function renderStarterPage(p: StarterPage): string {- return `---\ntitle: ${p.title}\nstatus: stub\n---\n# ${p.title}\n\n${p.body}\n\n`+ return `---\ntitle: ${p.title}\n${p.type ? `type: ${p.type}\n` : ''}status: stub\n---\n# ${p.title}\n\n${p.body}\n\n`+ '_This page is an empty form (status: stub). It holds no facts until you add your own lines; then remove the stub line from the frontmatter._\n';}@@ -155,13 +166,14 @@ export function renderLayoutBlock(harness: string, scope: LayoutScope = 'user','- Add a new decision to company/decisions as a dated entry with why, who and what would make us revisit it.',`- Save company facts and decisions with --source ${COMPANY_SOURCE}; personal ones go to the default source.`);}- lines.push('- Never overwrite a page: add a new dated line. Save facts I tell you with remember, naming where they came from.',+ lines.push('- A page with type: facts holds one dated line per fact: quote only its dated lines, and add a new fact as a new dated line.',+ '- Never overwrite a page: add a new dated line. Save facts I tell you with remember, naming where they came from.','- A page whose frontmatter says status: stub is an empty form: it holds no facts yet.');return lines.join('\n');}-/** Markdown files under `dir` (dot folders skipped), counted up to `cap` + 1, with the first one found. */-export function countNotes(dir: string, cap = IMPORT_INLINE_MAX): { count: number; first: string | null } {+/** Markdown files (or files matching `files`) under `dir` (dot folders skipped), counted up to `cap` + 1, with the first one found. */+export function countNotes(dir: string, cap = IMPORT_INLINE_MAX, files = /\.(md|markdown)$/i): { count: number; first: string | null } {let count = 0;let first: string | null = null;const walk = (d: string): void => {@@ -175,7 +187,7 @@ export function countNotes(dir: string, cap = IMPORT_INLINE_MAX): { count: numbetry { st = lstatSync(p); } catch { continue; }if (st.isSymbolicLink()) continue;if (st.isDirectory()) walk(p);- else if (/\.(md|markdown)$/i.test(name)) { count++; first ??= p; }+ else if (files.test(name)) { count++; first ??= p; }}};walk(dir);@@ -206,12 +218,12 @@ export function candidateNoteFolders(home: string = homedir()): string[] {return [...new Set([...vaults, ...fixed])].filter(p => { try { return statSync(p).isDirectory(); } catch { return false; } });}-/** --shape / --notes / --docs / --team validation; a string is the refusal (nothing written). */-export function parseLayoutFlags(value: (flag: string) => string | undefined, has: (flag: string) => boolean, harness: string | undefined): { brain?: BrainShape; notes?: string | null; docs?: string | null; team?: boolean } | string {+/** --shape / --notes / --docs / --transcripts / --team validation; a string is the refusal (nothing written). */+export function parseLayoutFlags(value: (flag: string) => string | undefined, has: (flag: string) => boolean, harness: string | undefined): { brain?: BrainShape; notes?: string | null; docs?: string | null; transcripts?: string | null; team?: boolean } | string {const brain = value('--shape') as BrainShape | undefined;if (brain !== undefined && !['personal', 'company', 'both', 'none'].includes(brain)) return `unknown --shape '${brain}'; pass personal, company, both or none`;- const out: { brain?: BrainShape; notes?: string | null; docs?: string | null; team?: boolean } = brain ? { brain } : {};- const folders = [['--notes', 'notes', hasPersonal, 'personal or both'], ['--docs', 'docs', hasCompany, 'company or both']] as const;+ const out: { brain?: BrainShape; notes?: string | null; docs?: string | null; transcripts?: string | null; team?: boolean } = brain ? { brain } : {};+ const folders = [['--notes', 'notes', hasPersonal, 'personal or both'], ['--docs', 'docs', hasCompany, 'company or both'], ['--transcripts', 'transcripts', hasCompany, 'company or both']] as const;for (const [flag, key, needs, shapes] of folders) {const raw = value(flag);if (raw === undefined) continue;@@ -226,7 +238,9 @@ export function parseLayoutFlags(value: (flag: string) => string | undefined, haif (has('--team') && has('--solo')) return '--team and --solo do not go together';if ((has('--team') || has('--solo')) && !hasCompany(brain)) return '--team and --solo need --shape company or both';if (has('--team')) {- if (out.docs) return `--docs imports into this machine's company source, and with --team the company part lives on a shared brain; drop --docs or use --solo (gbrain setup ${harness ?? '<harness>'} --shape ${brain} --solo)`;+ for (const flag of ['docs', 'transcripts'] as const) {+ if (out[flag]) return `--${flag} imports into this machine's company source, and with --team the company part lives on a shared brain; drop --${flag} or use --solo (gbrain setup ${harness ?? '<harness>'} --shape ${brain} --solo)`;+ }out.team = true;}return out;@@ -234,15 +248,29 @@ export function parseLayoutFlags(value: (flag: string) => string | undefined, haexport interface ImportOutcome { dir: string; files: number; action: 'imported' | 'deferred' | 'failed'; argv: string[]; detail?: string }+/** The call-transcript import: counts from gbrain import --calls, and who can read the pages (gbrain access who-can-read). */+export interface TranscriptsOutcome extends ImportOutcome {+ imported?: number;+ unchanged?: number;+ kept?: number;+ redactions?: number;+ readers?: { members: 'every_source_reader' | string[] | null; serves: 'one' | 'several' | null; detail: string };+ /** What can send call text off this machine, from doctor's auto_chronicle and extract_atoms_backlog checks. */+ egress?: { leaves: boolean | null; detail: string };+}+export interface LayoutOutcome {shape: BrainShape;pages: Array<{ slug: string; source: string | null; action: 'write' | 'keep' | 'failed'; detail?: string }>;notes: ImportOutcome | null;docs: ImportOutcome | null;+ transcripts: TranscriptsOutcome | null;company: { source: string; action: 'created' | 'kept' | 'team' | 'failed'; federated: boolean | null; root: string | null; detail?: string } | null;block: { path: string; action: 'write' | 'keep' | 'remove' | 'skip' | 'preserve'; detail: string } | null;check: { ok: boolean; query: string | null; detail: string };next_question: string | null;+ /** What the conversation archive is doing on this brain, read from doctor's transcript_archive_freshness check. */+ archive: { state: 'on' | 'off' | 'offered' | 'unknown'; detail: string } | null;}/** A gbrain child; `source` pins it to one source through GBRAIN_SOURCE (null: the caller's environment as it is). */@@ -294,6 +322,73 @@ function importFolder(exec: Run, launcher: string, dir: string, source: string |return { outcome: { dir, files: count, action: 'imported', argv }, title: first ? noteTitle(first) : null };}+/** Who can read the call pages, from gbrain access who-can-read on one of them and gbrain access serves; read only. */+function readersOf(exec: Run, launcher: string, slug: string): NonNullable<TranscriptsOutcome['readers']> {+ const unknown = { members: null, serves: null, detail: `unknown; run gbrain access who-can-read ${slug} --source ${COMPANY_SOURCE}` };+ let page: { readers: string[] | null; members: 'every_source_reader' | string[] } | undefined;+ let serves: { serves?: 'one' | 'several'; enabled_members?: string[] } = {};+ try { page = (JSON.parse(exec([launcher, 'access', 'who-can-read', slug, '--source', COMPANY_SOURCE, '--json'], undefined, null).stdout) as { pages?: Array<NonNullable<typeof page>> }).pages?.[0]; } catch { return unknown; }+ try { serves = JSON.parse(exec([launcher, 'access', 'serves', '--json', '--no-open-pages'], undefined, null).stdout) as typeof serves; } catch { /* the serves clause is left out */ }+ if (!page) return unknown;+ const who = serves.serves === 'several' ? `this brain serves several people: ${(serves.enabled_members ?? []).join(', ') || 'none enabled'}`+ : serves.serves === 'one' ? 'this brain serves one person' : null;+ const members = page.members;+ const clauses = [...(members === 'every_source_reader' ? [] : [`access rules on source ${COMPANY_SOURCE} cover ${CALLS_PREFIX}/`]), ...(who ? [who] : [])];+ const detail = `${members === 'every_source_reader' ? `everyone who can read source ${COMPANY_SOURCE}` : `${members.join(', ') || 'no member'} only`}${clauses.length ? ` (${clauses.join('; ')})` : ''}`;+ return { members, serves: serves.serves ?? null, detail };+}++/** One read-only import of a call-transcript folder into the company source, deferred to the agent above IMPORT_INLINE_MAX files. */+function importCalls(exec: Run, launcher: string, dir: string, dryRun: boolean): TranscriptsOutcome {+ const { count } = countNotes(dir, IMPORT_INLINE_MAX, CALL_FILES);+ const args = ['import', dir, '--calls', '--prefix', CALLS_PREFIX, '--no-embed'];+ const argv = ['gbrain', ...args, '--source', COMPANY_SOURCE];+ if (count > IMPORT_INLINE_MAX) return { dir, files: count, action: 'deferred', argv, detail: `more than ${IMPORT_INLINE_MAX} call files; run the import as its own step` };+ if (dryRun) return { dir, files: count, action: 'imported', argv, detail: 'would import (read only)' };+ const imp = exec([launcher, ...args, '--json'], undefined, COMPANY_SOURCE);+ let doc: { imported?: number; unchanged?: number; kept?: number; errors?: number; redactions?: number; pages?: Array<{ slug: string; status: string; error?: string }> };+ try { doc = JSON.parse(imp.stdout) as typeof doc; } catch { return { dir, files: count, action: 'failed', argv, detail: lastLine(imp.stderr || imp.stdout) }; }+ const landed = (doc.pages ?? []).filter(p => p.status !== 'error');+ const failed = (doc.pages ?? []).find(p => p.status === 'error');+ const counts = { imported: doc.imported ?? 0, unchanged: doc.unchanged ?? 0, kept: doc.kept ?? 0, redactions: doc.redactions ?? 0 };+ if (!landed.length && (failed || imp.code !== 0)) return { dir, files: count, action: 'failed', argv, ...counts, detail: failed?.error ?? lastLine(imp.stderr) };+ return { dir, files: count, action: 'imported', argv, ...counts, ...(failed ? { detail: `${doc.errors} file(s) not imported: ${failed.error}` } : {}),+ ...(landed[0] ? { readers: readersOf(exec, launcher, landed[0].slug) } : {}) };+}++type DoctorChecks = Array<{ name: string; details?: Record<string, unknown> }>;++/** Whether scheduled extraction can send imported call text to a chat provider; embedding stays held either way. */+export function callEgress(checks: DoctorChecks): NonNullable<TranscriptsOutcome['egress']> {+ if (!['auto_chronicle', 'extract_atoms_backlog'].every(name => checks.some(c => c.name === name))) {+ return { leaves: null, detail: 'could not be checked; gbrain doctor --only auto_chronicle,extract_atoms_backlog shows it' };+ }+ const details = (name: string) => checks.find(c => c.name === name)?.details;+ const chronicle = details('auto_chronicle');+ const chat = chronicle?.chat_available;+ const readers: string[] = [];+ if (chronicle?.enabled === true && chat === true) readers.push(`event extraction (auto_chronicle, at most ${chronicle.daily_limit} page(s) a day)`);+ if (details('extract_atoms_backlog')?.pack_declares_phase === true && chat !== false) readers.push('atom extraction (within cycle.extract_atoms.budget_usd)');+ const held = 'embedding waits for your approval';+ return readers.length+ ? { leaves: true, detail: `with a chat model key set, ${readers.join(' and ')} can send call text to your chat provider, within the limits you set; ${held}` }+ : { leaves: false, detail: `nothing; no extraction reads call pages here, and ${held}` };+}++/** What the conversation archive is doing here, from doctor's transcript_archive_freshness check; its first-run notice is not repeated. With `calls`, the same doctor run also reads what can send call text off this machine. */+function archiveState(exec: Run, launcher: string, calls: TranscriptsOutcome | null): NonNullable<LayoutOutcome['archive']> {+ const only = ['transcript_archive_freshness', ...(calls ? ['auto_chronicle', 'extract_atoms_backlog'] : [])];+ const out = exec([launcher, 'doctor', '--only', only.join(','), '--json'], undefined, null);+ let checks: DoctorChecks = [];+ try { checks = (JSON.parse(out.stdout) as { checks?: DoctorChecks }).checks ?? []; } catch { /* unknown below */ }+ if (calls) calls.egress = callEgress(checks);+ const details = checks.find(c => c.name === 'transcript_archive_freshness')?.details as { enabled?: boolean; offered?: boolean } | undefined;+ if (!details) return { state: 'unknown', detail: 'could not be read; gbrain transcripts archive status shows it' };+ if (details.enabled) return { state: 'on', detail: 'on: your agent conversations are kept, redacted, under conversations/; call transcripts are separate (gbrain transcripts archive off turns it off)' };+ if (details.offered) return { state: 'offered', detail: 'offered, not on: this brain may serve more than one person (gbrain transcripts archive on turns it on)' };+ return { state: 'off', detail: 'off (gbrain transcripts archive on turns it on)' };+}+/** Whether keyless search (scoped to `source`, or default search for null) puts `title` in its top 5. */function searchFinds(exec: Run, launcher: string, title: string, source: string | null): boolean {const hits = exec([launcher, 'search', title, '--json'], undefined, source);@@ -331,7 +426,7 @@ export function applyBrainLayout(opts: { harness: string; scope?: LayoutScope; sconst source = opts.source ?? null;const scope = opts.scope ?? 'user';const team = !!flags.team;- const empty = (shape: BrainShape, block: LayoutOutcome['block']): LayoutOutcome => ({ shape, pages: [], notes: null, docs: null, company: null, block, check: { ok: true, query: null, detail: 'nothing to check' }, next_question: null });+ const empty = (shape: BrainShape, block: LayoutOutcome['block']): LayoutOutcome => ({ shape, pages: [], notes: null, docs: null, transcripts: null, company: null, block, check: { ok: true, query: null, detail: 'nothing to check' }, next_question: null, archive: null });const written = flags.brain ? blockShape(flags.brain, team) : undefined;const removed = opts.instructionsDeclined ? syncLayoutBlock(opts.instructionsPath, harness, scope, source, 'none', flags.dryRun) : null;const block = opts.instructionsDeclined ? (removed?.action === 'skip' ? null : removed)@@ -378,6 +473,7 @@ export function applyBrainLayout(opts: { harness: string; scope?: LayoutScope; sif (found) outcome.next_question = `In a new session, ask: "what did we decide about ${title}, and why?"`;}}+ if (flags.transcripts) outcome.transcripts = importCalls(exec, launcher, flags.transcripts, flags.dryRun);if (!outcome.next_question && !flags.dryRun && !hasPersonal(flags.brain)) {outcome.next_question = 'Run gbrain sources demo company-brain to see how a company brain answers, then add one dated line to company/decisions and ask about it in a new session.';}@@ -391,6 +487,7 @@ export function applyBrainLayout(opts: { harness: string; scope?: LayoutScope; s: { ok: false, query: null, detail: 'me/facts could not be read back' };outcome.next_question = 'Add one dated line to me/facts, then in a new session ask: "what does my brain say about me?"';}+ if (!flags.dryRun) outcome.archive = archiveState(exec, launcher, outcome.transcripts?.action === 'imported' ? outcome.transcripts : null);return outcome;}@@ -418,6 +515,15 @@ export function describeLayout(o: LayoutOutcome, dryRun: boolean): string[] {for (const [label, i] of [['notes', o.notes], ['docs', o.docs]] as const) {if (i) lines.push(` ${label.padEnd(8)} ${i.action === 'imported' ? `${would}import ${i.files} file(s) from ${i.dir} (read only)` : `${i.action}: ${i.detail ?? ''} (${i.argv.join(' ')})`}`);}+ const t = o.transcripts;+ if (t) {+ lines.push(t.action !== 'imported' ? ` calls ${t.action}: ${t.detail ?? ''} (${t.argv.join(' ')})`+ : ` calls ${would}import ${t.files} call file(s) from ${t.dir} as ${CALLS_PREFIX}/<date>-<title> (read only, credentials redacted)`+ + (t.imported === undefined ? '' : `: ${t.imported} new, ${t.unchanged} unchanged, ${t.kept} kept, ${t.redactions} credential(s) redacted${t.detail ? `; ${t.detail}` : ''}`));+ if (t.readers) lines.push(` readable by: ${t.readers.detail}`);+ if (t.egress) lines.push(` what leaves this machine: ${t.egress.detail}`);+ }+ if (o.archive) lines.push(` archive conversation archive ${o.archive.detail}`);if (!dryRun && o.shape !== 'none' && o.check.detail !== 'nothing to check') lines.push(` check ${o.check.ok ? 'ok' : 'not verified'}: ${o.check.detail}`);if (o.next_question) lines.push(`Next question: ${o.next_question}`);return lines;@@ -427,11 +533,11 @@ export function describeLayout(o: LayoutOutcome, dryRun: boolean): string[] {export function layoutNotices(o: LayoutOutcome | null, harness: string, scope: LayoutScope = 'user', source: string | null = null): Notice[] {if (!o) return [];const out: Notice[] = [];- for (const i of [o.notes, o.docs]) {+ for (const i of [o.notes, o.docs, o.transcripts]) {if (!i || i.action === 'imported') continue;out.push({code: 'brain_layout_import_pending', kind: 'coaching',- why: i.action === 'deferred' ? `${i.dir} holds more than ${IMPORT_INLINE_MAX} markdown files, so setup did not import it inline.`+ why: i.action === 'deferred' ? `${i.dir} holds more than ${IMPORT_INLINE_MAX} ${i === o.transcripts ? 'call' : 'markdown'} files, so setup did not import it inline.`: `The import of ${i.dir} did not finish (${i.detail ?? 'unknown error'}); nothing else changed.`,fix: { argv: i.argv, consent: [], actor: 'agent', requires_exclusive: true, why: 'Imports the folder (read only) into the brain; run it as its own step.' },});@@ -484,7 +590,7 @@ export function brainShapeDecision(harness: string, folders: string[] = candidatoptions: [...folders.slice(0, 3).map((f, i) => ({ id: `personal_notes_${i + 1}`, label: `Personal brain, importing ${f}`, argv: [...shape('personal'), '--notes', f] })),{ id: 'personal', label: 'Personal brain, no notes folder yet', argv: shape('personal') },- { id: 'company', label: 'Company brain, just me (add --docs <folder> to import company docs)', argv: shape('company') },+ { id: 'company', label: 'Company brain, just me (add --docs <folder> for company docs, --transcripts <folder> for call transcripts)', argv: shape('company') },{ id: 'both', label: 'Personal and company brain, just me', argv: shape('both') },{ id: 'company_team', label: 'Company brain shared with a team (prints where it lives; creates nothing)', argv: [...shape('company'), '--team'] },{ id: 'none', label: 'No starter pages (memory works as it is)' },@@ -495,8 +601,8 @@ export function brainShapeDecision(harness: string, folders: string[] = candidat}/** The inline brain_shape questions; readLine answers eof (decline) unless isInteractive(). */-export async function askBrainShape(folders: string[] = candidateNoteFolders()): Promise<{ brain?: BrainShape; notes?: string | null; docs?: string | null; team?: boolean }> {- const line = async (prompt: string): Promise<string | null> => { const r = await readLine({ prompt }); return r.kind === 'line' ? r.text.trim() : null; };+export async function askBrainShape(folders: string[] = candidateNoteFolders(), read: typeof readLine = readLine): Promise<{ brain?: BrainShape; notes?: string | null; docs?: string | null; transcripts?: string | null; team?: boolean }> {+ const line = async (prompt: string): Promise<string | null> => { const r = await read({ prompt }); return r.kind === 'line' ? r.text.trim() : null; };const pick = await line('What are you making? 1) a personal brain 2) a company brain 3) both 4) skip [4]: ');const brain = ({ '1': 'personal', '2': 'company', '3': 'both' } as Record<string, BrainShape>)[pick ?? ''];if (!brain) return {};@@ -509,11 +615,14 @@ export async function askBrainShape(folders: string[] = candidateNoteFolders()):process.stderr.write(`${picked} is not a folder; skipping that import (run gbrain import <dir> --no-embed later)\n`);return null;};- const out: { brain: BrainShape; notes?: string | null; docs?: string | null; team?: boolean } = { brain };+ const out: { brain: BrainShape; notes?: string | null; docs?: string | null; transcripts?: string | null; team?: boolean } = { brain };if (hasPersonal(brain)) out.notes = await folder('Notes folder to import, read only', folders[0]);if (hasCompany(brain)) {out.team = (await line('Just you, or a team? 1) just me 2) a team [1]: ')) === '2';- if (!out.team) out.docs = await folder('Company docs folder to import, read only');+ if (!out.team) {+ out.docs = await folder('Company docs folder to import, read only');+ out.transcripts = await folder('Folder of call transcripts (.txt or .md exports) to import, read only');+ }}return out;}diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex d0fd4eb5d5..b0c69d14eb 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -227,6 +227,11 @@ Flags:500 markdown files, setup prints the import command instead.--docs DIR With --shape company or both: import a company docs folder intothe company source the same way, read only.+ --transcripts DIR With --shape company or both (not --team): import exported call+ transcripts (.txt, .md) once each as company/calls/<date>-<title>+ pages in the company source: words kept, credentials redacted,+ keyword-only, readable by whoever reads that source. Setup says+ who that is. Not the conversation archive (conversations/).--team | --solo With a company shape: --team prints where a team's shared companybrain lives and creates nothing for it; --solo (the default) makesthe company part on this brain.@@ -313,11 +318,13 @@ interface SetupFlags {notes?: string | null;/** GST-2731: the company docs folder imported read only with --shape company; null for --docs none. */docs?: string | null;+ /** GST-2731: the call-transcript folder imported read only into the company source; null for --transcripts none. */+ transcripts?: string | null;/** GST-2731: --team, the company part lives on a shared brain; setup prints the route and creates nothing for it. */team?: boolean;}-const VALUE_FLAGS = new Set(['--shape', '--notes', '--docs', '--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading', '--agent', '--live-fraction', '--pins-route', '--owner-sender', '--serves', '--members', '--members-file', '--stdio-member']);+const VALUE_FLAGS = new Set(['--shape', '--notes', '--docs', '--transcripts', '--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading', '--agent', '--live-fraction', '--pins-route', '--owner-sender', '--serves', '--members', '--members-file', '--stdio-member']);function parseFlags(args: string[]): SetupFlags | string {const value = (flag: string): string | undefined => {@@ -727,13 +734,13 @@ function liveServeConflict(live: NonNullable<Target['live_owner']>, harness: Set* (nothing is written until it is answered, --yes included).*/async function layoutFor(harness: SetupHarnessId, flags: SetupFlags, launcher: string, instructions: BrainFirstOutcome | null, brainCreate: boolean): Promise<{ outcome: LayoutOutcome | null; notices: (base: Notice[]) => Notice[] }> {- let shape: { brain?: BrainShape; notes?: string | null; docs?: string | null; team?: boolean } = { brain: flags.brain, notes: flags.notes, docs: flags.docs, team: flags.team };+ let shape: { brain?: BrainShape; notes?: string | null; docs?: string | null; transcripts?: string | null; team?: boolean } = { brain: flags.brain, notes: flags.notes, docs: flags.docs, transcripts: flags.transcripts, team: flags.team };const ask = brainCreate && !shape.brain;if (ask && !flags.json && isInteractive()) shape = await askBrainShape();const scope = flags.scope ?? 'user';const source = flags.source ?? (process.env.GBRAIN_SOURCE && isValidSourceId(process.env.GBRAIN_SOURCE) ? process.env.GBRAIN_SOURCE : null);const outcome = applyBrainLayout({ harness, scope, source, launcher, instructionsPath: instructions?.path ?? null, instructionsDeclined: instructions?.decision.value === 'declined',- flags: { brain: shape.brain, notes: shape.notes, docs: shape.docs, team: shape.team, dryRun: flags.dryRun } });+ flags: { brain: shape.brain, notes: shape.notes, docs: shape.docs, transcripts: shape.transcripts, team: shape.team, dryRun: flags.dryRun } });return { outcome, notices: (base) => [...(ask && !shape.brain ? withBrainShape(base, brainShapeDecision(harness, undefined, scope, source)) : base), ...layoutNotices(outcome, harness, scope, source)] };}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 1662828681..5fe082b3e1 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--only', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--room', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--card', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--all-sources', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--body', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--calls', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--concurrent', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--days', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--finalize', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--from-prefix', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--history', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--labelled-only', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-open-pages', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--priority', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--push-remote', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--read-sources', '--reader-mode', '--readers', '--reads-unscoped', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--room', '--root', '--routing', '--rules', '--run', '--runtime', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--strict-json', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--synopsis', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unattended', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unschedule', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--wakeshift', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--card', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -78,11 +78,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'guests': ['--add', '--brain', '--client', '--guest-source', '--help', '--id', '--if-version', '--json', '--read-sources', '--source', '--sources', '--to', '--writer', '--yes'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--sdk-url', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--verify', '--workspace', '--yes'],- 'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],+ 'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--calls', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--prefix', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--admin-intent', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-stdio-member', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--reason', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--room', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--alert', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--card', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-revision', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finalize', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--out', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--patch', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--privacy-url', '--probe', '--propose', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reads-unscoped', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--schedule', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--synopsis', '--target', '--terms-url', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--unattended', '--uninstall', '--unschedule', '--unshallow', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wakeshift', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--alert', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--calls', '--card', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--drop-field', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-revision', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filter', '--filters', '--finalize', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-content', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--migrate-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--out', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--patch', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--prefix', '--preview', '--priority', '--privacy-url', '--probe', '--propose', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--readers', '--reads-unscoped', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--schedule', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--serves', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdio-member', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--synopsis', '--target', '--terms-url', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--unattended', '--uninstall', '--unschedule', '--unshallow', '--untrack', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wakeshift', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--readers', '--rebase', '--require-clean', '--resolve', '--room', '--scan-secrets', '--scan-timeout', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],@@ -125,7 +125,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--apply', '--backend', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--labelled-only', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-open-pages', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--command', '--credentials-file', '--docs', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--held', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embed', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--notes', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--shape', '--show-toplevel', '--skill-loading', '--skills-index-only', '--solo', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--team', '--token', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--calls', '--capture', '--catalog', '--command', '--credentials-file', '--docs', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--held', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embed', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--notes', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--prefix', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--shape', '--show-toplevel', '--skill-loading', '--skills-index-only', '--solo', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--team', '--token', '--transcripts', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--no-extensions', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--show-toplevel', '--skill-loading', '--source', '--text', '--top-gate', '--top-k'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],@@ -136,7 +136,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--reason', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--apply', '--brain', '--card', '--client', '--dir', '--drop-field', '--dry-run', '--expect', '--expected-revision', '--finalize', '--from-prefix', '--help', '--id', '--json', '--jsonl', '--only', '--out', '--patch', '--plan', '--push-remote', '--repo', '--restore-only', '--restored-to', '--scopes', '--source', '--status', '--store', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--room', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--alert', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get', '--get-regexp', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--watch', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--alert', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-read', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--calls', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get', '--get-regexp', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--priority', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--watch', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dir', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--from', '--full', '--held', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--room', '--since', '--source', '--source-id', '--timeout', '--timings', '--to', '--wait'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex a837195631..c407804e3f 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -288,6 +288,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['transcript_secret_exposure',// GST-2768: the conversation archive keeping up with the harness sessions (doctor/checks/transcript-archive.ts).'transcript_archive_freshness',+ // GST-2731: facts pages with undated fact lines (doctor/checks/facts-pages.ts).+ 'facts_undated_lines',// #5254 — pages written database-only to a source with no canonical owner.'unbound_source','undeclared_db_only_pages',diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex 5dcb94380f..ba92c50eb1 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -119,9 +119,10 @@ async function segmentedSampleWindows(engine: BrainEngine, pageId: number): Prom/*** GST-2768: holds that apply to a page of any size. A small page is otherwise unmetered, so the conversation archive's* backfill (archive_backfill: waits for the owner's approval of the previewed cost) and its open day (archive_open_day:- * waits until the day closes or goes quiet) name the page here and the embed paths skip it until then.+ * waits until the day closes or goes quiet) name the page here and the embed paths skip it until then. GST-2731: an+ * imported call transcript (call_import: gbrain import --calls) is held the same way until the owner approves it.*/-export const ANY_SIZE_HOLD_REASONS: readonly string[] = ['archive_backfill', 'archive_open_day'];+export const ANY_SIZE_HOLD_REASONS: readonly string[] = ['archive_backfill', 'archive_open_day', 'call_import'];/*** One point read per plan: the archive's frontmatter hold marker (transcript_archive.embedding_hold) and the page's@@ -131,7 +132,7 @@ export const ANY_SIZE_HOLD_REASONS: readonly string[] = ['archive_backfill', 'ar*/async function readHolds(engine: BrainEngine, pageId: number): Promise<{ marker: string | null; state: string | null; reason: string | null }> {const [row] = await engine.executeRaw<{ marker: string | null; state: string | null; reason: string | null }>(- `SELECT p.frontmatter->'transcript_archive'->>'embedding_hold' AS marker, b.state, b.reason+ `SELECT COALESCE(p.frontmatter->'transcript_archive'->>'embedding_hold', p.frontmatter->'call_import'->>'embedding_hold') AS marker, b.state, b.reasonFROM pages p LEFT JOIN page_embedding_budget b ON b.page_id = p.id WHERE p.id = $1`, [pageId]);return row ?? { marker: null, state: null, reason: null };}diff --git a/src/core/page-size-policy.ts b/src/core/page-size-policy.tsindex d00b56caab..1ff66bb270 100644--- a/src/core/page-size-policy.ts+++ b/src/core/page-size-policy.ts@@ -49,12 +49,12 @@ export function largePageBodyFilter(alias: string): string {* `pages` row aliased `page`: the row is held or capped and still applies.* The budget meters large pages only, so a row left on a page edited down to* the inline threshold or under no longer applies, except a conversation-archive- * hold (archive_backfill, archive_open_day; GST-2768), which applies at any size. The one rule the embedding+ * hold (archive_backfill, archive_open_day; GST-2768) or an imported call's hold (call_import; GST-2731), which apply at any size. The one rule the embedding* queue, the held list (`gbrain embed --held`) and the held count (doctor* `partial_embedding`) share.*/export function budgetRowAppliesFilter(budget: string, page: string): string {- return `${budget}.state <> 'open' AND (${largePageBodyFilter(page)} OR ${budget}.reason IN ('archive_backfill', 'archive_open_day'))`;+ return `${budget}.state <> 'open' AND (${largePageBodyFilter(page)} OR ${budget}.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))`;}/** SQL over a `pages` row aliased `alias`: the page has a held or capped budget row that still applies (budgetRowAppliesFilter). */diff --git a/src/core/schema-pack/base/gbrain-base-v2.yaml b/src/core/schema-pack/base/gbrain-base-v2.yamlindex 30f32a568f..e7c3e340c9 100644--- a/src/core/schema-pack/base/gbrain-base-v2.yaml+++ b/src/core/schema-pack/base/gbrain-base-v2.yaml@@ -17,6 +17,9 @@# v1.6.0 adds `stored-object`, the type the storage verbs stamp on each# card on the storage shelf (and on interim records storage adopt moves# onto it): a non-extractable annotation outside the content taxonomy.+# v1.7.0 adds `facts`, the type gbrain setup stamps on the me/facts and+# company/facts starter pages (one dated line per fact): a non-extractable+# annotation outside the content taxonomy, set via frontmatter only.## STANDALONE pack (D11/F1): NO `extends:` field. Declaring inheritance# would compose gbrain-base's 24 types on top of the 16 declared here,@@ -39,7 +42,7 @@api_version: gbrain-schema-pack-v1name: gbrain-base-v2-version: 1.6.0+version: 1.7.0description: 15-type DRY/MECE canonical taxonomy + `note` catch-all (16 total). Successor to gbrain-base. Issue #1479.gbrain_min_version: 0.42.0extends: null@@ -371,6 +374,16 @@ page_types:extractable: falseexpert_routing: false+ # Quotable facts page (GST-2731): one dated line per fact, with where it came+ # from (me/facts, company/facts); agents quote only its dated lines, and+ # doctor's facts_undated_lines names a line with no date. Set via frontmatter only.+ - name: facts+ primitive: annotation+ path_prefixes: []+ aliases: []+ extractable: false+ expert_routing: false+# A pinned question's page (src/core/questions/pages.ts); the answer# lives in pinned_questions. Owner-private and never evidence. Set via# frontmatter only, so an existing questions/ folder keeps its own types.diff --git a/src/core/schema-pack/base/gbrain-base.yaml b/src/core/schema-pack/base/gbrain-base.yamlindex 6b39991582..f915532511 100644--- a/src/core/schema-pack/base/gbrain-base.yaml+++ b/src/core/schema-pack/base/gbrain-base.yaml@@ -305,6 +305,16 @@ page_types:extractable: falseexpert_routing: false+ # Quotable facts page (GST-2731): one dated line per fact, with where it came+ # from (me/facts, company/facts); agents quote only its dated lines, and+ # doctor's facts_undated_lines names a line with no date. Set via frontmatter only.+ - name: facts+ primitive: annotation+ path_prefixes: []+ aliases: []+ extractable: false+ expert_routing: false+# Pinned question page (C4): the question and the owner's notes; the answer# lives in pinned_questions. Owner-private and never evidence. Set via# frontmatter only, so an existing questions/ folder keeps its own types.diff --git a/src/core/types.ts b/src/core/types.tsindex 53f7ffa010..9fce9b0b10 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -65,6 +65,7 @@ export const ALL_PAGE_TYPES: readonly string[] = [// never mined into the facts table). Pack entries in gbrain-base.yaml.'event', 'diary','question', // C4 pinned-question page (question + owner notes; owner-private, never evidence; src/core/questions/pages.ts)+ 'facts', // GST-2731 quotable facts page (me/facts, company/facts): one dated line per fact; doctor facts_undated_lines] as const;/**diff --git a/test/doctor-facts-undated-lines.test.ts b/test/doctor-facts-undated-lines.test.tsnew file mode 100644index 0000000000..369d9e2c20--- /dev/null+++ b/test/doctor-facts-undated-lines.test.ts@@ -0,0 +1,50 @@+/**+ * facts_undated_lines doctor check (GST-2731): a facts page (type: facts) with fact lines that carry no date is+ * named with its line numbers, read-only, with a fix that names the page.+ *+ * PGLite in-memory ($0).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { factsUndatedLines, undatedFactLines } from '../src/commands/doctor/checks/facts-pages.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);++describe('facts_undated_lines doctor check', () => {+ test('undated list lines are found by line number', () => {+ expect(undatedFactLines('Intro text without a date.\n\n- 2026-01-01: 12 customers. Source: billing.\n- 15 customers now\n* 3. two founders\n1. 2026-02-02: dated\n')).toEqual([4, 5]);+ });++ test('a facts page whose lines all carry a date is ok, and the check reads as brain health', async () => {+ await engine.putPage('company/facts', { type: 'facts', title: 'Company facts', compiled_truth: 'Numbers agents may quote.\n\n- 2026-01-01: 12 paying customers. Source: billing export.\n' });+ const check = await factsUndatedLines(engine);+ expect(check.status).toBe('ok');+ expect(categorizeCheck('facts_undated_lines')).toBe('brain');+ });++ test('a facts page with an undated line is a warn naming the page and the line, never its text', async () => {+ await engine.putPage('me/facts', { type: 'facts', title: 'Facts about me', compiled_truth: 'True things about me.\n\n- 2026-01-01: I live in example-city.\n- I like tea\n' });+ await engine.putPage('notes/todo', { type: 'note', title: 'Todo', compiled_truth: '- buy milk\n' });+ const before = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages');+ const check = await factsUndatedLines(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('default:me/facts (line 4)');+ expect(check.message).not.toContain('I like tea');+ expect(check.message).not.toContain('notes/todo');+ expect((check.details as any).pages).toEqual([{ source_id: 'default', slug: 'me/facts', lines: [4] }]);+ expect((check.fix as any).argv).toEqual(['gbrain', 'get', 'me/facts', '--source', 'default']);+ expect((check.fix as any).ask_user).toBe(true);+ expect((check.fix as any).user_message).toContain('me/facts');+ expect((check.fix as any).verify.argv).toEqual(['gbrain', 'doctor', '--only', 'facts_undated_lines', '--json']);+ expect(await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages')).toEqual(before);+ });+});diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex d1b27839d6..0d4c47829b 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -55,7 +55,7 @@" [INFO] harness_wiring: No agent harness was detected. Wire one when the user picks an agent app."," [OK] agent_contract: No agent dead ends in the last 7 days (0 non-success event(s) logged)."," [OK] connection: Connected, 5 pages",- " [OK] persistence_capacity: No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 116115 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.",+ " [OK] persistence_capacity: No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 116700 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592."," [OK] persistence_terminal_failures: No terminal write failures in the last 7 d."," [OK] managed_sync_not_moving: No managed sync is pending."," [OK] managed_sync_blocked: No managed sync run is blocked.",@@ -285,6 +285,7 @@" [OK] embedding_plane_disagreement: The config file disables embeddings and the database holds no vectors."," [INFO] mcp_request_log_retention: The MCP request log holds 0 row(s) (0.0 MB); request-log retention is off, so it keeps every request."," [INFO] storage_manifest: No storage shelf and no interim storage records on this brain.",+ " [OK] facts_undated_lines: Every fact line on 0 facts page(s) carries a date."," [OK] fence_integrity: No malformed facts or takes fence is held, stored or waiting in a checkout (2 source(s) scanned)."," [OK] search_mode: Mode: conservative (no per-key overrides — mode bundle is canonical)."," [INFO] synopsis_tier_coverage: Not applicable: the configured contextual-retrieval tier is none, not per_chunk_synopsis.",@@ -312,8 +313,8 @@" [OK] entity_link_coverage: Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale"," [OK] timeline_coverage: Only 2 entity pages (< 5) — coverage ratio not meaningful at this scale"," [INFO] takes_count: 0 takes (takes.bootstrap_enabled is false; opt in to enable)",- " [OK] pack_upgrade_available: Active pack [email protected]+b2cec967 is current (no successor declared)",- " [OK] type_proliferation: 3 distinct typed values (pack gbrain-base-v2 declares 24)",+ " [OK] pack_upgrade_available: Active pack [email protected]+e142684a is current (no successor declared)",+ " [OK] type_proliferation: 3 distinct typed values (pack gbrain-base-v2 declares 25)"," [OK] dangling_aliases: No dangling aliases","Brain checks: 60/100 (category penalty)","Skill checks: 95/100",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 209bcd9e42..d965c72f9f 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -528,7 +528,7 @@"explicit_retention_days": null,"over_target": false,"target_bytes": 8589934592,- "used_bytes": 116115+ "used_bytes": 116700},"inspected": 2,"outstanding": [],@@ -538,7 +538,7 @@"verify": "gbrain doctor --only persistence_capacity --json"},"elapsed_ms": "<volatile>",- "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 116115 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.",+ "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 116700 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.","name": "persistence_capacity","status": "ok"},@@ -4237,6 +4237,13 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Every fact line on 0 facts page(s) carries a date.",+ "name": "facts_undated_lines",+ "status": "ok"+ },{"category": "brain","details": {@@ -4683,14 +4690,14 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "Active pack [email protected]+b2cec967 is current (no successor declared)",+ "message": "Active pack [email protected]+e142684a is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},{"category": "meta","elapsed_ms": "<volatile>",- "message": "3 distinct typed values (pack gbrain-base-v2 declares 24)",+ "message": "3 distinct typed values (pack gbrain-base-v2 declares 25)","name": "type_proliferation","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 4c11ea23af..5e67792feb 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -529,7 +529,7 @@"explicit_retention_days": null,"over_target": false,"target_bytes": 8589934592,- "used_bytes": 198727+ "used_bytes": 199663},"inspected": 2,"outstanding": [],@@ -539,7 +539,7 @@"verify": "gbrain doctor --only persistence_capacity --json"},"elapsed_ms": "<volatile>",- "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 198727 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.",+ "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 199663 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.","name": "persistence_capacity","status": "ok"},@@ -4501,6 +4501,13 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Every fact line on 0 facts page(s) carries a date.",+ "name": "facts_undated_lines",+ "status": "ok"+ },{"category": "brain","details": {@@ -5114,14 +5121,14 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "Active pack [email protected]+b2cec967 is current (no successor declared)",+ "message": "Active pack [email protected]+e142684a is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},{"category": "meta","elapsed_ms": "<volatile>",- "message": "5 distinct typed values (pack gbrain-base-v2 declares 24)",+ "message": "5 distinct typed values (pack gbrain-base-v2 declares 25)","name": "type_proliferation","status": "ok"},@@ -5975,7 +5982,7 @@"explicit_retention_days": null,"over_target": false,"target_bytes": 8589934592,- "used_bytes": 198727+ "used_bytes": 199663},"inspected": 2,"outstanding": [],@@ -5985,7 +5992,7 @@"verify": "gbrain doctor --only persistence_capacity --json"},"elapsed_ms": "<volatile>",- "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 198727 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.",+ "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 199663 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.","name": "persistence_capacity","status": "ok"},@@ -9959,6 +9966,13 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Every fact line on 0 facts page(s) carries a date.",+ "name": "facts_undated_lines",+ "status": "ok"+ },{"category": "brain","details": {@@ -10572,14 +10586,14 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "Active pack [email protected]+b2cec967 is current (no successor declared)",+ "message": "Active pack [email protected]+e142684a is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},{"category": "meta","elapsed_ms": "<volatile>",- "message": "5 distinct typed values (pack gbrain-base-v2 declares 24)",+ "message": "5 distinct typed values (pack gbrain-base-v2 declares 25)","name": "type_proliferation","status": "ok"},diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex a3b69318e5..916abd8d7d 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -523,7 +523,7 @@"explicit_retention_days": null,"over_target": false,"target_bytes": 8589934592,- "used_bytes": 199780+ "used_bytes": 200716},"inspected": 2,"outstanding": [],@@ -533,7 +533,7 @@"verify": "gbrain doctor --only persistence_capacity --json"},"elapsed_ms": "<volatile>",- "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 199780 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.",+ "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 200716 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.","name": "persistence_capacity","status": "ok"},@@ -4507,6 +4507,13 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Every fact line on 0 facts page(s) carries a date.",+ "name": "facts_undated_lines",+ "status": "ok"+ },{"category": "brain","details": {@@ -5118,14 +5125,14 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "Active pack [email protected]+b2cec967 is current (no successor declared)",+ "message": "Active pack [email protected]+e142684a is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},{"category": "meta","elapsed_ms": "<volatile>",- "message": "5 distinct typed values (pack gbrain-base-v2 declares 24)",+ "message": "5 distinct typed values (pack gbrain-base-v2 declares 25)","name": "type_proliferation","status": "ok"},@@ -5973,7 +5980,7 @@"explicit_retention_days": null,"over_target": false,"target_bytes": 8589934592,- "used_bytes": 199780+ "used_bytes": 200716},"inspected": 2,"outstanding": [],@@ -5983,7 +5990,7 @@"verify": "gbrain doctor --only persistence_capacity --json"},"elapsed_ms": "<volatile>",- "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 199780 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.",+ "message": "No cumulative write cap is set (the default), so receipt storage never refuses or pauses a write; it holds 200716 reserved bytes, and receipts not yet compacted are under the housekeeping target of 8589934592.","name": "persistence_capacity","status": "ok"},@@ -9969,6 +9976,13 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Every fact line on 0 facts page(s) carries a date.",+ "name": "facts_undated_lines",+ "status": "ok"+ },{"category": "brain","details": {@@ -10580,14 +10594,14 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "Active pack [email protected]+b2cec967 is current (no successor declared)",+ "message": "Active pack [email protected]+e142684a is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},{"category": "meta","elapsed_ms": "<volatile>",- "message": "5 distinct typed values (pack gbrain-base-v2 declares 24)",+ "message": "5 distinct typed values (pack gbrain-base-v2 declares 25)","name": "type_proliferation","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex b8c9b5c15b..9aee17f45f 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -3860,6 +3860,13 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Every fact line on 0 facts page(s) carries a date.",+ "name": "facts_undated_lines",+ "status": "ok"+ },{"category": "brain","details": {@@ -4216,7 +4223,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "Active pack [email protected]+b2cec967 is current (no successor declared)",+ "message": "Active pack [email protected]+e142684a is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex e64b64647e..65e2eca0a8 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -3905,6 +3905,13 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Every fact line on 0 facts page(s) carries a date.",+ "name": "facts_undated_lines",+ "status": "ok"+ },{"category": "brain","details": {@@ -4303,7 +4310,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "Active pack [email protected]+b2cec967 is current (no successor declared)",+ "message": "Active pack [email protected]+e142684a is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex e4772626a2..298450dc3b 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -3911,6 +3911,13 @@"severity": "info","status": "ok"},+ {+ "category": "brain",+ "elapsed_ms": "<volatile>",+ "message": "Every fact line on 0 facts page(s) carries a date.",+ "name": "facts_undated_lines",+ "status": "ok"+ },{"category": "brain","details": {@@ -4307,7 +4314,7 @@{"category": "meta","elapsed_ms": "<volatile>",- "message": "Active pack [email protected]+b2cec967 is current (no successor declared)",+ "message": "Active pack [email protected]+e142684a is current (no successor declared)","name": "pack_upgrade_available","status": "ok"},diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 54364ced33..53e4993d0a 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -1229,6 +1229,10 @@"category": "brain","name": "storage_manifest"},+ {+ "category": "brain",+ "name": "facts_undated_lines"+ },{"category": "brain","name": "fence_integrity"diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex 82c5fc378f..3540969f7c 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -33,8 +33,8 @@{"lane": "pool","params": [],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day')))",- "textSha256": "015e51a8ca10ded927bee5668092ab805f640a595a1fbe855dbd59d92216d9ee"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import')))",+ "textSha256": "a663c3904d099236b662aa2d95fcd384795fb5dd2e15691d70b328f4c067aa06"}],"signature+includeNullSignature": [@@ -49,8 +49,8 @@"params": ["string"],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR p.embedding_signature IS NULL OR p.embedding_signature <> $1) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day')))",- "textSha256": "57e533d34617f6186517a738198fb71b8b96255252ae8403813386061480a16f"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR p.embedding_signature IS NULL OR p.embedding_signature <> $1) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import')))",+ "textSha256": "ebb4c40746760a4e6702c9d61384848741b5e903cd46652d5b3ce6d09abeada5"}],"signature+sourceId": [@@ -66,8 +66,8 @@"string","string"],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) AND p.source_id = $2",- "textSha256": "cd7f5c8b2b3e27b383966bcd8ffb75a15ac5808700da532207fd8bdcb6c8f105"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) AND p.source_id = $2",+ "textSha256": "e049c07d6e1c4aabbc98f97034c1e3baa0679f0f7d396b92b395028c157603b5"}]},@@ -414,8 +414,8 @@"params": ["array<>"],- "sql": "WITH b AS (SELECT id FROM content_chunks WHERE id > 0 ORDER BY id LIMIT 5000), w AS (UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM b, pages p WHERE cc.id = b.id AND cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) RETURNING 1) SELECT (SELECT max(id) FROM b) AS last_id, (SELECT count(*) FROM b)::int AS checked, (SELECT count(*) FROM w)::int AS drifted",- "textSha256": "ac05675d4616689d3a83b47a484d97ca0adeefa087c60c1a4e3f2de782ae8b75"+ "sql": "WITH b AS (SELECT id FROM content_chunks WHERE id > 0 ORDER BY id LIMIT 5000), w AS (UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM b, pages p WHERE cc.id = b.id AND cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) RETURNING 1) SELECT (SELECT max(id) FROM b) AS last_id, (SELECT count(*) FROM b)::int AS checked, (SELECT count(*) FROM w)::int AS drifted",+ "textSha256": "4a44b5842e9de8097942f6266fc4cb466a2d3df9695ac837814f8cf50375b0e8"},{"event": "commit",@@ -448,8 +448,8 @@"array<>","string"],- "sql": "WITH b AS (SELECT id FROM content_chunks WHERE id > 0 ORDER BY id LIMIT 5000), w AS (UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM b, pages p WHERE cc.id = b.id AND cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) AND p.source_id = $2 RETURNING 1) SELECT (SELECT max(id) FROM b) AS last_id, (SELECT count(*) FROM b)::int AS checked, (SELECT count(*) FROM w)::int AS drifted",- "textSha256": "100146b42933adf362f4e85559488eb79967fcfd1981f51133af1f0021b982ee"+ "sql": "WITH b AS (SELECT id FROM content_chunks WHERE id > 0 ORDER BY id LIMIT 5000), w AS (UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM b, pages p WHERE cc.id = b.id AND cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) AND p.source_id = $2 RETURNING 1) SELECT (SELECT max(id) FROM b) AS last_id, (SELECT count(*) FROM b)::int AS checked, (SELECT count(*) FROM w)::int AS drifted",+ "textSha256": "94e086bbdf01347db6b34549cd9ac847ef709a63c2e11a9762a1f6d979b70b5f"},{"event": "commit",@@ -571,8 +571,8 @@"array<string>","number"],- "sql": "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 ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND (p.text_projection_revision IS DISTINCT FROM p.knowledge_revision OR COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ) r WHERE r.state = ANY($2::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $3",- "textSha256": "f478914714700c6ef4c75ac988da7b889ce83263aa2b106c86f297a9c5a04479"+ "sql": "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 ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND (p.text_projection_revision IS DISTINCT FROM p.knowledge_revision OR COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ) r WHERE r.state = ANY($2::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $3",+ "textSha256": "2567175a7dec0303306389a8e98d1e48bf83b152789215f015b310583aec3c80"}],"sourceIds": [@@ -591,8 +591,8 @@"array<string>","number"],- "sql": "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 ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[]) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND (p.text_projection_revision IS DISTINCT FROM p.knowledge_revision OR COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($3::text[]) ) r WHERE r.state = ANY($4::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $5",- "textSha256": "0cf94bb28cbf6fd1783b69ef51662416c561a56e9383e7f829ae53802757153b"+ "sql": "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 ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[]) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND (p.text_projection_revision IS DISTINCT FROM p.knowledge_revision OR COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($3::text[]) ) r WHERE r.state = ANY($4::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $5",+ "textSha256": "9ba132a7239b5b886dbded0f9266b1a038cf22c9961fdec1c6821c1591f6cad9"}]},@@ -611,8 +611,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($1, $2) ORDER BY cc.page_id, cc.chunk_index LIMIT $3",- "textSha256": "4f366ddb0cb5375db52db9848a68ee86ae47a507423190fa6b5da4d113676d38"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($1, $2) ORDER BY cc.page_id, cc.chunk_index LIMIT $3",+ "textSha256": "1fd270e62a63b3ebd67b1c986942f29d55c988f6a75189bb71726851f10e35d3"}],"sourceId": [@@ -630,8 +630,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($2, $3) ORDER BY cc.page_id, cc.chunk_index LIMIT $4",- "textSha256": "dc90c85af7d570cd7f06818d3e6d7c4dfc59bfb650ed638b4b30d0ec36d27bbd"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($2, $3) ORDER BY cc.page_id, cc.chunk_index LIMIT $4",+ "textSha256": "939a1b43407b094d58b33047360c3454f89b62629ba98aa9fbf93bffdda6a7b5"}],"updated_desc": [@@ -646,8 +646,8 @@"params": ["number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $1",- "textSha256": "456bc381607a7ff5de75acaa1539f6b1b7d9f31d3b96bb10019137d555eb795c"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $1",+ "textSha256": "85d736052c5e4b3e81f9ab58b749fcbc71a89848b0f642ceadc94180382b4cb1"}],"updated_desc+cursor": [@@ -668,8 +668,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $1::timestamptz OR (p.updated_at = $2::timestamptz AND p.id > $3) OR (p.updated_at = $4::timestamptz AND p.id = $5 AND cc.chunk_index > $6) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $7",- "textSha256": "f1cf43d12e7078f9f0154081c928c7a77089262ef960e8274c2a203ddd022fb5"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $1::timestamptz OR (p.updated_at = $2::timestamptz AND p.id > $3) OR (p.updated_at = $4::timestamptz AND p.id = $5 AND cc.chunk_index > $6) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $7",+ "textSha256": "771dc9a75473d91ea484b5bc8caf673424909fb79a1ff72cc523aa2eb07cb8b3"}],"updated_desc+sourceId": [@@ -685,8 +685,8 @@"string","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $2",- "textSha256": "8b6584cacd80ae18d63de7ce9eb92b76becbb22683c60ff9a1058754e2a9802d"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $2",+ "textSha256": "bd52a3d1dc0bb20de62e66aa8cc09e42ec0a06dbe87ca37938d9daabe982da69"}],"updated_desc+sourceId+cursor": [@@ -708,8 +708,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $2::timestamptz OR (p.updated_at = $3::timestamptz AND p.id > $4) OR (p.updated_at = $5::timestamptz AND p.id = $6 AND cc.chunk_index > $7) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $8",- "textSha256": "abe659f4d029c2a83bd8eadf25841a8326fd84e5a26a717e928e93f6c61cb399"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $2::timestamptz OR (p.updated_at = $3::timestamptz AND p.id > $4) OR (p.updated_at = $5::timestamptz AND p.id = $6 AND cc.chunk_index > $7) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $8",+ "textSha256": "3526a897637b33b4643094e917d845616e394bf5addbc3f479ef4b098f9f8d5e"}]},@@ -726,8 +726,8 @@"params": ["number"],- "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation))))) s GROUP BY s.state",- "textSha256": "ddb89f41cb9a37812467b2f20c9176687e9b0b043340f74d62cb92a3ed179f68"+ "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation))))) s GROUP BY s.state",+ "textSha256": "6e491e2b84d4d12f26d013d073c930d54b8929b108f53c7912b1d44651204768"},{"lane": "pool",@@ -755,8 +755,8 @@"number","array<string>"],- "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[])) s GROUP BY s.state",- "textSha256": "ea7342850de4b013bf3221c8e89bbafa30a9f62d751f99cb0db7318945c55fae"+ "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[])) s GROUP BY s.state",+ "textSha256": "923843ec2d34cdd38e6906ba5d0bd094c057989847ecaae0759db0c8a989a2aa"},{"lane": "pool",@@ -817,8 +817,8 @@{"lane": "pool","params": [],- "sql": "SELECT COALESCE(SUM(chars), 0)::bigint AS chars FROM (SELECT LENGTH(cc.chunk_text) AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day')))) stale",- "textSha256": "349bd8fa1be77137951bc1425da68b823145e2a2da20327922749e5c56bb039c"+ "sql": "SELECT COALESCE(SUM(chars), 0)::bigint AS chars FROM (SELECT LENGTH(cc.chunk_text) AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import')))) stale",+ "textSha256": "f0cc171bb8bb632a6228fd36c54d71e46939429228b6cb6358d5757726493b1c"}],"signature": [@@ -833,8 +833,8 @@"params": ["string"],- "sql": "SELECT COALESCE(SUM(chars), 0)::bigint AS chars FROM (SELECT LENGTH(cc.chunk_text) AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day'))) UNION ALL SELECT LENGTH(cc.chunk_text) AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NOT NULL AND p.embedding_signature <> $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day')))) stale",- "textSha256": "3124e504b8f95f784713ef345561b78e5fa065b928cbb75efe157c8254062cdc"+ "sql": "SELECT COALESCE(SUM(chars), 0)::bigint AS chars FROM (SELECT LENGTH(cc.chunk_text) AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import'))) UNION ALL SELECT LENGTH(cc.chunk_text) AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NOT NULL AND p.embedding_signature <> $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND ((CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576 OR peb.reason IN ('archive_backfill', 'archive_open_day', 'call_import')))) stale",+ "textSha256": "74f8b46ef5d9cb5feec2887756fe194684876379bb792caaec6024b79013e774"}]},diff --git a/test/import-calls.test.ts b/test/import-calls.test.tsnew file mode 100644index 0000000000..1231325bb2--- /dev/null+++ b/test/import-calls.test.ts@@ -0,0 +1,203 @@+/**+ * GST-2731 (GBRA-529 PR 3): `gbrain import <dir> --calls` (src/commands/import-calls.ts), the opt-in text mode for+ * exported call and meeting transcripts.+ *+ * Authoring gate:+ * 1. Protects: each .txt/.md call file becomes one page named from its date and title, its words kept, every+ * credential redacted by the archive's transcript redaction before anything is stored, no readable_by of its+ * own, keyword-only and out of the facts backstop; a rerun writes nothing again.+ * 2. Fails on: a planted credential in a stored page, a call imported twice, a changed file overwriting its page,+ * a --prefix value read as the import folder, a page written under conversations/.+ * 3. A new mode on an existing command; test/setup-brain-layout.test.ts covers it through gbrain setup.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { randomBytes } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';+import { callPageFor, listCallFiles } from '../src/commands/import-calls.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { listBudgetLimitedPages, planPageEmbedding } from '../src/core/page-embedding-budget.ts';++const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });+const temp = (prefix: string): string => { const d = mkdtempSync(join(tmpdir(), prefix)); roots.push(d); return d; };+const plantedToken = (): string => 'github' + '_pat_' + randomBytes(24).toString('hex');+const MTIME = new Date(2026, 0, 15, 12).getTime();++describe('call pages', () => {+ test('date and title come from a dated file name, else the first line, else the modified day', () => {+ const named = callPageFor('2026-03-04 acme-example renewal.txt', 'Alice: hello\n', MTIME, 'company/calls', []);+ expect(named).toMatchObject({ slug: 'company/calls/2026-03-04-acme-example-renewal', title: 'acme example renewal', date: '2026-03-04', date_from: 'file_name' });+ const line = callPageFor('q1/notes.md', '# Weekly sync 2026-02-01\n\nAlice: hi\n', MTIME, 'company/calls', []);+ expect(line).toMatchObject({ slug: 'company/calls/2026-02-01-weekly-sync', title: 'Weekly sync', date: '2026-02-01', date_from: 'first_line' });+ const neither = callPageFor('kickoff.txt', 'Kickoff with acme-example\nBob: hi\n', MTIME, 'calls', []);+ expect(neither).toMatchObject({ slug: 'calls/2026-01-15-kickoff-with-acme-example', date: '2026-01-15', date_from: 'modified' });+ expect(callPageFor('2026-13-45 odd.txt', 'Odd call\n', MTIME, 'calls', []).date_from).toBe('modified');+ const fm = callPageFor('call.md', '---\nfrom: export\n---\nStandup 2026-05-06\nhi\n', MTIME, 'calls', []);+ expect(fm).toMatchObject({ date: '2026-05-06', title: 'Standup' });+ });++ test('the words are kept, credentials are redacted, structure lines are neutral, and the page names no readers', () => {+ const token = plantedToken();+ const page = callPageFor('2026-03-04 sync.txt', `Alice: we agreed on annual billing.\nBob: my key is ${token} ok\n## Timeline\n`, MTIME, 'calls', []);+ expect(page.content).toContain('Alice: we agreed on annual billing.');+ expect(page.content).not.toContain(token);+ expect(page.content).toContain('Bob: my key is <REDACTED:github_pat> ok');+ expect(page.redactions).toBe(1);+ expect(page.content).toContain('\n\\## Timeline');+ expect(page.content).toContain('\nfacts_backstop: false\n');+ expect(page.content).toContain('\ntype: meeting\n');+ expect(page.content).not.toContain('readable_by');+ expect(callPageFor('2026-03-04 sync.txt', `Alice: we agreed on annual billing.\nBob: my key is ${token} ok\n## Timeline\n`, MTIME, 'calls', []).hash).toBe(page.hash);+ });++ test('a credential in a file name stays redacted in the title, though the title turns separators into spaces', () => {+ const token = plantedToken();+ const page = callPageFor(`2026-03-04 ${token}.txt`, 'Alice: hi\n', MTIME, 'calls', []);+ const payload = token.slice('github_pat_'.length);+ expect(page.content).not.toContain(payload);+ expect(page.title).not.toContain(payload);+ expect(page.slug).not.toContain(payload);+ expect(page.title).toContain('<REDACTED:github_pat>');+ });++ test('a digits-only folder id and content hash read back as the same strings', () => {+ const page = callPageFor('2026-03-04 sync.txt', 'Alice: hi\n', MTIME, 'calls', [], '012345678901');+ const ci = parseMarkdown(page.content).frontmatter.call_import as { root: unknown; hash: unknown };+ expect(ci.root).toBe('012345678901');+ expect(ci.hash).toBe(page.hash);+ });++ test('only .txt and .md files are listed; dot entries and symlinks are skipped', () => {+ const dir = temp('gbrain-calls-list-');+ mkdirSync(join(dir, 'sub'));+ mkdirSync(join(dir, '.hidden'));+ for (const f of ['a.txt', 'sub/b.md', '.hidden/c.txt', '.d.txt', 'e.pdf']) writeFileSync(join(dir, f), 'x\n');+ symlinkSync(join(dir, 'a.txt'), join(dir, 'link.txt'));+ expect(listCallFiles(dir)).toEqual([join(dir, 'a.txt'), join(dir, 'sub', 'b.md')]);+ });+});++describe('operations filter guard', () => {+ test('accepts the call importer as a local put_page caller', () => {+ const guard = spawnSync('bash', [join(import.meta.dir, '..', 'scripts/check-operations-filter-bypass.sh')], { encoding: 'utf8' });+ expect(guard.stderr + guard.stdout).not.toContain('src/commands/import-calls.ts');+ expect(guard.status).toBe(0);+ });+});++describe('gbrain import --calls', () => {+ test('imports each call once, never overwrites a changed one, and reads --prefix before the folder', async () => {+ const root = temp('gbrain-calls-cli-');+ const home = join(root, 'home');+ mkdirSync(home);+ const env = { HOME: home, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SKIP_STARTUP_HOOKS: '1' };+ expect((await runCli(['init', '--pglite', '--no-embedding', '--json'], { env })).exitCode).toBe(0);+ const calls = join(root, 'calls');+ mkdirSync(calls);+ const token = plantedToken();+ const renewal = join(calls, '2026-03-04 acme-example renewal.txt');+ writeFileSync(renewal, `Alice: annual billing.\nBob: key ${token}\n`);+ const kickoff = join(calls, 'kickoff.txt');+ writeFileSync(kickoff, 'Kickoff with acme-example\nBob: onboarding first.\n');+ utimesSync(kickoff, new Date(MTIME), new Date(MTIME));+ const run = async () => {+ const r = await runCli(['import', '--calls', '--prefix', 'company/calls', calls, '--no-embed', '--json'], { env });+ return { ...r, doc: JSON.parse(r.stdout) };+ };+ const first = await run();+ expect(first.exitCode).toBe(0);+ expect(first.doc).toMatchObject({ mode: 'calls', source_id: 'default', prefix: 'company/calls', total_files: 2, imported: 2, errors: 0, redactions: 1 });+ expect(first.doc.pages.map((p: any) => p.slug).sort()).toEqual(['company/calls/2026-01-15-kickoff-with-acme-example', 'company/calls/2026-03-04-acme-example-renewal']);+ const stored = await runCli(['get', 'company/calls/2026-03-04-acme-example-renewal'], { env });+ expect(stored.stdout).toContain('Alice: annual billing.');+ expect(stored.stdout).toContain('<REDACTED:github_pat>');+ expect(stored.stdout).not.toContain(token);++ const second = await run();+ expect(second.doc).toMatchObject({ imported: 0, unchanged: 2, kept: 0, errors: 0 });++ writeFileSync(renewal, 'Alice: a corrected export.\n');+ const third = await run();+ expect(third.doc).toMatchObject({ imported: 0, unchanged: 1, kept: 1, errors: 0 });+ expect((await runCli(['get', 'company/calls/2026-03-04-acme-example-renewal'], { env })).stdout).toContain('Alice: annual billing.');+ const listed = JSON.parse((await runCli(['list', '--json'], { env })).stdout) as Array<{ slug: string }>;+ expect(listed.some((p) => p.slug.startsWith('conversations/'))).toBe(false);+ }, 240_000);++ test('a rerun finds each file by its path: a new modified day or a mixed-case prefix imports nothing twice', async () => {+ const root = temp('gbrain-calls-rerun-');+ const home = join(root, 'home');+ mkdirSync(home);+ const env = { HOME: home, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SKIP_STARTUP_HOOKS: '1' };+ expect((await runCli(['init', '--pglite', '--no-embedding', '--json'], { env })).exitCode).toBe(0);+ const calls = join(root, 'calls');+ mkdirSync(calls);+ const kickoff = join(calls, 'kickoff.txt');+ writeFileSync(kickoff, 'Kickoff with acme-example\nBob: onboarding first.\n');+ utimesSync(kickoff, new Date(MTIME), new Date(MTIME));+ writeFileSync(join(calls, '2026-03-04 Renewal.txt'), 'Alice: hi\n');+ const run = async () => JSON.parse((await runCli(['import', calls, '--calls', '--prefix', 'Company/Calls', '--no-embed', '--json'], { env })).stdout);+ const first = await run();+ expect(first).toMatchObject({ prefix: 'company/calls', imported: 2, errors: 0 });+ expect(first.pages.map((p: any) => p.slug).sort()).toEqual(['company/calls/2026-01-15-kickoff-with-acme-example', 'company/calls/2026-03-04-renewal']);++ const later = MTIME + 36 * 86_400_000;+ utimesSync(kickoff, new Date(later), new Date(later));+ expect(await run()).toMatchObject({ imported: 0, unchanged: 2, kept: 0, errors: 0 });+ writeFileSync(kickoff, 'Kickoff with acme-example\nBob: an edited export.\n');+ utimesSync(kickoff, new Date(later), new Date(later));+ const edited = await run();+ expect(edited).toMatchObject({ imported: 0, unchanged: 1, kept: 1, errors: 0 });+ expect(edited.pages.find((p: any) => p.file === 'kickoff.txt').slug).toBe('company/calls/2026-01-15-kickoff-with-acme-example');+ const listed = JSON.parse((await runCli(['list', '--json'], { env })).stdout) as Array<{ slug: string }>;+ expect(listed.filter((p) => p.slug.startsWith('company/calls/')).length).toBe(2);+ }, 240_000);++ test('a credential in a file name is never stored or printed, and two folders with the same file name both import', async () => {+ const root = temp('gbrain-calls-paths-');+ const home = join(root, 'home');+ mkdirSync(home);+ const env = { HOME: home, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SKIP_STARTUP_HOOKS: '1' };+ expect((await runCli(['init', '--pglite', '--no-embedding', '--json'], { env })).exitCode).toBe(0);+ const token = plantedToken();+ const a = join(root, 'a');+ mkdirSync(join(a, `key ${token}`), { recursive: true });+ writeFileSync(join(a, `key ${token}`, 'standup.txt'), 'Standup 2026-04-01\nAlice: hi\n');+ writeFileSync(join(a, 'notes.txt'), 'Planning 2026-04-02\nAlice: plan.\n');+ const b = join(root, 'b');+ mkdirSync(b);+ writeFileSync(join(b, 'notes.txt'), 'Retro 2026-04-03\nBob: retro.\n');+ const imp = async (dir: string) => runCli(['import', dir, '--calls', '--no-embed', '--json'], { env });+ const first = await imp(a);+ expect(first.stdout).not.toContain(token);+ expect(JSON.parse(first.stdout)).toMatchObject({ imported: 2, errors: 0 });+ const stored = await runCli(['get', 'calls/2026-04-01-standup'], { env });+ expect(stored.stdout).toContain('Alice: hi');+ expect(stored.stdout).not.toContain(token);+ expect(stored.stdout).toContain('<REDACTED:github_pat>');+ expect(JSON.parse((await imp(b)).stdout)).toMatchObject({ imported: 1, kept: 0, errors: 0 });+ expect((await runCli(['get', 'calls/2026-04-03-retro'], { env })).stdout).toContain('Bob: retro.');+ }, 240_000);+});++describe('call page embedding', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => { await engine.disconnect(); });++ test('an imported call page is held from embedding until the owner approves it, at any size', async () => {+ const page = callPageFor('2026-03-04 sync.txt', 'Alice: short call.\n', MTIME, 'calls', []);+ const parsed = parseMarkdown(page.content);+ await engine.putPage(page.slug, { type: 'meeting', title: page.title, compiled_truth: parsed.compiled_truth, frontmatter: parsed.frontmatter });+ const stored = await engine.getPage(page.slug);+ const plan = await planPageEmbedding(engine, { id: stored!.id, compiled_truth: parsed.compiled_truth, timeline: '' }, [{ chunk_index: 0, chunk_text: 'Alice: short call.' }], { signature: null });+ expect(plan).toEqual({ kind: 'held', reason: 'call_import' });+ const held = await listBudgetLimitedPages(engine, { state: 'held' });+ expect(held.map(h => [h.slug, h.reason])).toContainEqual([page.slug, 'call_import']);+ });+});diff --git a/test/lens-pack-manifests.test.ts b/test/lens-pack-manifests.test.tsindex 29501e4b96..d66c83d8c9 100644--- a/test/lens-pack-manifests.test.ts+++ b/test/lens-pack-manifests.test.ts@@ -255,8 +255,8 @@ describe('v0.41 T4: gbrain-everything meta-pack shape', () => {describe('#2117: gbrain-base-v2 ships link-inference regexes + explicit phases', () => {const pack = loadPack('gbrain-base-v2');- test('version bumped to 1.6.0 (stored-object page type; 1.5.0 added code + extract_receipt, 1.4.0 question, 1.3.0 account, 1.2.0 open-loop link verbs)', () => {- expect(pack.version).toBe('1.6.0');+ test('version bumped to 1.7.0 (facts page type; 1.6.0 added stored-object, 1.5.0 code + extract_receipt, 1.4.0 question, 1.3.0 account, 1.2.0 open-loop link verbs)', () => {+ expect(pack.version).toBe('1.7.0');});test('declares the 4 v1 inference regexes (founded/invested_in/advises/works_at)', () => {diff --git a/test/schema-cli-db-config.test.ts b/test/schema-cli-db-config.test.tsindex 8f5eaae920..8f8e9b59b6 100644--- a/test/schema-cli-db-config.test.ts+++ b/test/schema-cli-db-config.test.ts@@ -63,7 +63,7 @@ describe('#4653 schema inspection verbs honor DB-config schema_pack (tier 4)', (test('schema show prints the DB-configured pack header', () => {const r = runSchema('show');expect(r.status).toBe(0);- expect((r.stdout ?? '').split('\n')[0]).toBe('# gbrain-base-v2 v1.6.0');+ expect((r.stdout ?? '').split('\n')[0]).toBe('# gbrain-base-v2 v1.7.0');}, 90_000);test('schema explain <v2-only type> exits 0', () => {diff --git a/test/schema-cli.test.ts b/test/schema-cli.test.tsindex 184b11e4ef..62da996634 100644--- a/test/schema-cli.test.ts+++ b/test/schema-cli.test.ts@@ -97,7 +97,9 @@ describe('gbrain schema CLI (Phase C)', () => {// unified extract receipt-writer surface (D-EXTRACT-19 belt+suspenders).// v0.42.56.0 (#2390): extended to 27 by adding the Life Chronicle// `event` + `diary` temporal types (life/events/, life/diary/).- expect(r.stdout).toContain('Page types (28)');+ // GST-2731: extended to 29 by adding the `facts` annotation type.+ expect(r.stdout).toContain('Page types (29)');+ expect(r.stdout).toContain('facts :: annotation');expect(r.stdout).toContain('event :: temporal');expect(r.stdout).toContain('diary :: temporal');expect(r.stdout).toContain('Link verbs (12)');@@ -132,7 +134,8 @@ describe('gbrain schema CLI (Phase C)', () => {// link verbs became 17. (#2117 history: 14 became 15 with `advises`.)// v1.3.0 (entity recall): +account page type (alias crm).// v1.4.0 (#6742): +question page type (the pinned-question writer's).- expect(r.stdout).toContain('gbrain-base-v2 v1.6.0');+ // v1.7.0 (GST-2731): +facts page type (the facts starter pages').+ expect(r.stdout).toContain('gbrain-base-v2 v1.7.0');expect(r.stdout).toContain('Page types (');expect(r.stdout).toContain('Link verbs (17)');});diff --git a/test/schema-pack-stats.test.ts b/test/schema-pack-stats.test.tsindex 3e99c206f9..e988d94700 100644--- a/test/schema-pack-stats.test.ts+++ b/test/schema-pack-stats.test.ts@@ -339,7 +339,7 @@ describe('runStatsCore — #4653 DB-plane schema_pack tier', () => {await engine.setConfig('schema_pack', 'gbrain-base-v2');const result = await runStatsCore(ctxOf());// Pre-fix: loadActivePackBestEffort never read the engine → '[email protected]+…'.- expect(result.pack_identity).toStartWith('[email protected]');+ expect(result.pack_identity).toStartWith('[email protected]');});});});diff --git a/test/setup-brain-layout.test.ts b/test/setup-brain-layout.test.tsindex e85acf1aef..f55bb721f5 100644--- a/test/setup-brain-layout.test.ts+++ b/test/setup-brain-layout.test.ts@@ -10,15 +10,18 @@* or docs folder, a page written before the shape question is answered (--yes* included), an inline import of a huge folder, a company source federated on a* shared brain, anything created for the company part with --team.+ * --transcripts (PR 3): a call imported twice, a planted credential stored, a call page readable more widely+ * than its source, a call page under conversations/, a missing archive line.* 3. New flags on an existing command; test/setup.test.ts keeps the rest of setup.*/import { afterAll, describe, expect, test } from 'bun:test';-import { createHash } from 'node:crypto';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { execSync } from 'node:child_process';+import { createHash, randomBytes } from 'node:crypto';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { runCli, type CliResult } from './helpers/cli-spawn.ts';-import { COMPANY_PAGES, LAYOUT_BEGIN, PERSONAL_PAGES, parseLayoutFlags, renderStarterPage, withBrainShape, brainShapeDecision, renderLayoutBlock, layoutNotices, applyBrainLayout, countNotes } from '../src/commands/setup-brain-layout.ts';+import { COMPANY_PAGES, LAYOUT_BEGIN, PERSONAL_PAGES, parseLayoutFlags, renderStarterPage, withBrainShape, brainShapeDecision, renderLayoutBlock, layoutNotices, applyBrainLayout, countNotes, askBrainShape, describeLayout, callEgress } from '../src/commands/setup-brain-layout.ts';const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');const roots: string[] = [];@@ -354,3 +357,173 @@ describe('layout units', () => {expect(countNotes(root)).toEqual({ count: 1, first: join(root, 'n.md') });});});++const plantedToken = (): string => 'github' + '_pat_' + randomBytes(24).toString('hex');+function callsDir(b: Box, token: string): string {+ const dir = join(b.root, 'call-exports');+ mkdirSync(join(dir, 'q1'), { recursive: true });+ writeFileSync(join(dir, '2026-03-04 acme-example renewal.txt'), `Alice: we agreed to move acme-example to annual billing.\nBob: the deploy key is ${token} for the record.\n`);+ writeFileSync(join(dir, 'q1', 'weekly-sync.md'), '# Weekly sync 2026-02-01\n\nAlice: pricing stays at 20 dollars per seat.\n');+ const undated = join(dir, 'kickoff.txt');+ writeFileSync(undated, 'Kickoff with acme-example\nBob: the first milestone is onboarding.\n');+ utimesSync(undated, new Date(2026, 0, 15, 12), new Date(2026, 0, 15, 12));+ writeFileSync(join(dir, 'slides.pdf'), 'not a call');+ return dir;+}+const CALL_SLUGS = ['company/calls/2026-03-04-acme-example-renewal', 'company/calls/2026-02-01-weekly-sync', 'company/calls/2026-01-15-kickoff-with-acme-example'];+const callPages = async (b: Box): Promise<string[]> => {+ const r = await gbrain(b, ['list', '--source', 'company', '--json']);+ return (JSON.parse(r.stdout) as Array<{ slug: string }>).map((p) => p.slug).filter((s) => s.startsWith('company/calls/')).sort();+};++describe('setup --transcripts', () => {+ test('a repo-less brain imports each call once into the company source, redacted, with the source readers and the archive line', async () => {+ const b = box();+ const token = plantedToken();+ const calls = callsDir(b, token);+ const before = treeHash(calls);+ const r = await setup(b, ['claude-code', '--shape', 'company', '--transcripts', calls]);+ expect(r.exitCode).toBe(0);+ const t = r.doc.brain_layout.transcripts;+ expect(t).toMatchObject({ action: 'imported', files: 3, imported: 3, unchanged: 0, kept: 0 });+ expect(t.argv).toEqual(['gbrain', 'import', calls, '--calls', '--prefix', 'company/calls', '--no-embed', '--source', 'company']);+ expect(t.redactions).toBeGreaterThanOrEqual(1);+ expect(t.readers).toEqual({ members: 'every_source_reader', serves: 'one', detail: 'everyone who can read source company (this brain serves one person)' });+ expect(t.egress).toEqual({ leaves: false, detail: 'nothing; no extraction reads call pages here, and embedding waits for your approval' });+ expect(r.doc.brain_layout.archive.state).toBe('on');+ expect(r.doc.brain_layout.archive.detail).toContain('call transcripts are separate');+ expect(await callPages(b)).toEqual([...CALL_SLUGS].sort());+ const page = await gbrain(b, ['get', CALL_SLUGS[0]!, '--source', 'company']);+ expect(page.exitCode).toBe(0);+ expect(page.stdout).toContain('Alice: we agreed to move acme-example to annual billing.');+ expect(page.stdout).not.toContain(token);+ expect(page.stdout).toContain('<REDACTED:github_pat>');+ expect(page.stdout).not.toContain('readable_by');+ expect(page.stdout).toContain('facts_backstop: false');+ expect((await gbrain(b, ['get', 'company/facts', '--source', 'company'])).stdout).toContain('type: facts');+ expect(treeHash(calls)).toBe(before);++ const again = await setup(b, ['claude-code', '--shape', 'company', '--transcripts', calls]);+ expect(again.exitCode).toBe(0);+ expect(again.doc.brain_layout.transcripts).toMatchObject({ action: 'imported', imported: 0, unchanged: 3, kept: 0 });+ expect(await callPages(b)).toEqual([...CALL_SLUGS].sort());+ }, 300_000);++ test('a git-backed company source gets the call files in its working tree, redacted', async () => {+ const b = box();+ expect((await gbrain(b, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ const repo = join(b.root, 'company-repo');+ mkdirSync(repo);+ execSync('git init -q && git config user.email [email protected] && git config user.name t && echo "# Company" > README.md && git add README.md && git commit -qm init', { cwd: repo });+ expect((await gbrain(b, ['sources', 'add', 'company', '--path', repo, '--json'])).exitCode).toBe(0);+ const token = plantedToken();+ const r = await setup(b, ['claude-code', '--shape', 'company', '--transcripts', callsDir(b, token)]);+ expect(r.exitCode).toBe(0);+ expect(r.doc.brain_layout.company).toMatchObject({ action: 'kept', root: repo });+ expect(r.doc.brain_layout.transcripts).toMatchObject({ action: 'imported', imported: 3 });+ const file = readFileSync(join(repo, 'company', 'calls', '2026-03-04-acme-example-renewal.md'), 'utf8');+ expect(file).toContain('<REDACTED:github_pat>');+ expect(file).not.toContain(token);+ expect(file).not.toContain('readable_by');+ expect((await gbrain(b, ['get', CALL_SLUGS[0]!, '--source', 'company'])).stdout).not.toContain(token);+ }, 300_000);++ test('on a shared brain the call pages get the company source rules as their readers, never wider', async () => {+ const b = box();+ expect((await setup(b, ['claude-code', '--shape', 'company'])).exitCode).toBe(0);+ expect((await gbrain(b, ['access', 'serves', 'several', '--members', 'alice-example,bob-example', '--yes', '--json'])).exitCode).toBe(0);+ expect((await gbrain(b, ['access', 'rule', 'add', '--prefix', 'company/calls/', '--readers', 'alice-example', '--source', 'company', '--yes', '--json'])).exitCode).toBe(0);+ const r = await setup(b, ['claude-code', '--shape', 'company', '--stdio-member', 'alice-example', '--transcripts', callsDir(b, plantedToken())]);+ expect(r.exitCode).toBe(0);+ const t = r.doc.brain_layout.transcripts;+ expect(t.imported).toBe(3);+ expect(t.readers.members).toEqual(['alice-example']);+ expect(t.readers.serves).toBe('several');+ expect(t.readers.detail).toStartWith('alice-example only (access rules on source company cover company/calls/; this brain serves several people');+ for (const slug of CALL_SLUGS) {+ const who = JSON.parse((await gbrain(b, ['access', 'who-can-read', slug, '--source', 'company', '--json'])).stdout).pages[0];+ expect(who.readers).toBeNull();+ expect(who.members).toEqual(['alice-example']);+ }+ }, 300_000);+});++describe('transcripts units', () => {+ test('--transcripts needs a local company shape', () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-layout-calls-flag-'));+ roots.push(dir);+ const parse = (args: string[]) => parseLayoutFlags((f) => { const i = args.indexOf(f); return i < 0 ? undefined : args[i + 1]; }, (f) => args.includes(f), 'claude-code');+ expect(parse(['--shape', 'personal', '--transcripts', dir])).toContain('--shape company or both');+ expect(parse(['--transcripts', dir])).toContain('--shape company or both');+ expect(parse(['--shape', 'company', '--team', '--transcripts', dir])).toContain('drop --transcripts or use --solo');+ expect(parse(['--shape', 'both', '--transcripts', dir])).toEqual({ brain: 'both', transcripts: dir });+ expect(parse(['--shape', 'company', '--transcripts', 'none'])).toEqual({ brain: 'company', transcripts: null });+ });++ test('a call folder over the inline limit is handed to the agent as the import command', () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-layout-calls-bulk-'));+ roots.push(dir);+ for (let i = 0; i < 501; i++) writeFileSync(join(dir, `call-${i}.txt`), 'hello\n');+ const calls: string[][] = [];+ const o = applyBrainLayout({ harness: 'claude-code', launcher: 'gbrain', instructionsPath: null, flags: { brain: 'company', transcripts: dir, dryRun: false },+ run: (argv) => {+ calls.push(argv);+ if (argv[1] === 'sources') return { code: 0, stdout: JSON.stringify({ sources: [{ id: 'company', local_path: '/c', federated: true }] }), stderr: '' };+ return argv[1] === 'get' ? { code: 0, stdout: '{}', stderr: '' } : { code: 0, stdout: '{}', stderr: '' };+ } })!;+ expect(o.transcripts).toMatchObject({ action: 'deferred', files: 501 });+ expect(calls.some((c) => c[1] === 'import')).toBe(false);+ const n = layoutNotices(o, 'claude-code').find((x) => x.code === 'brain_layout_import_pending')!;+ expect(n.why).toContain('more than 500 call files');+ expect(n.fix!.argv).toEqual(['gbrain', 'import', dir, '--calls', '--prefix', 'company/calls', '--no-embed', '--source', 'company']);+ });++ test('with a chat model key, the call line says extraction can send call text to the chat provider; without one, nothing leaves', () => {+ const chronicleOn = { name: 'auto_chronicle', details: { enabled: true, chat_available: true, daily_limit: 25 } };+ const atomsOn = { name: 'extract_atoms_backlog', details: { pack_declares_phase: true } };+ expect(callEgress([chronicleOn, atomsOn])).toEqual({ leaves: true,+ detail: 'with a chat model key set, event extraction (auto_chronicle, at most 25 page(s) a day) and atom extraction (within cycle.extract_atoms.budget_usd) can send call text to your chat provider, within the limits you set; embedding waits for your approval' });+ expect(callEgress([{ name: 'auto_chronicle', details: { enabled: false } }, atomsOn]).detail).toStartWith('with a chat model key set, atom extraction (within cycle.extract_atoms.budget_usd) can send');+ const keyless = { name: 'auto_chronicle', details: { enabled: true, chat_available: false, daily_limit: 25 } };+ expect(callEgress([keyless, atomsOn])).toEqual({ leaves: false, detail: 'nothing; no extraction reads call pages here, and embedding waits for your approval' });+ expect(callEgress([{ name: 'auto_chronicle', details: { enabled: false } }, { name: 'extract_atoms_backlog', details: { pack_declares_phase: false } }]).leaves).toBe(false);+ const unchecked = { leaves: null, detail: 'could not be checked; gbrain doctor --only auto_chronicle,extract_atoms_backlog shows it' };+ expect(callEgress([])).toEqual(unchecked);+ expect(callEgress([{ name: 'transcript_archive_freshness', details: { enabled: true } }, chronicleOn])).toEqual(unchecked);+ });++ test('the human report names who reads the call pages and what the archive is doing', () => {+ const o = { shape: 'company', pages: [], notes: null, docs: null, company: null, block: null, check: { ok: true, query: null, detail: 'nothing to check' }, next_question: null,+ transcripts: { dir: '/calls', files: 2, action: 'imported', argv: [], imported: 2, unchanged: 0, kept: 0, redactions: 1, readers: { members: 'every_source_reader', serves: 'one', detail: 'everyone who can read source company (this brain serves one person)' },+ egress: { leaves: true, detail: 'with a chat model key set, atom extraction (within cycle.extract_atoms.budget_usd) can send call text to your chat provider, within the limits you set; embedding waits for your approval' } },+ archive: { state: 'offered', detail: 'offered, not on: this brain may serve more than one person (gbrain transcripts archive on turns it on)' } } as any;+ const lines = describeLayout(o, false);+ expect(lines).toContain(' readable by: everyone who can read source company (this brain serves one person)');+ expect(lines).toContain(' what leaves this machine: with a chat model key set, atom extraction (within cycle.extract_atoms.budget_usd) can send call text to your chat provider, within the limits you set; embedding waits for your approval');+ expect(lines.find((l) => l.startsWith(' calls '))).toContain('2 new, 0 unchanged, 0 kept, 1 credential(s) redacted');+ expect(lines).toContain(' archive conversation archive offered, not on: this brain may serve more than one person (gbrain transcripts archive on turns it on)');+ });++ test('at a terminal, a local company brain asks for a call-transcript folder after the docs folder', async () => {+ const docs = mkdtempSync(join(tmpdir(), 'gbrain-layout-ask-docs-'));+ const calls = mkdtempSync(join(tmpdir(), 'gbrain-layout-ask-calls-'));+ roots.push(docs, calls);+ const answering = (answers: string[]) => {+ const prompts: string[] = [];+ return { prompts, read: async ({ prompt }: { prompt: string }) => { prompts.push(prompt); const a = answers.shift(); return a === undefined ? { kind: 'eof' as const } : { kind: 'line' as const, text: a }; } };+ };+ const solo = answering(['2', '1', docs, calls]);+ expect(await askBrainShape([], solo.read as any)).toEqual({ brain: 'company', team: false, docs, transcripts: calls });+ expect(solo.prompts[3]).toContain('call transcripts');+ const team = answering(['3', '', '2']);+ expect(await askBrainShape([], team.read as any)).toEqual({ brain: 'both', notes: null, team: true });+ expect(team.prompts.some((p) => p.includes('call transcripts'))).toBe(false);+ });++ test('the facts starter pages carry type: facts and the block names the facts convention', () => {+ expect(renderStarterPage(PERSONAL_PAGES.find((p) => p.slug === 'me/facts')!)).toContain('\ntype: facts\n');+ expect(renderStarterPage(COMPANY_PAGES.find((p) => p.slug === 'company/facts')!)).toContain('\ntype: facts\n');+ expect(renderStarterPage(COMPANY_PAGES.find((p) => p.slug === 'company/decisions')!)).not.toContain('type:');+ expect(renderLayoutBlock('claude-code', 'user', null, 'both')).toContain('A page with type: facts holds one dated line per fact: quote only its dated lines');+ });+});