Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

repair file-drift: --only/--skip file path globs bound into the preview hash; refuse --keep (#6696 C7)

garrytan7dcdd10dbc77
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 70bf7e306c..f3b3fa5a94 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -64,7 +64,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
gbrain repair fences [--source <id>] [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff]
[--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]
gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>])
- --prefer file|database [--apply --expect <preview-hash>] [--json]
+ [--only <glob>]... [--skip <glob>]... --prefer file|database [--apply --expect <preview-hash>] [--json]
gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]
[--keep prior|disk --apply --expect <preview-hash> --yes] [--json]
${REPAIR_CONTENT_HELP}
@@ -92,10 +92,13 @@ Options:
Explicit-only kinds: widen the preview to ambiguous items (its hash covers them).
--only <path>, --skip <path>
frontmatter, fences, slug-conflicts, content: select source-relative files (repeatable); the hash covers the selection.
+ file-drift: narrow the selected pages by canonical file path (repeatable; an exact path, or a glob with
+ * within a segment and ** across segments, e.g. --only 'concepts/**'); the hash and the apply command cover them.
--slug <slug> fences, file-drift: select a database page by slug (repeatable); the hash covers the selection.
--prefer file|database, --request <id>, --all-drifted, --class <name>
file-drift: the side that wins; select conflict receipts by request id (repeatable), or every page
- still drifted (refused across mixed drift classes unless --class keeps one).
+ still drifted (refused across mixed drift classes unless --class keeps one). --keep is refused here:
+ --prefer database keeps the database copy, --prefer file keeps the file.
--diff frontmatter, fences, slug-conflicts, content: print every per-file diff, not one sample per class or tier.
--no-llm Kinds that may call a paid model (${llmKinds}) and the content lane: use only the free tiers;
model-tier items stay held with llm_disabled.
@@ -121,7 +124,7 @@ const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--in
const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--keep', '--request-id']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
- '--only': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery'],
+ '--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'],
'--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
};
@@ -145,6 +148,26 @@ function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | und
`To cap paid repair work, preview gbrain doctor --remediation-plan --json, then after the user agrees run: gbrain doctor --remediate --yes --include-repairs --max-usd ${value} --expect <plan_hash> (plan_hash from the preview)`);
}
+/**
+ * #6696 C7: `--keep` belongs to stuck-recovery; on file-drift the side that wins is `--prefer`. The fix is the same
+ * command with `--keep <v>` replaced by `--prefer database` (an existing --prefer kept), as a read-only preview.
+ */
+function fileDriftKeepRefusal(args: string[], keep: string): OperationError {
+ const preview: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ const token = args[i]!;
+ const flag = token.split('=')[0]!;
+ if (flag === '--apply' || flag === '--yes' || flag === '--json') continue;
+ if (flag === '--keep' || flag === '--expect') { if (!token.includes('=')) i++; continue; }
+ preview.push(token);
+ }
+ const prefer = preview.includes('--prefer') || preview.some(token => token.startsWith('--prefer=')) ? [] : ['--prefer', 'database'];
+ const argv = ['gbrain', 'repair', ...preview, ...prefer, '--json'];
+ return opError('invalid_params', `--keep ${keep} does not apply to gbrain repair file-drift; it chooses the winning side with --prefer.`,
+ `Use --prefer database to keep the database copy (or --prefer file to keep the file), then preview again: ${shellQuote(argv.slice(0, -1))}`,
+ { fix: readFix('Previews the file-drift resolution with the database copy winning; without --apply it writes nothing.', { argv }) });
+}
+
/** 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, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],
@@ -153,6 +176,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
const positional: string[] = [];
let maxUsdText: string | undefined;
let maxUsdFlag: string | undefined;
+ let keepText: string | undefined;
for (let i = 0; i < args.length; i++) {
const token = args[i]!;
if (!token.startsWith('-')) { positional.push(token); continue; }
@@ -193,11 +217,8 @@ export function parseRepairArgs(args: string[]): RepairArgs {
}
else if (flag === '--request') parsed.requests.push(value);
else if (flag === '--class') parsed.driftClass = value;
- else if (flag === '--keep') {
- if (value !== 'prior' && value !== 'disk') throw invalid(`--keep must be prior or disk (got "${value}").`,
- 'Pass --keep prior to write the recorded prior bytes back, or --keep disk to keep the bytes on disk; the preview lists which are available.', ['gbrain', 'repair', 'stuck-recovery', '--json']);
- parsed.keep = value;
- } else if (flag === '--request-id') {
+ else if (flag === '--keep') keepText = value;
+ else if (flag === '--request-id') {
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw invalid(`--request-id must be a request UUID (got "${value}").`,
'Pass the request_id the stuck-recovery preview (or gbrain sources writer status --json) lists, e.g. --request-id 123e4567-e89b-42d3-a456-426614174000.', ['gbrain', 'repair', 'stuck-recovery', '--json']);
parsed.requestId = value.toLowerCase();
@@ -207,6 +228,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,
`Kinds: ${REPAIR_KINDS.join(', ')}.`);
parsed.kind = positional[0];
+ if (keepText !== undefined && parsed.kind === 'file-drift') throw fileDriftKeepRefusal(args, keepText);
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']);
@@ -216,6 +238,11 @@ export function parseRepairArgs(args: string[]): RepairArgs {
throw new OperationError('invalid_params', `${kindOnly} applies only to gbrain repair ${kinds.join(' or ')}.`,
`Preview it by name: gbrain repair ${kinds[kinds.length - 1]}${parsed.source ? ` --source ${parsed.source}` : ''}`);
}
+ if (keepText !== undefined) {
+ if (keepText !== 'prior' && keepText !== 'disk') throw invalid(`--keep must be prior or disk (got "${keepText}").`,
+ 'Pass --keep prior to write the recorded prior bytes back, or --keep disk to keep the bytes on disk; the preview lists which are available.', ['gbrain', 'repair', 'stuck-recovery', '--json']);
+ parsed.keep = keepText;
+ }
const llmKind = LLM_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind) || parsed.kind === CONTENT_LANE;
if (maxUsdFlag) {
if (!llmKind) throw maxUsdRefusal(maxUsdFlag, maxUsdText, parsed.kind);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index d3a4d01996..f4337a3db0 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.ts
index 675ee963e8..94751db1cf 100644
--- a/src/core/persistence/drift-conflicts.ts
+++ b/src/core/persistence/drift-conflicts.ts
@@ -147,6 +147,8 @@ export interface ConflictRow extends Record<string, unknown> {
last_committed: { request_id?: string; completed_at: string } | null;
source_path?: string | null;
git?: { tracked: boolean | null; committed: boolean | null };
+ /** Source-relative path of the canonical file the live check compared (trusted callers on the owner host). */
+ path?: string;
file_hash?: string;
db_revision?: string;
still_present: { value: boolean | null; reason: string };
@@ -261,7 +263,7 @@ export async function auditDriftConflicts(engine: BrainEngine, sourceId: string,
result.still_present = { value: live.still_present, reason: live.reason };
if (live.file_hash) result.file_hash = live.file_hash;
if (live.db_revision) result.db_revision = live.db_revision;
- if (live.path) result.git = gitState(root, live.path);
+ if (live.path) { result.path = live.path; result.git = gitState(root, live.path); }
if (live.still_present) {
report.totals.still_present++;
result.class = await driftClass(engine, sourceId, row.slug, !page?.source_path && !page?.source_uri);
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index a3e28389f6..464927180b 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -26,7 +26,12 @@
* `--all-drifted` takes every page the conflict audit finds still drifted. It
* refuses a selection that mixes drift classes unless `--class <name>` keeps
* exactly one, so one `--prefer` never resolves differently shaped drift in bulk.
- * Trusted local CLI only.
+ * #6696 C7: repeatable `--only` / `--skip` globs over the canonical file path,
+ * source-relative like the other kinds' `--only` (`*` within a segment, `**`
+ * across segments, sync's `matchesAnyGlob`; an exact path matches itself),
+ * narrow the selection before the class check, the bound and any preview
+ * work; they are part of the selection digest (so of the plan hash) and of
+ * every printed preview and apply command. Trusted local CLI only.
*/
import { randomUUID } from 'node:crypto';
import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
@@ -37,6 +42,8 @@ import { flushDirectory } from '../fs-durable.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { validateSlug } from '../utils.ts';
+import { matchesAnyGlob } from '../sync.ts';
+import { shellQuote } from '../agent-output.ts';
import type { ParsedPage } from '../import-file.ts';
import { digest, stableJson } from '../persistence/digest.ts';
import { currentVerifiedLocalWriter, readLocalWriter, withVerifiedLocalRegistration } from '../persistence/identity.ts';
@@ -56,7 +63,8 @@ export type DriftSide = 'file' | 'database';
export interface DriftException { path: string; reason: 'protected_metadata' | 'scan_state' | 'tags_union' | 'protected_takes_or_private_facts' | 'canonical_import' }
interface ApprovedPage { source_id: string; slug: string; artifact_digest: string; selection: string }
interface DriftItem extends RepairItem { page: ApprovedPage; hash: string; last: boolean }
-interface ArtifactPage { slug: string; prefer: DriftSide; class?: DriftClass; adopt_slug_path: boolean; exceptions: DriftException[]; result: ParsedPage; preview: ReconcileArtifact }
+/** One page's prepared resolution: the ready reconcile preview its apply submits, and where it departs from the preferred side. */
+export interface ArtifactPage { slug: string; prefer: DriftSide; class?: DriftClass; adopt_slug_path: boolean; exceptions: DriftException[]; result: ParsedPage; preview: ReconcileArtifact }
const ALL_DRIFTED_LIMIT = 1000;
const TOP_FIELDS = ['title', 'type', 'compiled_truth', 'timeline'] as const;
@@ -66,9 +74,15 @@ const escapePointer = (key: string) => key.replace(/~/g, '~0').replace(/\//g, '~
function previewCommand(sourceId: string, opts: RepairPlanOptions): string {
const select = opts.allDrifted ? ` --all-drifted${opts.driftClass ? ` --class ${opts.driftClass}` : ''}`
: [...(opts.slugs ?? []).map(slug => ` --slug ${slug}`), ...(opts.requests ?? []).map(id => ` --request ${id}`)].join('');
- return `gbrain repair file-drift --source ${sourceId}${select} --prefer ${opts.prefer ?? '<file|database>'}`;
+ const globs = [...(opts.only ?? []).flatMap(glob => ['--only', glob]), ...(opts.skip ?? []).flatMap(glob => ['--skip', glob])];
+ return `gbrain repair file-drift --source ${sourceId}${select}${globs.length ? ` ${shellQuote(globs)}` : ''} --prefer ${opts.prefer ?? '<file|database>'}`;
}
+/** Whether a canonical file path passes the `--only` / `--skip` globs (no `--only`: every path; an unknown path only then). */
+const selectedByGlobs = (path: string | undefined, opts: Pick<RepairPlanOptions, 'only' | 'skip'>) =>
+ path === undefined ? !opts.only?.length && !opts.skip?.length
+ : (!opts.only?.length || matchesAnyGlob(path, opts.only)) && !matchesAnyGlob(path, opts.skip);
+
/** The reconcile decisions that make the preferred side win every field reconcile lets a decision choose. */
export function preferSideDecisions(file: ParsedPage, database: ParsedPage, prefer: DriftSide): ReconcileDecision[] {
const take = prefer === 'file' ? 'take_file' : 'take_database';
@@ -139,15 +153,25 @@ function readArtifact(hash: string, command: string): Map<string, ArtifactPage>
} catch { throw previewChangedError(hash, command); }
}
-/** The slugs the selection names: exact slugs, the slugs of named conflict receipts, or every page the audit finds still drifted. */
-async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions): Promise<{ slugs: string[]; classes: Map<string, DriftClass> }> {
+/**
+ * The slugs the selection names: exact slugs, the slugs of named conflict receipts, or every page the audit finds
+ * still drifted. `--all-drifted` is narrowed here by the `--only` / `--skip` globs over each page's canonical file
+ * path (`not_selected` counts the pages they leave out), before the class check and the bound; an exact selection
+ * is narrowed by the plan from the same live check.
+ */
+async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPlanOptions): Promise<{ slugs: string[]; classes: Map<string, DriftClass>; notSelected: number }> {
const classes = new Map<string, DriftClass>();
if (opts.allDrifted) {
const drifted: string[] = [];
+ let notSelected = 0;
let cursor: string | undefined;
do {
const page = await auditDriftConflicts(engine, sourceId, { trusted: true, excludePrivate: false }, { limit: 100, cursor });
- for (const row of page.conflicts) if (row.still_present.value === true) { drifted.push(row.slug); classes.set(row.slug, row.class ?? 'error'); }
+ for (const row of page.conflicts) {
+ if (row.still_present.value !== true) continue;
+ if (!selectedByGlobs(row.path, opts)) { notSelected++; continue; }
+ drifted.push(row.slug); classes.set(row.slug, row.class ?? 'error');
+ }
cursor = page.next ?? undefined;
} while (cursor && drifted.length < ALL_DRIFTED_LIMIT);
const counts = new Map<DriftClass, number>();
@@ -158,7 +182,7 @@ async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPl
`Preview one class at a time: ${previewCommand(sourceId, { ...opts, driftClass: [...counts.keys()][0] })}, and so on for each class; or name pages with --slug.`,
{ fix: readFix('Lists the drifted pages with their drift class, read-only.', { argv: ['gbrain', 'sources', 'reconcile', sourceId, '--brain', 'host', '--audit', '--conflicts', '--json'] }) });
}
- return { slugs: drifted.filter(slug => !opts.driftClass || classes.get(slug) === opts.driftClass), classes };
+ return { slugs: drifted.filter(slug => !opts.driftClass || classes.get(slug) === opts.driftClass), classes, notSelected };
}
const slugs = new Set(opts.slugs ?? []);
if (opts.requests?.length) {
@@ -171,12 +195,12 @@ async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPl
{ fix: readFix('Lists the conflict receipts of this source grouped by slug, read-only.', { argv: ['gbrain', 'sources', 'reconcile', sourceId, '--brain', 'host', '--audit', '--conflicts', '--json'] }) });
for (const row of rows) slugs.add(row.slug);
}
- return { slugs: [...slugs].sort(), classes };
+ return { slugs: [...slugs].sort(), classes, notSelected: 0 };
}
function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined): asserts opts is RepairPlanOptions & { prefer: DriftSide } {
if (opts?.remote !== false) throw trustedCliRequired('gbrain repair file-drift runs only for the trusted local CLI on the brain host.');
- const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>]) --prefer file|database';
+ const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>]) [--only <glob>]... [--skip <glob>]... --prefer file|database';
if (scope.source_ids.length !== 1) throw opError('invalid_params', 'gbrain repair file-drift needs exactly one --source.', `Name the source: ${usage}`);
if (opts.prefer !== 'file' && opts.prefer !== 'database') throw opError('invalid_params', 'gbrain repair file-drift needs --prefer file or --prefer database.',
`Choose the side whose content wins (protected metadata, tags union, protected takes and private facts are kept either way): ${usage}`);
@@ -188,6 +212,12 @@ function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined
for (const slug of opts.slugs ?? []) {
try { validateSlug(slug); } catch { throw opError('invalid_params', `Invalid page slug '${slug}'.`, 'Pass each page by its exact stored slug.'); }
}
+ for (const glob of [...(opts.only ?? []), ...(opts.skip ?? [])]) {
+ try { validateSlug(glob); } catch {
+ throw opError('invalid_params', `Invalid file path glob '${glob}'.`,
+ `--only and --skip take canonical file path globs relative to the source, like the other kinds' --only, without a leading / or .. segment: * matches within one path segment, ** across segments, an exact path matches itself (e.g. --only 'concepts/**' or --only concepts/agi.md). ${usage}`);
+ }
+ }
if (opts.requests?.some(id => !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))) {
throw opError('invalid_params', '--request takes a conflict receipt request UUID.', 'Pass the request id the conflict audit lists (last_conflict_request_id).');
}
@@ -223,6 +253,28 @@ async function survey(engine: BrainEngine, scope: RepairScope): Promise<RepairPl
next_actions: next.length ? [...next.map(command => `Preview: ${command} (or --prefer database)`), 'Or preview single pages with --slug <slug>.'] : [] } };
}
+/**
+ * One drifted page resolved with `prefer` winning, as a ready reconcile preview: the preferred side's decisions over
+ * reconcile's protections, the size check, and the exceptions. Throws `invalid_params` when a path still needs a
+ * human decision. The caller runs it as the trusted local CLI and has checked the page is still drifted.
+ */
+export async function prepareDriftPage(engine: BrainEngine, sourceId: string, slug: string, prefer: DriftSide, assessmentAt: string): Promise<ArtifactPage> {
+ const snapshotRow = await engine.readPageSnapshot(slug, { sourceId });
+ const adopt = !!snapshotRow && !snapshotRow.page.source_path && !snapshotRow.page.source_uri;
+ const state = await readReconcileState(engine, sourceId, slug, assessmentAt, { adoptSlugPath: adopt });
+ const database = reconcileCanonical(state.snapshot.page, state.snapshot.tags);
+ const file = reconcileCanonical(state.file, state.file.tags);
+ const decisions = preferSideDecisions(state.file, database, prefer);
+ const prepared = await prepareReconcileResult(engine, state, decisions);
+ if (prepared.conflicts.length || !prepared.ready) throw opError('invalid_params', 'Some paths still need a decision.',
+ `Preview ${slug} with gbrain sources reconcile ${sourceId} ${slug} --brain host --preview --out <file> and resolve it there.`);
+ const preview: ReconcileArtifact = { format_version: 1, preview_id: randomUUID(), preconditions: state.pins,
+ preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),
+ decisions, conflicts: [], result: prepared.result, result_digest: digest(prepared.result), status: 'ready' };
+ await assertReconcileSize(engine, preview);
+ return { slug, prefer, adopt_slug_path: adopt, exceptions: driftExceptions(prepared.result, prefer === 'file' ? file : database), result: prepared.result, preview };
+}
+
function item(page: ApprovedPage, index: number, hash: string, last: boolean, prefer: DriftSide): DriftItem {
return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0, action: `prefer_${prefer}`, page, hash, last };
}
@@ -235,7 +287,10 @@ export const fileDriftRepair: RepairHandler = {
validateOptions(scope, opts);
const sourceId = scope.source_ids[0]!;
const command = previewCommand(sourceId, opts);
- const selection = digest({ prefer: opts.prefer, slugs: opts.slugs ?? [], requests: opts.requests ?? [], all: opts.allDrifted === true, class: opts.driftClass ?? null });
+ const only = [...new Set(opts.only ?? [])].sort();
+ const skip = [...new Set(opts.skip ?? [])].sort();
+ const selection = digest({ prefer: opts.prefer, slugs: opts.slugs ?? [], requests: opts.requests ?? [], all: opts.allDrifted === true, class: opts.driftClass ?? null,
+ ...(only.length ? { only } : {}), ...(skip.length ? { skip } : {}) });
if (opts.apply) {
if (!opts.expect) throw new OperationError('invalid_params', 'gbrain repair file-drift --apply applies only the set a preview printed.',
`Preview first: ${command} — then run the apply command it prints with --expect <preview-hash>.`, 'docs/guides/repair.md#explicit-only-repair-kinds');
@@ -244,39 +299,28 @@ export const fileDriftRepair: RepairHandler = {
const items = approved.items.map((page, index) => item(page, index, opts.expect!, index === approved.items.length - 1, opts.prefer));
return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
}
- const { slugs, classes } = await selectSlugs(engine, sourceId, opts);
+ const { slugs, classes, notSelected } = await selectSlugs(engine, sourceId, opts);
const assessmentAt = new Date().toISOString();
const pages: ArtifactPage[] = [];
const listing: NonNullable<RepairPlan['listing']> = [];
- const residuals: Record<string, number> = {};
+ const residuals: Record<string, number> = notSelected ? { not_selected: notSelected } : {};
const count = (key: string) => { residuals[key] = (residuals[key] ?? 0) + 1; };
await asLocalCli(engine, async () => {
for (const slug of slugs) {
try {
await authorizeReconcile(engine, sourceId, slug);
const live = await liveFileDrift(engine, sourceId, slug);
+ if (!opts.allDrifted && !selectedByGlobs(live.path, opts)) { count('not_selected'); continue; }
if (live.still_present !== true) {
count(live.still_present === false ? 'no_drift' : `unknown_${live.reason}`);
listing.push({ item: `${sourceId}:${slug}`, class: live.still_present === false ? 'no_drift' : 'unknown', detail: live.reason });
continue;
}
- const snapshotRow = await engine.readPageSnapshot(slug, { sourceId });
- const adopt = !!snapshotRow && !snapshotRow.page.source_path && !snapshotRow.page.source_uri;
- const state = await readReconcileState(engine, sourceId, slug, assessmentAt, { adoptSlugPath: adopt });
- const database = reconcileCanonical(state.snapshot.page, state.snapshot.tags);
- const file = reconcileCanonical(state.file, state.file.tags);
- const decisions = preferSideDecisions(state.file, database, opts.prefer);
- const prepared = await prepareReconcileResult(engine, state, decisions);
- if (prepared.conflicts.length || !prepared.ready) throw opError('invalid_params', 'Some paths still need a decision.',
- `Preview ${slug} with gbrain sources reconcile ${sourceId} ${slug} --brain host --preview --out <file> and resolve it there.`);
- const preview: ReconcileArtifact = { format_version: 1, preview_id: randomUUID(), preconditions: state.pins,
- preimages: JSON.parse(stableJson({ file_base64: state.raw.toString('base64'), database: state.snapshot, stored_page: state.storedPage })),
- decisions, conflicts: [], result: prepared.result, result_digest: digest(prepared.result), status: 'ready' };
- await assertReconcileSize(engine, preview);
- const exceptions = driftExceptions(prepared.result, opts.prefer === 'file' ? file : database);
- pages.push({ slug, prefer: opts.prefer, ...(classes.has(slug) ? { class: classes.get(slug) } : {}), adopt_slug_path: adopt, exceptions, result: prepared.result, preview });
+ const page = await prepareDriftPage(engine, sourceId, slug, opts.prefer, assessmentAt);
+ if (classes.has(slug)) page.class = classes.get(slug);
+ pages.push(page);
listing.push({ item: `${sourceId}:${slug}`, class: `prefer_${opts.prefer}`,
- detail: `${exceptions.length ? `kept: ${[...new Set(exceptions.map(e => e.reason))].join(', ')}` : 'exactly the preferred side'}${adopt ? '; adopts the file at its slug path' : ''}` });
+ detail: `${page.exceptions.length ? `kept: ${[...new Set(page.exceptions.map(e => e.reason))].join(', ')}` : 'exactly the preferred side'}${page.adopt_slug_path ? '; adopts the file at its slug path' : ''}` });
} catch (error) {
if (!(error instanceof OperationError) || ['owner_unavailable', 'writer_registration_required'].includes(error.code)) throw error;
count(`refused_${error.code}`);
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index b3f5093ddd..e3c1161456 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -274,7 +274,8 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
summary: 'Resolve pages whose canonical file differs from the database (source_changed / file_database_drift, #6643) through canonical reconciliation: '
+ '--prefer file or --prefer database wins every ordinary field, within reconcile\'s protections (protected metadata stays as stored, tags are '
+ 'the union, protected takes and private fact rows are kept; the preview lists each page\'s exceptions). Select with --slug <slug>, --request '
- + '<conflict request id> or --all-drifted (refused across mixed drift classes unless --class <name> keeps one). Needs --source. The preview '
+ + '<conflict request id> or --all-drifted (refused across mixed drift classes unless --class <name> keeps one), narrowed by --only/--skip '
+ + 'canonical file path globs (* within a segment, ** across; bound into the hash and the apply command). Needs --source. The preview '
+ 'writes each resolved result to a private artifact; --apply --expect <hash> applies exactly that set with request ids derived from the hash, '
+ 'resumable, per page repaired, refused or changed_since_preview. Backups are reconcile\'s own. Trusted local CLI only; runs only when named.',
},