Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Set a page's readers through the label-only repair, keeping its trust tier and provenance (GST-2476)

garrytan5c813d70b700
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index c8ebb8ce78..f776da7000 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -40,6 +40,7 @@ import { normalizeSeatLabel } from '../core/context/seat.ts';
import { agentSessionFlagArgs } from '../core/repair/agent-session-facts.ts';
import { privateLabelsLedger } from './repair-private-labels.ts';
import { isAbsolute } from 'node:path';
+import { readFileSync } from 'node:fs';
/** The content-repair lane's command word (#6377): parsed like a kind, dispatched to repair-content.ts, never a RepairKind. */
export const CONTENT_LANE = 'content';
@@ -102,6 +103,8 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
gbrain repair provenance [--source <id>] [--slug <slug>]... [--include-ambiguous] [--apply --expect <preview-hash> --yes] [--json]
gbrain repair secret-spans --source <id> --slug <slug>... [--rules <rule,...>] [--no-embed] [--apply --expect <preview-hash>] [--json]
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]
${REPAIR_ORDER_HELP}
${REPAIR_CONTACTS_HELP}
gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close]
@@ -138,6 +141,15 @@ Options:
--slug <slug> fences, file-drift: select a database page by slug (repeatable); the hash covers the selection.
rename-identity: the new page of the one open pair to preview (--from <old-slug> when two pairs share it).
--close rename-identity: release the pair's purge hold instead of carrying its identity; nothing moves.
+ --readers <id,group:<g>,...|none>
+ visibility, with --slug or --slugs-file: set the named pages' readable_by (none removes it) through the
+ label-only door: tier, provenance stamps and every other line of the file kept. Each reader must be an
+ enabled member or an existing group; a list that leaves out the brain owner refuses (a group holding the
+ owner does not count). Preview-bound: --apply --expect <hash>.
+ --slugs-file <file>
+ 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.
--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.
@@ -205,8 +217,8 @@ Pages a managed sync's checkpoint moved past with an older version of their file
A sources add --url clone whose pull stops at pull_blocked_local_changes: docs/guides/repair.md#url-clone-fences.
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']);
-const VALUE_FLAGS = new Set(['--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']);
+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']);
/** 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'],
@@ -218,12 +230,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'],
};
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' };
+ '--cwd': '/srv/agent-workers', '--session': 'SESSION_ID', '--principal': 'worker-a', '--readers': 'alice-example,group:team-a', '--slugs-file': 'slugs.txt' };
/** 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 }) });
@@ -234,7 +247,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 }
+ cwdPrefixes: string[]; sessions: string[]; principal?: string; readers?: string; slugsFile?: string; allowWithoutOwner: boolean }
/** `--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 {
@@ -264,10 +277,21 @@ function fileDriftKeepRefusal(args: string[], keep: string): OperationError {
{ fix: readFix('Previews the file-drift resolution with the database copy winning; without --apply it writes nothing.', { argv }) });
}
+/** GST-2476: the slugs a --slugs-file lists, one per line; blank lines and # comments are skipped. */
+function readSlugsFile(path: string): string[] {
+ let text: string;
+ try { text = readFileSync(path, 'utf8'); } catch (error) {
+ throw invalid(`--slugs-file ${path} could not be read (${(error as NodeJS.ErrnoException).code ?? 'error'}).`, 'Pass a readable file with one slug per line.', ['gbrain', 'repair', 'visibility', '--json']);
+ }
+ const slugs = text.split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#'));
+ if (!slugs.length) throw invalid(`--slugs-file ${path} lists no slug.`, 'Write one slug per line (e.g. notes/a-example).', ['gbrain', 'repair', 'visibility', '--json']);
+ return slugs;
+}
+
/** 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: [] };
+ allDrifted: false, held: false, requests: [], includeFailures: false, force: false, close: false, cwdPrefixes: [], sessions: [], allowWithoutOwner: false };
const used = new Set<string>();
const positional: string[] = [];
let maxUsdText: string | undefined;
@@ -299,6 +323,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--include-failures') parsed.includeFailures = true;
else if (flag === '--force') parsed.force = true;
else if (flag === '--close') parsed.close = true;
+ else if (flag === '--allow-without-owner') parsed.allowWithoutOwner = true;
else parsed.noEmbed = true;
continue;
}
@@ -310,6 +335,8 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--only') parsed.only.push(value);
else if (flag === '--skip') parsed.skip.push(value);
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 === '--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).',
@@ -383,6 +410,11 @@ export function parseRepairArgs(args: string[]): RepairArgs {
`Kinds: ${REPAIR_KINDS.join(', ')}.`);
parsed.kind = positional[0];
if (keepText !== undefined && parsed.kind === 'file-drift') throw fileDriftKeepRefusal(args, keepText);
+ if (parsed.readers === undefined && (parsed.slugsFile !== undefined || parsed.allowWithoutOwner)) {
+ 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.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.`,
['gbrain', 'repair', ...(parsed.kind ? [parsed.kind] : []), ...(parsed.source ? ['--source', parsed.source] : []), '--json']);
@@ -476,7 +508,8 @@ 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 } = parseRepairArgs(args);
+ generationKind, generationMode, run, key, generation, day, rules, cwdPrefixes, sessions, principal, readers, slugsFile, allowWithoutOwner } = parseRepairArgs(args);
+ 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;
if (generations) {
@@ -541,7 +574,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),
...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}),
...(k === kind && generations ? { generations } : {}), ...(k === kind && day ? { day } : {}), ...(k === kind && rules ? { rules } : {}),
- ...(k === kind && k === 'agent-session-facts' ? { cwdPrefixes, sessions, principal } : {}),
+ ...(k === kind && k === 'agent-session-facts' ? { cwdPrefixes, sessions, principal } : {}), ...(k === kind && readersRequest ? { readers: readersRequest } : {}),
...(apply ? { stop: stop.signal, recordDatabaseStops: true } : {}) })).finally(() => releaseSignals?.());
if (apply) clearHealthMemo(engine);
const paidKinds = results.filter(r => r.paid).map(r => r.kind);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4d6e6b602f..5513e8874d 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--filter', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--filter', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--import', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--members', '--members-file', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-stdio-member', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preload', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -113,7 +113,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', '--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', '--apply', '--as', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--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', '--prefer', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--rules', '--run', '--scopes', '--seat', '--session', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--yes'],
+ 'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--allow-without-owner', '--apply', '--as', '--auto-additive', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--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', '--prefer', '--principal', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--readers', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--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', '--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', '--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-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', '--rebase', '--redirect-uri', '--refresh-operations', '--remote', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retire', '--retry-failed', '--sample', '--scan-secrets', '--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/persistence/label-edit.ts b/src/core/persistence/label-edit.ts
index c04ccace45..43a3772d3f 100644
--- a/src/core/persistence/label-edit.ts
+++ b/src/core/persistence/label-edit.ts
@@ -2,11 +2,13 @@
* GST-2468: a label-only maintenance page write (`managed_maintenance_page` with `label_edit`) changes the page's
* privacy labels and nothing else, so its canonical file keeps its own bytes: only the label lines are removed, replaced
* or appended to the frontmatter block (page-prepare.ts labelEditFile). The edit names `set` (a key and its plain
- * scalar value) and `remove` (keys), both among LABEL_KEYS. The editor reads no YAML: a label line it cannot edit
- * as one line (a block or multi-line value, a duplicate key, a value that needs quoting, no frontmatter block) returns
- * null, and the write refuses instead of re-rendering the file.
+ * scalar value, or for `readable_by` its readers as a one-line flow list, GST-2476) and `remove` (keys), both among
+ * LABEL_KEYS and READERS_KEY. The editor reads no YAML: a label line it cannot edit as one line (a block or multi-line
+ * value, a duplicate key, a value that needs quoting, no frontmatter block) returns null, and the write refuses instead
+ * of re-rendering the file.
*/
import { opError } from '../ops/contract.ts';
+import { ACCESS_ID_RE } from '../access/principals.ts';
/** The frontmatter keys a label edit may touch: visibility and the privacy aliases (search/private-visibility.ts PRIVACY_ALIASES). */
export const LABEL_KEYS: readonly string[] = ['visibility', 'access', 'confidentiality'];
@@ -14,7 +16,16 @@ const PLAIN_VALUE = /^[A-Za-z][A-Za-z0-9_-]*$/;
/** A value a label edit can write as one unquoted line. */
export const isPlainLabelValue = (value: unknown): value is string => typeof value === 'string' && PLAIN_VALUE.test(value);
-export interface LabelEdit { set: Record<string, string>; remove: string[] }
+/** GST-2476: the readers key, written as `readable_by: [alice-example, group:team-a]` (repair/readers.ts). */
+export const READERS_KEY = 'readable_by';
+const EDIT_KEYS: readonly string[] = [...LABEL_KEYS, READERS_KEY];
+const READER = new RegExp(`^(?:group:|member:)?${ACCESS_ID_RE.source.slice(1, -1)}$`);
+/** Readers a label edit can write as one flow-list line: 1-256 member ids or group:<id>, each in its canonical spelling. */
+export const isPlainReaders = (value: unknown): value is string[] => Array.isArray(value) && value.length >= 1 && value.length <= 256
+ && value.every(entry => typeof entry === 'string' && READER.test(entry));
+const plainValue = (key: string, value: unknown) => key === READERS_KEY ? isPlainReaders(value) : isPlainLabelValue(value);
+
+export interface LabelEdit { set: Record<string, string | string[]>; remove: string[] }
/** The intent's label_edit, validated, or undefined when the intent carries none. */
export function readLabelEdit(value: unknown): LabelEdit | undefined {
@@ -22,11 +33,11 @@ export function readLabelEdit(value: unknown): LabelEdit | undefined {
const edit = value as { set?: unknown; remove?: unknown };
const set = edit.set ?? {}, remove = edit.remove ?? [];
const valid = typeof set === 'object' && set !== null && !Array.isArray(set) && Array.isArray(remove)
- && Object.entries(set).every(([key, v]) => LABEL_KEYS.includes(key) && isPlainLabelValue(v))
- && remove.every(key => typeof key === 'string' && LABEL_KEYS.includes(key) && !Object.hasOwn(set, key));
+ && Object.entries(set).every(([key, v]) => EDIT_KEYS.includes(key) && plainValue(key, v))
+ && remove.every(key => typeof key === 'string' && EDIT_KEYS.includes(key) && !Object.hasOwn(set, key));
if (!valid) throw opError('invalid_params', 'The label edit names a key or value a label edit cannot write.',
- `A label edit sets or removes only ${LABEL_KEYS.join(', ')}, each value a plain word. This is a gbrain planning defect: report it with the gbrain version; nothing was written.`);
- return { set: { ...set as Record<string, string> }, remove: [...new Set(remove as string[])] };
+ `A label edit sets or removes only ${EDIT_KEYS.join(', ')}, each value a plain word (${READERS_KEY}: a list of member ids or group:<id>). This is a gbrain planning defect: report it with the gbrain version; nothing was written.`);
+ return { set: Object.fromEntries(Object.entries(set as LabelEdit['set']).map(([key, v]) => [key, Array.isArray(v) ? [...v] : v])), remove: [...new Set(remove as string[])] };
}
/** frontmatter with the edit applied (key order kept, a new key last). */
@@ -36,7 +47,9 @@ export function labelEditedFrontmatter(frontmatter: Record<string, unknown>, edi
const KEY_LINES: Record<string, RegExp> = {
visibility: /^visibility[ \t]*:(?:[ \t]|\r?\n|$)/, access: /^access[ \t]*:(?:[ \t]|\r?\n|$)/, confidentiality: /^confidentiality[ \t]*:(?:[ \t]|\r?\n|$)/,
+ readable_by: /^readable_by[ \t]*:(?:[ \t]|\r?\n|$)/,
};
+const valueText = (value: string | string[]) => Array.isArray(value) ? `[${value.join(', ')}]` : value;
const keyLine = (key: string) => KEY_LINES[key] ?? /(?!)/;
/**
@@ -61,8 +74,8 @@ export function spliceLabelLines(text: string, edit: LabelEdit): { text: string;
const eol = lines[0]!.endsWith('\r\n') ? '\r\n' : '\n';
for (const [key, value] of Object.entries(edit.set)) {
const at = kept.findIndex(line => keyLine(key).test(line));
- if (at >= 0) kept[at] = `${key}: ${value}${kept[at]!.endsWith('\r\n') ? '\r\n' : '\n'}`;
- else kept.push(`${key}: ${value}${eol}`);
+ if (at >= 0) kept[at] = `${key}: ${valueText(value)}${kept[at]!.endsWith('\r\n') ? '\r\n' : '\n'}`;
+ else kept.push(`${key}: ${valueText(value)}${eol}`);
}
const head = bom + lines[0] + kept.join('') + lines[close];
return { text: head + lines.slice(close + 1).join(''), head };
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 75e9c74330..5ca2fbde32 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -52,6 +52,7 @@ import { classifyItemFailure, ItemRun, type ItemFailure } from '../item-failure.
import type { ProgressReporter } from '../progress.ts';
import type { GenerationsSelection } from '../generations/repair.ts';
import type { PrivateLabelsLedger } from './private-labels.ts';
+import type { ReadersRequest } from './readers.ts';
export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'atom-fence-rows', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'lost-fence-rows', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'access', 'private-labels'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
@@ -147,7 +148,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb
/** `agent-session-facts` (#8064): operator evidence, sessions whose cwd is under a prefix (`--cwd`) or named (`--session`), and the note's agent (`--principal`). */
cwdPrefixes?: string[]; sessions?: string[]; principal?: string;
/** `private-labels`: the undo ledger the CLI keeps (its path, lines for --class restore, and the append). */
- privateLabelsLedger?: PrivateLabelsLedger }
+ privateLabelsLedger?: PrivateLabelsLedger;
+ /** `visibility` (GST-2476): set the named pages' readers (`--readers`, `--allow-without-owner`, `--slugs-file`; repair/readers.ts). */
+ readers?: ReadersRequest }
export interface RepairHandler {
kind: RepairKind;
@@ -372,7 +375,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;
provenance?: string; cursor?: string; progress?: ProgressReporter;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[];
- cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger;
+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger; readers?: ReadersRequest;
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
/** GBRA-133: the CLI's termination signal; the apply stops before the next item with a result instead of dying mid-run. */
stop?: AbortSignal;
@@ -406,7 +409,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.limit !== undefined ? { limit: opts.limit } : {}), ...(opts.generations ? { generations: opts.generations } : {}),
...(opts.day ? { day: opts.day } : {}), ...(opts.rules?.length ? { rules: opts.rules } : {}),
...(opts.cwdPrefixes?.length ? { cwdPrefixes: opts.cwdPrefixes } : {}), ...(opts.sessions?.length ? { sessions: opts.sessions } : {}), ...(opts.principal ? { principal: opts.principal } : {}),
- ...(opts.privateLabelsLedger ? { privateLabelsLedger: opts.privateLabelsLedger } : {}) };
+ ...(opts.privateLabelsLedger ? { privateLabelsLedger: opts.privateLabelsLedger } : {}), ...(opts.readers ? { readers: opts.readers } : {}) };
const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);
const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;
const counters = await capacity(ctx);
diff --git a/src/core/repair/label-write.ts b/src/core/repair/label-write.ts
index bc389c8174..d9c52a3ddc 100644
--- a/src/core/repair/label-write.ts
+++ b/src/core/repair/label-write.ts
@@ -18,7 +18,7 @@ import { withTrustKeep } from '../persistence/context.ts';
import type { LabelEdit } from '../persistence/label-edit.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { labelEditFile } from '../persistence/page-prepare.ts';
-import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { maintenancePreflight, publishMaintenancePage, publishMaintenancePages, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
import type { RepairItemOutcome } from './core.ts';
const bounded = { timeoutMs: 120_000 };
@@ -101,12 +101,18 @@ export async function writeLabelFile(engine: BrainEngine, page: { source_id: str
/**
* One label-only page write at `revision`: the maintenance door on a managed brain (`authority`, from maintenancePreflight),
* the import under the page lock otherwise. The revision it wrote; null when the page moved before an unmanaged import.
+ * `batch` (GST-2476): the run's maintenance batch id, carried on the request so a run's writes can be counted with their Git
+ * effects (repair/readers.ts readersGitCounts); the Git effect runner commits queued files together.
*/
export async function writeLabelPage(ctx: OperationContext, page: { source_id: string; slug: string }, write: { revision: string; content: string; edit: LabelEdit;
- requestId: string; embed: boolean; preview: string },
+ requestId: string; embed: boolean; preview: string; batch?: string },
authority?: MaintenanceAuthority | null): Promise<string | null> {
const door = authority === undefined ? await maintenancePreflight(ctx.engine, page.source_id) : authority;
if (!door) return importAtRevision(ctx.engine, page, write.revision, write.content, write.embed, write.preview);
- await publishMaintenancePage(ctx.engine, door, page.slug, write.content, { expectedRevision: write.revision, requestId: write.requestId, keepTrust: true, labelEdit: write.edit });
+ const options = { expectedRevision: write.revision, requestId: write.requestId, keepTrust: true as const, labelEdit: write.edit };
+ if (write.batch) {
+ const [settled] = await publishMaintenancePages(ctx.engine, door, [{ slug: page.slug, content: write.content, ...options }], { batch: write.batch });
+ if ('error' in settled!) throw settled.error;
+ } else await publishMaintenancePage(ctx.engine, door, page.slug, write.content, options);
return (await ctx.engine.readPageSnapshot(page.slug, { sourceId: page.source_id }))?.revision ?? null;
}
diff --git a/src/core/repair/readers.ts b/src/core/repair/readers.ts
new file mode 100644
index 0000000000..9255379257
--- /dev/null
+++ b/src/core/repair/readers.ts
@@ -0,0 +1,198 @@
+/**
+ * GST-2476 (D1): `gbrain repair visibility --readers <list>` sets the readers of named pages (`--slug`, repeatable, or
+ * `--slugs-file`, one slug per line) through the label-only door (repair/label-write.ts): the page keeps its trust tier,
+ * files no lower_page proposal and keeps its provenance stamps (source_kind, ingested_via, ingested_at), its file changes
+ * only on the `readable_by` line (persistence/label-edit.ts), and the pages_access_derive_readers trigger (v282) sets
+ * pages.page_readers from the written frontmatter in the same write, so reads see the readers at once. A put_page that
+ * adds readers is an agent content write: it lowers the page and, on a managed brain, stamps put_page provenance.
+ *
+ * Every reader must name an enabled member (`alice-example`, `member:alice-example`) or an existing group
+ * (`group:team-a`); `none` removes the line. When `gbrain access owner` names an owner, a list that does not
+ * name the owner directly refuses unless `--allow-without-owner`: readers that leave the owner out close the page to the
+ * owner's own keys on every read path (access/caller.ts), and a group holding the owner does not count.
+ *
+ * Preview-bound: the preview lists each page's readers change and prints a hash over the selection (pages, readers as
+ * written, the flag, the owner) and the items; `--apply --expect <hash>` re-checks the readers and applies exactly that
+ * set. Other readers or flags, a different owner, or a page whose readers moved since the preview refuse preview_changed
+ * before anything is written. Works with no repository: a repo-less brain and a managed page under storage.db_only write
+ * the database label only.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { opError } from '../ops/contract.ts';
+import { getMember, listGroups } from '../access/members.ts';
+import { ownerView } from '../access/owner.ts';
+import { normalizePrincipal, normalizeReaders } from '../access/principals.ts';
+import { READERS_KEY, type LabelEdit } from '../persistence/label-edit.ts';
+import { digest } from '../persistence/digest.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import { afterCursor, type RepairCursor, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';
+
+/** The operator's request: `--readers` as typed (`none` removes), the owner flag, and the `--slugs-file` path with its slugs. */
+export interface ReadersRequest { readers: string; allowWithoutOwner?: boolean; slugsFile?: { path: string; slugs: string[] } }
+/** The phase a readers item's target carries (visibility.ts routes its apply here). */
+export const READERS_PHASE = 6;
+/** The most pages one readers preview lists. */
+export const READERS_MAX_PAGES = 10_000;
+
+interface ReadersChange { from: string[] | null; to: string[] | null }
+export interface ReadersItem extends RepairItem { target: RepairCursor; readers: ReadersChange; hash?: string; last?: boolean }
+interface Selection { source_ids: string[]; slugs: string[]; readers: string[] | null; allow_without_owner: boolean; owner: string | null }
+interface ApprovedReaders { target: RepairCursor; source_id: string; slug: string; chars: number; action: string; readers: ReadersChange; selection: Selection }
+
+const invalid = (message: string, suggestion: string, reason?: string) => opError('invalid_params', message, suggestion, reason ? { reason } : {});
+const unknownReader = (message: string, suggestion: string, reason: string) => opError('access_member_invalid', message, suggestion,
+ { reason, why: 'A reader that names no enabled member or existing group would close the page to everyone it meant to admit.' });
+const shown = (principal: string) => principal.startsWith('member:') ? principal.slice('member:'.length) : principal;
+const listText = (readers: string[] | null) => readers ? '[' + readers.map(shown).join(', ') + ']' : '(none)';
+const normalized = (readers: string[] | null) => readers ? normalizeReaders({ [READERS_KEY]: readers }) : null;
+const same = (a: string[] | null, b: string[] | null) => JSON.stringify(a) === JSON.stringify(b);
+
+/**
+ * The readers to write, as the frontmatter will hold them (members bare, groups as group:<id>, in the order typed, each
+ * once), or null for `none`. Refuses an entry that is no principal, an unknown, disabled or removed member, an unknown
+ * group, and a list without the owner unless the flag is passed; nothing is written before this passes.
+ */
+async function checkedReaders(engine: BrainEngine, request: ReadersRequest): Promise<{ readers: string[] | null; owner: string | null }> {
+ const { owner } = await ownerView(engine);
+ if (request.readers.trim() === 'none') return { readers: null, owner };
+ const entries = request.readers.split(',').map(entry => entry.trim()).filter(Boolean);
+ if (!entries.length) throw invalid('--readers names no reader.', 'Pass member ids and group:<id>, comma-separated (e.g. --readers alice-example,group:team-a), or none to remove the readers.');
+ const principals: string[] = [];
+ for (const entry of entries) {
+ const principal = normalizePrincipal(entry);
+ if (!principal) throw invalid('"' + entry + '" is not a member id or group:<id>.', 'Use member ids (alice-example) and groups (group:team-a): 1-64 lower-case letters, digits, ".", "_" or "-".');
+ if (!principals.includes(principal)) principals.push(principal);
+ }
+ for (const principal of principals) {
+ const id = shown(principal);
+ if (principal.startsWith('group:')) {
+ if (!(await listGroups(engine, id.slice('group:'.length))).length) throw unknownReader('No group "' + id.slice('group:'.length) + '" exists on this brain.', 'List groups with gbrain access group list, or create it: gbrain access group add ' + id.slice('group:'.length) + ' --members <ids>.', 'unknown_group');
+ continue;
+ }
+ const member = await getMember(engine, id);
+ if (member?.status !== 'enabled') {
+ throw unknownReader(member ? 'Member "' + id + '" is ' + member.status + '.' : 'No member "' + id + '" exists on this brain.',
+ member?.status === 'disabled' ? 'Enable it (gbrain access member enable ' + id + ') or name another member.' : 'Check the id with gbrain access member list, or add it: gbrain access member add ' + id + '.',
+ member ? member.status : 'unknown');
+ }
+ }
+ if (owner && !principals.includes('member:' + owner) && !request.allowWithoutOwner) {
+ throw invalid('These readers leave out the brain owner "' + owner + '", so the owner\'s own keys could no longer read the page; nothing was written. Name the owner, or pass --allow-without-owner.',
+ 'Add the owner to the list (--readers ' + [...principals.map(shown), owner].join(',') + '), or pass --allow-without-owner if the owner should not read it. A group that holds the owner does not count.',
+ 'readers_omit_owner');
+ }
+ return { readers: principals.map(shown), owner };
+}
+
+/** The read-only command that previews this selection again, with the caller's flags. */
+function previewCommand(scope: RepairScope, request: ReadersRequest, slugs: string[], sourceFlag: boolean): string {
+ const pages = request.slugsFile ? ' --slugs-file ' + request.slugsFile.path : slugs.map(slug => ' --slug ' + slug).join('');
+ return 'gbrain repair visibility' + (sourceFlag && scope.source_ids.length === 1 ? ' --source ' + scope.source_ids[0] : '') + pages
+ + ' --readers ' + request.readers + (request.allowWithoutOwner ? ' --allow-without-owner' : '');
+}
+
+/** The named pages whose readers differ from the selection's, in page-id order, with the pages not found and already set. */
+async function planPages(engine: BrainEngine, selection: Selection) {
+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; named: boolean; readers: unknown; chars: number }>(
+ `SELECT p.id, p.source_id, p.slug, p.frontmatter ? 'readable_by' AS named, p.frontmatter->'readable_by' AS readers, COALESCE(p.body_bytes, 0) AS chars
+ FROM pages p WHERE p.deleted_at IS NULL AND p.source_id = ANY($1::text[]) AND p.slug = ANY($2::text[]) ORDER BY p.id`, [selection.source_ids, selection.slugs], { timeoutMs: 120_000 });
+ const target = normalized(selection.readers);
+ const items: ReadersItem[] = rows.flatMap(row => {
+ const from = normalizeReaders(row.named ? { [READERS_KEY]: row.readers } : {});
+ if (same(from, target)) return [];
+ const id = Number(row.id);
+ return [{ cursor: { phase: READERS_PHASE, id }, target: { phase: READERS_PHASE, id }, source_id: row.source_id, slug: row.slug, chars: Number(row.chars),
+ action: 'readers ' + listText(from) + ' -> ' + listText(selection.readers), readers: { from, to: selection.readers } }];
+ });
+ const found = new Set(rows.map(row => row.slug));
+ return { items, residuals: { named_not_found: selection.slugs.filter(slug => !found.has(slug)).length, readers_already_set: rows.length - items.length } };
+}
+
+/** The maintenance batch id an approved readers apply carries on its managed writes (one per approved set and source). */
+const readersBatch = (hash: string, sourceId: string) => digest(['visibility-readers-batch-v1', hash, sourceId]);
+
+/**
+ * How the managed writes of the approved set `hash` reached Git: their Git effects by state. The Git effect runner commits
+ * queued files of one checkout together (up to 100 files per commit); a pending file is committed when it runs. A
+ * db_only page's effect is skipped (no file). Brains without managed persistence publish no Git effect.
+ */
+export async function readersGitCounts(engine: BrainEngine, scope: RepairScope, hash: string): Promise<Record<string, number>> {
+ const [row] = await engine.executeRaw<Record<string, number | string>>(`SELECT count(*) FILTER (WHERE e.state = 'committed' AND e.outcome->>'git' = 'committed') AS committed,
+ count(*) FILTER (WHERE e.state IN ('queued', 'running')) AS pending, count(*) FILTER (WHERE e.state = 'failed') AS failed,
+ count(*) FILTER (WHERE e.state = 'committed' AND e.outcome->>'git' = 'skipped') AS skipped
+ FROM persistence_requests r JOIN persistence_effects e ON e.request_id = r.id AND e.kind = 'git'
+ WHERE r.intent->>'maintenance_batch' = ANY($1::text[])`, [scope.source_ids.map(sourceId => readersBatch(hash, sourceId))]);
+ return Object.fromEntries(Object.entries(row ?? {}).map(([key, value]) => [key, Number(value)]));
+}
+
+const hashParts = (scope: RepairScope, selection: Selection, items: ReadersItem[]) => ({ kind: 'visibility-readers-v1', brain_id: scope.brain_id, selection,
+ items: items.map(item => ({ target: item.target, source_id: item.source_id, slug: item.slug, readers: item.readers })) });
+
+/**
+ * The apply's items: exactly the approved set, after the selection matched and every pending page still holds the readers
+ * the preview read (or, on a resumed run, already the new ones); anything else refuses preview_changed with nothing written.
+ */
+async function approvedItems(engine: BrainEngine, scope: RepairScope, selection: Selection, expect: string, command: string, after: RepairCursor | null): Promise<ReadersItem[]> {
+ const approved = await loadApprovedSet<ApprovedReaders>(engine, { command: 'visibility', hash: expect, previewCommand: command,
+ emptyHash: async () => previewHash(hashParts(scope, selection, (await planPages(engine, selection)).items)) });
+ if (approved.items.some(entry => digest(entry.selection) !== digest(selection))) throw previewChangedError(expect, command);
+ const items: ReadersItem[] = approved.items.map(({ selection: _selection, ...entry }, index) => ({ ...entry, cursor: { phase: 0, id: index }, hash: expect, last: index === approved.items.length - 1 }))
+ .filter(item => afterCursor(item.cursor, after));
+ const live = new Map((await planPages(engine, selection)).items.map(item => [item.target.id, item.readers.from]));
+ const target = normalized(selection.readers);
+ for (const item of items) {
+ const settled = !live.has(item.target.id);
+ if (settled ? !(await pageHolds(engine, item, target)) : !same(live.get(item.target.id)!, item.readers.from)) throw previewChangedError(expect, command);
+ }
+ return items;
+}
+
+/** Whether the page the item names is still live and already holds the target readers (an item a stopped apply wrote). */
+async function pageHolds(engine: BrainEngine, item: ReadersItem, target: string[] | null): Promise<boolean> {
+ const snapshot = await engine.readPageSnapshot(item.slug, { sourceId: item.source_id });
+ return !!snapshot && Number(snapshot.page.id) === item.target.id && same(normalizeReaders(snapshot.page.frontmatter), target);
+}
+
+/** The readers plan: the preview (saved under its hash) or the apply's approved items. */
+export async function planReaders(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null, opts: RepairPlanOptions & { readers: ReadersRequest }): Promise<RepairPlan> {
+ const request = opts.readers;
+ const slugs = [...new Set(request.slugsFile?.slugs ?? opts.slugs ?? [])].sort();
+ if (!slugs.length) throw invalid('gbrain repair visibility --readers names its pages with --slug or --slugs-file.', 'Name each page: --slug notes/a-example (repeatable), or --slugs-file <file> with one slug per line.');
+ if (opts.driftClass !== undefined) throw invalid('gbrain repair visibility takes --readers or --class, not both.', 'Set readers on named pages with --readers, or preview a visibility class with --class.');
+ if (slugs.length > READERS_MAX_PAGES) throw invalid('--readers lists ' + slugs.length + ' pages; one preview lists at most ' + READERS_MAX_PAGES + '.', 'Split the slugs file and preview each part.');
+ const command = previewCommand(scope, request, slugs, true);
+ if (opts.apply && !opts.expect) throw invalid('gbrain repair visibility --readers applies only the set a preview printed.', 'Preview first: ' + command + ' — then run the apply command it prints: ' + command + ' --apply --expect <preview-hash>');
+ const { readers, owner } = await checkedReaders(engine, request);
+ const selection: Selection = { source_ids: scope.source_ids, slugs, readers, allow_without_owner: request.allowWithoutOwner === true, owner };
+ if (opts.apply) return { items: await approvedItems(engine, scope, selection, opts.expect!, command, after), preview_hash: opts.expect, residuals: {} };
+ const { items, residuals } = await planPages(engine, selection);
+ const hash = previewHash(hashParts(scope, selection, items));
+ if (items.length) await saveApprovedSet<ApprovedReaders>(engine, { command: 'visibility', hash },
+ items.map(item => ({ target: item.target, source_id: item.source_id, slug: item.slug, chars: item.chars, action: item.action, readers: item.readers, selection })));
+ return { items: items.map((item, index) => ({ ...item, cursor: { phase: 0, id: index } })), preview_hash: hash, residuals,
+ ...(residuals.named_not_found ? { warnings: [residuals.named_not_found + ' named page(s) were not found in ' + scope.source_ids.join(', ') + ' and are not listed.'] } : {}),
+ listing: items.map(item => ({ item: item.source_id + ':' + item.slug, class: 'readers', detail: item.action })) };
+}
+
+/**
+ * One page's readers write: re-checked against the page (a page whose readers moved since the plan is skipped), then the
+ * label-only write (`write`, visibility.ts labelWrite) of the page with only `readable_by` changed. Its held outcome
+ * when the write could not be made; `readers_set` or `readers_removed` once written.
+ */
+export async function applyReaders(engine: BrainEngine, item: ReadersItem,
+ write: (snapshot: PageSnapshot, content: string, edit: LabelEdit, batch?: string) => Promise<RepairItemOutcome | null>): Promise<boolean | RepairItemOutcome> {
+ try {
+ const snapshot = await engine.readPageSnapshot(item.slug, { sourceId: item.source_id });
+ if (!snapshot || Number(snapshot.page.id) !== item.target.id || !same(normalizeReaders(snapshot.page.frontmatter), item.readers.from)) return false;
+ const { [READERS_KEY]: _readers, ...rest } = snapshot.page.frontmatter;
+ const to = item.readers.to;
+ const frontmatter = to ? { ...snapshot.page.frontmatter, [READERS_KEY]: to } : rest;
+ const edit: LabelEdit = to ? { set: { [READERS_KEY]: to }, remove: [] } : { set: {}, remove: [READERS_KEY] };
+ const held = await write(snapshot, serializePageToMarkdown({ ...snapshot.page, frontmatter }, snapshot.tags), edit, item.hash ? readersBatch(item.hash, item.source_id) : undefined);
+ return held ?? { applied: true, outcome: to ? 'readers_set' : 'readers_removed' };
+ } finally {
+ if (item.last && item.hash) await clearApprovedSet(engine, { command: 'visibility', hash: item.hash });
+ }
+}
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 4ff8baba41..006415069e 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -94,6 +94,7 @@ import { provenanceRepair } from './provenance.ts';
import { secretSpansRepair } from './secret-spans.ts';
import { rowsBehindRepair } from './rows-behind.ts';
import { privateLabelsRepair, type PrivateLabelsLedger } from './private-labels.ts';
+import type { ReadersRequest } from './readers.ts';
import { generationsRepair, generationsSelectionArgv, type GenerationsSelection } from '../generations/repair.ts';
import { lostFenceRowsRepair } from './lost-fence-rows.ts';
import { restoreDaysHint } from '../generations/config.ts';
@@ -795,18 +796,20 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number; stop?: AbortSignal; recordDatabaseStops?: boolean;
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string; provenance?: string; cursor?: string; progress?: ProgressReporter;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[];
- cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger } = {}): Promise<RepairResult> {
+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger; readers?: ReadersRequest } = {}): Promise<RepairResult> {
const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;
const spec = repairSpec(kind, opts.registry);
return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,
embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: [...(opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : []),
...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : []),
...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : []), ...(run.generations ? generationsSelectionArgv(run.generations) : []), ...(run.day ? ['--day', run.day] : []), ...(run.rules?.length ? ['--rules', run.rules.join(',')] : []),
- ...(kind === 'agent-session-facts' ? agentSessionFlagArgs(run).map(arg => shellQuote(arg)) : [])],
+ ...(kind === 'agent-session-facts' ? agentSessionFlagArgs(run).map(arg => shellQuote(arg)) : []),
+ ...(run.readers ? [...(run.readers.slugsFile ? ['--slugs-file', run.readers.slugsFile.path] : []), '--readers', run.readers.readers,
+ ...(run.readers.allowWithoutOwner ? ['--allow-without-owner'] : [])].map(arg => shellQuote(arg)) : [])],
explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, includeCrossEntity: run.includeCrossEntity, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, ...(run.stop ? { stop: run.stop } : {}), ...(run.recordDatabaseStops ? { recordDatabaseStops: true } : {}), prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,
held: run.held, side: run.side, state: run.state, provenance: run.provenance, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage, generations: run.generations, day: run.day, rules: run.rules,
- cwdPrefixes: run.cwdPrefixes, sessions: run.sessions, principal: run.principal, privateLabelsLedger: run.privateLabelsLedger });
+ cwdPrefixes: run.cwdPrefixes, sessions: run.sessions, principal: run.principal, privateLabelsLedger: run.privateLabelsLedger, readers: run.readers });
},
};
}
diff --git a/src/core/repair/visibility.ts b/src/core/repair/visibility.ts
index 76cd0aa3bc..ca925f4713 100644
--- a/src/core/repair/visibility.ts
+++ b/src/core/repair/visibility.ts
@@ -33,12 +33,16 @@
* private, tighten-only, preview-bound (a bare `--apply` refuses). It is the operator's single-page label change.
* Every item writes through the label-only door (repair/label-write.ts): the page keeps its trust tier, files no
* lower_page proposal and its file changes only on the visibility line (a fact item: its fence row).
+ *
+ * `--readers <list>` with `--slug` or `--slugs-file` (GST-2476, repair/readers.ts) sets the named pages' readable_by through
+ * the same door instead. A managed page with no file in its checkout outside a declared storage.db_only path is held
+ * `canonical_file_missing` with nothing written: a database-only label there would put the database ahead of Git.
*/
import type { BrainEngine } from '../engine.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { derivationPrivateSql, effectiveVisibility, folderRestrictedSql, privacyAliasSql, privateSnapshotFilterFragment, strictestVisibility, type Visibility } from '../search/private-visibility.ts';
import { strikeFenceRow } from '../facts/forget.ts';
-import { opError } from '../ops/contract.ts';
+import { opError, OperationError } from '../ops/contract.ts';
import { authorizeWrite } from '../persistence/authority.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
@@ -46,9 +50,11 @@ import { digest } from '../persistence/digest.ts';
import type { WriteRequest } from '../persistence/model.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { CANONICAL_FILE_MISSING } from '../persistence/publication-failure.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope, type RepairCursor } from './core.ts';
import { filesInCheckout, writeLabelFile, writeLabelPage } from './label-write.ts';
+import { applyReaders, planReaders, readersGitCounts, READERS_PHASE, type ReadersItem } from './readers.ts';
import type { LabelEdit } from '../persistence/label-edit.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
@@ -297,15 +303,26 @@ async function applyFactItem(ctx: Parameters<RepairHandler['apply']>[0], item: R
* GST-2468: one item's page write is a label-only maintenance write (repair/label-write.ts): it keeps the page's trust
* tier, files no lower_page proposal and changes only the label lines of the page's file (a fact item: its fence row).
* On a brain without managed persistence a page whose file sits in its source's checkout gets the same splice in that
- * file (label-write.ts writeLabelFile). Null once written; the held outcome for a page stored in segments or a file the
- * repair cannot write. A page that moved since it was read throws `revision_conflict`, which the apply counts as skipped.
+ * file (label-write.ts writeLabelFile). Null once written; the held outcome for a page stored in segments, a file the
+ * repair cannot write, or a managed page whose canonical file is missing (`canonical_file_missing`: never written, or gone
+ * outside gbrain, outside any declared storage.db_only path). A page that moved since it was read throws
+ * `revision_conflict`, which the apply counts as skipped.
*/
-async function labelWrite(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, snapshot: PageSnapshot, content: string, edit: LabelEdit): Promise<RepairItemOutcome | null> {
+async function labelWrite(ctx: Parameters<RepairHandler['apply']>[0], item: RepairItem, snapshot: PageSnapshot, content: string, edit: LabelEdit, batch?: string): Promise<RepairItemOutcome | null> {
if (isSegmentedPage(snapshot.page)) return { applied: false, outcome: 'segmented_page', reason: 'The page body is stored in segments; edit it by hand on the brain host.' };
const path = (await filesInCheckout(ctx.engine, [Number(snapshot.page.id)])).get(Number(snapshot.page.id));
- const write = { revision: snapshot.revision, content, edit, embed: true, preview: 'gbrain repair visibility' };
- const written = path ? await writeLabelFile(ctx.engine, item, { ...write, path })
- : await writeLabelPage(ctx, item, { ...write, requestId: await repairRequestId(ctx, 'visibility', item, snapshot.revision) });
+ const write = { revision: snapshot.revision, content, edit, embed: true, preview: 'gbrain repair visibility', ...(batch ? { batch } : {}) };
+ let written: Awaited<ReturnType<typeof writeLabelFile>>;
+ try {
+ written = path ? await writeLabelFile(ctx.engine, item, { ...write, path })
+ : await writeLabelPage(ctx, item, { ...write, requestId: await repairRequestId(ctx, 'visibility', item, snapshot.revision) });
+ } catch (error) {
+ if (!(error instanceof OperationError) || error.detail !== CANONICAL_FILE_MISSING) throw error;
+ return { applied: false, outcome: CANONICAL_FILE_MISSING, detail: { path: `${item.slug}.md` },
+ reason: `${item.source_id}:${item.slug} has no file in its source's checkout and is not under a declared storage.db_only path, so a label write would put the `
+ + `database ahead of Git; nothing was written. If the page belongs in the database only, declare its folder under storage.db_only in gbrain.yml, commit it `
+ + `and preview again; if its file was removed by mistake, restore it (gbrain repair ghost-pages --source ${item.source_id} lists pages whose file is gone).` };
+ }
if (written === null) throw opError('revision_conflict', `${item.source_id}:${item.slug} changed after it was read, so it was not written.`,
'Preview gbrain repair visibility again; the page is listed with its current state.');
return typeof written === 'string' ? null : written;
@@ -359,7 +376,10 @@ async function planClass(engine: BrainEngine, sourceIds: string[], cls: Visibili
export const visibilityRepair: RepairHandler = {
kind: 'visibility',
+ /** A --readers apply lists every page's outcome (--json outcome_items). */
+ outcomeItemsLimit: VISIBILITY_WINDOW_MAX,
async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null, opts?: RepairPlanOptions): Promise<RepairPlan> {
+ if (opts?.readers) return planReaders(engine, scope, after, { ...opts, readers: opts.readers });
const named = [...new Set(opts?.slugs ?? [])].sort();
if (named.length && opts?.driftClass !== undefined) throw opError('invalid_params', 'gbrain repair visibility takes --slug or --class, not both.',
'Name pages with --slug to make exactly them private, or preview a class with --class.');
@@ -430,9 +450,18 @@ export const visibilityRepair: RepairHandler = {
listing: items.map(item => ({ item: `${item.source_id}:${item.slug}`, class: CLASS_OF_PHASE[item.target.phase]!, detail: item.action })),
details: { window: { size, listed: items.length, pending, pending_past_window: pendingPastWindow, not_read: notRead, timed_out: timedOut, next_preview: next } } };
},
+ /** A --readers apply: how its managed writes reached Git (`details.git`, effect states; readers.ts readersGitCounts). */
+ async report(ctx, scope, result, opts) {
+ return opts.readers && result.mode === 'apply' && opts.expect ? { details: { ...result.details, git: await readersGitCounts(ctx.engine, scope, opts.expect) } } : {};
+ },
+ render(details) {
+ const git = details.git as Record<string, number> | undefined;
+ return git ? [` git: ${Object.entries(git).map(([key, value]) => `${key}=${value}`).join(', ')} (file(s) by Git effect state; queued files commit together, up to 100 per commit)`] : [];
+ },
async apply(ctx, entry) {
const item = entry as VisibilityItem;
const target = item.target ?? item.cursor;
+ if (target.phase === READERS_PHASE) return applyReaders(ctx.engine, item as ReadersItem, (snapshot, content, edit, batch) => labelWrite(ctx, item, snapshot, content, edit, batch));
try {
if (target.phase === 4) return await applyFactItem(ctx, item, target.id);
const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index c5066c77fa..54c2952f1c 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -492,6 +492,7 @@ test/qm-personal-tools.test.ts
test/qm-scope-read.test.ts
test/qm-scope-writes.test.ts
test/read-meta-diag.test.ts
+test/readers-label-setter.test.ts
test/reason-trailers-gbra217.test.ts
test/recall-page-fill.test.ts
test/receipt-compaction-newest-sync-gbra130.test.ts
diff --git a/test/readers-label-setter.test.ts b/test/readers-label-setter.test.ts
new file mode 100644
index 0000000000..637e6fac9f
--- /dev/null
+++ b/test/readers-label-setter.test.ts
@@ -0,0 +1,379 @@
+/**
+ * GST-2059 / GST-2476 (D1): gbrain repair visibility --readers sets a page's readable_by through the label-only door.
+ *
+ * 1. Protects: the operator command that names a page's readers on one page (--slug) or a listed set (--slugs-file),
+ * preview-bound (--apply --expect <hash>, a changed plan refuses preview_changed). Every reader must be an enabled
+ * member or an existing group; a list that leaves out the brain owner refuses unless --allow-without-owner (a group
+ * holding the owner does not count). The write keeps the trust tier, files no lower_page proposal, keeps the
+ * source_kind / ingested_via / ingested_at stamps, changes the page's file only on the readable_by line, and updates
+ * pages.page_readers in the same write, so remote reads see the readers at once. Works on a repo-less brain, a managed
+ * page with a file, a managed page under a declared storage.db_only path; a managed page with no file outside any
+ * db_only path is held canonical_file_missing with nothing written.
+ * 2. Fails when: the readers write lowers the tier, files a proposal, stamps put_page provenance, re-renders the file,
+ * leaves page_readers stale, accepts an unknown member or group, drops the owner without the flag, applies a plan that
+ * changed since its preview, or writes a database label ahead of Git on a managed page with no file.
+ * 3. Real seams: the managed-brain harness (claimed Git worktree, managed sync, the maintenance door, the Git effect), a
+ * repo-less brain, the gbrain repair command entry (remote:false), and tokens bound to members read through MCP dispatch
+ * (remote:true, transport http). PGLite, and Postgres with DATABASE_URL.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operations } from '../src/core/operations.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { withCoordinatedWrite, withTrustBackfill } from '../src/core/persistence/context.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { readLabelEdit, spliceLabelLines } from '../src/core/persistence/label-edit.ts';
+import { readersGitCounts } from '../src/core/repair/readers.ts';
+import { renderRepairResult, runRepairCommand } from '../src/commands/repair.ts';
+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { addGroup, addMember, bindCredential, disableMember } from '../src/core/access/members.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { durableGitRepo, git } from './helpers/git-publication.ts';
+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const NL = String.fromCharCode(10);
+const CR = String.fromCharCode(13);
+const putPage = operations.find(op => op.name === 'put_page')!;
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const OWNER = 'owner-example';
+/** Keys out of canonical order, a slug key, provenance stamps (source_kind, ingested_via) in the frontmatter. */
+const file = (slug: string, canary = 'canaryrdrplain') => ['---', 'title: Example Page', 'slug: ' + slug, 'source_kind: email-example', 'ingested_via: connector-example', 'type: note',
+ 'owner_note: kept', 'tags:', ' - alpha', '---', '', 'Body line one of ' + slug + ' ' + canary + '.', '', 'Second paragraph.', ''].join(NL);
+const withLine = (text: string, line: string) => text.replace(NL + '---' + NL + NL, NL + line + NL + '---' + NL + NL);
+const readersLine = (...readers: string[]) => 'readable_by: [' + readers.join(', ') + ']';
+const ownerAnd = (...readers: string[]) => [...readers, OWNER].join(',');
+
+async function capture(fn: () => Promise<void>): Promise<string> {
+ let printed = '';
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { printed += parts.map(String).join(' ') + NL; };
+ try { await fn(); } finally { console.log = original; }
+ return printed;
+}
+const runRepair = async (engine: BrainEngine, argv: string[]) => {
+ try { return await withEnv({ GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() => runRepairCommand(engine, argv))); }
+ finally { _resetCliExitVerdictForTests(); }
+};
+const repair = async (engine: BrainEngine, argv: string[]) => JSON.parse(await runRepair(engine, [...argv, '--json'])).results[0];
+const refusal = (engine: BrainEngine, argv: string[]) => repair(engine, argv).then(
+ result => ({ code: 'none', message: JSON.stringify(result) }), (error: { code?: string; message: string }) => ({ code: error.code ?? 'unknown', message: error.message }));
+const previewApply = async (engine: BrainEngine, argv: string[]) => {
+ const preview = await repair(engine, argv);
+ expect(preview.preview_hash).toBeString();
+ const applied = await repair(engine, [...argv, '--apply', '--expect', preview.preview_hash]);
+ expect(applied.failed).toEqual([]);
+ return { preview, applied };
+};
+const STAMPS = 'SELECT trust_tier::text AS tier, source_kind, ingested_via, ingested_at::text AS ingested_at FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL';
+const stamps = async (engine: BrainEngine, slug: string, sourceId = 'default') => (await engine.executeRaw(STAMPS, [sourceId, slug]))[0];
+const row = async (engine: BrainEngine, slug: string, sourceId = 'default') => (await engine.executeRaw<{ frontmatter: Record<string, unknown>; page_readers: string[] | null }>(
+ 'SELECT frontmatter, page_readers FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]))[0]!;
+const proposals = async (engine: BrainEngine) => engine.executeRaw<{ proposer: string }>('SELECT proposer FROM trust_proposals ORDER BY id');
+const stampProvenance = (engine: BrainEngine, slug: string, sourceId = 'default') => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(
+ "UPDATE pages SET source_kind='mail-example', ingested_via='connector-example', ingested_at='2026-01-02T00:00:00Z' WHERE source_id=$1 AND slug=$2", [sourceId, slug]), TEST_WRITE_ATTRIBUTION));
+
+/** alice-example and bob-example, the owner, group team-example (alice, bob) and group family-example (alice, the owner). */
+async function seedMembers(engine: BrainEngine): Promise<void> {
+ for (const id of ['alice-example', 'bob-example', OWNER]) await addMember(engine, id);
+ await addGroup(engine, 'team-example', ['alice-example', 'bob-example']);
+ await addGroup(engine, 'family-example', ['alice-example', OWNER]);
+ await setOwner(engine, OWNER);
+}
+
+describe('the label editor writes readable_by as one flow-list line', () => {
+ const text = ['---', 'title: A', 'type: note', '---', '', 'Body.', ''].join(NL);
+ test('add, replace and remove splice only that line', () => {
+ const added = spliceLabelLines(text, readLabelEdit({ set: { readable_by: ['alice-example', 'group:team-example'] }, remove: [] })!)!.text;
+ expect(added).toBe(withLine(text, readersLine('alice-example', 'group:team-example')));
+ const crlf = added.replace('title: A' + NL, 'title: A' + CR + NL);
+ const replaced = spliceLabelLines(crlf, readLabelEdit({ set: { readable_by: [OWNER] }, remove: [] })!)!.text;
+ expect(replaced).toBe(withLine(text, readersLine(OWNER)).replace('title: A' + NL, 'title: A' + CR + NL));
+ expect(spliceLabelLines(added, readLabelEdit({ set: {}, remove: ['readable_by'] })!)!.text).toBe(text);
+ });
+ test('a block list, a duplicate key, or a reader that is not a plain principal is refused', () => {
+ const block = text.replace('type: note', 'type: note' + NL + 'readable_by:' + NL + ' - alice-example');
+ expect(spliceLabelLines(block, readLabelEdit({ set: { readable_by: [OWNER] }, remove: [] })!)).toBeNull();
+ const twice = text.replace('type: note', 'type: note' + NL + 'readable_by: [a]' + NL + 'readable_by: [b]');
+ expect(spliceLabelLines(twice, readLabelEdit({ set: {}, remove: ['readable_by'] })!)).toBeNull();
+ for (const bad of [[], ['Alice Example'], ['group:'], ['a, b'], 'alice-example'] as unknown[]) {
+ expect(() => readLabelEdit({ set: { readable_by: bad }, remove: [] })).toThrow();
+ }
+ expect(() => readLabelEdit({ set: { visibility: ['private'] }, remove: [] })).toThrow();
+ });
+});
+
+for (const backend of testBackends()) describe('[' + backend + '] repair visibility --readers on a managed git source', () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const setup = ({ root }: { root: string }) => {
+ writeFileSync(join(root, '.gitignore'), 'archive/' + NL);
+ writeFileSync(join(root, 'gbrain.yml'), 'storage:' + NL + ' db_only:' + NL + ' - email/' + NL);
+ mkdirSync(join(root, 'email'), { recursive: true });
+ writeFileSync(join(root, 'email', '.keep'), '');
+ durableGitRepo(root, ['.gitignore', 'gbrain.yml', 'email/.keep']);
+ };
+ async function seed(engine: BrainEngine, root: string, files: Record<string, string>) {
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ for (const [slug, text] of Object.entries(files)) writeFileSync(join(root, slug + '.md'), text);
+ git(root, 'add', '--', ...Object.keys(files).map(slug => slug + '.md'));
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'owner notes');
+ await performManagedSync(engine, OPTS);
+ await settleManagedGitEffects(engine);
+ for (const slug of Object.keys(files)) {
+ expect((await stamps(engine, slug))!.tier).toBe('operator_curated');
+ await stampProvenance(engine, slug);
+ }
+ await seedMembers(engine);
+ }
+ const onDisk = (root: string, slug: string) => readFileSync(join(root, slug + '.md'), 'utf8');
+ /** A page under the declared db_only path email/, written by put_page (no file in Git), with provenance stamps. */
+ async function dbOnlyPage(engine: BrainEngine, ctx: Parameters<typeof putPage.handler>[0], slug: string) {
+ await putPage.handler(ctx, { slug, content: file(slug), request_id: randomUUID(), wait_ms: 30_000 });
+ await settleManagedGitEffects(engine);
+ await stampProvenance(engine, slug);
+ }
+ /** The email/ folder stops being db_only and the page's local cache file is gone: a page with no file outside db_only. */
+ function dropDbOnly(root: string, slug: string) {
+ rmSync(join(root, slug + '.md'), { force: true });
+ writeFileSync(join(root, 'gbrain.yml'), 'storage:' + NL + ' db_tracked:' + NL + ' - notes/' + NL);
+ git(root, 'add', '--', 'gbrain.yml');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'email is no longer db_only');
+ }
+
+ test('one page: add, replace and remove readers; tier, provenance and every other byte of the file kept', () => managedBrain(async ({ engine, root }) => {
+ const slug = 'notes/one-example';
+ await seed(engine, root, { [slug]: file(slug) });
+ const before = onDisk(root, slug), stamped = await stamps(engine, slug), frontmatter = (await row(engine, slug)).frontmatter;
+ const argv = (readers: string) => ['visibility', '--slug', slug, '--readers', readers];
+ const { preview, applied } = await previewApply(engine, argv(ownerAnd('alice-example')));
+ expect(preview.listing).toEqual([{ item: 'default:' + slug, class: 'readers', detail: 'readers (none) -> [alice-example, ' + OWNER + ']' }]);
+ expect(applied.applied).toBe(1);
+ expect(applied.outcomes).toMatchObject({ readers_set: 1 });
+ await settleManagedGitEffects(engine);
+ expect(onDisk(root, slug)).toBe(withLine(before, readersLine('alice-example', OWNER)));
+ expect(git(root, 'show', 'HEAD:' + slug + '.md')).toBe(withLine(before, readersLine('alice-example', OWNER)));
+ expect(git(root, 'status', '--porcelain', '--', slug + '.md').trim()).toBe('');
+ expect(await stamps(engine, slug)).toEqual(stamped);
+ expect(await row(engine, slug)).toEqual({ frontmatter: { ...frontmatter, readable_by: ['alice-example', OWNER] }, page_readers: ['member:alice-example', 'member:' + OWNER] });
+ expect(await proposals(engine)).toEqual([]);
+
+ await previewApply(engine, argv(ownerAnd('group:team-example')));
+ await settleManagedGitEffects(engine);
+ expect(onDisk(root, slug)).toBe(withLine(before, readersLine('group:team-example', OWNER)));
+ expect((await row(engine, slug)).page_readers).toEqual(['group:team-example', 'member:' + OWNER]);
+
+ const removed = await previewApply(engine, argv('none'));
+ expect(removed.applied.outcomes).toMatchObject({ readers_removed: 1 });
+ await settleManagedGitEffects(engine);
+ expect(onDisk(root, slug)).toBe(before);
+ expect(await row(engine, slug)).toEqual({ frontmatter, page_readers: null });
+ expect(await stamps(engine, slug)).toEqual(stamped);
+ expect(await proposals(engine)).toEqual([]);
+ }, { databaseUrl, setup }), 240_000);
+
+ test('a listed set (--slugs-file): file pages and a db_only page, per-page outcomes in --json and counts in the text', () => managedBrain(async ({ engine, root, ctx }) => {
+ const filed = ['notes/a-example', 'notes/b-example'], mail = 'email/listed-example';
+ await seed(engine, root, Object.fromEntries(filed.map(slug => [slug, file(slug)])));
+ await dbOnlyPage(engine, ctx, mail);
+ const before = Object.fromEntries(filed.map(slug => [slug, onDisk(root, slug)]));
+ const stamped = Object.fromEntries(await Promise.all([...filed, mail].map(async slug => [slug, await stamps(engine, slug)] as const)));
+ const list = join(root, '..', 'readers-slugs.txt');
+ writeFileSync(list, ['# pages for the assistant', ...filed, '', mail, 'notes/missing-example', ''].join(NL));
+ const argv = ['visibility', '--slugs-file', list, '--readers', ownerAnd('group:team-example')];
+ const preview = await repair(engine, argv);
+ expect(preview.listing.map((entry: { item: string }) => entry.item).sort()).toEqual([mail, ...filed].map(slug => 'default:' + slug).sort());
+ expect(preview.residuals).toMatchObject({ named_not_found: 1 });
+ expect(preview.apply_command).toContain('--slugs-file ' + list);
+ const head = git(root, 'rev-parse', 'HEAD').trim();
+ const text = await runRepair(engine, [...argv, '--apply', '--expect', preview.preview_hash]);
+ expect(text).toContain('outcomes: readers_set=3');
+ expect(text).toMatch(/git: committed=\d+, pending=\d+, failed=0, skipped=\d+/);
+ await settleManagedGitEffects(engine);
+ // The two tracked files reach Git through the Git effect (the one door), committed together; the db_only page has no file.
+ expect(git(root, 'rev-list', '--count', head + '..HEAD').trim()).toBe('1');
+ expect(git(root, 'diff', '--name-only', head, 'HEAD').trim().split(NL).sort()).toEqual(filed.map(slug => slug + '.md'));
+ expect(await readersGitCounts(engine, { brain_id: preview.scope?.brain_id ?? '', source_ids: ['default'] }, preview.preview_hash)).toEqual({ committed: 2, pending: 0, failed: 0, skipped: 1 });
+ for (const slug of filed) expect(onDisk(root, slug)).toBe(withLine(before[slug]!, readersLine('group:team-example', OWNER)));
+ for (const slug of [...filed, mail]) {
+ expect(await stamps(engine, slug)).toEqual(stamped[slug]);
+ expect((await row(engine, slug)).page_readers).toEqual(['group:team-example', 'member:' + OWNER]);
+ }
+ expect(git(root, 'ls-files', 'email').trim()).toBe('email/.keep');
+ expect(await proposals(engine)).toEqual([]);
+ const again = await repair(engine, argv);
+ expect(again.listing).toEqual([]);
+ expect(again.residuals).toMatchObject({ readers_already_set: 3 });
+ }, { databaseUrl, setup }), 240_000);
+
+ test('a db_only page: only the database label is written, tier and provenance kept, no file', () => managedBrain(async ({ engine, root, ctx }) => {
+ const slug = 'email/mail-example';
+ await dbOnlyPage(engine, ctx, slug);
+ await seedMembers(engine);
+ const before = await stamps(engine, slug), frontmatter = (await row(engine, slug)).frontmatter, proposalsBefore = await proposals(engine);
+ const { applied } = await previewApply(engine, ['visibility', '--slug', slug, '--readers', ownerAnd('alice-example')]);
+ await settleManagedGitEffects(engine);
+ expect(applied.outcome_items).toEqual([expect.objectContaining({ item: 'default:' + slug, outcome: 'readers_set' })]);
+ expect(await stamps(engine, slug)).toEqual(before);
+ expect(await row(engine, slug)).toEqual({ frontmatter: { ...frontmatter, readable_by: ['alice-example', OWNER] }, page_readers: ['member:alice-example', 'member:' + OWNER] });
+ expect(await proposals(engine)).toEqual(proposalsBefore);
+ expect(git(root, 'ls-files', 'email').trim()).toBe('email/.keep');
+ }, { databaseUrl, setup }), 240_000);
+
+ test('a page with no file outside any db_only path is held canonical_file_missing: nothing written, no put_page provenance, tier kept', () => managedBrain(async ({ engine, root, ctx }) => {
+ const slug = 'email/nofile-example';
+ await dbOnlyPage(engine, ctx, slug);
+ await seedMembers(engine);
+ dropDbOnly(root, slug);
+ const before = await stamps(engine, slug), stored = await row(engine, slug), proposalsBefore = await proposals(engine);
+ const argv = ['visibility', '--slug', slug, '--readers', ownerAnd('alice-example')];
+ const { applied } = await previewApply(engine, argv);
+ expect(applied.applied).toBe(0);
+ expect(applied.outcome_items).toEqual([expect.objectContaining({ item: 'default:' + slug, outcome: 'canonical_file_missing', reason: expect.stringContaining('storage.db_only') })]);
+ expect(renderRepairResult(applied, { diff: false })).toContain('outcomes: canonical_file_missing=1');
+ expect(await stamps(engine, slug)).toEqual(before);
+ expect(await row(engine, slug)).toEqual(stored);
+ expect(stored.frontmatter.readable_by).toBeUndefined();
+ expect(await proposals(engine)).toEqual(proposalsBefore);
+ expect(git(root, 'ls-files', 'email').trim()).toBe('email/.keep');
+ expect((await repair(engine, argv)).listing).toHaveLength(1);
+ }, { databaseUrl, setup }), 240_000);
+});
+
+/** A repo-less brain (no managed persistence, no checkout: the default keyless install) is the database record. */
+for (const backend of testBackends()) describe('[' + backend + '] repair visibility --readers on a repo-less brain', () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const SRC = 'readers-src';
+ const PAGES = { shared: { slug: 'notes/shared-example', canary: 'canaryrdrshared' }, other: { slug: 'notes/other-example', canary: 'canaryrdrother' } } as const;
+ /** A canary counts only as a whole token: no letter or digit right after it. */
+ const has = (text: string, canary: string) => new RegExp(canary + '(?![A-Za-z0-9])').test(text);
+
+ async function repoless(fn: (engine: BrainEngine, home: string) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-readers-repoless-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
+ for (const { slug, canary } of Object.values(PAGES)) {
+ expect((await importFromContent(engine, slug, file(slug, canary), { noEmbed: true, sourceId: SRC })).status).toBe('imported');
+ await engine.transaction(tx => withCoordinatedWrite(tx, [SRC], () => withTrustBackfill(tx, () => tx.executeRaw(
+ "UPDATE pages SET trust_tier='operator_curated', source_kind='mail-example', ingested_via='connector-example', ingested_at='2026-01-02T00:00:00Z' WHERE source_id=$1 AND slug=$2",
+ [SRC, slug])), TEST_WRITE_ATTRIBUTION));
+ }
+ await seedMembers(engine);
+ await fn(engine, home);
+ } finally { await disposePersistenceConsumer(engine); await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }
+ const one = (readers: string, ...more: string[]) => ['visibility', '--source', SRC, '--slug', PAGES.shared.slug, '--readers', readers, ...more];
+
+ test('a listed set keeps the tier and provenance and updates page_readers; a bound member key reads it through MCP, another does not, the owner does', () => repoless(async (engine, home) => {
+ const tokens: Record<string, string> = {};
+ for (const member of ['alice-example', 'bob-example', OWNER]) {
+ const minted = await mintLegacyToken(engine, { name: member, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });
+ tokens[member] = minted.token;
+ await bindCredential(engine, { kind: 'token', id: minted.id }, { member });
+ }
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const call = async (who: string, op: string, params: Record<string, unknown>) => {
+ const auth = await provider.verifyAccessToken(tokens[who]!) as unknown as AuthInfo;
+ const sourceId = auth.sourceId ?? 'default';
+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, sourceId);
+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'],
+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}) });
+ return out.content.map(c => c.text).join(NL);
+ };
+ const reads = async (who: string) => ({
+ get_page: has(await call(who, 'get_page', { slug: PAGES.shared.slug }), PAGES.shared.canary),
+ list_pages: (await call(who, 'list_pages', { limit: 100 })).split(/[^A-Za-z0-9/_-]+/).includes(PAGES.shared.slug),
+ search: has(await call(who, 'search', { query: 'second paragraph', match: 'keyword', fields: 'full', limit: 50 }), PAGES.shared.canary),
+ });
+ const every = (value: boolean) => ({ get_page: value, list_pages: value, search: value });
+ expect(await reads('bob-example')).toEqual(every(true));
+
+ const list = join(home, 'slugs.txt');
+ writeFileSync(list, [PAGES.shared.slug, PAGES.other.slug].join(NL) + NL);
+ const before = await Promise.all(Object.values(PAGES).map(page => stamps(engine, page.slug, SRC)));
+ const { applied } = await previewApply(engine, ['visibility', '--source', SRC, '--slugs-file', list, '--readers', ownerAnd('alice-example')]);
+ expect(applied.applied).toBe(2);
+ expect(await Promise.all(Object.values(PAGES).map(page => stamps(engine, page.slug, SRC)))).toEqual(before);
+ for (const { slug } of Object.values(PAGES)) {
+ const stored = await row(engine, slug, SRC);
+ expect(stored.frontmatter.readable_by).toEqual(['alice-example', OWNER]);
+ expect(stored.frontmatter.source_kind).toBe('email-example');
+ expect(stored.page_readers).toEqual(['member:alice-example', 'member:' + OWNER]);
+ }
+ expect(await proposals(engine)).toEqual([]);
+
+ expect(await reads('alice-example')).toEqual(every(true));
+ expect(await reads('bob-example')).toEqual(every(false));
+ expect(await reads(OWNER)).toEqual(every(true));
+ }), 240_000);
+
+ test('a listed set of 150 pages applies page by page (no run-wide transaction) and lists each page in --json', () => repoless(async (engine, home) => {
+ const slugs = Array.from({ length: 150 }, (_, index) => 'bulk/page-' + String(index).padStart(3, '0'));
+ for (const slug of slugs) expect((await importFromContent(engine, slug, file(slug), { noEmbed: true, sourceId: SRC })).status).toBe('imported');
+ const list = join(home, 'bulk.txt');
+ writeFileSync(list, slugs.join(NL) + NL);
+ const { preview, applied } = await previewApply(engine, ['visibility', '--source', SRC, '--slugs-file', list, '--readers', ownerAnd('group:team-example')]);
+ expect(preview.listing).toHaveLength(150);
+ expect(applied.applied).toBe(150);
+ expect(applied.outcome_items).toHaveLength(150);
+ expect(await engine.executeRaw("SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug LIKE 'bulk/%' AND page_readers = ARRAY['group:team-example','member:owner-example']", [SRC])).toEqual([{ n: 150 }]);
+ }), 240_000);
+
+ test('an unknown member or group, a disabled member, or a list without the owner refuses before anything is written; the flag passes', () => repoless(async engine => {
+ const frontmatter = (await row(engine, PAGES.shared.slug, SRC)).frontmatter;
+ expect(await refusal(engine, one(ownerAnd('zed-example')))).toMatchObject({ code: 'access_member_invalid', message: expect.stringContaining('zed-example') });
+ expect(await refusal(engine, one(ownerAnd('group:nobody-example')))).toMatchObject({ code: 'access_member_invalid', message: expect.stringContaining('nobody-example') });
+ expect(await refusal(engine, one('Not A Reader'))).toMatchObject({ code: 'invalid_params' });
+ expect(await refusal(engine, one('alice-example'))).toMatchObject({ code: 'invalid_params', message: expect.stringContaining(OWNER) });
+ // A group that holds the owner does not name the owner.
+ expect(await refusal(engine, one('group:family-example'))).toMatchObject({ code: 'invalid_params', message: expect.stringContaining('--allow-without-owner') });
+ await disableMember(engine, 'bob-example');
+ expect(await refusal(engine, one(ownerAnd('bob-example')))).toMatchObject({ code: 'access_member_invalid', message: expect.stringContaining('bob-example') });
+ expect((await row(engine, PAGES.shared.slug, SRC)).frontmatter).toEqual(frontmatter);
+
+ const { applied } = await previewApply(engine, one('alice-example', '--allow-without-owner'));
+ expect(applied.applied).toBe(1);
+ expect((await row(engine, PAGES.shared.slug, SRC)).page_readers).toEqual(['member:alice-example']);
+ }), 240_000);
+
+ test('a changed plan refuses preview_changed: other readers, another flag, or a page whose readers moved; a reader disabled since refuses', () => repoless(async engine => {
+ const preview = await repair(engine, one(ownerAnd('alice-example')));
+ expect(await refusal(engine, [...one(ownerAnd('bob-example')), '--apply', '--expect', preview.preview_hash])).toMatchObject({ code: 'preview_changed' });
+ expect(await refusal(engine, [...one(ownerAnd('alice-example'), '--allow-without-owner'), '--apply', '--expect', preview.preview_hash])).toMatchObject({ code: 'preview_changed' });
+ await previewApply(engine, one(ownerAnd('group:team-example')));
+ expect(await refusal(engine, [...one(ownerAnd('alice-example')), '--apply', '--expect', preview.preview_hash])).toMatchObject({ code: 'preview_changed' });
+ expect((await row(engine, PAGES.shared.slug, SRC)).page_readers).toEqual(['group:team-example', 'member:' + OWNER]);
+
+ const next = await repair(engine, one(ownerAnd('alice-example')));
+ await disableMember(engine, 'alice-example');
+ expect(await refusal(engine, [...one(ownerAnd('alice-example')), '--apply', '--expect', next.preview_hash])).toMatchObject({ code: 'access_member_invalid' });
+ expect((await row(engine, PAGES.shared.slug, SRC)).page_readers).toEqual(['group:team-example', 'member:' + OWNER]);
+ }), 240_000);
+
+ test('--readers needs --slug or --slugs-file, refuses --class and a bare --apply; the owner flag needs --readers', () => repoless(async engine => {
+ expect(await refusal(engine, ['visibility', '--source', SRC, '--readers', OWNER])).toMatchObject({ code: 'invalid_params', message: expect.stringContaining('--slug') });
+ expect(await refusal(engine, [...one(OWNER), '--class', 'aliases'])).toMatchObject({ code: 'invalid_params' });
+ expect(await refusal(engine, [...one(OWNER), '--apply'])).toMatchObject({ code: 'invalid_params', message: expect.stringContaining('preview') });
+ expect(await refusal(engine, ['visibility', '--source', SRC, '--allow-without-owner', '--slug', PAGES.shared.slug])).toMatchObject({ code: 'invalid_params' });
+ }), 120_000);
+});