Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(q1): sources set-sync, doctor cron_gbrain_home, lp-c charge diagnostics

garrytanca2b134d774c
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index b1f0693269..c783ebf531 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -675,7 +675,9 @@ vars — incident-time escape hatches, not everyday knobs.
every queued sync job), and the daemon prints `git_pull: off
(autopilot.git_pull=false)` once per tick (`{"event":"git_pull_disabled"}`
under `--json`). Per-source `syncEnabled: false` still removes a source from
- automatic sync entirely; an explicit `gbrain sync --source <id>` keeps its
+ automatic sync entirely (set it with `gbrain sources set-sync <id> off`;
+ preview with `--dry-run`, then apply the printed command, which carries
+ `--expect`); an explicit `gbrain sync --source <id>` keeps its
own `--pull`/`--no-pull` choice. Managed brains never pull automatically
whatever this key says (item 8).
diff --git a/src/commands/doctor/checks/cron-gbrain-home.ts b/src/commands/doctor/checks/cron-gbrain-home.ts
new file mode 100644
index 0000000000..7115946201
--- /dev/null
+++ b/src/commands/doctor/checks/cron-gbrain-home.ts
@@ -0,0 +1,105 @@
+/**
+ * `cron_gbrain_home` (GBRA-108): a cron line, or a script a cron line runs, that calls gbrain without the home this
+ * brain lives in. Cron starts commands with a bare environment, so a line that runs `bun run src/cli.ts` straight from
+ * a checkout, or the `gbrain` binary while this brain is under a non-default GBRAIN_HOME, reads and writes
+ * `~/.gbrain` instead: a second, silent brain state (locks, queue, config) beside the real one.
+ *
+ * Read-only and bounded: `crontab -l` (5 s; no crontab, no check), plus at most 20 scripts the lines name (64 KiB
+ * each). A line or script counts as setting the home when it assigns GBRAIN_HOME (on the line, in the crontab's
+ * environment lines, or anywhere in the script). Warns, never fails; the user edits the crontab.
+ */
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { isAbsolute, join } from 'node:path';
+import { execFileSync } from '../../../core/spawn.ts';
+import type { Check } from '../../doctor.ts';
+import { doctorVerify } from '../check-fix.ts';
+
+const SCRIPTS_MAX = 20;
+const SCRIPT_BYTES_MAX = 64 * 1024;
+const DIRECT_CLI = /(?:^|[\s;&|(=])(?:\S*\/)?src\/cli\.ts\b/;
+const GBRAIN_BINARY = /(?:^|[\s;&|(\/])gbrain\s+[a-z]/;
+const SETS_HOME = /(?:^|[\s;&|(])(?:export\s+)?GBRAIN_HOME=/;
+
+export interface CronGbrainHomeFinding { where: string; command: string; reason: 'direct_cli' | 'default_home' }
+
+const expand = (path: string) => path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;
+
+function readScript(path: string): string | null {
+ try {
+ const file = expand(path);
+ if (!isAbsolute(file) || !existsSync(file) || !statSync(file).isFile() || statSync(file).size > SCRIPT_BYTES_MAX) return null;
+ return readFileSync(file, 'utf8');
+ } catch { return null; }
+}
+
+/** The command part of a schedule line (after five time fields or an @keyword), or null for env, comment and blank lines. */
+function cronCommand(line: string): string | null {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed.startsWith('#') || /^[A-Za-z_][A-Za-z0-9_]*\s*=/.test(trimmed)) return null;
+ const at = /^@\w+\s+(.*)$/.exec(trimmed);
+ if (at) return at[1]!;
+ const fields = trimmed.split(/\s+/);
+ return fields.length > 5 ? fields.slice(5).join(' ') : null;
+}
+
+/** The first path-like word of a command after any VAR=value prefixes: the script a line runs, if it runs one. */
+function scriptOf(command: string): string | null {
+ for (const word of command.split(/\s+/)) {
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) continue;
+ return /^(?:\/|~\/)/.test(word) && !/\/(?:bun|node|bash|sh|zsh|env|gbrain)$/.test(word) ? word : null;
+ }
+ return null;
+}
+
+function classify(command: string, homeSet: boolean, customHome: boolean): CronGbrainHomeFinding['reason'] | null {
+ if (homeSet || SETS_HOME.test(command)) return null;
+ if (DIRECT_CLI.test(command)) return 'direct_cli';
+ return customHome && GBRAIN_BINARY.test(command) ? 'default_home' : null;
+}
+
+/** Pure: the findings for one crontab text. `customHome` is this process's GBRAIN_HOME when it is set. */
+export function cronGbrainHomeFindings(crontab: string, customHome: string | undefined, read: (path: string) => string | null = readScript): CronGbrainHomeFinding[] {
+ const lines = crontab.split('\n');
+ const cronHome = lines.some(line => /^\s*GBRAIN_HOME\s*=/.test(line));
+ const findings: CronGbrainHomeFinding[] = [];
+ let scripts = 0;
+ lines.forEach((line, index) => {
+ const command = cronCommand(line);
+ if (!command) return;
+ const reason = classify(command, cronHome, !!customHome);
+ if (reason) findings.push({ where: `crontab line ${index + 1}`, command: command.slice(0, 200), reason });
+ const script = scriptOf(command);
+ if (!script || cronHome || SETS_HOME.test(command) || scripts >= SCRIPTS_MAX) return;
+ scripts++;
+ const text = read(script);
+ if (text === null || SETS_HOME.test(text)) return;
+ text.split('\n').forEach((scriptLine, n) => {
+ if (scriptLine.trim().startsWith('#')) return;
+ const inner = classify(scriptLine, false, !!customHome);
+ if (inner) findings.push({ where: `${script}:${n + 1} (run by crontab line ${index + 1})`, command: scriptLine.trim().slice(0, 200), reason: inner });
+ });
+ });
+ return findings;
+}
+
+export function cronGbrainHomeCheck(crontab: string | null, customHome: string | undefined, read?: (path: string) => string | null): Check | null {
+ if (crontab === null) return null;
+ const findings = cronGbrainHomeFindings(crontab, customHome, read);
+ if (!findings.length) return { name: 'cron_gbrain_home', status: 'ok', message: 'No cron line or script it runs calls gbrain without its GBRAIN_HOME.', details: { findings } };
+ const home = customHome ? `GBRAIN_HOME=${customHome}` : 'GBRAIN_HOME set to the home this brain uses';
+ const listed = findings.slice(0, 5).map(f => `${f.where}: ${f.command}`).join(' | ');
+ return { name: 'cron_gbrain_home', status: 'warn', details: { findings, gbrain_home: customHome ?? null },
+ message: `${findings.length} cron command(s) run gbrain without GBRAIN_HOME, so they use ~/.gbrain rather than this brain's home: ${listed}${findings.length > 5 ? ' ...' : ''}. `
+ + `Cron passes no GBRAIN_HOME of its own; set it on the line or in the script, or call a wrapper that sets it.`,
+ fix: { argv: ['crontab', '-e'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'A cron command without GBRAIN_HOME reads and writes a second brain state under ~/.gbrain; only the user edits the crontab.',
+ user_message: `These cron commands run gbrain without GBRAIN_HOME: ${listed}. Add ${home} to each (or to the script it runs), or point them at a wrapper that exports it, so they act on this brain.`,
+ verify: doctorVerify('cron_gbrain_home') } };
+}
+
+/** `crontab -l` on a local machine; null when there is no crontab or it cannot be read in 5 s. */
+export function readCrontab(): string | null {
+ try { return execFileSync('crontab', ['-l'], { stdio: ['ignore', 'pipe', 'ignore'], timeout: 5_000 }).toString(); }
+ catch { return null; }
+}
diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.ts
index 5b88e9549c..994e363460 100644
--- a/src/commands/doctor/checks/local-audits.ts
+++ b/src/commands/doctor/checks/local-audits.ts
@@ -493,6 +493,15 @@ async function runHomeDirInWorktree(ctx: DoctorContext): Promise<Check[]> {
// Best-effort filesystem-hygiene check; never block doctor (a missing/
// unparseable config.json lands here and skips, same fail-open posture).
}
+ // GBRA-108: cron lines (and scripts they run) that call gbrain without GBRAIN_HOME (doctor/checks/cron-gbrain-home.ts).
+ // No environment gate: a container can run cron too; without a crontab the check emits nothing.
+ try {
+ const { cronGbrainHomeCheck, readCrontab } = await import('./cron-gbrain-home.ts');
+ const cron = cronGbrainHomeCheck(readCrontab(), process.env.GBRAIN_HOME || undefined);
+ if (cron) checks.push(cron);
+ } catch {
+ // Best-effort: an unreadable crontab never blocks doctor.
+ }
// Engine graduation state (filesystem only; src/commands/doctor/checks/engine-graduation.ts).
try {
const { graduationStateCheck } = await import('./engine-graduation.ts');
@@ -506,7 +515,7 @@ async function runHomeDirInWorktree(ctx: DoctorContext): Promise<Check[]> {
export const homeDirInWorktreeEntry: DoctorEntry = {
name: 'home_dir_in_worktree',
- emits: ['home_dir_in_worktree', 'npm_squat', 'pglite_leftovers', 'graduation_interrupted'],
+ emits: ['home_dir_in_worktree', 'npm_squat', 'pglite_leftovers', 'graduation_interrupted', 'cron_gbrain_home'],
run: runHomeDirInWorktree,
};
diff --git a/src/commands/sources-sync-enabled.ts b/src/commands/sources-sync-enabled.ts
new file mode 100644
index 0000000000..c0b88c0229
--- /dev/null
+++ b/src/commands/sources-sync-enabled.ts
@@ -0,0 +1,77 @@
+/**
+ * `gbrain sources set-sync <id> <on|off> [--dry-run] [--expect <on|off>] [--json]` (GBRA-108): sets `config.syncEnabled`,
+ * the switch that excludes a source from automatic sync (`sync --all`, autopilot's freshness dispatcher and the full-cycle
+ * fan-out; sync-policy.ts). An explicit `gbrain sync --source <id>` still runs either way. Before this verb the only way
+ * to set it was a raw write to `sources.config`.
+ *
+ * Preview first: `--dry-run` prints the current state, the target and the exact apply command, which carries
+ * `--expect <current>`; the apply refuses `preview_changed` when the state moved since. One writer:
+ * `updateSourceConfig`'s single-key merge, as `set-strategy` and `set-pull-strategy` do.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { OperationError, opError } from '../core/ops/contract.ts';
+import { cliRenderContext, toAgentError } from '../core/agent-output.ts';
+import { isSyncDisabledConfig } from '../core/sync-policy.ts';
+
+const USAGE = 'gbrain sources set-sync <id> <on|off> [--dry-run] [--expect <on|off>] [--json]';
+type SyncSwitch = 'on' | 'off';
+const isSwitch = (value: unknown): value is SyncSwitch => value === 'on' || value === 'off';
+
+export interface SetSyncResult { source_id: string; dry_run: boolean; current: SyncSwitch; target: SyncSwitch; changed: boolean; apply?: string[] }
+
+export function parseSetSyncArgs(args: string[]): { sourceId: string; target: SyncSwitch; dryRun: boolean; expect?: SyncSwitch } {
+ const positional: string[] = [];
+ let expect: string | undefined, dryRun = false;
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]!;
+ if (arg === '--json') continue;
+ if (arg === '--dry-run') { dryRun = true; continue; }
+ if (arg === '--expect') { expect = args[++i]; continue; }
+ if (arg.startsWith('-')) throw opError('invalid_params', `Unknown flag ${arg}.`, `Usage: ${USAGE}`);
+ positional.push(arg);
+ }
+ const [sourceId, target] = positional;
+ if (!sourceId || !isSwitch(target) || positional.length > 2) throw opError('invalid_params', 'Name one source and on or off.', `Usage: ${USAGE}`);
+ if (expect !== undefined && !isSwitch(expect)) throw opError('invalid_params', '--expect takes on or off.', `Usage: ${USAGE}`);
+ return { sourceId, target, dryRun, ...(expect ? { expect } : {}) };
+}
+
+export async function setSourceSync(engine: BrainEngine, opts: ReturnType<typeof parseSetSyncArgs>): Promise<SetSyncResult> {
+ const [src] = await engine.executeRaw<{ config: unknown; archived: boolean | null }>('SELECT config, archived FROM sources WHERE id=$1', [opts.sourceId]);
+ if (!src || src.archived) {
+ throw opError('invalid_params', `No active source ${opts.sourceId}.`, 'Name an active source; gbrain sources list prints them.',
+ { fix: { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the active source ids, read-only.' } });
+ }
+ const current: SyncSwitch = isSyncDisabledConfig(src.config) ? 'off' : 'on';
+ const preview = ['gbrain', 'sources', 'set-sync', opts.sourceId, opts.target, '--dry-run', '--json'];
+ if (opts.expect && opts.expect !== current) {
+ throw opError('preview_changed', `Automatic sync of source ${opts.sourceId} is ${current}, not ${opts.expect} as the preview showed; nothing changed.`,
+ `Preview again with ${preview.join(' ')} and apply the command it prints.`,
+ { fix: { argv: preview, consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the current state and the apply command for it; changes nothing.' } });
+ }
+ const changed = current !== opts.target;
+ if (opts.dryRun) return { source_id: opts.sourceId, dry_run: true, current, target: opts.target, changed,
+ apply: ['gbrain', 'sources', 'set-sync', opts.sourceId, opts.target, '--expect', current] };
+ if (changed) await engine.updateSourceConfig(opts.sourceId, { syncEnabled: opts.target === 'on' });
+ return { source_id: opts.sourceId, dry_run: false, current, target: opts.target, changed };
+}
+
+function describe(result: SetSyncResult): string {
+ const what = result.target === 'on' ? 'included in automatic sync' : 'excluded from automatic sync (an explicit gbrain sync --source still runs)';
+ if (result.dry_run) return `Source "${result.source_id}": automatic sync is ${result.current}; ${result.changed ? `it would be ${what}` : 'nothing would change'}.\nApply: ${result.apply!.join(' ')}`;
+ return result.changed ? `Source "${result.source_id}" is now ${what} (was ${result.current}).` : `Source "${result.source_id}": automatic sync is already ${result.current}; nothing changed.`;
+}
+
+export async function runSetSync(engine: BrainEngine, args: string[]): Promise<void> {
+ const json = args.includes('--json');
+ try {
+ const result = await setSourceSync(engine, parseSetSyncArgs(args));
+ console.log(json ? JSON.stringify(result) : describe(result));
+ } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ const env = toAgentError(error, { transport: 'cli', command: 'sources set-sync', render: cliRenderContext() });
+ console.log(json ? JSON.stringify(env) : `Refused (${error.code}): ${error.message}\nFix: ${error.suggestion ?? USAGE}`);
+ setCliExitVerdict(error.code === 'invalid_params' ? 2 : 1);
+ }
+}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 968b74d4c4..6409b3e667 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1905,6 +1905,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
case 'mirror-readonly': case 'mirror-writable': return (await import('./sources-mirror.ts')).runMirrorMode(engine, rest, sub === 'mirror-readonly');
case 'set-strategy': return (await import('./sources-strategy.ts')).runSetStrategy(engine, rest);
case 'set-pull-strategy': return (await import('./sources-pull-strategy.ts')).runSetPullStrategy(engine, rest);
+ case 'set-sync': return (await import('./sources-sync-enabled.ts')).runSetSync(engine, rest);
case 'refresh': return (await import('./sources-refresh.ts')).runSourcesRefresh(engine, rest);
case 'archive': return runArchive(engine, rest);
case 'restore': return runRestore(engine, rest);
@@ -2005,6 +2006,7 @@ Subcommands:
mirror-writable <id> [--dry-run] Undo mirror-readonly. --dry-run previews either and writes nothing.
set-strategy <id> <markdown|code|auto> Persist the sync strategy every sync of the source uses (PR #5955).
set-pull-strategy <id> <rebase|merge> How pulls reconcile local commits with origin (#5429); default rebase.
+ set-sync <id> <on|off> [--dry-run] [--expect <on|off>] Include or exclude the source from automatic sync (config.syncEnabled).
refresh <id> [--dry-run] [--wait-drain <s>] [--fetch-timeout-ms <ms>] [--resume|--abandon] [--json]
Managed brains: drain writes to the source's worktree, fast-forward
it to its upstream (git merge --ff-only) and sync every source bound
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 289def7d00..557e960953 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1224,6 +1224,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'In a managed canonical worktree, `gbrain git commit-push -m <msg> -- <paths>` now commits the named paths there (outcome `committed_local`, exit 0) instead of refusing `writer_coordinator_required`. It takes the commit lock and commits only those paths: it never fetches, merges, pushes or moves the checkout, so the persistence owner stays the only publisher; the owner\'s next Git publish, or `gbrain git commit-push --push-only --keep-checkout`, pushes the commit. --pending, --branch, --resolve, --expect-remote and --allow-outside-source-root are refused there (`commit_paths_invalid`).' },
{ since: 'TBD', text: 'The `refresh_diverged` refusal of `gbrain sources refresh` now counts the checkout\'s local commits and its fix is `gbrain git commit-push --push-only --keep-checkout --path <root> --json` (actor user, ask_user): it merges the upstream in memory, refuses on a conflict, pushes the merge and never moves the checkout, after which the refresh fast-forwards. It used to suggest reconciling in a separate clone or recloning, which drops the local commits.' },
{ since: 'TBD', text: '`gbrain sources writer status --json` has a new `checkouts` block: each canonical checkout on this host against its last fetched upstream (no fetch), with branch, upstream, ahead, behind, `diverged`, each commit the upstream lacks (sha, author, date, subject, paths; at most 20) and porcelain counts (staged, modified, untracked, conflicted). doctor `git_convergence` adds the same commits and counts for a managed canonical checkout, and now warns at once when one has diverged from its upstream (it blocks `gbrain sources refresh`), with the keep-checkout publish as an ask-user fix.' },
+ { since: 'TBD', text: 'New `gbrain sources set-sync <id> <on|off>` sets `config.syncEnabled`, which includes or excludes a source from automatic sync (`sync --all`, autopilot\'s freshness dispatcher and the full-cycle fan-out; an explicit `gbrain sync --source <id>` runs either way). `--dry-run` prints the current state and the apply command, which carries `--expect <current>`; an apply whose expectation no longer holds refuses `preview_changed` and changes nothing. Setting it used to need a raw write to `sources.config`.' },
+ { since: 'TBD', text: 'New doctor check `cron_gbrain_home` reads `crontab -l` (read-only, 5 s; no crontab, no check) and the scripts its lines run (at most 20, 64 KiB each) and warns on each command that runs `src/cli.ts` directly without GBRAIN_HOME, or the `gbrain` binary without GBRAIN_HOME while this brain runs under one: cron passes no GBRAIN_HOME, so those commands act on `~/.gbrain` instead of this brain. A GBRAIN_HOME assignment on the line, in the crontab\'s environment lines or in the script counts. The fix asks the user to edit the crontab.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4eaef3c428..699c289d6b 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -26,7 +26,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
- 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
+ 'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--keep-checkout', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--probe', '--resume', '--save', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
@@ -76,11 +76,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--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', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--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', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--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', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--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', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-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', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
- 'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
+ 'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--user', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
@@ -113,7 +113,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--accept-pending', '--acknowledge-managed', '--after', '--all', '--all-drifted', '--apply', '--background', '--brain', '--break-lock', '--class', '--client', '--close', '--cursor', '--day', '--diff', '--expect', '--explain', '--ff-only', '--follow', '--force', '--force-break-lock', '--from', '--full', '--full-history', '--generation', '--held', '--help', '--id', '--include-ambiguous', '--include-cross-entity', '--include-failures', '--include-repairs', '--json', '--keep', '--key', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-usd', '--mode', '--no-accept-pending', '--no-delegate', '--no-embed', '--no-llm', '--older-than', '--only', '--prefer', '--probe', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--remediate', '--remediation-plan', '--request', '--request-id', '--reset-checkpoint', '--retry-failed', '--run', '--scopes', '--side', '--since', '--skip', '--skip-failed', '--slug', '--slugs', '--source', '--stale', '--state', '--timeout', '--timings', '--url', '--wait', '--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', '--timings', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--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', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--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', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ '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', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--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', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--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', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--timings', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -127,7 +127,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--timings', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--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', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--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', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--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', '--background', '--backups', '--batch-check', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--cursor', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--future-days', '--get', '--get-all', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--holds', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--keep-storage', '--kind', '--lanes', '--legacy-lock', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--not', '--only', '--operations', '--origin', '--others', '--out', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--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', '--set-upstream-to', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--symbolic-full-name', '--takes-holders', '--timeout', '--timings', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unindexed', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 1d71429e20..40b6afb4fe 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -307,6 +307,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'google_api_access',
'google_oauth',
'home_dir_in_worktree',
+ // GBRA-108: cron commands that run gbrain without GBRAIN_HOME (doctor/checks/cron-gbrain-home.ts).
+ 'cron_gbrain_home',
'index_audit',
'npm_squat',
'oauth_client_scope_health',
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index d34f20e0fc..30abd8e8be 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -16,7 +16,7 @@ import { acquireWorktree, getWorktreeBinding, guardOwnership, type WorktreeBindi
import { chargePreparationAttempt, clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters, markRecovering, prepareRecovery, releaseUnpublishedClaim } from './journal.ts';
import type { WaitingOn } from './claim-phase.ts';
import { PREPARATION_BUDGET_KEYS, preparationKind } from './preparation-budget.ts';
-import { chargeTransientInterruption, transientInterruption, type TransientInterruption } from './transient-retry.ts';
+import { chargeTransientInterruption, chargedInterruptionDetail, transientInterruption, type TransientInterruption } from './transient-retry.ts';
import { readWriteSwitchSnapshot } from './switches.ts';
import { isSharedReadFailure } from './bounded-reads.ts';
import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';
@@ -351,7 +351,7 @@ export async function releaseChargedInterruption(engine: BrainEngine, row: Write
return null;
}).then(outcome => ({ outcome }), () => null);
if (!done) return null;
- await faultPoint('persistence:interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });
+ await faultPoint('persistence:interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation, ...chargedInterruptionDetail(charge.interruption, error) });
return done.outcome ?? (await getWriteRequestById(engine, row.id))!;
}
@@ -636,7 +636,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
// A charged interruption under the limit is retried after its backoff whatever error it surfaced as (a publication the
// ceiling cancelled can reject with a bare AbortError); past the limit it is the terminal failure.
const charged = transactionBodyCompleted ? null : await chargedInterruption(engine, row, error);
- if (!transactionBodyCompleted && transientInterruption(error)) await faultPoint('persistence:recovery_interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });
+ if (!transactionBodyCompleted && transientInterruption(error)) await faultPoint('persistence:recovery_interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation, ...chargedInterruptionDetail(transientInterruption(error), error) });
const terminal = charged ? charged.failure
: !transactionBodyCompleted && !mayReprepare(row, requestError(error)) && !transientDatabaseFailure(error) ? requestError(error) : null;
const failure = terminal ? withAttempt(terminal, published ? 'after_file_publication' : 'publication') : undefined;
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index fb3f42933a..77a72f25c0 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -100,6 +100,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
*/
/** `writeId` is the write request row: rows of a caller-bound replay share one `requestId` (crash-robot per-request seams key on the row). */
export interface FaultDetail { requestId?: string; writeId?: string; effectId?: string; sourceId?: string; operation?: string | null; signal?: AbortSignal; slug?: string; path?: string;
+ /** The `*_interruption_charged` seams: what was charged and the error it was charged for, so a probe can name a charge it did not expect. */
+ interruption?: { cause: string; sqlstate: string | null; error: string };
round?: number; read?: string; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number; narrow?: string; across?: true } | null; reused?: number;
/** `sync:level_read`: the level and the input it was read with (sync-pass.ts `readShadowLevel`), for probes that read it again. */
shadow?: unknown; input?: unknown } }
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index f40651ba91..2b8ab2ea8d 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -63,7 +63,7 @@ import { sharedReadFailure } from './bounded-reads.ts';
import { chargedInterruption, decoratePublicationOutcome, finishPreparationStalled, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, preparationAbortReason,
publicationPostimage, publishMutation, publishPersistenceFile, recoverPublication, releaseChargedInterruption, type PreparedMutation, type PublicationHooks } from './coordinator.ts';
import { withAttempt } from './publication-failure.ts';
-import { transientInterruption, type TransientInterruption } from './transient-retry.ts';
+import { chargedInterruptionDetail, transientInterruption, type TransientInterruption } from './transient-retry.ts';
import { pipelined } from '../page-state/transactions.ts';
import { jsonBytes } from './digest.ts';
import { EFFECT_BYTES_SQL, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';
@@ -418,7 +418,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
for (const { row } of recorded.values()) {
try {
const charged = await chargedInterruption(engine, row, error);
- if (charged) await faultPoint('persistence:recovery_interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });
+ if (charged) await faultPoint('persistence:recovery_interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation, ...chargedInterruptionDetail(transientInterruption(error), error) });
const failure = charged?.failure ? withAttempt(charged.failure, 'publication') : undefined;
await markRecovering(engine, row, failure ? 'publication_failed' : 'publication_not_started', failure);
const recovered = await recoverPublication(engine, row.id, hostId, true, failure, true);
diff --git a/src/core/persistence/transient-retry.ts b/src/core/persistence/transient-retry.ts
index 4a9e151133..63cc60e4df 100644
--- a/src/core/persistence/transient-retry.ts
+++ b/src/core/persistence/transient-retry.ts
@@ -52,6 +52,12 @@ export function transientInterruption(error: unknown): TransientInterruption | n
return code === '57014' ? { cause: 'statement_cancel', sqlstate: '57014' } : null;
}
+/** The `*_interruption_charged` fault-point detail: the charge and the error it was charged for. */
+export function chargedInterruptionDetail(interruption: TransientInterruption | null, error: unknown) {
+ const e = error as { name?: unknown; code?: unknown; message?: unknown } | null;
+ return interruption ? { interruption: { ...interruption, error: `${String(e?.name ?? 'Error')} ${String(e?.code ?? '')} ${String(e?.message ?? error).slice(0, 200)}` } } : {};
+}
+
/**
* Counts one transient interruption on a claim this owner still holds and schedules its next claim. Token-fenced; run it
* in the transaction that releases or finishes the claim, so a crash never counts an interruption twice. Returns the count.
diff --git a/test/doctor-cron-gbrain-home.test.ts b/test/doctor-cron-gbrain-home.test.ts
new file mode 100644
index 0000000000..64a118290c
--- /dev/null
+++ b/test/doctor-cron-gbrain-home.test.ts
@@ -0,0 +1,44 @@
+/**
+ * doctor `cron_gbrain_home` (GBRA-108): cron commands, and scripts they run, that call gbrain without GBRAIN_HOME.
+ */
+import { expect, test } from 'bun:test';
+import { cronGbrainHomeCheck, cronGbrainHomeFindings } from '../src/commands/doctor/checks/cron-gbrain-home.ts';
+
+const scripts: Record<string, string> = {
+ '/opt/example/run-sync.sh': '#!/bin/bash\ncd /opt/example/gbrain\nbun run src/cli.ts sync --all\n',
+ '/opt/example/wrapped.sh': '#!/bin/bash\nexport GBRAIN_HOME=/srv/brain-a\nbun run src/cli.ts sync --all\n',
+};
+const read = (path: string) => scripts[path] ?? null;
+
+test('a direct src/cli.ts call without GBRAIN_HOME is flagged on the line and inside a script the line runs', () => {
+ const crontab = [
+ '# m h dom mon dow command',
+ 'SHELL=/bin/bash',
+ '*/5 * * * * cd /opt/example/gbrain && bun run src/cli.ts sync --all >> /tmp/sync.log 2>&1',
+ '*/5 * * * * GBRAIN_HOME=/srv/brain-a bun run /opt/example/gbrain/src/cli.ts dream',
+ '0 * * * * /opt/example/run-sync.sh',
+ '0 * * * * /opt/example/wrapped.sh',
+ '@hourly cd ~/gbrain && git pull',
+ ].join('\n');
+ expect(cronGbrainHomeFindings(crontab, undefined, read)).toEqual([
+ { where: 'crontab line 3', command: 'cd /opt/example/gbrain && bun run src/cli.ts sync --all >> /tmp/sync.log 2>&1', reason: 'direct_cli' },
+ { where: '/opt/example/run-sync.sh:3 (run by crontab line 5)', command: 'bun run src/cli.ts sync --all', reason: 'direct_cli' },
+ ]);
+});
+
+test('the gbrain binary without GBRAIN_HOME is flagged only while this brain runs under a GBRAIN_HOME; a crontab env line covers every line', () => {
+ const crontab = '0 * * * * /usr/local/bin/gbrain sync --all\n15 * * * * gbrain doctor --json\n';
+ expect(cronGbrainHomeFindings(crontab, undefined, read)).toEqual([]);
+ expect(cronGbrainHomeFindings(crontab, '/srv/brain-a', read).map(f => [f.where, f.reason])).toEqual([['crontab line 1', 'default_home'], ['crontab line 2', 'default_home']]);
+ expect(cronGbrainHomeFindings(`GBRAIN_HOME=/srv/brain-a\n${crontab}0 * * * * /opt/example/run-sync.sh\n`, '/srv/brain-a', read)).toEqual([]);
+});
+
+test('the check: no crontab emits nothing, a clean one is ok, findings warn with a user fix naming the home', () => {
+ expect(cronGbrainHomeCheck(null, undefined, read)).toBeNull();
+ expect(cronGbrainHomeCheck('0 * * * * gbrain sync --all\n', undefined, read)).toMatchObject({ name: 'cron_gbrain_home', status: 'ok' });
+ const check = cronGbrainHomeCheck('0 * * * * gbrain sync --all\n', '/srv/brain-a', read)!;
+ expect(check).toMatchObject({ name: 'cron_gbrain_home', status: 'warn', details: { gbrain_home: '/srv/brain-a' },
+ fix: { argv: ['crontab', '-e'], actor: 'user', verify: { argv: ['gbrain', 'doctor', '--only', 'cron_gbrain_home', '--json'] } } });
+ expect(check.message).toContain('crontab line 1');
+ expect((check.fix as { user_message: string }).user_message).toContain('GBRAIN_HOME=/srv/brain-a');
+});
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 9f9a394759..522dbb15b2 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -189,6 +189,10 @@
"category": "ops",
"name": "pglite_leftovers"
},
+ {
+ "category": "ops",
+ "name": "cron_gbrain_home"
+ },
{
"category": "ops",
"name": "graduation_interrupted"
diff --git a/test/pathological/lp-c-publication-ceiling-retry.test.ts b/test/pathological/lp-c-publication-ceiling-retry.test.ts
index f84bbd2040..7e3bae8d07 100644
--- a/test/pathological/lp-c-publication-ceiling-retry.test.ts
+++ b/test/pathological/lp-c-publication-ceiling-retry.test.ts
@@ -78,7 +78,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
/** Every publication of claims `overruns(k)` parks past the ceiling and then fails as a discarded connection. */
function overrun(requestId: string, overruns: (claim: number) => boolean) {
- const seen = { claims: 0, publications: 0, transient: [] as number[], preparation: [] as number[] };
+ const seen = { claims: 0, publications: 0, transient: [] as number[], preparation: [] as number[], charges: [] as string[] };
installFaultHook(async (point, detail) => {
if (detail.requestId !== requestId) return;
if (point === 'consumer:preparing') {
@@ -89,6 +89,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
return;
}
if (point === 'persistence:interruption_charged' || point === 'persistence:recovery_interruption_charged') {
+ seen.charges.push(`claim ${seen.claims} ${point} ${JSON.stringify(detail.interruption ?? null)}`);
// Only a released row: one still held (the recovery route charges before it requeues) keeps its backoff, which the
// owner's reclaim of a row it released itself must honour.
await engine.executeRaw("UPDATE persistence_requests SET next_attempt_at=now() WHERE request_id=$1::uuid AND state='queued'", [requestId]).catch(() => undefined);
@@ -105,6 +106,17 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
return seen;
}
+ /** A claim count other than the expected one prints every charge (its cause and error) and the row, so a load-only failure names its cause. */
+ async function expectClaims(seen: { claims: number; transient: number[]; preparation: number[]; charges: string[] }, expected: number, requestId: string) {
+ if (seen.claims !== expected) console.error('lp-c unexpected claims', JSON.stringify({ expected, ...seen, row: await row(requestId).then(({ state, error_code, error_detail, preparation_attempts, transient_interruptions }) =>
+ ({ state, error_code, error_detail, preparation_attempts, transient_interruptions }), error => String(error)) }));
+ expect(seen.claims).toBe(expected);
+ }
+ /** The grouped tests' charge log: each member's charges with their cause and error, printed when a member is charged other than once. */
+ function recordCharge(charges: Map<string, string[]>, point: string, detail: { requestId?: string; interruption?: unknown }) {
+ if (point.endsWith('interruption_charged') && detail.requestId) charges.set(detail.requestId, [...charges.get(detail.requestId) ?? [], `${point} ${JSON.stringify(detail.interruption ?? null)}`]);
+ }
+
beforeAll(async () => {
if (backend === 'pglite') { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
else { const pg = await isolatedPersistencePostgres(databaseUrl!); engine = pg.engine; closePostgres = pg.close; }
@@ -129,7 +141,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
const seen = overrun(requestId, () => true);
const outcome = await call({ slug, content: page(`Overrun ${n}`), request_id: requestId }).catch(error => error as { code?: string });
installFaultHook(undefined);
- expect(seen.claims).toBe(6);
+ await expectClaims(seen, 6, requestId);
// One publication per claim: on Postgres a cancelled group of one is never published again under the same claim.
expect(seen.publications).toBe(6);
expect((outcome as { code?: string }).code).toBe('write_interrupted');
@@ -146,7 +158,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
const slug = `db/overrun-once-${++n}`, requestId = randomUUID();
const seen = overrun(requestId, claim => claim === 1);
expect(await call({ slug, content: page(`Once ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });
- expect(seen.claims).toBe(2);
+ await expectClaims(seen, 2, requestId);
expect(seen.transient).toEqual([0, 1]);
expect(await engine.readPageSnapshot(slug, { sourceId: 'default' })).not.toBeNull();
}, 180_000);
@@ -177,7 +189,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
const seen = overrun(requestId, () => true);
const outcome = await call({ slug, content: page(`Next ${n}`), request_id: requestId, expected_revision: before!.revision }, sourceId).catch(error => error as { code?: string });
installFaultHook(undefined);
- expect(seen.claims).toBe(3);
+ await expectClaims(seen, 3, requestId);
expect((outcome as { code?: string }).code).toBe('write_interrupted');
expect(seen.transient).toEqual([0, 1, 2]);
expect(await row(requestId)).toMatchObject({ state: 'failed', error_code: 'write_interrupted', transient_interruptions: 3, recovery: null,
@@ -236,9 +248,10 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
});
// A publication overruns only while another member prepared in the same pass is still unpublished (a group of two):
// the members prepare together and then reach before_commit one after the other inside the one transaction.
- const unpublished = new Set<string>(), claims = new Map<string, number>(), grouped: string[][] = [];
+ const unpublished = new Set<string>(), claims = new Map<string, number>(), grouped: string[][] = [], charges = new Map<string, string[]>();
installFaultHook(async (point, detail) => {
if (detail.sourceId !== sourceId) return;
+ recordCharge(charges, point, detail);
if (point === 'consumer:preparing') { unpublished.add(detail.requestId!); claims.set(detail.requestId!, (claims.get(detail.requestId!) ?? 0) + 1); return; }
if (point !== 'publication:before_commit') return;
const together = unpublished.size;
@@ -261,6 +274,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
[sourceId, `${dir}/%`]);
expect(rows.length).toBe(2);
for (const member of rows) {
+ if (member.transient_interruptions !== 1 || claims.get(member.request_id) !== 2) console.error('lp-c unexpected member charges', JSON.stringify({ member, claims: claims.get(member.request_id), charges: charges.get(member.request_id) ?? [], grouped }));
expect(member).toMatchObject({ state: 'committed', transient_interruptions: 1 });
expect(claims.get(member.request_id)).toBe(2);
}
@@ -280,9 +294,10 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
// As above, and each member's charge is followed by a pause longer than the first backoff (1 s), as on a loaded host:
// the first member's backoff has elapsed before the pass is done with the group, so only the charge itself keeps the
// pass from taking that claim back and publishing its old preparation under it.
- const unpublished = new Set<string>(), claims = new Map<string, number>(), grouped: string[][] = [];
+ const unpublished = new Set<string>(), claims = new Map<string, number>(), grouped: string[][] = [], charges = new Map<string, string[]>();
installFaultHook(async (point, detail) => {
if (detail.sourceId !== sourceId) return;
+ recordCharge(charges, point, detail);
if (point === 'consumer:preparing') { unpublished.add(detail.requestId!); claims.set(detail.requestId!, (claims.get(detail.requestId!) ?? 0) + 1); return; }
if (point === 'persistence:recovery_interruption_charged') { await new Promise(resolve => setTimeout(resolve, 1_200)); return; }
if (point !== 'publication:before_commit') return;
@@ -305,6 +320,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
[sourceId, `${dir}/%`]);
expect(rows.length).toBe(2);
for (const member of rows) {
+ if (member.transient_interruptions !== 1 || claims.get(member.request_id) !== 2) console.error('lp-c unexpected member charges', JSON.stringify({ member, claims: claims.get(member.request_id), charges: charges.get(member.request_id) ?? [], grouped }));
expect(member).toMatchObject({ state: 'committed', transient_interruptions: 1 });
expect(claims.get(member.request_id)).toBe(2);
}
@@ -317,7 +333,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}
const requestId = randomUUID();
const seen = overrun(requestId, claim => claim === 1);
expect(await call({ slug, content: page(`Next ${n}`), request_id: requestId, expected_revision: before!.revision }, sourceId)).toMatchObject({ state: 'committed' });
- expect(seen.claims).toBe(2);
+ await expectClaims(seen, 2, requestId);
expect(seen.transient).toEqual([0, 1]);
expect(readFileSync(join(brainDir, `${slug}.md`), 'utf8')).toContain(`Next ${n}`);
}, 180_000);
diff --git a/test/sources-set-sync.test.ts b/test/sources-set-sync.test.ts
new file mode 100644
index 0000000000..d3fe6f7bdf
--- /dev/null
+++ b/test/sources-set-sync.test.ts
@@ -0,0 +1,57 @@
+/**
+ * `gbrain sources set-sync <id> <on|off>` (GBRA-108): sets config.syncEnabled preview-first, with --expect binding the
+ * apply to the previewed state, by a single-key merge; automatic sync reads it through sync-policy.ts.
+ */
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { automaticSyncSkip } from '../src/core/sync-policy.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+async function cli(args: string[]): Promise<{ out: string; verdict: number | null }> {
+ const out: string[] = [];
+ _resetCliExitVerdictForTests();
+ const logSpy = spyOn(console, 'log').mockImplementation((...parts: unknown[]) => { out.push(parts.map(String).join(' ')); });
+ try { await runSources(engine, args); } finally { logSpy.mockRestore(); }
+ const verdict = currentExitCode() || null;
+ _resetCliExitVerdictForTests();
+ process.exitCode = 0;
+ return { out: out.join('\n'), verdict };
+}
+const row = async (id: string) => (await engine.executeRaw<{ id: string; local_path: string | null; config: unknown }>('SELECT id, local_path, config FROM sources WHERE id=$1', [id]))[0]!;
+const config = async (id: string) => { const c = (await row(id)).config; return (typeof c === 'string' ? JSON.parse(c) : c) as Record<string, unknown>; };
+
+test('set-sync previews, applies under --expect, keeps the other config keys and turns automatic sync off and on', async () => {
+ const id = `sync-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,'/tmp/${id}','{"strategy":"code"}')`, [id]);
+ const preview = await cli(['set-sync', id, 'off', '--dry-run', '--json']);
+ expect(JSON.parse(preview.out)).toEqual({ source_id: id, dry_run: true, current: 'on', target: 'off', changed: true, apply: ['gbrain', 'sources', 'set-sync', id, 'off', '--expect', 'on'] });
+ expect(await config(id)).toEqual({ strategy: 'code' });
+ const applied = await cli(['set-sync', id, 'off', '--expect', 'on', '--json']);
+ expect(JSON.parse(applied.out)).toEqual({ source_id: id, dry_run: false, current: 'on', target: 'off', changed: true });
+ expect(await config(id)).toEqual({ strategy: 'code', syncEnabled: false });
+ expect((await automaticSyncSkip(engine, await row(id)))?.reason).toBe('sync_disabled');
+ expect(JSON.parse((await cli(['set-sync', id, 'off', '--json'])).out)).toMatchObject({ changed: false, current: 'off' });
+ await cli(['set-sync', id, 'on', '--expect', 'off']);
+ expect(await config(id)).toEqual({ strategy: 'code', syncEnabled: true });
+ expect((await automaticSyncSkip(engine, await row(id)))?.reason).not.toBe('sync_disabled');
+});
+
+test('an apply whose --expect no longer holds refuses preview_changed and changes nothing; bad input and unknown sources refuse', async () => {
+ const id = `sync-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,'/tmp/${id}','{"syncEnabled":false}')`, [id]);
+ const stale = await cli(['set-sync', id, 'on', '--expect', 'on', '--json']);
+ expect(stale.verdict).toBe(1);
+ expect(JSON.parse(stale.out)).toMatchObject({ error: 'preview_changed', fix: { argv: ['gbrain', 'sources', 'set-sync', id, 'on', '--dry-run', '--json'] } });
+ expect(await config(id)).toEqual({ syncEnabled: false });
+ expect((await cli(['set-sync', id, 'maybe', '--json'])).verdict).toBe(2);
+ expect((await cli(['set-sync', id, 'on', '--expect', 'yes'])).verdict).toBe(2);
+ const missing = await cli(['set-sync', 'no-such-source', 'off', '--json']);
+ expect(missing.verdict).toBe(2);
+ expect(JSON.parse(missing.out)).toMatchObject({ error: 'invalid_params' });
+});