Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 2 L4: fault-table exits, source_changed routing, hold escalation, repair file-drift --since

garrytanaf5c77295401
diff --git a/src/commands/agent-logs.ts b/src/commands/agent-logs.ts
index 2c1f6c835c..14f03a4924 100644
--- a/src/commands/agent-logs.ts
+++ b/src/commands/agent-logs.ts
@@ -15,6 +15,7 @@ import { readSubagentAuditForJob } from '../core/minions/handlers/subagent-audit
import type { SubagentAuditEvent } from '../core/minions/handlers/subagent-audit.ts';
import { loadTranscriptRows, renderTranscript } from '../core/minions/transcript.ts';
import type { SubagentMessageRow } from '../core/minions/transcript.ts';
+import { parseSince } from '../core/since.ts';
export interface AgentLogsOpts {
follow?: boolean;
@@ -144,32 +145,8 @@ async function readJobStatus(engine: BrainEngine, jobId: number): Promise<string
return rows[0]?.status ?? null;
}
-const RELATIVE_RE = /^(\d+)\s*(s|m|h|d)$/i;
-
-/** Parse `--since`. Accepts ISO-8601 or relative ("5m", "1h", "2d"). */
-export function parseSince(input: string | undefined): string | undefined {
- if (!input) return undefined;
- const trimmed = input.trim();
- if (!trimmed) return undefined;
- const rel = RELATIVE_RE.exec(trimmed);
- if (rel) {
- const [, nStr, unitRaw] = rel;
- const unit = unitRaw!.toLowerCase();
- const n = parseInt(nStr!, 10);
- const mult = unit === 's' ? 1000
- : unit === 'm' ? 60_000
- : unit === 'h' ? 3_600_000
- : 86_400_000; // 'd'
- return new Date(Date.now() - n * mult).toISOString();
- }
- // Assume ISO. `new Date(input).toISOString()` both validates and
- // normalizes; invalid ISO throws.
- const d = new Date(trimmed);
- if (isNaN(d.getTime())) {
- throw new Error(`--since: could not parse "${input}" as ISO-8601 or relative (e.g. "5m", "1h")`);
- }
- return d.toISOString();
-}
+/** Parse `--since`. Accepts ISO-8601 or relative ("5m", "1h", "2d"); the shared parser (#6712 PR 2). */
+export { parseSince };
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve) => {
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 463557b2cf..8468a9aa57 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -23,6 +23,7 @@ import { OperationError, opError } from '../core/ops/contract.ts';
import { readFix } from '../core/ops/op-fix.ts';
import { shellQuote } from '../core/agent-output.ts';
import { OLDER_THAN_RE } from '../cli/strict-args.ts';
+import { parseSince } from '../core/since.ts';
import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';
import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';
import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, LLM_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMayEmbed, repairMaySpend,
@@ -66,7 +67,7 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
[--no-llm] [--max-usd <n>] [--apply [--expect <preview-hash>]] [--limit <n>] [--json]
gbrain repair receipt-compaction [--older-than <72h|30d>] [--include-failures] [--force]
[--apply --expect <preview-hash> --yes] [--limit <n>] [--json]
- gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>])
+ gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>])
[--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]
@@ -103,6 +104,10 @@ Options:
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). --keep is refused here:
--prefer database keeps the database copy, --prefer file keeps the file.
+ --since <ISO-8601|7d>
+ file-drift: keep only pages whose newest drift conflict is at or after the instant (with --all-drifted, or
+ the bare survey). An age (7d, 12h) is resolved once to a concrete instant; the preview, its hash and the
+ printed apply command carry that instant, so the apply selects exactly what the preview did.
--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.
@@ -126,16 +131,16 @@ A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-r
Live pages whose canonical file is missing (ghost pages): docs/guides/repair.md#ghost-pages.`;
const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force']);
-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--keep', '--request-id', '--older-than']);
+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than']);
/** 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'],
- '--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'],
+ '--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
};
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', '--keep': 'prior',
+ '--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--keep': 'prior',
'--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d' };
/** 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,
@@ -143,7 +148,7 @@ const invalid = (message: string, suggestion: string, preview: string[] = ['gbra
interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;
noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];
- allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string;
+ allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;
keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean }
/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */
@@ -225,6 +230,11 @@ export function parseRepairArgs(args: string[]): RepairArgs {
}
else if (flag === '--request') parsed.requests.push(value);
else if (flag === '--class') parsed.driftClass = value;
+ else if (flag === '--since') {
+ try { parsed.since = parseSince(value, '--since'); } catch (error) {
+ throw invalid((error as Error).message, 'Pass an ISO-8601 instant (2026-10-01T00:00:00Z) or an age (7d, 12h); the preview prints the concrete instant it selected.', ['gbrain', 'repair', 'file-drift', ...(parsed.source ? ['--source', parsed.source] : []), '--json']);
+ }
+ }
else if (flag === '--older-than') {
if (!OLDER_THAN_RE.test(value)) throw invalid(`--older-than takes hours (72 or 72h) or days (30d) (got "${value}").`, 'Pass the age, e.g. --older-than 30d.',
['gbrain', 'repair', 'receipt-compaction', '--json']);
@@ -320,9 +330,11 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }
export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,
- prefer, requests, allDrifted, driftClass, keep, requestId, olderThan, includeFailures, force } = parseRepairArgs(args);
+ prefer, requests, allDrifted, driftClass, since, keep, requestId, olderThan, includeFailures, force } = parseRepairArgs(args);
const limit = limitText === undefined ? undefined : Number(limitText);
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');
+ // #6712 PR 2: a repair apply is a soak intervention; a file-drift apply is a content decision (soak-counters.ts).
+ if (apply && (kind === CONTENT_LANE || REPAIR_KINDS.includes(kind as RepairKind) || (!kind && all))) await (await import('../core/persistence/soak-counters.ts')).recordSoakEvent(engine, kind === 'file-drift' ? 'file_drift_apply' : 'repair_apply');
if (kind === CONTENT_LANE) {
if (all) throw invalid('Pass either content or --all, not both.', 'Drop --all to run the content lane, or drop content to run every automatic kind.', ['gbrain', 'repair', CONTENT_LANE, ...(source ? ['--source', source] : []), '--json']);
const { runRepairContentCommand } = await import('./repair-content.ts');
@@ -359,7 +371,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous,
...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),
...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),
- ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass } : {}),
+ ...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since } : {}),
...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),
...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}) });
results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index d090801d9d..66c3056230 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -13,7 +13,7 @@ import { cliRenderContext, renderAction } from '../../core/agent-output.ts';
import { writeJsonDocument } from '../../core/cli-force-exit.ts';
import { opError } from '../../core/ops/contract.ts';
import { readSyncStatus, unblockSync } from '../../core/persistence/sync-status.ts';
-import { HOLD_ATTEMPTS_NEEDS_HUMAN } from '../../core/persistence/sync-fault-class.ts';
+import { HOLD_ATTEMPTS_NEEDS_HUMAN, HOLD_ESCALATE_MS } from '../../core/persistence/sync-fault-class.ts';
import { CONTENT_REPAIR_HOLD_KINDS } from '../../core/repair/content-lane.ts';
import { resolveSourceIdEngineFree } from '../../core/source-resolver.ts';
@@ -61,7 +61,8 @@ leaves a file out, and each refusal names the file, why, and its fix.
on a person, the user's spend decision or the owner host is
listed, not retried.
other repair holds refused with the repair preview to run
- held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times refused: the page keeps moving; needs a person
+ ${HOLD_ATTEMPTS_NEEDS_HUMAN} failed attempts refused once also held ${HOLD_ESCALATE_MS / 3_600_000} h: the page keeps moving; needs a
+ person (never a file still being edited, never an image)
--no-llm repairs keep to their free tiers (model-tier files stay held)
--no-repair refuse every repair-class hold instead (the pre-#6377 behaviour)
@@ -117,6 +118,8 @@ export async function runSyncUnblock(engine: BrainEngine, args: string[]): Promi
if (args.includes('--help') || args.includes('-h')) return printSyncUnblockHelp();
const sourceId = sourceOf(args);
const outcome = await unblockSync(engine, sourceId, { apply: args.includes('--apply'), noLlm: args.includes('--no-llm'), noRepair: args.includes('--no-repair') });
+ // #6712 PR 2: a soak intervention (soak-counters.ts).
+ if (outcome.apply) await (await import('../../core/persistence/soak-counters.ts')).recordSoakEvent(engine, 'unblock_apply');
const ctx = cliRenderContext();
const rendered = { ...outcome,
applied: outcome.applied.map(entry => entry.action === 'repair' ? { ...entry, repair: { ...entry.repair, next: renderAction(entry.repair.next, ctx) } } : entry),
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 1eb18a176d..2a782dcee5 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--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'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--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', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--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'],
@@ -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', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--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-extract', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--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', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--touchpoint', '--url', '--url-env', '--user', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--all-drifted', '--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', '--detach', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-frontmatter', '--include-gitignored', '--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-extract', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--oversized', '--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', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--touchpoint', '--url', '--url-env', '--user', '--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', '--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', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--held', '--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', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--prefer', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--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'],
@@ -101,13 +101,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--brain', '--class', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--brain', '--class', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--since', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--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', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--lanes', '--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', '--priority', '--provenance', '--query', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--schema-pack', '--scopes', '--search-mode', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--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', '--scopes', '--source', '--timeout'],
- 'repair': ['--all', '--all-drifted', '--apply', '--brain', '--class', '--client', '--diff', '--expect', '--force', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--scopes', '--skip', '--slug', '--slugs', '--source', '--stale', '--yes'],
+ 'repair': ['--acknowledge-managed', '--all', '--all-drifted', '--apply', '--brain', '--break-lock', '--class', '--client', '--diff', '--expect', '--force', '--force-break-lock', '--full', '--help', '--id', '--include-ambiguous', '--include-failures', '--include-repairs', '--json', '--keep', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--scopes', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--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', '--audit', '--auto-additive', '--autostash', '--backups', '--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', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.ts
index 3e1ce7da74..6ebe001e5f 100644
--- a/src/core/persistence/sync-fault-class.ts
+++ b/src/core/persistence/sync-fault-class.ts
@@ -41,17 +41,23 @@ export interface SyncFaultRule {
/** #6340: a hold earned at or after this many re-holds of one path says the page keeps moving under the sync. */
export const HOLD_ATTEMPTS_NEEDS_HUMAN = 3;
+/**
+ * #6712 PR 2 (L4): and only once this long has passed since the path was first held with its code, so a burst of re-holds
+ * (three syncs in ten minutes) never pages a person; a live `worktree_dirty` editor and image holds never escalate.
+ */
+export const HOLD_ESCALATE_MS = 24 * 60 * 60 * 1000;
+const ESCALATE_AFTER = `${HOLD_ATTEMPTS_NEEDS_HUMAN} failed attempts over ${HOLD_ESCALATE_MS / 3_600_000} h`;
export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
// Page class: one entry, held; the run finished.
{ code: 'worktree_dirty', class: 'page', safe_actions: ['retry_when_clean'], needs_human: false,
- escalate: `held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times: the file keeps changing without being committed`, human_reason: 'Someone (or an agent) keeps editing the file without committing it; find out who and commit or restore it.' },
+ escalate: `${ESCALATE_AFTER} with no edit in the last ${HOLD_ESCALATE_MS / 3_600_000} h: the uncommitted edit is abandoned`, human_reason: 'An uncommitted edit of the file has sat in the checkout for a day without being committed; find out who made it and commit or restore it.' },
{ code: 'concurrent_write', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: the file and the database page diverge',
human_reason: 'The Git file and the database page both changed; a person chooses which version wins (gbrain sources reconcile <source> <slug> --preview shows both and writes nothing).' },
{ code: 'file_drift', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: the page changed in the database since its file was last imported',
human_reason: 'The database page moved since sync last imported its file, and importing would replace it; a person chooses which version wins (gbrain repair file-drift --source <source> --slug <slug> --prefer database|file previews it and writes nothing until applied).' },
{ code: 'preparation_stalled', class: 'page', safe_actions: ['retry', 'upgrade'], needs_human: false,
- escalate: `held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times, or writer status names a step that never finishes`, human_reason: 'The write owner cannot finish preparing this file; writer status names the step, fix or report it.' },
+ escalate: `${ESCALATE_AFTER}, or writer status names a step that never finishes`, human_reason: 'The write owner cannot finish preparing this file; writer status names the step, fix or report it.' },
{ code: 'invalid_fence', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the fence repair preview offers no plan (a manual reason)', human_reason: 'Edit the facts or takes table the hold names and commit.' },
{ code: 'invalid_frontmatter', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation (--include-ambiguous)', human_reason: 'Approve the proposed frontmatter fix or edit the file.' },
{ code: 'frontmatter_slug_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation', human_reason: 'Decide which page keeps the slug.' },
@@ -60,11 +66,28 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [
{ code: 'content_rejected', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The content-sanity gate rejected the file; remove the junk or change junk_disposition.' },
{ code: 'parser_regression', class: 'page', safe_actions: ['upgrade'], needs_human: true, escalate: 'always: a gbrain bug', human_reason: 'Report the file and gbrain version, then upgrade or pin the last good release.' },
{ code: 'managed_image_sync_unsupported', class: 'page', safe_actions: ['none'], needs_human: false, escalate: 'never: images stay held while multimodal embedding is off', human_reason: 'Leave images held, exclude them with sync.exclude, or set GBRAIN_EMBEDDING_MULTIMODAL=true so the next sync imports them.' },
+ // #6712 PR 2 (L4): two content refusals that hold the file; only the owner or the user changes the outcome.
+ { code: 'purged_content', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: only the owner clears a purge tombstone',
+ human_reason: 'The file carries content the owner purged; delete or edit the file and commit, or (only if the purge was a mistake) the owner clears it with gbrain pages unpurge <slug> --source <source> on the brain host.' },
+ { code: 'write_gate_rejected', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always: write_gate.external_mode=reject is the user\'s setting',
+ human_reason: 'The write gate refuses the file\'s external instruction-like content under write_gate.external_mode=reject; the user decides whether to edit the file or switch the setting back to quarantine.' },
// Older releases recorded these as run failures; a rerun on this release holds the page instead.
{ code: 'revision_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'page_identity_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'pinned_git_worktree_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
{ code: 'source_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },
+ // #6712 PR 2 (L4): `source_changed` refined by its recorded reason (`detail`); an admission race (`pending_import`, a file that moved
+ // between freeze and publication) keeps the retry above, two-sided drift and a missing file need a decision, a binding change an inspection.
+ { code: 'pending_import', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path refuses again after a sync imported its file' },
+ { code: 'raw_file_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun re-freezes it' },
+ { code: 'file_database_drift', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: the file and the database page diverge',
+ human_reason: 'The canonical file and the database page both changed; a person chooses which version wins (gbrain repair file-drift --source <source> --slug <slug> --prefer database|file previews it and writes nothing until applied).' },
+ { code: 'canonical_file_missing', class: 'page', safe_actions: ['repair'], needs_human: true, escalate: 'always: no sync can import a file that is not there',
+ human_reason: 'The page is live but its canonical file is gone (a ghost page); a person restores the file and syncs, or removes the page (gbrain repair ghost-pages --source <source> previews it and writes nothing).' },
+ { code: 'source_binding_changed', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: the source or its checkout binding moved',
+ human_reason: 'The source was replaced, archived or re-bound under the write; inspect it with gbrain sources writer status --source <source> --json before anything is resubmitted.' },
+ { code: 'unsafe_file_target', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: the file target resolves outside its source',
+ human_reason: 'The canonical file target resolves outside its source (a symlink or a moved checkout); inspect the checkout with gbrain sources writer status --source <source> --json, then the user decides how to repair it.' },
{ code: 'cancelled', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same group is cancelled again after a rerun' },
// #6643: refinements of `cancelled` / `revision_conflict` by the receipt's recorded cause; they take precedence over the code.
// #6712 retired both producers (one page, one fate); the rows render what older builds wrote as superseded.
@@ -149,20 +172,26 @@ export function contentRepairHumanReason(input: ContentRepairHoldInput): string
export interface SyncFaultVerdict { class: SyncFaultClass; safe_actions: SyncSafeAction[]; needs_human: boolean; human_reason?: string }
/**
- * The verdict for one fault. `attempts` is a hold's re-hold count: a page held `HOLD_ATTEMPTS_NEEDS_HUMAN` times with the
- * same code keeps moving under the sync, so its own safe action is exhausted and a person is named. `detail` is a receipt's
+ * The verdict for one fault. `attempts` is a hold's failed-attempt count (re-holds plus failed safe actions): a page held
+ * `HOLD_ATTEMPTS_NEEDS_HUMAN` times with the same code for at least `HOLD_ESCALATE_MS` (`held_for_ms`) keeps moving under the
+ * sync, so its own safe action is exhausted and a person is named; a live editor (`live_editor`) is never escalated. `detail` is a receipt's
* `reason` (for example `pinned_git_worktree_conflict` under `source_changed`) or a drain stop's `cause`; it refines the code
* when the table knows it. `content_repair` is a slug-conflict hold's recorded verdict: a recommended merge or an
* undecidable pair names a person. An unknown code is systemic and human: an agent must not guess at it.
*/
-export function classifySyncFault(input: { code: string; detail?: string | null; attempts?: number | null; message?: string | null; content_repair?: ContentRepairHoldInput | null }): SyncFaultVerdict {
+export function classifySyncFault(input: { code: string; detail?: string | null; attempts?: number | null; message?: string | null; content_repair?: ContentRepairHoldInput | null;
+ /** #6712 PR 2: how long ago the path was first held with this code (`holdEscalation`); escalation needs `HOLD_ESCALATE_MS`. */
+ held_for_ms?: number | null;
+ /** #6712 PR 2: a `worktree_dirty` hold whose uncommitted bytes changed within `HOLD_ESCALATE_MS`: someone is still editing. */
+ live_editor?: boolean }): SyncFaultVerdict {
const judged = input.content_repair && input.code === 'frontmatter_slug_conflict' ? contentRepairHumanReason(input.content_repair) : undefined;
if (judged) return { class: 'page', safe_actions: ['none'], needs_human: true, human_reason: judged };
const rule = (input.detail ? BY_CODE.get(input.detail) : undefined) ?? BY_CODE.get(input.code)
?? (/ECONN|ETIMEDOUT|EPIPE|connection.*closed|CONNECTION_ENDED/i.test(input.message ?? '') ? BY_CODE.get('connection_lost') : undefined);
if (!rule) return { class: 'systemic', safe_actions: ['none'], needs_human: true, human_reason: `Unknown code ${input.code}; run gbrain doctor --json and read gbrain errors ${input.code}.` };
- const exhausted = !rule.needs_human && (input.attempts ?? 0) >= HOLD_ATTEMPTS_NEEDS_HUMAN && rule.safe_actions[0] !== 'none' && rule.class === 'page';
+ const exhausted = !rule.needs_human && (input.attempts ?? 0) >= HOLD_ATTEMPTS_NEEDS_HUMAN && (input.held_for_ms ?? 0) >= HOLD_ESCALATE_MS && !input.live_editor
+ && rule.safe_actions[0] !== 'none' && rule.class === 'page';
if (!exhausted) return { class: rule.class, safe_actions: rule.safe_actions, needs_human: rule.needs_human, ...(rule.needs_human && rule.human_reason ? { human_reason: rule.human_reason } : {}) };
return { class: rule.class, safe_actions: ['none'], needs_human: true,
- human_reason: `${rule.human_reason ?? 'The page keeps moving under the sync.'} (held ${input.attempts} times with code ${rule.code})` };
+ human_reason: `${rule.human_reason ?? 'The page keeps moving under the sync.'} (held ${input.attempts} times over ${Math.floor(input.held_for_ms! / 3_600_000)} h with code ${rule.code})` };
}
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.ts
index 807836ae38..b088be5c21 100644
--- a/src/core/persistence/sync-holds.ts
+++ b/src/core/persistence/sync-holds.ts
@@ -42,13 +42,13 @@ import { FENCE_VERSION } from '../fence-repair/refusal.ts';
import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';
import { contentHoldDocs, contentHoldFix } from '../content-repair/hold-fix.ts';
import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';
-import type { SyncRename } from './sync-discovery.ts';
+import type { SyncDiscovery, SyncRename } from './sync-discovery.ts';
import { isCodeFilePath, isImageFilePath, isMultimodalEnabled } from '../sync.ts';
import { VERSION } from '../../version.ts';
import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';
import { chunkerStamp } from '../chunkers/code.ts';
import { gitBlobOid, sha256 } from './digest.ts';
-import { HOLD_ATTEMPTS_NEEDS_HUMAN } from './sync-fault-class.ts';
+import { HOLD_ATTEMPTS_NEEDS_HUMAN, HOLD_ESCALATE_MS } from './sync-fault-class.ts';
export const GIT_HOLD_OP = 'sync-hold';
export const GIT_HOLD_SUMMARY_OP = 'sync-hold-summary';
@@ -110,8 +110,14 @@ export interface GitHoldMeta {
expected_revision?: string;
/** #6340 `worktree_dirty`: sha256 of the uncommitted working-tree bytes the hold protected (`blob_oid` is the pinned blob). */
working_hash?: string;
- /** #6340: how many times this path was held again with the same code since the hold was first written; at `HOLD_ATTEMPTS_NEEDS_HUMAN` the page keeps moving. */
+ /** #6340: how many times this path was held again with the same code since the hold was first written, plus (#6712 PR 2) the hold's safe actions that ran and failed; at `HOLD_ATTEMPTS_NEEDS_HUMAN` over `HOLD_ESCALATE_MS` the page keeps moving. */
attempts?: number;
+ /** #6712 PR 2: when this path was first held with its code (attempts count from it); `held_at` resets when the held bytes change. */
+ first_held_at?: string;
+ /** #6712 PR 2 `worktree_dirty`: when the uncommitted bytes last changed (`working_hash` moved); a recent edit is a live editor, never escalated. */
+ edited_at?: string;
+ /** #6712 PR 2: when the soak sweep counted this hold as needing a person (`soak-counters.ts`); kept across re-holds with the same code, so it counts once. */
+ needs_human_at?: string;
/** #6188: the last fence repair attempt (repair kind or maintenance phase) that left this hold in place; location and reason only. */
fence_repair?: FenceHoldRepairState;
/** #6377 `frontmatter_slug_conflict`: the content-repair lane's last verdict or attempt on this hold; codes and slugs only. */
@@ -268,7 +274,7 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'version
const sameBytes = existing && existing.code === input.code && existing.upstream_version === input.upstream_version;
const kept = sameBytes ? { ...(existing.meta.fence_repair && !input.meta.fence_repair ? { fence_repair: existing.meta.fence_repair } : {}),
...(existing.meta.content_repair && !input.meta.content_repair ? { content_repair: existing.meta.content_repair } : {}) } : {};
- const record: GitHoldRecord = { version: 1, ...input, meta: { ...kept, ...input.meta, attempts },
+ const record: GitHoldRecord = { version: 1, ...input, meta: { ...kept, ...input.meta, attempts, ...escalationStamps(existing, input, now) },
held_at: existing && existing.upstream_version === input.upstream_version && existing.code === input.code ? existing.held_at : now, updated_at: now };
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
@@ -284,6 +290,41 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'version
return 'inserted';
}
+/** #6712 PR 2: the first-held time of the code's attempt count, the soak count's stamp, and a `worktree_dirty` hold's last edit (a changed `working_hash`). */
+function escalationStamps(existing: GitHoldRecord | null, input: Pick<GitHoldRecord, 'code' | 'meta'>, now: string): Pick<GitHoldMeta, 'first_held_at' | 'edited_at' | 'needs_human_at'> {
+ const same = existing?.code === input.code ? existing : null;
+ const kept = { first_held_at: same ? same.meta.first_held_at ?? same.held_at : now, ...(same?.meta.needs_human_at ? { needs_human_at: same.meta.needs_human_at } : {}) };
+ if (input.code !== 'worktree_dirty') return kept;
+ return { ...kept, edited_at: same && same.meta.working_hash === input.meta.working_hash ? same.meta.edited_at ?? same.held_at : now };
+}
+
+/**
+ * #6712 PR 2 (L4): what escalation reads from a hold: its failed attempts, how long since it was first held with its code,
+ * and whether a `worktree_dirty` hold's uncommitted bytes changed within `HOLD_ESCALATE_MS` (someone is still editing).
+ */
+export function holdEscalation(record: Pick<GitHoldRecord, 'code' | 'meta' | 'held_at'>, now = Date.now()): { attempts: number; held_for_ms: number; live_editor: boolean } {
+ const since = (at: string | undefined) => Math.max(0, now - Date.parse(at ?? record.held_at));
+ return { attempts: record.meta.attempts ?? 1, held_for_ms: since(record.meta.first_held_at),
+ live_editor: record.code === 'worktree_dirty' && since(record.meta.edited_at) < HOLD_ESCALATE_MS };
+}
+
+/**
+ * #6712 PR 2 (L4): a hold's safe action ran and the hold stands (`sync unblock --apply` found the edit still uncommitted, or
+ * its repair left the file held): one more failed attempt, and for `worktree_dirty` the uncommitted bytes it saw now
+ * (`workingHash`), so a changed edit restarts the live-editor clock. A no-op when the path holds another code by now.
+ */
+export async function recordHoldAttempt(tx: Exec, input: { sourceId: string; incarnation: string; path: string; code: GitHoldCode; workingHash?: string }): Promise<boolean> {
+ await lockSummary(tx, input.sourceId, input.incarnation);
+ const existing = await readRow(tx, input.sourceId, input.incarnation, input.path);
+ if (!existing || existing.code !== input.code) return false;
+ const now = new Date().toISOString();
+ const edited = input.workingHash !== undefined && input.workingHash !== existing.meta.working_hash ? { working_hash: input.workingHash, edited_at: now } : {};
+ const record: GitHoldRecord = { ...existing, meta: { ...existing.meta, ...escalationStamps(existing, existing, now), ...edited, attempts: (existing.meta.attempts ?? 1) + 1 }, updated_at: now };
+ await tx.executeRaw('UPDATE op_checkpoints SET completed_keys=$3::text::jsonb, updated_at=now() WHERE op=$1 AND fingerprint=$2',
+ [GIT_HOLD_OP, gitHoldFingerprint(input.sourceId, input.incarnation, input.path), JSON.stringify([record])]);
+ return true;
+}
+
/**
* Clears a path's hold. Call it only inside the transaction that commits the
* file's import, deletion or no-op; `observedAt` is the discovery time of the
@@ -691,6 +732,18 @@ export async function clearGitHoldRetryPaths(engine: Exec, sourceId: string, inc
await engine.executeRaw(`DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND jsonb_array_length(completed_keys->0->'paths')=0`, [GIT_HOLD_RETRY_OP, fingerprint]);
}
+/**
+ * #6712 PR 2: a discovery that found nothing to write still releases the held paths that left the source (excluded by
+ * sync.exclude, an image while multimodal embedding is off) and consumes the re-screens it took, inside the run's
+ * freshness write. Before, those waited for the next commit, so a printed exit (exclude the file, then sync) did not
+ * clear its hold.
+ */
+export async function releaseDiscoveredHolds(tx: Exec, discovery: Pick<SyncDiscovery, 'sourceId' | 'incarnation' | 'discoveredAt' | 'releasedHolds' | 'retryTaken'>): Promise<void> {
+ const observedAt = discovery.discoveredAt ?? new Date().toISOString();
+ for (const path of discovery.releasedHolds ?? []) await clearGitHold(tx, { sourceId: discovery.sourceId, incarnation: discovery.incarnation, path, observedAt });
+ await clearGitHoldRetryPaths(tx, discovery.sourceId, discovery.incarnation, discovery.retryTaken ?? []);
+}
+
export interface SyncHoldPolicy {
/** `fail` restores fail-closed blocking: a content refusal blocks the sync as before holds existed. */
mode: 'hold' | 'fail';
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index d7942a6c28..d3a2547437 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -27,7 +27,7 @@ import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { managedSyncResumeArgs } from '../sync-reconcile.ts';
import { readManagedSyncFailures, type ManagedSyncFailure } from './sync-failures.ts';
-import { fenceAutoRepairFor, gitHoldFix, readGitSourceHolds, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';
+import { fenceAutoRepairFor, gitHoldFix, holdEscalation, readGitSourceHolds, recordHoldAttempt, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';
import type { FenceAutoRepair } from '../fence-repair/hold-fix.ts';
import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, type SyncFaultVerdict } from './sync-fault-class.ts';
import { CONTENT_REPAIR_KINDS, contentHoldDisposition, runContentLane, type ContentHoldDisposition } from '../repair/content-lane.ts';
@@ -38,7 +38,8 @@ import { laneFaultInMessage } from './sync-window.ts';
import { cursorFenceCause, syncKnockOnSql } from './sync-knock-on.ts';
import { listIncompleteSyncReceipts, type SyncSettledIndexes } from './checkpoint-validation.ts';
import { drainEstimate } from './sync-drain.ts';
-import { resolveManagedSyncContext } from './sync-discovery.ts';
+import { readSyncFile, resolveManagedSyncContext } from './sync-discovery.ts';
+import { sha256 } from './digest.ts';
export interface SyncStatusHold extends SyncFaultVerdict {
code: string;
@@ -152,11 +153,11 @@ async function retiredCursorStands(engine: BrainEngine, sourceId: string, incarn
* paragraph for the lane's codes when it knows them; otherwise the hold's own code decides.
*/
function holdVerdict(record: GitHoldRecord, auto: FenceAutoRepair | undefined): SyncFaultVerdict {
- const attempts = record.meta.attempts ?? 1;
+ const escalation = holdEscalation(record);
const content = record.meta.content_repair ? { content_repair: { ...record.meta.content_repair, path: record.path, slug: record.slug } } : {};
const disposition = contentHoldDisposition(record, auto);
- if (disposition.action !== 'listed' || disposition.state === 'owner') return classifySyncFault({ code: record.code, attempts, ...content });
- const verdict = classifySyncFault({ code: record.code, attempts, detail: disposition.reason, ...content });
+ if (disposition.action !== 'listed' || disposition.state === 'owner') return classifySyncFault({ code: record.code, ...escalation, ...content });
+ const verdict = classifySyncFault({ code: record.code, ...escalation, detail: disposition.reason, ...content });
if (verdict.needs_human) return verdict;
const reason = disposition.state === 'paid'
? `Model repair of ${record.path} waits on a setting only the user changes (${disposition.reason}); the hold's fix names it.`
@@ -348,14 +349,20 @@ function receiptOf(detail: Record<string, unknown> | undefined): Record<string,
return Object.keys(rest).length ? rest : undefined;
}
+/** The sha256 of a held file's uncommitted bytes, when they can be read. */
+function workingHashOf(root: string, path: string): { workingHash?: string } {
+ try { const bytes = readSyncFile(root, path); return bytes ? { workingHash: sha256(bytes) } : {}; } catch { return {}; }
+}
+
/**
* Performs the safe action for every hold that has one. `retry_when_clean` (`worktree_dirty`): the file is re-screened only
* when its working-tree bytes are committed at HEAD now; still-dirty files are refused `still_dirty`. `retry`
* (`preparation_stalled`): scheduled for a re-screen. `repair` (#6377; a hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to
* a lane kind, unless `noRepair`): the kind runs on exactly those paths as one bounded apply under its caps (each item bound
* to the bytes the kind's plan read), each path reports `repaired | held | needs_human | skipped` with the
- * kind's receipt or reason, and repaired paths are scheduled for the re-screen. A hold whose attempts reached
- * `HOLD_ATTEMPTS_NEEDS_HUMAN`, a `concurrent_write` hold, a repair-class hold whose stored state waits on a person, the
+ * kind's receipt or reason, and repaired paths are scheduled for the re-screen. #6712 PR 2: an applied action that leaves
+ * the hold standing (still dirty, a repair that held) counts one failed attempt on the hold. A hold whose attempts reached
+ * `HOLD_ATTEMPTS_NEEDS_HUMAN` over `HOLD_ESCALATE_MS`, a `concurrent_write` hold, a repair-class hold whose stored state waits on a person, the
* user's spend decision or the owner host, and a repair-class hold no lane kind clears yet are refused by name with their
* fix. Idempotent: scheduling twice is one re-screen, a repaired file is `already_clean` on the next pass, and a preview
* writes nothing.
@@ -380,7 +387,11 @@ export async function unblockSync(engine: BrainEngine, sourceId: string, opts: U
if (status.needs_human) { refuse(status.human_reason ?? 'needs a person'); continue; }
if (hold.code === 'worktree_dirty') {
const committed = context ? headCommittedBytes(context, hold.path) : null;
- if (!committed) { refuse(context ? 'still_dirty: the working-tree bytes are not committed at HEAD yet' : 'checkout_unreadable: the source checkout could not be resolved'); continue; }
+ if (!committed) {
+ refuse(context ? 'still_dirty: the working-tree bytes are not committed at HEAD yet' : 'checkout_unreadable: the source checkout could not be resolved');
+ if (opts.apply && context) await recordHoldAttempt(engine, { sourceId, incarnation: source.incarnation, path: hold.path, code: hold.code, ...workingHashOf(context.root, hold.path) });
+ continue;
+ }
applied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'retry_when_clean', detail: `committed at HEAD as blob ${committed.oid.slice(0, 12)}; scheduled for a re-screen` });
continue;
}
@@ -424,6 +435,7 @@ export async function unblockSync(engine: BrainEngine, sourceId: string, opts: U
const message = typeof detail?.message === 'string' ? detail.message : undefined;
const llmUsd = item?.llm_usd;
if (outcome === 'repaired') retry.push(hold.path);
+ else if (outcome === 'held') await recordHoldAttempt(engine, { sourceId, incarnation: source.incarnation, path: hold.path, code: hold.code });
applied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'repair',
detail: outcome === 'repaired' ? `repaired by gbrain repair ${kind}${typeof detail?.tier === 'string' ? ` (${detail.tier})` : ''}; scheduled for a re-screen`
: `${outcome} (${reason})${message ? `: ${message}` : !item && stop ? `: ${stop.message}` : ''}`,
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
index f8cc46b1d7..92afcd508e 100644
--- a/src/core/persistence/terminal-classify.ts
+++ b/src/core/persistence/terminal-classify.ts
@@ -110,6 +110,16 @@ function inspect(sourceId: string, why: string, userMessage?: string): Action {
...(userMessage ? { user_message: userMessage } : {}), verify: { argv: failuresArgv(sourceId) }, docs: 'docs/guides/troubleshooting.md#terminal-write-failures' };
}
+/**
+ * #6712 PR 2 (L4): the file-drift preview over every page still drifted since `since` (a concrete instant, never an age),
+ * the fix of a group of drift conflicts on several pages; a single page keeps its `--slug` preview.
+ */
+export function driftSinceAction(sourceId: string, since: string): Action {
+ return { argv: ['gbrain', 'repair', 'file-drift', '--source', sourceId, '--all-drifted', '--since', since, '--prefer', 'database'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Previews keeping the database copy of every page still drifted since ${since} and writes nothing (it refuses a mix of drift classes and names --class for each); --prefer file previews importing the files instead. Decide with the user, then apply with the printed plan hash.`,
+ verify: { argv: failuresArgv(sourceId) }, docs: 'docs/guides/write-refusals.md#file_database_drift' };
+}
+
function build(input: TerminalInput): string | null {
const attempt = (input.error_detail as { attempt?: { consumer_version?: unknown } } | null | undefined)?.attempt?.consumer_version;
const value = typeof attempt === 'string' ? attempt : input.build ?? null;
@@ -230,22 +240,25 @@ function route(input: TerminalInput): Partial_ {
if (code === 'source_changed') {
const known = stringField(detail, 'reason') ?? (input.error_message ? writeFailureDiagnostic(code, input.error_message).reason : null);
if (!known || known === 'source_changed') return diagnosis(input, code, origin, `The write was refused source_changed with no recorded cause${input.compacted ? ' (its receipt was compacted)' : ''}.`);
+ // #6712 PR 2 (L4): the recorded reason picks the exit; the verdict text is the fault table's row for it.
+ const row = (key: string) => { const v = classifySyncFault({ code, detail: key }); return { class: v.class, safe_actions: v.safe_actions, needs_human: v.needs_human, human_reason: v.human_reason, escalate: escalateOf(key) }; };
if (known === 'file_database_drift' || known === 'canonical_path_occupied' || known === 'unbound_source') {
- return { category: 'file_conflict', code, origin: origin ?? known, class: 'page', safe_actions: ['reconcile'], needs_human: true,
- human_reason: 'The page\'s Git file and its database copy differ; a person chooses which version wins.', escalate: 'always: the file and the database page diverge',
- action: { argv: ['gbrain', 'sources', 'reconcile', source, input.slug, '--preview'], consent: [], actor: 'agent', requires_exclusive: false,
- why: 'Previews both versions of the page and writes nothing; apply the resolved preview, then resubmit the write with a new request id.',
+ return { category: 'file_conflict', code, origin: origin ?? known, ...row('file_database_drift'),
+ action: { argv: ['gbrain', 'repair', 'file-drift', '--source', source, '--slug', input.slug, '--prefer', 'database'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Previews keeping the database copy of ${input.slug} and rewriting its file, and writes nothing; --prefer file previews importing the file instead. Decide with the user, apply with the printed plan hash, then resubmit the write with a new request id.`,
verify: { argv: failuresArgv(source) }, docs: 'docs/guides/write-refusals.md#file_database_drift' } };
}
if (known === 'canonical_file_missing') {
- return { category: 'canonical_file_missing', code, origin: origin ?? known, class: 'page', safe_actions: ['repair'], needs_human: true,
- human_reason: 'The page\'s canonical file is gone but the database page is still live (a ghost page); a person chooses to restore the file or remove the page.',
- escalate: 'always: no sync can import a file that is not there',
+ return { category: 'canonical_file_missing', code, origin: origin ?? known, ...row('canonical_file_missing'),
action: { argv: ['gbrain', 'repair', 'ghost-pages', '--source', source], consent: [], actor: 'agent', requires_exclusive: false,
why: 'Previews the live pages whose canonical file is missing and writes nothing; apply only after the user agrees, or restore the file and sync.',
verify: { argv: failuresArgv(source) }, docs: 'docs/guides/write-refusals.md#canonical_file_missing' } };
}
- if (known === 'source_binding_changed' || known === 'unsafe_file_target') return diagnosis(input, code, known, `The write was refused source_changed (${known}).`);
+ if (known === 'source_binding_changed' || known === 'unsafe_file_target') {
+ const v = row(known);
+ return { category: 'diagnosis_required', code, origin: known, ...v,
+ action: inspect(source, `The write was refused source_changed (${known}). Writer status shows the source binding and its checkout, read-only.`, v.human_reason) };
+ }
return fromTable('sync_fault', code, origin ?? known, syncRetry(source, `The file changed under the write (${known}); a sync imports the current bytes.`), known === 'pinned_git_worktree_conflict' ? known : 'source_changed');
}
if (code === 'revision_conflict' || code === 'page_identity_changed') {
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
index 44577879e4..0e70fd78be 100644
--- a/src/core/persistence/terminal-failures.ts
+++ b/src/core/persistence/terminal-failures.ts
@@ -24,7 +24,7 @@ import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { isStatementTimeout } from './bounded-reads.ts';
import { readReceiptRetentionDays, DEFAULT_RECEIPT_RETENTION_DAYS } from './limits.ts';
-import { classifyTerminal, dispositionOf, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
+import { classifyTerminal, dispositionOf, driftSinceAction, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
type TerminalDisposition, type TerminalVerdict, CONNECTION_MESSAGE_PATTERN, LEGACY_PUBLICATION_PREFIX } from './terminal-classify.ts';
export const TERMINAL_WINDOW_KEY = 'persistence.terminal_failures.window_days';
@@ -290,14 +290,17 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailu
const limit = Math.min(100, Math.max(1, q.limit ?? 20));
const state = q.state ?? 'unresolved';
const out: TerminalFailureRow[] = [];
+ // #6712 PR 2: the oldest admission per drift group, so the group's file-drift fix selects every page in it with one concrete --since.
+ const driftSince = new Map<string, string>();
let cursor = q.before ?? null, scanned = 0, exhausted = false;
const want = q.groupBy ? MAX_SCAN : limit + 1;
while (out.length < want && scanned < MAX_SCAN && !exhausted) {
- const batch = await bounded<KeyColumns & { request_id: string; sequence: string; slug: string; error_detail: Record<string, unknown> | null; ended_at: string; later_state: string | null; same_intent: boolean | null }>(engine,
+ const batch = await bounded<KeyColumns & { request_id: string; sequence: string; slug: string; error_detail: Record<string, unknown> | null; ended_at: string; admitted_at: string; later_state: string | null; same_intent: boolean | null }>(engine,
`SELECT r.request_id::text AS request_id, r.sequence::text AS sequence, r.source_id, r.slug, r.operation, r.state, r.error_code, r.error_detail,
r.error_detail->>'origin' AS origin, r.error_detail->>'reason' AS reason, r.error_detail->>'cause' AS cause,
r.recovery IS NOT NULL AS has_recovery, r.blocked_reason, r.compacted, ${terminalKnockOnSql('r')} AS knock_on, ${ROUTED_MESSAGE('r')} AS routed_message, ${BUILD('r')} AS build,
- to_char(${ENDED('r')} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS ended_at, later.state AS later_state, later.same_intent
+ to_char(${ENDED('r')} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS ended_at, to_char(r.created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS admitted_at,
+ later.state AS later_state, later.same_intent
FROM persistence_requests r
LEFT JOIN LATERAL (SELECT c.state, c.digest=r.digest AS same_intent FROM persistence_requests c WHERE ${supersessionSql('r', 'c')}
ORDER BY ${supersessionOrderSql('r', 'c')} LIMIT 1) later ON r.recovery IS NULL
@@ -319,6 +322,9 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailu
compacted: row.compacted, ended_at: row.ended_at, cursor: row.sequence, ...(v.root_request_id ? { root_request_id: v.root_request_id } : {}),
inspect: { argv: terminalInspectArgv(row.request_id), consent: [], actor: 'agent', requires_exclusive: false, why: 'The receipt with its diagnosis and structured fix, read-only.' },
fix: v.action });
+ const driftKey = `${v.code}\0${v.origin ?? ''}\0${v.category}`;
+ const seen = driftSince.get(driftKey);
+ if (matches && v.category === 'file_conflict' && (!seen || row.admitted_at < seen)) driftSince.set(driftKey, row.admitted_at);
if (out.length >= want || scanned >= MAX_SCAN) { exhausted = exhausted && row === batch.at(-1); break; }
}
}
@@ -343,6 +349,10 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailu
g.rows++;
if (g.samples.length < 3) g.samples.push({ request_id: row.request_id, slug: row.slug, state: row.state, ended_at: row.ended_at, inspect: row.inspect });
}
+ for (const [key, since] of driftSince) {
+ const g = groups.get(key);
+ if (g && new Set(out.filter(row => row.category === 'file_conflict' && `${row.code}\0${row.origin ?? ''}\0${row.category}` === key).map(row => row.slug)).size > 1) g.fix = driftSinceAction(q.sourceId, since);
+ }
const sorted = [...groups.values()].sort((a, b) => b.rows - a.rows || a.category.localeCompare(b.category) || a.code.localeCompare(b.code) || (a.origin ?? '').localeCompare(b.origin ?? ''));
// Groups count the receipts this call scanned; a scan that stopped at its bound continues from where it stopped.
const resume = !exhausted ? cursor : null;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 6975658947..6b63c6a6d5 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -91,6 +91,8 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb
remote?: boolean;
/** `file-drift` (#6643): the side that wins, conflict receipt ids, every still-drifted page, and the one drift class kept. */
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string;
+ /** #6712 PR 2 `file-drift`: only pages whose newest drift conflict is at or after this concrete instant (ISO; `--since`, parsed by `since.ts`). */
+ since?: string;
/** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */
keep?: 'prior' | 'disk'; requestId?: string;
/** `receipt-compaction` (#6696 A9): the age (`72h`, `30d`), failures too, and compaction inside the retention window. */
@@ -273,7 +275,7 @@ function writerHeld(error: unknown): error is OperationError {
export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,
opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];
explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;
- prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string;
+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string;
keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean;
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */
@@ -294,7 +296,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.slugs?.length ? { slugs: opts.slugs } : {}), ...(opts.noLlm ? { noLlm: true } : {}), ...(opts.maxLlmUsd !== undefined ? { maxLlmUsd: opts.maxLlmUsd } : {}),
...(opts.deadline !== undefined ? { deadline: opts.deadline } : {}), remote: ctx.remote !== false,
...(opts.prefer ? { prefer: opts.prefer } : {}), ...(opts.requests?.length ? { requests: opts.requests } : {}),
- ...(opts.allDrifted ? { allDrifted: true } : {}), ...(opts.driftClass ? { driftClass: opts.driftClass } : {}),
+ ...(opts.allDrifted ? { allDrifted: true } : {}), ...(opts.driftClass ? { driftClass: opts.driftClass } : {}), ...(opts.since ? { since: opts.since } : {}),
...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),
...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}) };
const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);
@@ -320,7 +322,7 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
+ `${opts.requestId ? ` --request-id ${opts.requestId}` : ''}${opts.keep ? ` --keep ${opts.keep}` : ''}`
+ `${[...(opts.only ?? []).flatMap(path => ['--only', path]), ...(opts.skip ?? []).flatMap(path => ['--skip', path]),
...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.requests ?? []).flatMap(id => ['--request', id]),
- ...(opts.allDrifted ? ['--all-drifted'] : []), ...(opts.driftClass ? ['--class', opts.driftClass] : []),
+ ...(opts.allDrifted ? ['--all-drifted'] : []), ...(opts.driftClass ? ['--class', opts.driftClass] : []), ...(opts.since ? ['--since', opts.since] : []),
...(opts.prefer ? ['--prefer', opts.prefer] : [])].map(arg => ` ${shellQuote([arg])}`).join('')}`
+ `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`
+ ` --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}${spec?.consent === 'destructive' ? ' --yes' : ''}`,
diff --git a/src/core/repair/file-drift.ts b/src/core/repair/file-drift.ts
index 30bf62a137..819f40dab0 100644
--- a/src/core/repair/file-drift.ts
+++ b/src/core/repair/file-drift.ts
@@ -1,5 +1,5 @@
/**
- * `gbrain repair file-drift --source <id> (--slug <s>... | --request <id>... | --all-drifted [--class <c>]) --prefer file|database`
+ * `gbrain repair file-drift --source <id> (--slug <s>... | --request <id>... | --all-drifted [--class <c>] [--since <ISO|7d>]) --prefer file|database`
* (#6643 B2): resolve pages whose canonical file differs from their database row
* (the `source_changed` / `file_database_drift` refusal) through canonical
* reconciliation, preferring one side.
@@ -31,7 +31,9 @@
* segments; `path-glob.ts`, file-drift being the only kind that takes globs),
* 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.
+ * every printed preview and apply command. #6712 PR 2: `--since` keeps the pages whose newest
+ * drift conflict is at or after one concrete instant (the CLI resolves an age once, `since.ts`), part of
+ * the selection digest and of every printed 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';
@@ -72,7 +74,7 @@ const artifactDirectory = () => join(canonicalFilesystemPath(configDir()), 'repa
const escapePointer = (key: string) => key.replace(/~/g, '~0').replace(/\//g, '~1');
function previewCommand(sourceId: string, opts: RepairPlanOptions): string {
- const select = opts.allDrifted ? ` --all-drifted${opts.driftClass ? ` --class ${opts.driftClass}` : ''}`
+ const select = opts.allDrifted ? ` --all-drifted${opts.driftClass ? ` --class ${opts.driftClass}` : ''}${opts.since ? ` --since ${opts.since}` : ''}`
: [...(opts.slugs ?? []).map(slug => ` --slug ${slug}`), ...(opts.requests ?? []).map(id => ` --request ${id}`)].join('');
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>'}`;
@@ -83,6 +85,9 @@ const selectedByGlobs = (path: string | undefined, opts: Pick<RepairPlanOptions,
path === undefined ? !opts.only?.length && !opts.skip?.length
: (!opts.only?.length || matchesRepairPath(path, opts.only)) && !matchesRepairPath(path, opts.skip);
+/** #6712 PR 2: whether a page's newest drift conflict (`last_seen`) is at or after `--since` (no `--since`: every page). */
+const sinceSelects = (lastSeen: string, since: string | undefined) => !since || Date.parse(lastSeen) >= Date.parse(since);
+
/** 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';
@@ -169,7 +174,7 @@ async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPl
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) continue;
- if (!selectedByGlobs(row.path, opts)) { notSelected++; continue; }
+ if (!selectedByGlobs(row.path, opts) || !sinceSelects(row.last_seen, opts.since)) { notSelected++; continue; }
drifted.push(row.slug); classes.set(row.slug, row.class ?? 'error');
}
cursor = page.next ?? undefined;
@@ -200,13 +205,14 @@ async function selectSlugs(engine: BrainEngine, sourceId: string, opts: RepairPl
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>]) [--only <glob>]... [--skip <glob>]... --prefer file|database';
+ const usage = 'gbrain repair file-drift --source <id> (--slug <slug>... | --request <id>... | --all-drifted [--class <name>] [--since <ISO-8601|7d>]) [--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}`);
const modes = [opts.slugs?.length ? 1 : 0, opts.requests?.length ? 1 : 0, opts.allDrifted ? 1 : 0].reduce((a, b) => a + b, 0);
if (modes !== 1) throw opError('invalid_params', 'Select pages one way: --slug, --request or --all-drifted.', `Pick one selection: ${usage}`);
if (opts.driftClass && !opts.allDrifted) throw opError('invalid_params', '--class only narrows --all-drifted.', `Drop --class, or use it with --all-drifted: ${usage}`);
+ if (opts.since && !opts.allDrifted) throw opError('invalid_params', '--since only narrows --all-drifted.', `Drop --since, or use it with --all-drifted: ${usage}`);
if (opts.driftClass && !(DRIFT_CLASSES as readonly string[]).includes(opts.driftClass)) throw opError('invalid_params', `Unknown drift class '${opts.driftClass}'.`,
`Pass one of ${DRIFT_CLASSES.join(', ')}; the conflict audit lists each drifted page's class.`);
for (const slug of opts.slugs ?? []) {
@@ -227,7 +233,7 @@ function validateOptions(scope: RepairScope, opts: RepairPlanOptions | undefined
* The bare `gbrain repair file-drift` (the explicit-only preview command doctor and `repair --all` print): a read-only
* survey of the drifted pages per source with their drift class and the preview command for each class. Nothing to apply.
*/
-async function survey(engine: BrainEngine, scope: RepairScope): Promise<RepairPlan> {
+async function survey(engine: BrainEngine, scope: RepairScope, opts: Pick<RepairPlanOptions, 'since'>): Promise<RepairPlan> {
const listing: NonNullable<RepairPlan['listing']> = [];
const residuals: Record<string, number> = {};
const next: string[] = [];
@@ -238,7 +244,7 @@ async function survey(engine: BrainEngine, scope: RepairScope): Promise<RepairPl
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) continue;
+ if (row.still_present.value !== true || !sinceSelects(row.last_seen, opts.since)) continue;
const kind = row.class ?? 'error';
counts.set(kind, (counts.get(kind) ?? 0) + 1);
residuals[`drifted_${kind}`] = (residuals[`drifted_${kind}`] ?? 0) + 1;
@@ -247,7 +253,7 @@ async function survey(engine: BrainEngine, scope: RepairScope): Promise<RepairPl
seen += page.conflicts.length;
cursor = page.next ?? undefined;
} while (cursor && seen < ALL_DRIFTED_LIMIT);
- for (const kind of counts.keys()) next.push(previewCommand(sourceId, { apply: false, allDrifted: true, driftClass: kind, prefer: 'file' }));
+ for (const kind of counts.keys()) next.push(previewCommand(sourceId, { apply: false, allDrifted: true, driftClass: kind, ...(opts.since ? { since: opts.since } : {}), prefer: 'file' }));
}
return { items: [], residuals, listing, details: { survey: true,
next_actions: next.length ? [...next.map(command => `Preview: ${command} (or --prefer database)`), 'Or preview single pages with --slug <slug>.'] : [] } };
@@ -283,14 +289,14 @@ export const fileDriftRepair: RepairHandler = {
kind: 'file-drift',
outcomeItemsLimit: 1000,
async plan(engine, scope, after, opts): Promise<RepairPlan> {
- if (opts?.remote === false && !opts.apply && !opts.prefer && !opts.slugs?.length && !opts.requests?.length && !opts.allDrifted && !opts.driftClass) return survey(engine, scope);
+ if (opts?.remote === false && !opts.apply && !opts.prefer && !opts.slugs?.length && !opts.requests?.length && !opts.allDrifted && !opts.driftClass) return survey(engine, scope, opts);
validateOptions(scope, opts);
const sourceId = scope.source_ids[0]!;
const command = previewCommand(sourceId, opts);
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 } : {}) });
+ ...(opts.since ? { since: opts.since } : {}), ...(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');
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 2fc2738214..e94352355b 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -429,7 +429,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
*/
async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];
slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number;
- prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string;
+ prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string;
keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean } = {}): 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);
@@ -437,7 +437,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
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'] : [])],
explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
- maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass,
+ maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,
keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force });
},
};
diff --git a/src/core/since.ts b/src/core/since.ts
new file mode 100644
index 0000000000..b349d842e8
--- /dev/null
+++ b/src/core/since.ts
@@ -0,0 +1,22 @@
+/**
+ * #6712 PR 2 (L4): the one `--since` parser. A relative age (`90s`, `15m`, `6h`, `7d`) or an ISO-8601 instant
+ * (`2026-10-01`, `2026-10-01T12:00:00Z`) becomes one concrete instant, so a command that prints its own follow-up
+ * (`gbrain repair file-drift ... --since`, `gbrain agent logs --since`) prints that instant, never the relative age:
+ * the same command run later selects the same rows and its plan hash still matches.
+ */
+const RELATIVE = /^(\d+)\s*(s|m|h|d)$/i;
+const ISO_DATE = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
+const UNIT_MS: Record<string, number> = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
+
+/** The instant `input` names (ISO string), `undefined` for an empty value; throws on anything else. */
+export function parseSince(input: string | undefined, flag = '--since', now = Date.now()): string | undefined {
+ const trimmed = input?.trim();
+ if (!trimmed) return undefined;
+ const relative = RELATIVE.exec(trimmed);
+ if (relative) return new Date(now - Number(relative[1]) * UNIT_MS[relative[2]!.toLowerCase()]!).toISOString();
+ const at = ISO_DATE.test(trimmed) ? new Date(trimmed) : null;
+ if (!at || Number.isNaN(at.getTime())) {
+ throw new Error(`${flag}: could not parse "${input}" as ISO-8601 (2026-10-01 or 2026-10-01T12:00:00Z) or relative (e.g. "5m", "1h", "7d")`);
+ }
+ return at.toISOString();
+}