Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(autopilot): --install goes through requireConsent (persistent_install) with --dry-run (E9)

garrytan71bbc0eb68c3
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 710958d9be..43d3b141bb 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -4,7 +4,7 @@
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
src/cli.ts 3211 ratchet +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult
-src/commands/autopilot.ts 1639 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts)
+src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)
src/commands/doctor.ts 663 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2217 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)
src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 56ebeb41a6..e22b74ff88 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -127,6 +127,7 @@
"test/autopilot-fanout-wiring.test.ts": 14,
"test/autopilot-fanout.test.ts": 10,
"test/autopilot-global-maintenance.test.ts": 986,
+ "test/autopilot-install-consent.test.ts": 600,
"test/autopilot-install.test.ts": 75,
"test/autopilot-lock-path.test.ts": 13,
"test/autopilot-lock.test.ts": 81,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index c9a5dd7c41..28cc6a01cc 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -747,6 +747,7 @@
"unit:test/autopilot-fanout-wiring.test.ts": 196,
"unit:test/autopilot-fanout.test.ts": 177,
"unit:test/autopilot-global-maintenance.test.ts": 2252,
+ "unit:test/autopilot-install-consent.test.ts": 600,
"unit:test/autopilot-install.test.ts": 455,
"unit:test/autopilot-lock-path.test.ts": 195,
"unit:test/autopilot-lock.test.ts": 431,
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index a22d99bb37..e8fa913224 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -82,6 +82,7 @@ import {
systemdUnitPath,
unitWrapperPath,
} from './autopilot/jobs.ts';
+import { autopilotInstallConsent, renderInstallDryRun } from './autopilot/install-consent.ts';
export { cronLineBelongsToBrain, crontabIndicatesAutopilotInstall, plistWrapperPath, scriptWrapperPath, unitWrapperPath };
export { autopilotLockPath, autopilotDisabledMarkerPath, autopilotPausedMarkerPath, autopilotLaunchdLabel };
export { relativeSourceLocalPathSkipWarning as relativeLocalPathSkipWarning };
@@ -931,6 +932,8 @@ async function installDaemon(engine: BrainEngine, args: string[]) {
process.exit(1);
}
+ if (args.includes('--dry-run')) { console.log(renderInstallDryRun({ target, repoPath, job })); return; }
+ if (!await autopilotInstallConsent(engine, args, { target, repoPath, job })) return;
const wrapperPath = writeWrapperScript(repoPath, target, job);
// #2608: tell the operator about the deterministic key channel — launchd/
// systemd don't inherit the login shell env, and rc-file interactive guards
diff --git a/src/commands/autopilot/install-consent.ts b/src/commands/autopilot/install-consent.ts
new file mode 100644
index 0000000000..ab4826c79b
--- /dev/null
+++ b/src/commands/autopilot/install-consent.ts
@@ -0,0 +1,93 @@
+/**
+ * `gbrain autopilot --install` consent (agent-first operator wave E9).
+ *
+ * Installing the autopilot daemon is a `persistent_install`: a background job
+ * that outlives the session and, when provider keys are configured, runs paid
+ * LLM/embedding phases within the configured budgets. The install goes
+ * through `requireConsent` (TTY prompt, `--yes`, or the user's
+ * `consent.preapprove.persistent_install`); a non-TTY caller without it gets
+ * the exit-3 `confirmation_required` payload and nothing is written.
+ * `--dry-run` prints the plan (target, job, every file it would write) and
+ * changes nothing.
+ */
+import { join } from 'node:path';
+import type { BrainEngine } from '../../core/engine.ts';
+import { gbrainPath, loadConfigFileOnly } from '../../core/config.ts';
+import { isConsentRefusal, printConsentRefusal, requireConsent } from '../../core/consent.ts';
+import { setCliExitVerdict } from '../../core/cli-force-exit.ts';
+import type { AutopilotJob } from '../../core/autopilot-paths.ts';
+import type { InstallTarget } from '../autopilot.ts';
+import { plistPath, systemdUnitPath } from './jobs.ts';
+
+export interface AutopilotInstallPlan {
+ target: InstallTarget;
+ repoPath: string;
+ job: AutopilotJob;
+}
+
+const TARGET_LABEL: Record<InstallTarget, string> = {
+ macos: 'launchd agent (starts at login, restarts on exit)',
+ 'linux-systemd': 'systemd user service (starts at boot, restarts on exit)',
+ 'ephemeral-container': 'container start script (runs when the container starts)',
+ 'linux-cron': 'crontab entry (runs every few minutes)',
+};
+
+/** Every file or table entry the install would write, for the dry run and the consent text. */
+export function installWrites(plan: AutopilotInstallPlan): string[] {
+ const wrapper = join(gbrainPath(), 'autopilot-run.sh');
+ const job = plan.target === 'macos' ? plistPath(plan.job.launchdLabel)
+ : plan.target === 'linux-systemd' ? systemdUnitPath(plan.job.systemdUnit)
+ : plan.target === 'ephemeral-container' ? plan.job.startScriptPath
+ : 'your crontab (one gbrain autopilot line)';
+ return [wrapper, job];
+}
+
+function providerKeysPresent(): boolean {
+ const file = loadConfigFileOnly() as Record<string, unknown> | null;
+ return !!(process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY || process.env.VOYAGE_API_KEY
+ || file?.anthropic_api_key || file?.openai_api_key || file?.voyage_api_key);
+}
+
+/** `--dry-run`: the plan, nothing written. */
+export function renderInstallDryRun(plan: AutopilotInstallPlan): string {
+ return [
+ `gbrain autopilot --install --dry-run: nothing was written.`,
+ ` target: ${plan.target} — ${TARGET_LABEL[plan.target]}`,
+ ` repo: ${plan.repoPath}`,
+ ` would write:`,
+ ...installWrites(plan).map((w) => ` ${w}`),
+ ` ${providerKeysPresent() ? 'Provider keys are configured, so LLM and embedding phases will spend provider credits within the configured budgets.' : 'No provider keys are configured, so only free maintenance phases will run.'}`,
+ ` Install: gbrain autopilot --install --yes (after the user agrees). Remove later: gbrain autopilot --uninstall`,
+ ].join('\n');
+}
+
+/**
+ * True when the install may proceed. On refusal prints the consent payload
+ * (`--json` → one JSON document) and sets exit 3; nothing has been written.
+ */
+export async function autopilotInstallConsent(engine: BrainEngine, args: string[], plan: AutopilotInstallPlan): Promise<boolean> {
+ const paid = providerKeysPresent();
+ const passthrough = args.filter((a) => a !== '--yes' && a !== '--dry-run' && a !== '--json');
+ try {
+ await requireConsent({
+ command: 'autopilot',
+ effects: ['persistent_install'],
+ actor: 'agent',
+ what: 'Install the gbrain autopilot background service',
+ why: `Installs a ${TARGET_LABEL[plan.target]} that keeps the brain at ${plan.repoPath} synced, extracted and consolidated in the background. Writes: ${installWrites(plan).join(', ')}.`
+ + (paid ? ' Provider keys are configured, so its LLM and embedding phases spend provider credits within the configured budgets.' : ''),
+ risk: 'A background job keeps running after this session and starts again at login/boot until `gbrain autopilot --uninstall` removes it.',
+ user_message: `I'd like to install gbrain's background maintenance (autopilot) so your brain stays synced and indexed without you running anything.`
+ + (paid ? ' It will use your configured AI provider keys, which costs a little within your budget settings.' : '')
+ + ' You can remove it any time with `gbrain autopilot --uninstall`. OK?',
+ argv: ['gbrain', 'autopilot', ...passthrough, '--yes'],
+ preview_argv: ['gbrain', 'autopilot', ...passthrough, '--dry-run'],
+ args,
+ }, { getConfig: (k) => engine.getConfig(k) });
+ return true;
+ } catch (e) {
+ if (!isConsentRefusal(e)) throw e;
+ setCliExitVerdict(printConsentRefusal(e, { json: args.includes('--json') }));
+ return false;
+ }
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e7ed749792..fb872252c8 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -19,7 +19,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
'apply-migrations': ['--acknowledge-no-backup', '--apply', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--require-db', '--skip-verify', '--source', '--yes'],
'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
- 'autopilot': ['--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--params', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--verify', '--version', '--yes'],
+ 'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-usd', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
@@ -46,7 +46,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', '--entity', '--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', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--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-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--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-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--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'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
@@ -83,7 +83,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
'notices': ['--brain', '--help', '--json', '--source'],
- 'onboard': ['--access', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--fact', '--federated-read', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stats', '--surface', '--take', '--target-score', '--timeline', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'onboard': ['--access', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--fact', '--federated-read', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--only', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stats', '--surface', '--take', '--target-score', '--timeline', '--trusted-extraction', '--types', '--url', '--yes'],
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--http', '--json', '--path', '--source', '--vectors', '--yes'],
@@ -101,7 +101,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--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', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--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', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
- 'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],
+ 'remote': ['--brain', '--help', '--json', '--mcp-only', '--only', '--scopes', '--source', '--timeout'],
'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
diff --git a/test/autopilot-install-consent.test.ts b/test/autopilot-install-consent.test.ts
new file mode 100644
index 0000000000..30450b7e4c
--- /dev/null
+++ b/test/autopilot-install-consent.test.ts
@@ -0,0 +1,81 @@
+/**
+ * `gbrain autopilot --install` consent (agent-first operator wave E9).
+ *
+ * The install is a persistent_install: a non-TTY caller without `--yes` (or
+ * the user's consent.preapprove.persistent_install) gets exit 3 with the
+ * confirmation_required payload and nothing is written; `--dry-run` prints the
+ * plan and writes nothing; `--yes` installs; the preapproval installs and says
+ * so on stderr.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { emptyHome, withEnv } from './helpers/with-env.ts';
+import { runAutopilot } from '../src/commands/autopilot.ts';
+import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+
+async function install(extra: string[], opts: { preapprove?: boolean } = {}) {
+ const gbrainHome = emptyHome();
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ap-consent-home-'));
+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-ap-consent-repo-'));
+ const bin = mkdtempSync(join(tmpdir(), 'gbrain-ap-consent-bin-'));
+ writeFileSync(join(bin, 'gbrain'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ if (opts.preapprove) {
+ mkdirSync(join(gbrainHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(gbrainHome, '.gbrain', 'config.json'), JSON.stringify({ consent: { preapprove: { persistent_install: true } } }));
+ }
+ const stdout: string[] = [];
+ const stderr: string[] = [];
+ await withEnv({ GBRAIN_HOME: gbrainHome, HOME: home, PATH: `${bin}:${process.env.PATH}`, GBRAIN_NON_INTERACTIVE: '1', ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined }, async () => {
+ const log = console.log;
+ const outWrite = process.stdout.write.bind(process.stdout);
+ const errWrite = process.stderr.write.bind(process.stderr);
+ console.log = (...p: unknown[]) => { stdout.push(p.map(String).join(' ')); };
+ process.stdout.write = ((c: string | Uint8Array) => { stdout.push(String(c)); return true; }) as typeof process.stdout.write;
+ process.stderr.write = ((c: string | Uint8Array) => { stderr.push(String(c)); return true; }) as typeof process.stderr.write;
+ _resetCliExitVerdictForTests();
+ try {
+ const engine = { kind: 'postgres', getConfig: async () => null } as never;
+ await runAutopilot(engine, ['--install', '--target', 'ephemeral-container', '--repo', repo, '--no-inject', ...extra]);
+ } finally {
+ console.log = log;
+ process.stdout.write = outWrite;
+ process.stderr.write = errWrite;
+ }
+ });
+ const wrapper = join(gbrainHome, '.gbrain', 'autopilot-run.sh');
+ return { stdout: stdout.join('\n'), stderr: stderr.join(''), verdict: currentExitCode(), wrapperWritten: existsSync(wrapper) };
+}
+
+describe('autopilot --install consent', () => {
+ test('non-TTY without --yes: exit 3, confirmation_required payload, nothing written', async () => {
+ const r = await install(['--json']);
+ expect(r.verdict).toBe(3);
+ expect(r.wrapperWritten).toBe(false);
+ const payload = JSON.parse(r.stdout);
+ expect(payload).toMatchObject({ status: 'confirmation_required', code: 'confirmation_required', effects: ['persistent_install'] });
+ expect(payload.fix.argv).toContain('--yes');
+ expect(payload.user_message).toContain('gbrain autopilot --uninstall');
+ });
+
+ test('--dry-run prints the plan and writes nothing', async () => {
+ const r = await install(['--dry-run']);
+ expect(r.wrapperWritten).toBe(false);
+ expect(r.stdout).toContain('nothing was written');
+ expect(r.stdout).toContain('autopilot-run.sh');
+ expect(r.stdout).toContain('ephemeral-container');
+ });
+
+ test('--yes installs', async () => {
+ const r = await install(['--yes']);
+ expect(r.wrapperWritten).toBe(true);
+ expect(r.verdict).toBe(0);
+ });
+
+ test("the user's persistent_install preapproval installs and is announced", async () => {
+ const r = await install([], { preapprove: true });
+ expect(r.wrapperWritten).toBe(true);
+ expect(r.stderr).toContain('consent.preapprove.persistent_install');
+ });
+});
diff --git a/test/autopilot-launchd-lifecycle.serial.test.ts b/test/autopilot-launchd-lifecycle.serial.test.ts
index f5461f70fd..f5ae7d92f6 100644
--- a/test/autopilot-launchd-lifecycle.serial.test.ts
+++ b/test/autopilot-launchd-lifecycle.serial.test.ts
@@ -193,7 +193,7 @@ describe.skipIf(SKIP_SUBPROCESS)('autopilot launchd lifecycle — shimmed (all p
expect(refused.stderr).toContain('--force');
expect(existsSync(plist())).toBe(false);
- const r = runCli(['autopilot', '--install', '--force', '--target', 'macos', '--repo', repoDir], env, 90_000);
+ const r = runCli(['autopilot', '--install', '--force', '--yes', '--target', 'macos', '--repo', repoDir], env, 90_000);
expect(r.exitCode).toBe(0);
expect(existsSync(plist())).toBe(true);
const xml = readFileSync(plist(), 'utf8');
@@ -247,7 +247,7 @@ describe.skipIf(SKIP_SUBPROCESS)('autopilot launchd lifecycle — shimmed (all p
// marker-clearing while leaving an immediately-doomed install.
mkdirSync(repoDir, { recursive: true });
// --force: PGLite daemon guard (#677) — see test 2.
- const r = runCli(['autopilot', '--install', '--force', '--target', 'macos', '--repo', repoDir], env, 90_000);
+ const r = runCli(['autopilot', '--install', '--force', '--yes', '--target', 'macos', '--repo', repoDir], env, 90_000);
expect(r.exitCode).toBe(0);
expect(existsSync(marker())).toBe(false);
}, 120_000);
@@ -337,7 +337,7 @@ describe.skipIf(SKIP_SUBPROCESS || !LAUNCHD_OK)('autopilot launchd lifecycle —
test('1. install loads a real job and RunAtLoad runs our wrapper', async () => {
// --force: PGLite daemon guard (#677) — the shimmed describe pins the
// refusal; this one exercises the real-launchd arc past it.
- const r = runCli(['autopilot', '--install', '--force', '--target', 'macos', '--repo', repoDir], env, 90_000);
+ const r = runCli(['autopilot', '--install', '--force', '--yes', '--target', 'macos', '--repo', repoDir], env, 90_000);
expect(r.exitCode).toBe(0);
expect(existsSync(plist())).toBe(true);
diff --git a/test/autopilot-operator-pause.test.ts b/test/autopilot-operator-pause.test.ts
index e6cb0da630..7544299248 100644
--- a/test/autopilot-operator-pause.test.ts
+++ b/test/autopilot-operator-pause.test.ts
@@ -73,7 +73,7 @@ describe('autopilot operator pause', () => {
const engine = { kind: 'postgres', getConfig: async () => null } as never;
const log = console.log;
console.log = () => {};
- try { await runAutopilot(engine, ['--install', '--target', 'ephemeral-container', '--repo', repo, '--no-inject']); } finally { console.log = log; }
+ try { await runAutopilot(engine, ['--install', '--yes', '--target', 'ephemeral-container', '--repo', repo, '--no-inject']); } finally { console.log = log; }
expect(existsSync(autopilotPausedMarkerPath())).toBe(false);
expect(existsSync(autopilotOperatorPauseMarkerPath())).toBe(true);
expect(autopilotPaused()).toBe(true);
diff --git a/test/e2e/autopilot-linux-lifecycle.serial.test.ts b/test/e2e/autopilot-linux-lifecycle.serial.test.ts
index 36574f4f0d..28ce9baaf4 100644
--- a/test/e2e/autopilot-linux-lifecycle.serial.test.ts
+++ b/test/e2e/autopilot-linux-lifecycle.serial.test.ts
@@ -250,7 +250,7 @@ describe('autopilot linux lifecycle (PATH-shimmed crontab/systemctl)', () => {
});
test('install --target linux-cron adds ONE autopilot line; foreign lines survive byte-identical', () => {
- const r = runCli(['autopilot', '--install', '--force', '--target', 'linux-cron', '--repo', repoDir]);
+ const r = runCli(['autopilot', '--install', '--force', '--yes', '--target', 'linux-cron', '--repo', repoDir]);
expect(r.status, `install failed:\nSTDOUT:\n${r.stdout}\nSTDERR:\n${r.stderr}`).toBe(0);
expect(r.stdout).toContain('Installed crontab entry for gbrain autopilot (every 5 minutes)');
@@ -279,7 +279,7 @@ describe('autopilot linux lifecycle (PATH-shimmed crontab/systemctl)', () => {
test('reinstall is idempotent: exactly one autopilot line, no table rewrite, foreign intact', () => {
const callsBefore = readLines(cronArgvLog).length;
- const r = runCli(['autopilot', '--install', '--force', '--target', 'linux-cron', '--repo', repoDir]);
+ const r = runCli(['autopilot', '--install', '--force', '--yes', '--target', 'linux-cron', '--repo', repoDir]);
expect(r.status, `reinstall failed:\nSTDOUT:\n${r.stdout}\nSTDERR:\n${r.stderr}`).toBe(0);
expect(r.stdout).toContain('Crontab entry already exists');
@@ -310,7 +310,7 @@ describe('autopilot linux lifecycle (PATH-shimmed crontab/systemctl)', () => {
test('install --target linux-systemd writes a 0644 unit and runs daemon-reload → enable --now → try-restart', () => {
rmSync(sysctlLog, { force: true });
- const r = runCli(['autopilot', '--install', '--force', '--target', 'linux-systemd', '--repo', repoDir]);
+ const r = runCli(['autopilot', '--install', '--force', '--yes', '--target', 'linux-systemd', '--repo', repoDir]);
expect(r.status, `systemd install failed:\nSTDOUT:\n${r.stdout}\nSTDERR:\n${r.stderr}`).toBe(0);
expect(r.stdout).toContain('Installed systemd user service: gbrain-autopilot.service');
diff --git a/test/e2e/autopilot-multi-brain.serial.test.ts b/test/e2e/autopilot-multi-brain.serial.test.ts
index c0fe307844..b8e34e7e4a 100644
--- a/test/e2e/autopilot-multi-brain.serial.test.ts
+++ b/test/e2e/autopilot-multi-brain.serial.test.ts
@@ -61,7 +61,7 @@ function run(gbrainHome: string | null, args: string[]): { status: number | null
}
function install(gbrainHome: string | null, target: string): { status: number | null; out: string } {
- return run(gbrainHome, ['--install', '--force', '--target', target, '--repo', repoDir]);
+ return run(gbrainHome, ['--install', '--force', '--yes', '--target', target, '--repo', repoDir]);
}
function status(gbrainHome: string | null): Record<string, any> {