Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

repair visibility --propose: suggest reader sets for open shared pages, preview only (GST-2670 phase 2)

garrytandb71edfa7280
diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.md
index 00ed3a4db6..6a3f75e1cc 100644
--- a/docs/architecture/key-files/access.md
+++ b/docs/architecture/key-files/access.md
@@ -7,6 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/access/open-twins.ts` (GST-2603) — `openTwins(engine, pages, readers, cover)`: for the pages a label or rule preview changes, the live pages with the same slug in other sources that are not private by their own labels (`privateSnapshotFilterFragment`; no links are read) and that the empty identity or an enabled member outside `readers` passes by its own readers and folder rules (`readersAllowedSql`, `folderRulesAllowedSql` with `folderAccessFor`), since labels and rules apply per source. Read-only and bounded (`OPEN_TWINS_PAGES` 1000 pages checked, `OPEN_TWINS_LISTED` 50 named, `count` over all); never part of a preview hash. Callers: `repair/visibility.ts` (pages turning private, owner inside), `repair/readers.ts` (`--readers`), `repair/private-labels.ts` (`--class restore`) and `commands/access-rules.ts` `previewRules` (each narrowed rule's pages); `cover(source, slugs)` names the same repair or rule with `--source <other>`. Test: `test/label-repair-derived-stamps-gst2603.test.ts`.
- `src/core/access/federation-exposure.ts` (#8982) — `remotePagesFederationExposes(engine, source)`: the live pages of a source that name no readers and no folder rule, that the read paths' privacy rules (`privacyPartSql`) do not hide from a no-grant connection (#9068; skipped when `remotePrivacyRelaxed` says an operator opted out), and whose live revision (`pages.revision_principal_*`) or any version (`page_versions.write_principal_*`) a token or OAuth client wrote (revoked or deleted included; no record keeps a credential's member at write time, so an unbound, rebound or deleted one counts and each example names its member now; a tag change moves the revision attribution without a version, hiding the earlier author): count, the first five slugs, and shell-quoted `who-can-read` / `access rule add` commands. `remotePagesFederationExposesOrWarn` runs it, after the change commits, only for a change that added the source to the no-grant floor (federate reads the prior state under the source row lock), and turns a failed read into a stderr warning, so the caller's federation never changes. Read by `sources federate`, the unmanaged `sources restore` (stderr; `--json` as `pages_exposed`) and the managed `source_lifecycle` restore result. Pinned by `test/sources-federate-member-pages.test.ts` and `test/federation-exposure-private-9068.test.ts`.
- `src/core/access/serves.ts` + `src/commands/access-serves.ts` (GST-363 PR 1) — whether a brain serves several people (`brainServes`: config `access.serves` `one`|`several` wins, else `access.serves_derived`, which migration v309's trigger keeps as `several` while 2+ members are enabled; `since` is `access.serves_since`, set once) and `gbrain access serves [several --members a,b [--yes]]`: preview, then config, members (kept when present), one folder rule `people/<member>/` per member through `addFolderRules` (`access-rules.ts`, the `rule add` preview-then-write path; a git store commits `.gbrain/access.yml` through the commit door), and one read-write token `member-<id>` per member through `auth-mint.ts` (the `auth create` mint) written to `<configDir>/member-keys/<id>.key` (0600, dir 0700, refused inside a git work tree: `access_serves_key_dir_in_git`). Idempotent on the member id; a token whose file is gone is reported, never re-minted. `GBRAIN_SETUP_ABORT_AFTER=serves-members|serves-rules|serves-key` is the crash seam. Doctor: `checks/unlabeled-people-folders.ts` fails a `people/<x>/` folder with pages no rule covers on a several-person brain. Tests: `test/setup-serves-several.test.ts` (both engines). GST-2670: `src/core/access/open-pages.ts` counts the pages every member's key reads (`openPages`: `accessAllowedSql` with the empty identity under `withoutCallerAccess`, so it never depends on the caller; private pages split out unless `remotePrivacyRelaxed` or a reading member's `private_pages` grant opens their source; throws `open_pages_unknown` when `gbrain_access_state_unreadable()`; Postgres runs it read-only under `SET LOCAL statement_timeout`), over the sources the bound tokens, OAuth clients and config `mcp.stdio_member` binding of enabled, non-labelled-only members other than the owner read (`credentialReadSources`, `stdioReadSources`), or every source when none reads one (doctor then reports information); `SENSITIVE_PAGE_TYPES` (`grants/shared-exposure.ts`) is the DM, chat, conversation and mail tier. `readOpenPages` never throws; `ServesReceipt.open_pages` / `open_pages_error` carry it in the preview and receipt (planned members counted against the source their keys will read, this run's `people/<member>/` rules excluded), `gbrain access serves` prints it, `--labelled-only` calls `setMemberLabelledOnly` after the members step (the owner in the roster is BLOCKED), doctor `checks/open-shared-pages.ts` warns on sensitive pages, and `printOpenPagesUpgradeNotice` runs in post-upgrade. Callers gate on `brainServes`, so a one-person brain runs no query. Test: `test/open-shared-pages.test.ts` (both engines, repo-less).
+- `src/commands/repair-propose.ts` (GST-2670 phase 2) — `gbrain repair visibility --propose [--source <id>] [--out <dir>]`, preview only: gated on `brainServes` (a one-person or pinned-one brain gets "nothing to propose" before any pages query), it reads the open pages through `open-pages.ts` `withOpenScope` / `openPageSql` / `membersReadOpen` (the same predicates as the count), takes each page's `participants`, `attendees`, `to`, `from`, `cc` entries (`Name <a@b>` read as the address), matches each to an enabled member's declared email through `assertMemberEmail` (exact, case-folded; anything else is `unmatched`), groups pages by source and reader set with the owner (`ownerView`) first, writes one slugs file per set (0600, split at `READERS_MAX_PAGES`) under `<configDir>/visibility-proposals/` or `--out` (refused inside a git work tree with `gitRootAbove` from `access-serves.ts`: `repair_propose_dir_in_git`), and prints the `repair visibility --slugs-file --readers` command per set and the `access rule add --prefix` command per folder of `SENSITIVE_PAGE_TYPES` pages with no address list. Writes no label, rule, config or page. `src/commands/repair.ts` parses `--propose`/`--out` (only `--source`, `--out`, `--json` beside it) and dispatches before the kind run. Test: `test/repair-visibility-propose-gst2670.test.ts` (both engines, repo-less).
- `gbrain serve --stdio-member <id>` (GST-363 PR 3) — `parseStdioMemberFlag`, `registeredStdioMember` and `withStdioMember` live in `src/core/stdio-member-flag.ts` (kept out of `mcp-registration.ts` so serve and doctor pick up no registration flags); serve passes the value to `startMcpServer`, dispatch sets `OperationContext.stdioMember` only for an unauthenticated stdio call, and `caller.ts` resolves it live ahead of config `mcp.stdio_member` (a disabled or unknown member reads as nobody, no fallback). Stored writes stamp it on `WriteAuthority.stdioMember` (jsonb, no migration); a stdio watch uses principal id `registration` so the wake drain re-checks that member. Setup writes it into one claude-code or codex entry (`ClaudeSetupPlan`/`CodexSetupPlan.stdioMember`); inspection reports an owned entry's member so setup re-runs and `refreshHookLaunchers` carry it, and `setupRerunArgv` never names it.
- `src/core/access/requester-scope.ts` + `src/commands/doctor/checks/unscoped-shared-reads.ts` (GST-363 PR 2) — on a brain that serves several people (`servesPolicyFrom` in `search/private-visibility.ts`, read from the request config snapshot: explicit `access.serves` wins, else `access.serves_derived`; a brain pinned `one` never gates) a remote read from a connection bound to no member (no member identity, no audience, not attested, no `reads_unscoped`) is refused `requester_scope_required` before any work. Deny by default: every op not `mutating: true`, and every read-scope one (`think`), except `REQUESTER_SCOPE_EXEMPT` and `OWN_JOB_OPS` for a non-admin credential; `test/requester-scope.test.ts` pins the list and spies every handler. `requesterScopeGate` runs in `dispatchToolCall` after access resolves (attested calls exempt; an unreachable op keeps the unknown-tool envelope) and in `brain-allowlist.ts` `scopedJobAccess` per job tool call; a bound caller's access is never changed. `readsUnscoped`/`createdAt` come from the verifiers (`token-binding.ts` `credentialScopeFields`), else `credentialScopeFor`. Grace: 14 days from `access.serves_since` (migration v309's trigger sets it once) for connections created at or before it (unknown creation and stdio count as old), with `_meta.access.requester_scope`; `access.requester_scope_enforce false` (hosted) gives the notice only. An unreadable policy (`servesUnknown`) is read once more (`withServesReread`); a second failure refuses `requester_scope_unknown` (retryable). `assertCredentialScoped` refuses unbound `auth create`/`register-client` and `POST /admin/api/api-keys` (`credential_scope_required`); `--reads-unscoped [none]` changes go to the `access-reads-unscoped` audit file. `unscopedConnections` feeds doctor `unscoped_shared_reads`, `whoami` (`requesterScopeView`) and post-upgrade.
- `src/core/access/stdio-bind-route.ts` + `src/commands/doctor/checks/shared-stdio-binding.ts` (GST-363 PR 2) — `stdioBindRoute()` is the one place that says how to bind an unbound stdio connection: `gbrain setup claude-code|codex --stdio-member <id>` for a harness one person uses (that harness entry, either engine), else a per-person `serve --http` key. The requester-scope refusal and notice, `gbrain access owner`'s Bind-one line and whoami's unbound note read it. Doctor `shared_stdio_binding` fails when `mcp.stdio_member` is set and `sharedStdioHarness()` (`setup-serves.ts`; a `hermes` on PATH counts only as a script, not React Native's compiled engine) finds OpenClaw or Hermes on a brain that serves several people (not applicable on a one-person brain); fix `gbrain config unset mcp.stdio_member`. `requesterScopeRefuses()` lets dispatch drop hot memory from the ops the gate does not cover for a connection it would refuse. Tests: `test/shared-stdio-binding.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 1562c676ea..a17b4592c3 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -4492,6 +4492,16 @@ Reasons: `rename_source_changed`.
More: [docs/guides/troubleshooting.md#repair-preview-timeout](../../docs/guides/troubleshooting.md#repair-preview-timeout)
+### repair_propose_dir_in_git
+
+<a id="repair_propose_dir_in_git"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain repair visibility --propose was pointed at a directory inside a git work tree for its slugs files, so nothing was written. | The slugs files list page slugs and who would read them; a file inside a checkout can be committed and pushed. | Pass --out <dir> outside any git checkout, or leave --out off to use the gbrain config directory (with GBRAIN_HOME outside any checkout). | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/repair.md#propose-readers](../../docs/guides/repair.md#propose-readers)
+
### request_already_submitted
<a id="request_already_submitted"></a>
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 1b67039d00..34c58ea9b0 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -139,6 +139,23 @@ and its own keys would stop reading the page; a group the owner belongs to does
not count. Pass `--allow-without-owner` when that is what you want. A page whose
readers changed after the preview is skipped.
+<a id="propose-readers"></a>
+**Proposed readers.** On a brain that serves several people, `gbrain repair visibility --propose [--source <id>] [--out <dir>] [--json]`
+suggests readers for the pages every member's key can read (no `readable_by`, no
+folder or page rule). It reads each such page's `participants`, `attendees`, `to`, `from` and
+`cc` addresses and matches each one to an enabled member by the email declared on it
+(`gbrain access member set <id> --email <address>`), exactly and ignoring case. Pages
+whose addresses all match are grouped by reader set, with the owner first in every set. Each set gets
+a slugs file (mode 0600, in `<config dir>/visibility-proposals/` or `--out`, never inside a
+git work tree) and the `--readers` command above to preview it, then apply it with
+`--apply --expect <hash>`. A page with any address that names no enabled member is
+listed as unmatched and gets no proposal. DM, chat and mail pages with no address list are listed by
+folder with a `gbrain access rule add --prefix <folder>/ --readers <owner>,<list>` command to fill in.
+Labelling a page also hides its derived atoms, facts and chronicle events from every remote caller
+except the owner, unless `access.members_read_lineage` is on. `--propose` itself labels nothing
+and changes nothing any key reads. A one-person brain, or one with `access.serves` set to `one`, gets
+"nothing to propose". It works the same on a repo-less brain.
+
No lock or transaction spans the run, so a long list does not hold up other
writers. On a managed brain the apply admits a source's pages together, one
admission window at a time; on Postgres the owner publishes them in groups of
diff --git a/src/commands/access-serves.ts b/src/commands/access-serves.ts
index 26d779374e..8cec5b4377 100644
--- a/src/commands/access-serves.ts
+++ b/src/commands/access-serves.ts
@@ -75,7 +75,7 @@ export function rosterEmpty(command: string): Error {
}
/** The first directory at or above `dir` that holds .git, or null; symlinks are resolved, so a link into a checkout counts. */
-function gitRootAbove(dir: string): string | null {
+export function gitRootAbove(dir: string): string | null {
let existing = dir;
while (!existsSync(existing) && dirname(existing) !== existing) existing = dirname(existing);
const physical = join(realpathSync(existing), relative(existing, dir));
diff --git a/src/commands/repair-propose.ts b/src/commands/repair-propose.ts
new file mode 100644
index 0000000000..d6b9514482
--- /dev/null
+++ b/src/commands/repair-propose.ts
@@ -0,0 +1,178 @@
+/**
+ * GST-2670 phase 2 (GBRA-502, decision B1): `gbrain repair visibility --propose [--source <id>] [--out <dir>]`, a
+ * preview that proposes readers for open pages (open-pages.ts: no readable_by, no applied or pending rule) on a brain
+ * that serves several people. It reads each open page's frontmatter participants, attendees, to, from and cc email
+ * lists and matches every address to an enabled member by its declared email (GST-1158), exactly and case-folded,
+ * never a search hit. A page whose addresses all match proposes those members plus the owner (first); a page with any
+ * address that matches no enabled member is listed under unmatched, never guessed. Pages are grouped by source and
+ * reader set, one slugs file per set, each with the existing preview-bound command
+ * gbrain repair visibility --source <s> --slugs-file <f> --readers <set> (readers.ts), whose --apply --expect stays the
+ * only way a label is written. DM, chat and mail pages with no address list are listed by folder with the
+ * gbrain access rule add --prefix command instead.
+ *
+ * It writes only the slugs files (mode 0600) under <configDir>/visibility-proposals/ or --out, refusing a directory
+ * inside a git work tree as member keys do. It never writes a label, a rule, config or a page. A one-person brain, or
+ * one pinned to access.serves one, gets "nothing to propose" before any pages query (brainServes, the gate open-pages.ts
+ * callers use). Everything it reads is database state, so a repo-less brain gets it unchanged.
+ */
+import { chmodSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import type { BrainEngine } from '../core/engine.ts';
+import { configDir } from '../core/config.ts';
+import { opError } from '../core/ops/contract.ts';
+import { digest } from '../core/persistence/digest.ts';
+import { privacyPartSql } from '../core/search/private-visibility.ts';
+import { SENSITIVE_PAGE_TYPES } from '../core/grants/shared-exposure.ts';
+import { assertMemberEmail, listMembers } from '../core/access/members.ts';
+import { ownerView } from '../core/access/owner.ts';
+import { brainServes } from '../core/access/serves.ts';
+import { membersReadLineageOn } from '../core/access/lineage.ts';
+import { membersReadOpen, openPageSql, withOpenScope } from '../core/access/open-pages.ts';
+import { gitRootAbove } from './access-serves.ts';
+import { READERS_MAX_PAGES } from '../core/repair/readers.ts';
+
+export const PROPOSAL_FIELDS = ['participants', 'attendees', 'to', 'from', 'cc'] as const;
+export const PROPOSAL_DIR = 'visibility-proposals';
+
+export interface ProposedSet { source: string; readers: string[]; pages: number; file: string; command: string }
+export interface UnmatchedPage { source: string; slug: string; addresses: string[] }
+export interface ProposedFolder { source: string; folder: string; pages: number; command: string }
+export interface VisibilityProposal {
+ /** False on a one-person brain or one pinned to access.serves one: nothing was read or written. */
+ applicable: boolean;
+ message: string;
+ owner: string | null;
+ /** The configured owner when it names no enabled member: every printed command refuses until it is fixed. */
+ owner_inactive?: string;
+ /** Where the slugs files were written; null when no set was proposed. */
+ dir: string | null;
+ sets: ProposedSet[];
+ unmatched: UnmatchedPage[];
+ folders: ProposedFolder[];
+ members_read_lineage: boolean;
+ cost: string;
+}
+
+const LINEAGE_COST = 'Labelling a page also hides its derived atoms, facts and chronicle events from every remote caller except the owner, unless access.members_read_lineage is on (gbrain access members-read-lineage on lets the members a page lists read them too).';
+const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
+
+/** The address entries a frontmatter value lists: a list or one string (comma or semicolon separated), each "Name <a@b>" read as a@b. */
+function entries(value: unknown): string[] {
+ const items = Array.isArray(value) ? value : value === null || value === undefined ? [] : [value];
+ return items.flatMap(item => typeof item === 'string' ? item.split(/[,;]/) : item && typeof item === 'object' && typeof (item as { email?: unknown }).email === 'string'
+ ? [(item as { email: string }).email] : [JSON.stringify(item)])
+ .map(entry => entry.trim()).filter(Boolean).map(entry => entry.match(/<([^<>]+)>$/)?.[1]?.trim() ?? entry);
+}
+
+const canonical = (entry: string): string | null => { try { return assertMemberEmail(entry); } catch { return null; } };
+
+/** Refuses a proposals directory inside a git work tree, as member keys are refused (access-serves.ts). */
+function assertOutsideGit(dir: string): void {
+ const root = gitRootAbove(dir);
+ if (!root) return;
+ throw opError('repair_propose_dir_in_git', `Proposal files go to ${dir}, which is inside the git work tree at ${root}; a file there could be committed, so nothing was written.`,
+ 'Pass --out <dir> outside any git checkout, or leave --out off to use the gbrain config directory (with GBRAIN_HOME outside any checkout).',
+ { why: 'Proposal files list page slugs and who reads them; a commit could publish them.' });
+}
+
+/** The proposal; writes only the slugs files. `out`: their directory (default <configDir>/visibility-proposals). */
+export async function proposeVisibility(engine: BrainEngine, opts: { source?: string; out?: string } = {}): Promise<VisibilityProposal> {
+ const lineage = await membersReadLineageOn(engine);
+ const serves = await brainServes(engine);
+ if (serves.serves === 'one') {
+ const why = serves.from === 'config' ? 'access.serves is one' : plural(serves.enabled_members.length, 'enabled member');
+ return { applicable: false, message: `Nothing to propose: this brain serves one person (${why}), so no page needs readers for members.`,
+ owner: null, dir: null, sets: [], unmatched: [], folders: [], members_read_lineage: lineage, cost: LINEAGE_COST };
+ }
+ const dir = resolve(opts.out ?? join(configDir(), PROPOSAL_DIR));
+ assertOutsideGit(dir);
+ const view = await ownerView(engine);
+ const owner = view.owner;
+ const byEmail = new Map((await listMembers(engine)).filter(m => m.status === 'enabled' && m.email).map(m => [m.email!, m.id]));
+ const rows = await withOpenScope(engine, {}, async (scope, bounded) => {
+ const sources = opts.source ? [opts.source] : scope.sources;
+ if (!sources.length) return [];
+ const found = await bounded(e => e.executeRaw<{ source: string; slug: string; type: string | null; visible: unknown; fields: Record<string, unknown> | null }>(
+ `SELECT p.source_id AS source, p.slug, p.type, (${privacyPartSql('p')}) AS visible,
+ jsonb_strip_nulls(jsonb_build_object(${PROPOSAL_FIELDS.map(f => `'${f}', p.frontmatter->'${f}'`).join(', ')})) AS fields
+ FROM pages p
+ WHERE ${openPageSql('p')} AND p.source_id = ANY($1::text[])
+ AND (p.frontmatter ?| $2::text[] OR p.type = ANY($3::text[]))
+ ORDER BY p.source_id, p.slug`, [sources, [...PROPOSAL_FIELDS], [...SENSITIVE_PAGE_TYPES]]));
+ return found.filter(row => membersReadOpen(scope, row.source, row.visible));
+ });
+ const groups = new Map<string, { source: string; readers: string[]; slugs: string[] }>();
+ const unmatched: UnmatchedPage[] = [];
+ const folders = new Map<string, ProposedFolder>();
+ const ownerFirst = owner ? `${owner},` : '';
+ for (const row of rows) {
+ const listed = PROPOSAL_FIELDS.flatMap(f => entries(row.fields?.[f]));
+ if (!listed.length) {
+ if (!row.type || !SENSITIVE_PAGE_TYPES.includes(row.type)) continue;
+ const cut = row.slug.lastIndexOf('/');
+ const folder = cut > 0 ? row.slug.slice(0, cut + 1) : '(root)';
+ const key = JSON.stringify([row.source, folder]);
+ const f = folders.get(key) ?? { source: row.source, folder, pages: 0, command: folder === '(root)'
+ ? `gbrain repair visibility --source ${row.source} --slug <slug> --readers ${ownerFirst}<list>`
+ : `gbrain access rule add --prefix ${folder} --readers ${ownerFirst}<list> --source ${row.source}` };
+ folders.set(key, f);
+ f.pages++;
+ continue;
+ }
+ const members = new Set<string>();
+ const missing: string[] = [];
+ for (const entry of listed) {
+ const email = canonical(entry);
+ const id = email ? byEmail.get(email) : undefined;
+ if (id) members.add(id);
+ else if (!missing.includes(entry)) missing.push(entry);
+ }
+ if (missing.length) { unmatched.push({ source: row.source, slug: row.slug, addresses: missing }); continue; }
+ if (owner) members.delete(owner);
+ const readers = [...(owner ? [owner] : []), ...[...members].sort()];
+ const key = JSON.stringify([row.source, readers]);
+ const g = groups.get(key) ?? { source: row.source, readers, slugs: [] };
+ groups.set(key, g);
+ g.slugs.push(row.slug);
+ }
+ const sets: ProposedSet[] = [];
+ if (groups.size) mkdirSync(dir, { recursive: true, mode: 0o700 });
+ for (const g of [...groups.values()].sort((a, b) => a.source.localeCompare(b.source) || b.slugs.length - a.slugs.length || a.readers.join(',').localeCompare(b.readers.join(',')))) {
+ const parts = Math.ceil(g.slugs.length / READERS_MAX_PAGES);
+ for (let i = 0; i < parts; i++) {
+ const slugs = g.slugs.slice(i * READERS_MAX_PAGES, (i + 1) * READERS_MAX_PAGES);
+ const file = join(dir, `${g.source}-${digest([g.source, g.readers]).slice(0, 12)}${parts > 1 ? `-${i + 1}` : ''}.txt`);
+ writeFileSync(file, `${slugs.join('\n')}\n`, { mode: 0o600 });
+ chmodSync(file, 0o600);
+ sets.push({ source: g.source, readers: g.readers, pages: slugs.length, file,
+ command: `gbrain repair visibility --source ${g.source} --slugs-file ${file} --readers ${g.readers.join(',')}` });
+ }
+ }
+ const sorted = [...folders.values()].sort((a, b) => a.source.localeCompare(b.source) || b.pages - a.pages || a.folder.localeCompare(b.folder));
+ const proposed = sets.reduce((n, s) => n + s.pages, 0);
+ const chats = sorted.reduce((n, f) => n + f.pages, 0);
+ return { applicable: true, owner, ...(view.inactive ? { owner_inactive: view.inactive.value } : {}), dir: sets.length ? dir : null, sets, unmatched, folders: sorted,
+ members_read_lineage: lineage, cost: LINEAGE_COST,
+ message: `${plural(proposed, 'open page')} in ${plural(sets.length, 'reader set')}, ${unmatched.length} unmatched, ${plural(chats, 'DM, chat or mail page')} with no address list.` };
+}
+
+/** The human preview: the sets and their commands, the unmatched pages, the folders and what labelling costs. */
+export function proposalLines(p: VisibilityProposal, limit = 20): string[] {
+ if (!p.applicable) return [p.message];
+ const lines = [`Proposed readers (preview only; nothing was labelled): ${p.message}`];
+ if (p.owner_inactive) lines.push(` WARNING: access.owner_member is "${p.owner_inactive}", which names no enabled member, so each command below refuses until the owner is fixed (gbrain access owner set <member>).`);
+ else if (!p.owner) lines.push(' No owner is set (gbrain access owner set <member>), so each reader set names only the matched members.');
+ if (p.sets.length) lines.push('', `Reader sets (slugs files in ${p.dir}). Preview each, then run the --apply --expect <hash> it prints:`);
+ for (const s of p.sets) lines.push(` ${s.source}: ${plural(s.pages, 'page')} -> ${s.readers.join(', ')}`, ` ${s.command}`);
+ if (p.unmatched.length) {
+ lines.push('', `Unmatched (${p.unmatched.length}): an address names no enabled member's declared email, so nothing is proposed. Declare it on the right member (gbrain access member set <id> --email <address>) and run --propose again, or label these by hand:`);
+ for (const u of p.unmatched.slice(0, limit)) lines.push(` ${u.source}:${u.slug} (${u.addresses.join(', ')})`);
+ if (p.unmatched.length > limit) lines.push(` ... and ${p.unmatched.length - limit} more (--json lists every one)`);
+ }
+ if (p.folders.length) {
+ lines.push('', 'DM, chat and mail pages with no address list, by folder. Name who reads each folder (each command previews; --yes applies):');
+ for (const f of p.folders) lines.push(` ${f.source}:${f.folder} ${plural(f.pages, 'page')}`, ` ${f.command}`);
+ }
+ lines.push('', `Cost: ${p.cost} It is ${p.members_read_lineage ? 'on' : 'off'} on this brain.`);
+ return lines;
+}
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index bdc1b8513e..755a32c55a 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -107,6 +107,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
gbrain repair segmented-tiling --source <id> [--slug <slug>]... [--apply --expect <preview-hash>] [--json]
gbrain repair visibility [--source <id>] (--slug <slug>... | --slugs-file <file>) --readers <id,group:<g>,...|none>
[--allow-without-owner] [--apply --expect <preview-hash>] [--json]
+ gbrain repair visibility --propose [--source <id>] [--out <dir>] [--json]
${REPAIR_ORDER_HELP}
${REPAIR_CONTACTS_HELP}
gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close]
@@ -152,6 +153,12 @@ Options:
visibility --readers: the pages, one slug per line (blank lines and # comments ignored).
--allow-without-owner
visibility --readers: accept readers that leave out the brain owner, whose own keys then stop reading those pages.
+ --propose visibility: preview readers for the pages every member's key can read (no readable_by, no rule) on a brain
+ that serves several people. Matches each participants, attendees, to, from and cc address to an enabled
+ member by declared email (exact), groups the pages by reader set (owner first), writes one slugs file per
+ set and prints the --readers command for each; a page with any unmatched address is listed, never
+ guessed. Labels nothing.
+ --out <dir> visibility --propose: where the slugs files go (default <config dir>/visibility-proposals; never inside a git work tree).
--cwd <prefix>, --session <id>, --principal <label>
agent-session-facts: sessions whose recorded cwd is under an absolute prefix, or this session id, are agent-launched
(both repeatable); --principal names the agent in the note when no speaker sidecar does. The hash covers them.
@@ -219,10 +226,11 @@ Pages a sync soft-deleted although Git never held their file (restore before the
Pages a managed sync's checkpoint moved past with an older version of their file: docs/guides/repair.md#rows-behind.
Facts of a strict source with no Git home (preview, apply): docs/guides/repair.md#facts-home.
A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/guides/repair.md#url-clone-fences.
+Proposed readers for the pages every member's key reads (visibility --propose): docs/guides/repair.md#propose-readers.
Renames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;
-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--include-cross-entity', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close', '--held', '--allow-without-owner']);
-const VALUE_FLAGS = new Set(['--readers', '--slugs-file', '--rules', '--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--cursor', '--provenance', '--kind', '--mode', '--run', '--key', '--generation', '--day', '--cwd', '--session', '--principal']);
+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--include-cross-entity', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close', '--held', '--allow-without-owner', '--propose']);
+const VALUE_FLAGS = new Set(['--readers', '--slugs-file', '--out', '--rules', '--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from', '--side', '--state', '--after', '--cursor', '--provenance', '--kind', '--mode', '--run', '--key', '--generation', '--day', '--cwd', '--session', '--principal']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],
@@ -234,13 +242,13 @@ const KIND_FLAGS: Record<string, readonly string[]> = {
'--after': ['uncommitted-deletions'],
'--kind': ['generations'], '--mode': ['generations'], '--run': ['generations'], '--key': ['generations'], '--generation': ['generations'], '--day': ['fact-claim-dates'], '--rules': ['secret-spans'],
'--cwd': ['agent-session-facts'], '--session': ['agent-session-facts'], '--principal': ['agent-session-facts'],
- '--readers': ['visibility'], '--slugs-file': ['visibility'], '--allow-without-owner': ['visibility'],
+ '--readers': ['visibility'], '--slugs-file': ['visibility'], '--allow-without-owner': ['visibility'], '--propose': ['visibility'], '--out': ['visibility'],
};
const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md',
'--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--side': 'deleted', '--state': 'tombstone_edited', '--keep': 'prior',
'--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old', '--after': '1200', '--cursor': 'NEXT_CURSOR', '--provenance': 'never_committed',
'--kind': 'atom', '--mode': 'restore', '--run': 'RUN_ID', '--key': 'page:notes/a', '--generation': '42', '--day': '2026-01-15', '--rules': 'openai,aws_access_key',
- '--cwd': '/srv/agent-workers', '--session': 'SESSION_ID', '--principal': 'worker-a', '--readers': 'alice-example,group:team-a', '--slugs-file': 'slugs.txt' };
+ '--cwd': '/srv/agent-workers', '--session': 'SESSION_ID', '--principal': 'worker-a', '--readers': 'alice-example,group:team-a', '--slugs-file': 'slugs.txt', '--out': '/srv/proposals' };
/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */
const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,
{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });
@@ -251,7 +259,7 @@ interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolea
held: boolean; side?: string; state?: string; provenance?: string; cursor?: string;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean; afterPage?: number;
generationKind?: string; generationMode?: string; run?: string; key?: string; generation?: number; day?: string; rules?: string[];
- cwdPrefixes: string[]; sessions: string[]; principal?: string; readers?: string; slugsFile?: string; allowWithoutOwner: boolean }
+ cwdPrefixes: string[]; sessions: string[]; principal?: string; readers?: string; slugsFile?: string; allowWithoutOwner: boolean; propose: boolean; out?: string }
/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */
function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {
@@ -295,7 +303,7 @@ function readSlugsFile(path: string): string[] {
/** Strict parse: every flag is known, value flags carry a value, at most one kind. */
export function parseRepairArgs(args: string[]): RepairArgs {
const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, includeCrossEntity: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],
- allDrifted: false, held: false, requests: [], includeFailures: false, force: false, close: false, cwdPrefixes: [], sessions: [], allowWithoutOwner: false };
+ allDrifted: false, held: false, requests: [], includeFailures: false, force: false, close: false, cwdPrefixes: [], sessions: [], allowWithoutOwner: false, propose: false };
const used = new Set<string>();
const positional: string[] = [];
let maxUsdText: string | undefined;
@@ -328,6 +336,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--force') parsed.force = true;
else if (flag === '--close') parsed.close = true;
else if (flag === '--allow-without-owner') parsed.allowWithoutOwner = true;
+ else if (flag === '--propose') parsed.propose = true;
else parsed.noEmbed = true;
continue;
}
@@ -341,6 +350,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--slug') parsed.slugs.push(value);
else if (flag === '--readers') parsed.readers = value;
else if (flag === '--slugs-file') parsed.slugsFile = value;
+ else if (flag === '--out') parsed.out = value;
else if (flag === '--max-usd') { maxUsdText = value; maxUsdFlag = flag; }
else if (flag === '--prefer') {
if (value !== 'file' && value !== 'database') throw invalid('--prefer takes file or database.', 'Pass --prefer file (the canonical file wins) or --prefer database (the database copy wins).',
@@ -418,6 +428,12 @@ export function parseRepairArgs(args: string[]): RepairArgs {
throw invalid(`${parsed.slugsFile !== undefined ? '--slugs-file' : '--allow-without-owner'} applies only with --readers.`,
'Set readers on named pages: gbrain repair visibility --slugs-file <file> --readers <ids> (or --slug <slug>).', ['gbrain', 'repair', 'visibility', '--json']);
}
+ if (parsed.out !== undefined && !parsed.propose) throw invalid('--out applies only with --propose.', 'Preview proposed readers: gbrain repair visibility --propose --out <dir>.', ['gbrain', 'repair', 'visibility', '--propose', '--json']);
+ if (parsed.propose) {
+ const extra = args.map(token => token.split('=')[0]!).find(flag => flag.startsWith('-') && !['--propose', '--source', '--out', '--json'].includes(flag));
+ if (extra) throw invalid(`${extra} does not apply with --propose: it only previews, so it takes --source, --out and --json.`,
+ 'Run gbrain repair visibility --propose, then preview and apply each printed --readers command on its own.', ['gbrain', 'repair', 'visibility', '--propose', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);
+ }
if (parsed.slugsFile !== undefined && parsed.slugs.length) throw invalid('Pass --slug or --slugs-file, not both.', 'List every page in the slugs file, or name them with --slug.', ['gbrain', 'repair', 'visibility', '--json']);
if (used.has('--yes') && REPAIR_REGISTRY.find(spec => spec.kind === parsed.kind)?.consent !== 'destructive') throw invalid('`--yes` is not accepted by gbrain repair; pass --apply to write.',
`Preview first with gbrain repair${parsed.kind ? ` ${parsed.kind}` : ''}, then run the same command with --apply instead of --yes.`,
@@ -512,7 +528,14 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
const { kind, apply, all, json, noEmbed, includeAmbiguous, includeCrossEntity, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,
prefer, requests, allDrifted, driftClass, since, held, side, state, provenance, cursor, keep, requestId, olderThan, includeFailures, force, from, close, afterPage,
- generationKind, generationMode, run, key, generation, day, rules, cwdPrefixes, sessions, principal, readers, slugsFile, allowWithoutOwner } = parseRepairArgs(args);
+ generationKind, generationMode, run, key, generation, day, rules, cwdPrefixes, sessions, principal, readers, slugsFile, allowWithoutOwner, propose, out } = parseRepairArgs(args);
+ if (propose) {
+ if (source) await resolveRepairScope(engine, source);
+ const { proposeVisibility, proposalLines } = await import('./repair-propose.ts');
+ const proposal = await proposeVisibility(engine, { ...(source ? { source } : {}), ...(out ? { out } : {}) });
+ console.log(json ? JSON.stringify(proposal, null, 2) : proposalLines(proposal).join('\n'));
+ return;
+ }
const readersRequest = readers === undefined ? undefined : { readers, ...(allowWithoutOwner ? { allowWithoutOwner } : {}), ...(slugsFile ? { slugsFile: { path: slugsFile, slugs: readSlugsFile(slugsFile) } } : {}) };
const generations: GenerationsSelection | undefined = kind === 'generations' ? { kind: generationKind ?? '', mode: (generationMode ?? 'restore') as GenerationMode,
...(run ? { run } : {}), ...(since ? { since } : {}), ...(key ? { key } : {}), ...(generation !== undefined ? { generation } : {}), ...(held ? { held } : {}) } : undefined;
diff --git a/src/core/access/open-pages.ts b/src/core/access/open-pages.ts
index 5eb7558513..bb3968062a 100644
--- a/src/core/access/open-pages.ts
+++ b/src/core/access/open-pages.ts
@@ -9,7 +9,8 @@
* clients read. Read-only and best effort everywhere it is shown: access serves several (preview and receipt),
* gbrain access serves, doctor open_shared_pages and post-upgrade. Callers gate on brainServes first, so a
* one-person brain, or one pinned to access.serves one, never runs it. Everything is database state, so a repo-less
- * brain gets it unchanged.
+ * brain gets it unchanged. gbrain repair visibility --propose (commands/repair-propose.ts) reads the same pages through
+ * withOpenScope, openPageSql and membersReadOpen.
*/
import type { BrainEngine } from '../engine.ts';
import { accessAllowedSql, privacyPartSql, readHonorAliases, remotePrivacyRelaxed, withoutCallerAccess } from '../search/private-visibility.ts';
@@ -121,8 +122,29 @@ async function bounded<T>(engine: BrainEngine, fn: (e: BrainEngine) => Promise<T
}, { readOnly: true });
}
-/** The open pages the counted members' keys read (OpenPages); throws when the access state cannot be read. */
-export async function openPages(engine: BrainEngine, opts: OpenPagesOptions = {}): Promise<OpenPages> {
+/** Who reads the open pages: the owner, the counted members, the sources their keys read, and how private pages read. */
+export interface OpenScope {
+ owner: string | null;
+ members: { reading: number; counted: number };
+ /** The sources the reading members read, or every source when no member reads one. */
+ sources: string[];
+ /** Remote privacy is relaxed, so members read visibility: private pages too. */
+ relaxed: boolean;
+ /** Sources whose private pages some reading member's grant opens. */
+ privateSources: string[];
+}
+
+/** The open-page predicate over pages alias `p`: live, and the read path's floor with an empty identity admits it. */
+export const openPageSql = (p: string) => `${p}.deleted_at IS NULL AND ${accessAllowedSql(p, [], [])}`;
+
+/** Whether the members read an open page of `source` whose privacyPartSql value is `visible`. */
+export const membersReadOpen = (scope: OpenScope, source: string, visible: unknown) => visible === true || scope.relaxed || scope.privateSources.includes(source);
+
+/**
+ * The OpenScope; throws open_pages_unknown when the folder-rule state cannot be read. `read` then runs a query built on
+ * openPageSql under the same statement bound, outside any caller record, so it never depends on who asks.
+ */
+export async function withOpenScope<T>(engine: BrainEngine, opts: OpenPagesOptions, read: (scope: OpenScope, bounded: <R>(fn: (e: BrainEngine) => Promise<R>) => Promise<R>) => Promise<T>): Promise<T> {
return withoutCallerAccess(async () => {
const [state] = await engine.executeRaw<{ unreadable: unknown }>('SELECT gbrain_access_state_unreadable() AS unreadable');
if (state?.unreadable === true) {
@@ -131,29 +153,38 @@ export async function openPages(engine: BrainEngine, opts: OpenPagesOptions = {}
const owner = await ownerMemberId(engine);
const { reads, privateSources } = await memberReads(engine, owner, opts.planned);
const reading = [...reads.values()].filter(s => s.size > 0);
- const read = [...new Set(reading.flatMap(s => [...s]))].sort();
- const sources = read.length ? read : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(s => s.id);
- const result: OpenPages = { owner, members: { reading: reading.length, counted: reads.size }, sources, total: 0, sensitive: 0, private: 0,
+ const readSources = [...new Set(reading.flatMap(s => [...s]))].sort();
+ const sources = readSources.length ? readSources : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(s => s.id);
+ if (sources.length) await readHonorAliases(engine);
+ const relaxed = sources.length ? await remotePrivacyRelaxed(engine) : false;
+ const scope: OpenScope = { owner, members: { reading: reading.length, counted: reads.size }, sources, relaxed, privateSources: [...privateSources].sort() };
+ return read(scope, fn => bounded(engine, fn));
+ });
+}
+
+/** The open pages the counted members' keys read (OpenPages); throws when the access state cannot be read. */
+export async function openPages(engine: BrainEngine, opts: OpenPagesOptions = {}): Promise<OpenPages> {
+ return withOpenScope(engine, opts, async (scope, boundedRead) => {
+ const { owner, sources } = scope;
+ const result: OpenPages = { owner, members: scope.members, sources, total: 0, sensitive: 0, private: 0,
folders: [], other: { folders: 0, pages: 0, sensitive: 0 }, top_sensitive: null };
if (!sources.length) return result;
- await readHonorAliases(engine);
- const relaxed = await remotePrivacyRelaxed(engine);
const params: unknown[] = [sources];
const exclude = (opts.exclude ?? []).map(x => {
params.push(x.source, x.prefix);
return ` AND NOT (p.source_id = $${params.length - 1} AND starts_with(p.slug, $${params.length}))`;
}).join('');
- const rows = await bounded(engine, e => e.executeRaw<{ source: string; folder: string; type: string | null; visible: unknown; pages: number | string }>(
+ const rows = await boundedRead(e => e.executeRaw<{ source: string; folder: string; type: string | null; visible: unknown; pages: number | string }>(
`SELECT p.source_id AS source, CASE WHEN strpos(p.slug, '/') > 0 THEN split_part(p.slug, '/', 1) ELSE '(root)' END AS folder,
p.type AS type, (${privacyPartSql('p')}) AS visible, count(*)::int AS pages
FROM pages p
- WHERE p.deleted_at IS NULL AND p.source_id = ANY($1::text[]) AND ${accessAllowedSql('p', [], [])}${exclude}
+ WHERE ${openPageSql('p')} AND p.source_id = ANY($1::text[])${exclude}
GROUP BY 1, 2, 3, 4`, params));
const folders = new Map<string, OpenFolder>();
const byType = new Map<string, { source: string; type: string; pages: number }>();
for (const row of rows) {
const n = Number(row.pages);
- if (row.visible !== true && !relaxed && !privateSources.has(row.source)) { result.private += n; continue; }
+ if (!membersReadOpen(scope, row.source, row.visible)) { result.private += n; continue; }
const key = `${row.source}/${row.folder}`;
const f = folders.get(key) ?? { source: row.source, folder: row.folder, pages: 0, sensitive: 0 };
folders.set(key, f);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 8edb3dd05d..c78d58255d 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -82,7 +82,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--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', '--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', '--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'],
'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'],
@@ -114,7 +114,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reindex-search-vector': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--room', '--source', '--timeout', '--timings', '--wait', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--check', '--code', '--concurrency', '--confirm-destructive', '--content-root', '--cursor', '--db-only', '--detail', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--hold-state', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--plan', '--prefer', '--prefer-postgres', '--preview', '--priority', '--provenance', '--query', '--quiet', '--redact-paths', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--remediation-plan', '--request-id', '--scopes', '--source', '--timeout'],
- 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--audit', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--conflicts', '--cursor', '--cwd', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--out', '--prefer', '--preview', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--room', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],
+ 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--audit', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--conflicts', '--cursor', '--cwd', '--day', '--diff', '--email', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--out', '--prefer', '--prefix', '--preview', '--principal', '--probe', '--progress-interval', '--progress-json', '--propose', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--room', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--slugs-file', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],
'repair-jsonb': ['--accept-pending', '--as', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--supabase', '--timeout', '--timings', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--approval-out', '--approved', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--force-with-lease', '--format', '--from', '--from-git', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--heads', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--install', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--limit', '--list-out', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--may-act-for', '--member', '--message', '--migrate-legacy', '--migration', '--min-trust', '--mode', '--name', '--name-only', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-edit', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-follow-tags', '--no-harden', '--no-lanes', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--not', '--only', '--operation', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--pull', '--push-only', '--push-remote', '--quiet', '--read-sources', '--readers', '--reads-unscoped', '--rebase', '--recurse-submodules', '--redirect-uri', '--refresh-operations', '--remote', '--remove', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--stat', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--to', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--uninstall', '--unset-all', '--unsettle', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 719170b32b..0d9f5aa566 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -92,6 +92,7 @@ export const CODES = {
credential_scope_required: { class: 'caller', docs: 'docs/guides/write-refusals.md#credential_scope_required', summary: 'gbrain auth create or gbrain auth register-client was asked for a credential bound to no member on a brain that serves several people, so nothing was created.', why: 'A credential bound to nobody on such a brain is refused on every read (requester_scope_required); creating one would hand out a key that cannot work, or one that reads everyone\'s unmarked notes.', suggestion: 'Bind it to the person it serves: gbrain auth create <name> --member <id> (gbrain access member list names the members). A shared agent passes --may-act-for <members> instead; --reads-unscoped --yes creates one that reads every page no rule restricts for any asker, on purpose.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists the members a credential can be bound to.' } },
access_serves_roster_empty: { class: 'caller', summary: 'gbrain setup --serves several or gbrain access serves several was given no people (no --members, an empty --members-file), so nothing was written.', why: 'Each person gets a member, a folder only they read and a key bound to them; the installer never guesses who they are.', suggestion: 'Name every person: --members alice-example,bob-example, or --members-file <file> with one id per line.' },
access_serves_key_dir_in_git: { class: 'caller', summary: 'The directory the per-member keys would be written to is inside a git work tree, so no key, member or rule was written.', why: 'Key files hold live credentials; a file inside a checkout can be committed and pushed.', suggestion: 'Point GBRAIN_HOME at a directory outside any git checkout (the default is your home directory) and run the command again.' },
+ repair_propose_dir_in_git: { class: 'caller', docs: 'docs/guides/repair.md#propose-readers', summary: 'gbrain repair visibility --propose was pointed at a directory inside a git work tree for its slugs files, so nothing was written.', why: 'The slugs files list page slugs and who would read them; a file inside a checkout can be committed and pushed.', suggestion: 'Pass --out <dir> outside any git checkout, or leave --out off to use the gbrain config directory (with GBRAIN_HOME outside any checkout).' },
access_member_id_retired: { class: 'caller', summary: "The member id was removed earlier and member ids are never reused, so nothing was created or enabled.", why: 'Pages and audit history may still name a removed id; reusing it would hand that history to a different person.', docs: 'docs/guides/write-refusals.md#access_member_id_retired', suggestion: 'Choose a new member id.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status, removed ones included.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },
access_labelled_only_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A labelled-only grant was asked for on the brain owner (gbrain access member labelled-only <owner> on), or a labelled-only member was named the owner (gbrain access owner set), so nothing was changed.", why: "The owner reads the whole brain. A labelled-only grant hides every page that does not name its member, so on the owner it would silently hide the owner's own brain from every credential bound to it.", suggestion: 'Ask the user which member the group or audience credential should read as; give it its own member and mark that one labelled-only, or clear the grant before naming the owner.' },
access_labelled_only_unnamed: { class: 'caller', summary: "A credential whose member is labelled-only tried to create a page that would not name it: the page has no readable_by holding the member or one of its groups, and no folder or page rule over its slug lists them, so nothing was written.", why: 'A labelled-only member reads only pages labelled for it, so a page it creates must name it; otherwise it would write a page it could never read back, readable by every other caller its source admits.', suggestion: 'Add readable_by naming the member or one of its groups to the frontmatter (readable_by: [alice-example, group:team-a]), or ask the brain operator to add a folder rule over the path that lists it, then submit again with a new request_id.' },
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index a4c3f219b3..4c980f6bb1 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -6873,7 +6873,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_history_unreadable\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"openclaw_not_found\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_adopt_field_refused\" | \"storage_adopt_unverified\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"timeout\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"page_body_rows_unreadable\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_identity_unavailable\" | \"access_member_disabled\" | \"autopilot_no_repo\" | \"autopilot_pglite_daemon\" | \"cycle_already_running\" | \"engine_degraded\" | \"maintenance_disabled\" | \"maintenance_owned_by_serve\" | \"schedule_unsupported\" | \"schedule_install_failed\" | \"maintenance_owned_by_autopilot\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_history_unreadable\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"requester_scope_required\" | \"requester_scope_unknown\" | \"credential_scope_required\" | \"access_serves_roster_empty\" | \"access_serves_key_dir_in_git\" | \"repair_propose_dir_in_git\" | \"access_member_id_retired\" | \"access_labelled_only_owner\" | \"access_labelled_only_unnamed\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"append_links_fence\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"valid_time_undeclared\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"host_upgrade_required\" | \"change_reason_rejected\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkout_not_a_source\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_behind\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_base_moved\" | \"commit_paths_invalid\" | \"commit_paths_skipped\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_filter_owned\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"downgrade_blocked_deferred_writes\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_alert_act\" | \"doctor_alert_unknown\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"enforced_member_refused\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_scope_required\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"foreign_table\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"moved_pages_mass_fold_refused\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_delta\" | \"conversion_file_in_source_root\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"link_dates_unattributed\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"memory_setting_write_outcome_unknown\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_projection_stale\" | \"label_edit_refused\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"publish_secret_found\" | \"publish_scan_unreadable\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"postgres_tls_required\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"proposal_closed\" | \"proposal_expired\" | \"proposals_pending_limit\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"reason_purge_scan_capped\" | \"reason_purge_scan_failed\" | \"reason_scan_capped\" | \"reason_scan_failed\" | \"reason_trailer_secret\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"pending_import_expired\" | \"refresh_barrier_expired\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"repair_preview_timeout\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_backfill_pending\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"openclaw_not_found\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"setup_serves_several\" | \"setup_serves_unreadable\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_catalog_mismatch\" | \"skill_catalog_too_large\" | \"skill_catalog_unknown\" | \"skill_index_incompatible\" | \"skill_index_locked\" | \"skill_index_missing\" | \"skill_index_removed\" | \"skill_resolve_invalid_input\" | \"skill_resolve_no_input\" | \"skill_resolve_timeout\" | \"skill_resolver_config_invalid\" | \"skill_resolver_config_unreadable\" | \"skill_resolver_setup_incomplete\" | \"skill_resolver_plugin_not_installed\" | \"skill_resolver_host_not_local\" | \"skill_resolver_selftest_failed\" | \"skill_resolver_pin_unknown\" | \"skill_resolver_library_missing\" | \"skill_resolver_library_mismatch\" | \"skill_resolver_library_skew\" | \"skill_resolver_worker_crash\" | \"skill_resolver_worker_stuck\" | \"skill_resolver_worker_unavailable\" | \"skill_resolver_state_missing\" | \"skill_resolver_host_load_cut\" | \"skill_resolver_internal\" | \"skill_source_invalid\" | \"skill_source_unreadable\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"skillpack_backup_corrupt\" | \"skillpack_journal_not_found\" | \"skillpack_restore_conflict\" | \"skillpack_state_locked\" | \"skillpack_update_incomplete\" | \"skillpack_workspace_locked\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_pages_remain\" | \"source_referenced\" | \"source_retire_superseded\" | \"source_root_conflict\" | \"source_root_unreadable\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stable_invalid\" | \"stable_missing\" | \"stable_unreadable\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"storage_adopt_field_refused\" | \"storage_adopt_unverified\" | \"storage_card_exists\" | \"storage_manifest_missing\" | \"storage_record_invalid\" | \"storage_record_secret\" | \"storage_revision_conflict\" | \"storage_source_managed\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"tag_too_long\" | \"target_escape\" | \"timeline_comment_markup\" | \"source_writer_restricted\" | \"guest_page_immutable\" | \"guest_page_promoted\" | \"guest_attribution_missing\" | \"guest_frontmatter_refused\" | \"guest_readers_invalid\" | \"guest_promotion_owner_only\" | \"guest_mark_immutable\" | \"guest_source_database_only\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"untrack_not_db_only\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"wakeshift_key_invalid\" | \"wakeshift_needs_conversation\" | \"wakeshift_not_enabled\" | \"wakeshift_refused\" | \"wakeshift_shared_brain\" | \"wakeshift_unavailable\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"worktree_refreshing\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index a4716d57ef..c1f258764f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -603,6 +603,7 @@ test/repair-receipt-compaction.test.ts
test/repair-rename-identity-6729.test.ts
test/repair-secret-spans.test.ts
test/repair-unwithdrawn-facts-8819.test.ts
+test/repair-visibility-propose-gst2670.test.ts
test/request-tools-combined-gbra449.test.ts
test/requester-scope.test.ts
test/retrieval-coverage-notices.test.ts
diff --git a/test/repair-visibility-propose-gst2670.test.ts b/test/repair-visibility-propose-gst2670.test.ts
new file mode 100644
index 0000000000..82849ee29b
--- /dev/null
+++ b/test/repair-visibility-propose-gst2670.test.ts
@@ -0,0 +1,225 @@
+/**
+ * GST-2670 phase 2 (GBRA-502, decision B1): gbrain repair visibility --propose.
+ *
+ * 1. Protects: on a brain that serves several people, --propose reads the open pages' participants, attendees, to,
+ * from and cc addresses, matches each to an enabled member by declared email (exact, case-folded), groups pages by
+ * reader set with the owner first, writes one 0600 slugs file per set and prints the existing --readers command;
+ * a page with any unmatched address is listed, never guessed; DM, chat and mail pages with no list get the folder
+ * rule command. It labels nothing, refuses an --out inside a git work tree, and on a one-person brain (or one
+ * pinned to access.serves one) says "nothing to propose" before any pages query.
+ * 2. Fails when: a guess or a disabled member's email makes a proposal, the owner is missing or not first, a slugs
+ * file holds other slugs or is readable by others, a write lands in pages, rules, config or members, a printed
+ * command does not parse with the real flag tables, or a one-person brain runs a pages query.
+ * 3. Real seams: the gbrain repair CLI module (parse and dispatch), the access rule CLI module, PGLite repo-less
+ * (Postgres when DATABASE_URL is set); the printed command previewed and applied for real.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { addMember } from '../src/core/access/members.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';
+import { runAccessRules } from '../src/commands/access-rules.ts';
+import { proposalLines, type VisibilityProposal } from '../src/commands/repair-propose.ts';
+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+import { CODES } from '../src/core/error-registry.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SRC = 'source-a';
+const fm = (type: string, extra = '') => `---\ntype: ${type}\ntitle: t\n${extra}---\n# t\n\nHarbor ledger body.\n`;
+const PAGES: Array<[string, string]> = [
+ ['meetings/m1', fm('meeting', 'attendees: [[email protected], [email protected]]\n')],
+ ['meetings/m5', fm('meeting', 'attendees: [[email protected], [email protected], [email protected]]\n')],
+ ['meetings/m4', fm('meeting', 'participants: [[email protected]]\n')],
+ ['emails/e1', fm('email', 'from: "Alice Example <[email protected]>"\nto: [[email protected]]\n')],
+ ['emails/e2', fm('email', 'from: [email protected]\ncc: [[email protected]]\n')],
+ ['emails/e3', fm('email', 'participants: [[email protected]]\n')],
+ ['meetings/m2', fm('meeting', 'attendees: [alice-example]\n')],
+ ['chats/team-a/day-1', fm('dm')],
+ ['chats/team-a/day-2', fm('conversation')],
+ ['notes/plain', fm('note')],
+ ['labelled/m3', fm('meeting', 'attendees: [[email protected]]\nreadable_by: [owner-example, alice-example]\n')],
+];
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+const tempDir = (p: string) => { const d = mkdtempSync(join(tmpdir(), p)); roots.push(d); return d; };
+
+/** Counts the queries that read the pages table. */
+function spyPages(engine: BrainEngine): { count: () => number; restore: () => void } {
+ const own = Object.prototype.hasOwnProperty.call(engine, 'executeRaw');
+ const original = engine.executeRaw;
+ let n = 0;
+ (engine as any).executeRaw = function (this: BrainEngine, sql: string, params?: unknown[]) { if (/\bFROM pages\b/i.test(sql)) n++; return original.call(this, sql, params as never); };
+ return { count: () => n, restore: () => { if (own) (engine as any).executeRaw = original; else delete (engine as any).executeRaw; } };
+}
+
+async function stateHash(engine: BrainEngine): Promise<string> {
+ const rows = await Promise.all([
+ engine.executeRaw("SELECT slug, source_id, frontmatter::text AS f, page_readers::text AS r FROM pages ORDER BY source_id, slug"),
+ engine.executeRaw("SELECT source_id, rule_id FROM access_rules ORDER BY 1, 2"),
+ engine.executeRaw("SELECT key, value FROM config WHERE key NOT LIKE 'doctor.%' ORDER BY key"),
+ engine.executeRaw("SELECT id, email, labelled_only, disabled_at FROM access_members ORDER BY id"),
+ ]);
+ return JSON.stringify(rows);
+}
+
+async function capture(fn: () => Promise<unknown>): Promise<string> {
+ const lines: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });
+ try { await fn(); } finally { spy.mockRestore(); }
+ return lines.join('\n');
+}
+
+for (const kind of testBackends()) {
+ describe(`repair visibility --propose (${kind}, repo-less)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let home: string;
+ const repair = (args: string[]) => withEnv({ GBRAIN_HOME: home }, () => capture(() => runRepairCommand(engine, args)));
+ const propose = async (extra: string[] = []): Promise<VisibilityProposal> => JSON.parse(await repair(['visibility', '--propose', ...extra, '--json']));
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ home = tempDir('gbrain-propose-');
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING", [SRC]);
+ for (const [slug, text] of PAGES) await importFromContent(engine, slug, text, { sourceId: SRC, noEmbed: true });
+ await importFromContent(engine, 'meetings/elsewhere', fm('meeting', 'attendees: [[email protected]]\n'), { sourceId: 'default', noEmbed: true });
+ }, 120_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test('a brain with no member, then one member, has nothing to propose and runs no pages query', async () => {
+ for (const add of [null, 'owner-example']) {
+ if (add) { await addMember(engine, add, { email: '[email protected]' }); await setOwner(engine, add); }
+ const spy = spyPages(engine);
+ try {
+ const p = await propose();
+ expect(p.applicable).toBe(false);
+ expect(p.message).toStartWith('Nothing to propose');
+ expect(proposalLines(p)).toEqual([p.message]);
+ expect(p.sets).toEqual([]);
+ expect(spy.count()).toBe(0);
+ } finally { spy.restore(); }
+ }
+ expect(existsSync(join(home, '.gbrain', 'visibility-proposals'))).toBe(false);
+ }, 60_000);
+
+ test('a brain pinned to access.serves one with several enabled members has nothing to propose either', async () => {
+ await addMember(engine, 'alice-example', { email: '[email protected]' });
+ await addMember(engine, 'bob-example', { email: '[email protected]' });
+ await addMember(engine, 'carol-example', { email: '[email protected]' });
+ await engine.executeRaw("UPDATE access_members SET disabled_at = now() WHERE id = 'carol-example'");
+ await engine.setConfig('access.serves', 'one');
+ const spy = spyPages(engine);
+ try {
+ const p = await propose();
+ expect(p.applicable).toBe(false);
+ expect(p.message).toContain('access.serves is one');
+ expect(spy.count()).toBe(0);
+ } finally { spy.restore(); await engine.unsetConfig('access.serves'); }
+ }, 60_000);
+
+ test('it groups fully matched pages by reader set, owner first, lists unmatched and chat folders, and writes nothing but 0600 slugs files', async () => {
+ const before = await stateHash(engine);
+ const p = await propose(['--source', SRC]);
+ expect(await stateHash(engine)).toBe(before);
+ expect(p.applicable).toBe(true);
+ expect(p.owner).toBe('owner-example');
+ const sets = Object.fromEntries(p.sets.map(s => [s.readers.join(','), readFileSync(s.file, 'utf8')]));
+ expect(sets).toEqual({
+ 'owner-example,alice-example,bob-example': 'meetings/m1\nmeetings/m5\n',
+ 'owner-example,alice-example': 'emails/e1\n',
+ 'owner-example,bob-example': 'meetings/m4\n',
+ });
+ for (const s of p.sets) {
+ expect(s.readers[0]).toBe('owner-example');
+ expect(s.source).toBe(SRC);
+ expect(statSync(s.file).mode & 0o777).toBe(0o600);
+ expect(s.file.startsWith(join(home, '.gbrain', 'visibility-proposals') + '/')).toBe(true);
+ expect(s.command).toBe(`gbrain repair visibility --source ${SRC} --slugs-file ${s.file} --readers ${s.readers.join(',')}`);
+ }
+ expect(readdirSync(join(home, '.gbrain', 'visibility-proposals')).sort()).toEqual(p.sets.map(s => basename(s.file)).sort());
+ expect(Object.fromEntries(p.unmatched.map(u => [u.slug, u.addresses]))).toEqual({
+ 'emails/e2': ['[email protected]'], 'emails/e3': ['[email protected]'], 'meetings/m2': ['alice-example'] });
+ expect(p.folders).toEqual([{ source: SRC, folder: 'chats/team-a/', pages: 2,
+ command: `gbrain access rule add --prefix chats/team-a/ --readers owner-example,<list> --source ${SRC}` }]);
+ expect(JSON.stringify(p)).not.toContain('notes/plain');
+ const all = [...p.sets.flatMap(s => readFileSync(s.file, 'utf8').trim().split('\n')), ...p.unmatched.map(u => u.slug)];
+ expect(all).not.toContain('labelled/m3');
+ expect(all).not.toContain('meetings/elsewhere');
+ const text = await repair(['visibility', '--propose', '--source', SRC]);
+ expect(text).toContain('derived atoms, facts and chronicle events');
+ expect(text).toContain('access.members_read_lineage');
+ expect(text).toContain('emails/e2 ([email protected])');
+ expect(await stateHash(engine)).toBe(before);
+ }, 60_000);
+
+ test('without --source it reads every source, still only open pages', async () => {
+ const p = await propose();
+ const elsewhere = p.sets.find(s => s.source === 'default');
+ expect(elsewhere?.readers).toEqual(['owner-example', 'alice-example']);
+ expect(readFileSync(elsewhere!.file, 'utf8')).toBe('meetings/elsewhere\n');
+ }, 60_000);
+
+ test('an --out inside a git work tree is refused before anything is written', async () => {
+ const repo = tempDir('gbrain-propose-git-');
+ execFileSync('git', ['init', '-q', repo]);
+ const out = join(repo, 'nested', 'proposals');
+ const before = await stateHash(engine);
+ let error: any;
+ try { await propose(['--out', out]); } catch (e) { error = e; }
+ expect(error?.code).toBe('repair_propose_dir_in_git');
+ expect(CODES.repair_propose_dir_in_git).toBeDefined();
+ expect(existsSync(join(repo, 'nested'))).toBe(false);
+ expect(await stateHash(engine)).toBe(before);
+ const outside = join(tempDir('gbrain-propose-out-'), 'sets');
+ const p = await propose(['--source', SRC, '--out', outside]);
+ expect(p.dir).toBe(outside);
+ for (const s of p.sets) expect(s.file.startsWith(outside + '/')).toBe(true);
+ }, 60_000);
+
+ test('--propose takes only --source, --out and --json, and --out needs --propose', () => {
+ for (const extra of [['--apply'], ['--expect', 'h'], ['--readers', 'alice-example'], ['--slug', 'notes/a'], ['--limit', '5']]) {
+ expect(() => parseRepairArgs(['visibility', '--propose', ...extra])).toThrow(/does not apply with --propose/);
+ }
+ expect(() => parseRepairArgs(['visibility', '--out', '/srv/x'])).toThrow(/--out applies only with --propose/);
+ expect(() => parseRepairArgs(['frontmatter', '--propose'])).toThrow(/--propose applies only to gbrain repair visibility/);
+ expect(CLI_FLAG_REGISTRY.repair).toEqual(expect.arrayContaining(['--propose', '--out']));
+ });
+
+ test('each printed command parses with the real flag tables, previews, and applying one closes exactly its pages', async () => {
+ const p = await propose(['--source', SRC]);
+ for (const s of p.sets) {
+ const argv = s.command.split(' ');
+ expect(argv.slice(0, 3)).toEqual(['gbrain', 'repair', 'visibility']);
+ const parsed = parseRepairArgs(argv.slice(2));
+ expect(parsed).toMatchObject({ kind: 'visibility', source: SRC, slugsFile: s.file, readers: s.readers.join(','), apply: false, propose: false });
+ for (const flag of argv.filter(a => a.startsWith('--'))) expect(CLI_FLAG_REGISTRY.repair).toContain(flag);
+ }
+ for (const f of p.folders) {
+ const argv = f.command.replace('<list>', 'alice-example').split(' ');
+ expect(argv.slice(0, 4)).toEqual(['gbrain', 'access', 'rule', 'add']);
+ for (const flag of argv.filter(a => a.startsWith('--'))) expect(CLI_FLAG_REGISTRY.access).toContain(flag);
+ const before = await stateHash(engine);
+ const preview = JSON.parse(await capture(() => runAccessRules(engine, 'rule', [...argv.slice(3), '--json'], true)));
+ expect(preview.applied).toBe(false);
+ expect(await stateHash(engine)).toBe(before);
+ }
+ const set = p.sets.find(s => s.readers.length === 3)!;
+ const preview = JSON.parse(await repair([...set.command.split(' ').slice(2), '--json'])).results[0];
+ expect(preview.affected).toBe(2);
+ await repair([...set.command.split(' ').slice(2), '--apply', '--expect', preview.preview_hash, '--json']);
+ const rows = await engine.executeRaw<{ slug: string; r: unknown }>("SELECT slug, frontmatter->'readable_by' AS r FROM pages WHERE source_id = $1 AND slug IN ('meetings/m1', 'meetings/m5') ORDER BY slug", [SRC]);
+ for (const row of rows) expect(row.r).toEqual(['owner-example', 'alice-example', 'bob-example']);
+ const again = await propose(['--source', SRC]);
+ expect(again.sets.map(s => s.readers.join(',')).sort()).toEqual(['owner-example,alice-example', 'owner-example,bob-example']);
+ }, 120_000);
+ });
+}