Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(consent): peel the harness, retriage and migrate consent requests into helpers; regenerate skills lock + plugin tree; trim key-files
garrytan135e6e3d0931
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex a957239ed3..503e5c381c 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -40,7 +40,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. `reportPersistenceCliError` owns the write exit verdict (`writeErrorExitCode` in `persistence/write-wait.ts`: pending exits 10 with `poll_command`, 0 with `--accept-pending`); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`.-- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Consent (agent operator wave C2) goes through `requireConsent` via `consentGate` (`src/core/consent-cli.ts`): effect `destructive`, bound to a `plan_hash` over the data dir, its WAL segment names and a stale postmaster.pid (`--dry-run --json` reports it; the approved command is `--yes --expect <plan_hash>`, so a bare `--yes` re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the sibling `.wal-repair-backup-<ts>` folder, the undo command from `restoreCommand`) is printed on stderr, carried by the consent payload and the dry run, and the receipt adds `restore_command` with the real backup path. Non-TTY without approval changes nothing and exits 3 with the consent payload; the TTY prompt is interaction.readLine on stderr (EOF/timeout = decline). `src/commands/reinit-pglite.ts` asks the same way (destructive, plan bound to the brain path and target model/width, the `.bak` restore command in the risk text; the `.bak` collision is refused before asking). The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.+- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Consent (C2) is `consentGate` (`src/core/consent-cli.ts`): `destructive`, bound to a `plan_hash` over the data dir, WAL segment names and a stale postmaster.pid (`--dry-run --json` reports it; approval is `--yes --expect <plan_hash>`, a bare `--yes` re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the `.wal-repair-backup-<ts>` folder, `restoreCommand`'s undo) is on stderr, in the payload and the dry run; the receipt adds `restore_command`. Non-TTY without approval exits 3; the TTY prompt is interaction.readLine (EOF = decline). `src/commands/reinit-pglite.ts` asks the same way (destructive, plan bound to the brain path and target model/width, the `.bak` restore command in the risk text; the `.bak` collision is refused before asking). The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.@@ -55,7 +55,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.- `src/commands/projections.ts` + `src/cli/commands/projections.ts` — `gbrain projections drain [--limit <n>] [--json]` (#5401). Trusted-local CLI, not an operation. Rebuilds queued Markdown and code projections in-process in batches of up to 100 until every row queued at the run start has been tried once (it waits for the database clock to pass the run start, so a page that fails in the run is not retried); `--limit` caps pages tried. Exit 0 (nothing tried failed), 1 (a page failed; each failure prints source, slug, reason and next action), 2 (did not run: bad usage, or `projection_owner_resident` when a process holds the selected PGLite brain, checked with `persistenceConfigForBrain` before any engine opens, so a mounted PGLite brain on a Postgres host is refused too). On Postgres it runs beside a resident owner (per-page locks plus the revision recheck). `residentDrainSteps` gives the stop-drain-restart commands for the serve service, autopilot and a manual serve, shared with doctor. Tests: `projection-drain.test.ts` (both engines via `test/e2e/projection-drain-postgres.test.ts`), `projections-drain-cli.serial.test.ts`.-- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks live `page_kind = 'code'` pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. `--force` rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in `reindex-code-delegate.ts`. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). Consent (agent operator wave C2): the cost preview feeds `requireConsent` via `consentGate` (effect `paid`, the estimate as `est_usd`); `--yes`, `--max-cost <usd>`, a per-run preapproval or `spend.posture=tokenmax` authorize it, and without authorization a non-interactive or `--json` run spends nothing and exits 3 with the consent payload. A run without a user cap is capped at the derived cap (BudgetTracker `capSource`), except under tokenmax, which keeps its documented uncapped meaning (`tokenmaxUncappedEnv`); `--max-cost off` stays the explicit uncapped choice. The owner-delegated path asks the same way with no estimate (default cap). Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source). --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow.+- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks live `page_kind = 'code'` pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. `--force` rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in `reindex-code-delegate.ts`. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). Consent (C2): the cost preview feeds `consentGate` (effect `paid`); `--yes`, `--max-cost <usd>`, a preapproval or tokenmax authorize it, otherwise exit 3 with the consent payload. Without a user cap the run gets the derived cap, except under tokenmax (`tokenmaxUncappedEnv`: stays uncapped); `--max-cost off` is the explicit uncapped choice. The owner-delegated path asks the same way (default cap). Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source). --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow.- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch; it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it). Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands). Consent (agent operator wave C3): every run first previews one selection (the rows whose stored `effective_date`/`effective_date_source` would change, scoped by `--source` and `--slug-prefix` through `backfillEffectiveDate`'s `sourceId` filter) and hashes it; the dry run reports that `plan_hash`. An apply asks through `requireConsent` (effect `destructive`, bound to the plan: `--yes --expect <plan_hash>`; a changed row is `preview_changed`) and writes only the approved ids (`onlyIds`). `--json` never implies consent: non-interactive without approval changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Scoped walks never read or write the orchestrator's brain-wide checkpoint. Pinned by `test/reindex-frontmatter-consent.test.ts` (two-source scope, binding).diff --git a/plugin/skills/chat-connectors/SKILL.md b/plugin/skills/chat-connectors/SKILL.mdindex 0a38827214..7859805f29 100644--- a/plugin/skills/chat-connectors/SKILL.md+++ b/plugin/skills/chat-connectors/SKILL.md@@ -69,7 +69,29 @@ gbrain connectors auth claude --cookie - # paste `sessionKey=<value>`, CtrEvery auth run ends with a probe + a one-line verdict. Nothing is saved on afailed probe unless you pass `--force`. `gbrain connectors auth chatgpt--try-oauth` attempts OAuth PKCE first (best-effort/forward-compat; ChatGPT-tokens are usually codex-scoped, so it falls back to the cookie lane).+tokens are usually codex-scoped, so it falls back to the cookie lane); add+`--no-browser` to print the sign-in URL instead of opening a browser. OAuth+waits for a local browser redirect, so it only runs with a person at the+terminal.++**When you (the agent) run it without a terminal:** `gbrain connectors auth+<provider>` with no credential does not wait for a paste. It prints an+`[AGENT]` block with the cookie checklist fenced in `[SHOW USER]`, saves+nothing and exits 1. The cookie is the user's credential, so:++1. Relay the `[SHOW USER]` checklist verbatim and ask the user to copy the+ cookie from a browser where they are logged in. Never reuse, guess or+ search for a cookie yourself.+2. Ask the user to hand it over without pasting it into the chat when+ possible (for example, they run `pbpaste | gbrain connectors auth chatgpt+ --cookie -` themselves). If they give it to you, pass it only on stdin:+ `printf '%s' "$COOKIE" | gbrain connectors auth <provider> --cookie -`.+3. If the user would rather not share a session cookie, use the official+ export instead (`gbrain transcripts ingest <export-file>`).++A stdin that stays open without data ends after 30 seconds with "stdin was+open but silent" (set `GBRAIN_STDIN_TIMEOUT_MS` to wait longer); nothing is+saved.**If the probe is blocked** by a Cloudflare/bot challenge (`forbidden`): theprovider is refusing server-side fetch from this machine. Use the officialdiff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex e46ca62054..66bbc17f1b 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -21,7 +21,6 @@ src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 378 ssrc/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/import.ts runImport 963 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts)src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/migrate-embeddings.ts runMigrateEmbeddings 325 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/serve.ts installStdioLifecycle 315 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/sources.ts runAdd 365 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 4 #5673: connector sources print that autopilot keeps them synced after the first syncdiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 76d1179a40..954a837d20 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -31,7 +31,7 @@"bulk-ingestion/SKILL.md": "8149c1ff02b320b80c3850d5f837cbebbdc8e088b24da7da9a78046f919ba9aa","bulk-ingestion/routing-eval.jsonl": "2bf8ffaf90b8ef761fa3cef54bf3af2eb8cc3ef736d054b5bf8b9361f6448d5a","capture/SKILL.md": "98568ac96331f57397ea072749641d9748b1ce31e8b09d512b8db25c8fcda65f",- "chat-connectors/SKILL.md": "f0218cab53f7e82d1543ba8c6f574b39821ecae780219aa5d408586a00de8062",+ "chat-connectors/SKILL.md": "affda80da48be0b893e433458a377cf50a9a1b093cdf582ae41a3f1320e863c1","chat-connectors/routing-eval.jsonl": "688b6bab2020a9628535fb739019f1ac54098e17327e6b1c8828c0d0c4a58be6","citation-fixer/SKILL.md": "abdadbf0740a529b9c4f86f05bba416417624503fdcbc6054402d5546afd08b4","citation-fixer/routing-eval.jsonl": "52b23b71e66fdc18aee67d0576099b0c83997d648cf4ecf8fe7753b91b6c9c53",diff --git a/src/commands/dream-retriage.ts b/src/commands/dream-retriage.tsindex d705f35a7a..4e4016cfc6 100644--- a/src/commands/dream-retriage.ts+++ b/src/commands/dream-retriage.ts@@ -37,6 +37,7 @@import { basename } from 'node:path';import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';+import type { Authorization } from '../core/consent.ts';import type { BrainEngine, DreamVerdict } from '../core/engine.ts';import {loadSynthConfig,@@ -264,6 +265,23 @@ async function retriageS7(engine: BrainEngine, config: Awaited<ReturnType<typeof};}+/** A4 consent for retriage spend above the gate (paid, the estimate in the relay text); null after a printed refusal. */+async function retriageConsent(engine: BrainEngine | null, args: string[], json: boolean,+ e: { missCount: number; triageModel: string; estimateUsd: number | null; auditSuffix: string }): Promise<Authorization | null> {+ const cost = e.estimateUsd !== null ? `about $${e.estimateUsd.toFixed(2)}` : 'an amount that cannot be estimated (unpriced model)';+ return consentGate({+ command: 'dream retriage', effects: ['paid'], actor: 'agent',+ what: `Re-judge ${e.missCount} transcript file(s) with ${e.triageModel}`,+ why: 'Re-runs the dream triage verdicts so transcripts judged under an older model or threshold get current verdicts.',+ risk: `Spends ${cost} with the model provider${e.auditSuffix}. Verdicts are cached; nothing is deleted.`,+ user_message: `Re-judge ${e.missCount} transcript file(s) for ${cost}?`,+ argv: ['gbrain', 'dream', 'retriage', ...args.filter(a => a !== '--yes')],+ preview_argv: ['gbrain', 'dream', 'retriage', ...args.filter(a => a !== '--yes' && a !== '--json'), '--dry-run'],+ est_usd: e.estimateUsd,+ args,+ }, { json, env: engineConsentEnv(engine) });+}+export async function runDreamRetriage(engine: BrainEngine | null, args: string[]): Promise<void> {let parsed: RetriageArgs;try {@@ -411,18 +429,7 @@ export async function runDreamRetriage(engine: BrainEngine | null, args: string[// a preapproval); --json never implies it. Without a user cap the soft-stop// runs at the derived cap. Below the gate small sweeps proceed as before.if (gateTriggered) {- const cost = estimateUsd !== null ? `about $${estimateUsd.toFixed(2)}` : 'an amount that cannot be estimated (unpriced model)';- const auth = await consentGate({- command: 'dream retriage', effects: ['paid'], actor: 'agent',- what: `Re-judge ${missCount} transcript file(s) with ${triageModel}`,- why: 'Re-runs the dream triage verdicts so transcripts judged under an older model or threshold get current verdicts.',- risk: `Spends ${cost} with the model provider${auditSuffix}. Verdicts are cached; nothing is deleted.`,- user_message: `Re-judge ${missCount} transcript file(s) for ${cost}?`,- argv: ['gbrain', 'dream', 'retriage', ...args.filter(a => a !== '--yes')],- preview_argv: ['gbrain', 'dream', 'retriage', ...args.filter(a => a !== '--yes' && a !== '--json'), '--dry-run'],- est_usd: estimateUsd,- args,- }, { json: parsed.json, env: engineConsentEnv(engine) });+ const auth = await retriageConsent(engine, args, parsed.json, { missCount, triageModel, estimateUsd, auditSuffix });if (!auth) return;if (budgetUsd === null && auth.cap_usd !== null && perFileUsd !== null) budgetUsd = auth.cap_usd;}diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.tsindex ee1d658cab..c2fd10168a 100644--- a/src/commands/migrate-embeddings.ts+++ b/src/commands/migrate-embeddings.ts@@ -878,6 +878,53 @@ export interface RunMigrateEmbeddingsOpts {exit?: (code: number) => never;}+/**+ * Consent gate (A4): effects paid + destructive. `spend.posture=tokenmax`+ * covers only the paid part; the schema rebuild (existing vectors are+ * dropped, retrieval is degraded until the re-embed finishes) still needs+ * `--yes`. Spend stays bounded by the migration's own durable authorization+ * (`--max-cost-usd` must cover the printed worst case), so the consent cap is+ * not threaded into the run. No plan hash: the brain-wide target is fully+ * named by the argv, and a resume re-runs the same command. Resolves false+ * after a printed refusal.+ */+async function migrateConsent(engine: BrainEngine, args: string[], flags: ReturnType<typeof parseMigrateEmbeddingsFlags>,+ plan: MigrationPlan, opts: RunMigrateEmbeddingsOpts): Promise<boolean> {+ if (!flags.yes) {+ const { resolveSpendPosture } = await import('../core/spend-posture.ts');+ if (await resolveSpendPosture(engine) === 'tokenmax') {+ serr(' [migrate] spend.posture=tokenmax: the cost estimate above is informational; the destructive rebuild still needs the user\'s approval.');+ }+ }+ const priceNote = plan.price_known ? `about $${plan.est_cost_usd.toFixed(2)}` : 'an unpriced amount';+ const worstCase = plan.worst_case_authorization.usd;+ const auth = await consentGate({+ command: 'migrate embeddings',+ effects: ['paid', 'destructive'],+ actor: 'agent',+ what: `Move the brain's embeddings to ${flags.to}${flags.dim !== undefined ? ` (${flags.dim}d)` : ''}`,+ why: `Re-embeds ${plan.chunks_to_embed} chunk(s), ${plan.facts_to_embed ?? 0} fact(s) and ${plan.takes_to_embed ?? 0} take(s) with ${flags.to} (${priceNote}) so search runs in the new model's vector space; pages and facts are kept.`,+ risk: 'Rebuilds the embedding column in place: existing vectors are dropped and vector search is degraded until the re-embed finishes '+ + `(a killed run resumes with the same command; status: ${EMBEDDING_MIGRATION_RECOVERY.status_command}). `+ + `Spends up to the --max-cost-usd authorization${worstCase !== null ? ` (worst case $${worstCase.toFixed(2)})` : ''} with the target provider.`,+ user_message: `Switch your brain's embeddings to ${flags.to}? It re-embeds ${plan.chunks_to_embed} chunk(s) for ${priceNote}`+ + `${worstCase !== null ? ` (at most $${worstCase.toFixed(2)})` : ''}; search is degraded until it finishes. Your pages and facts are kept.`,+ argv: ['gbrain', 'migrate', 'embeddings', ...args.filter(a => a !== '--yes')],+ preview_argv: ['gbrain', 'migrate', 'embeddings', ...args.filter(a => a !== '--yes' && a !== '--json'), '--dry-run', '--json'],+ est_usd: plan.price_known ? plan.est_cost_usd : null,+ args,+ }, {+ json: flags.json,+ env: engineConsentEnv(engine, {+ configuredCapUsd: flags.maxCostUsd ?? 0,+ note: () => {},+ ...(opts.isTTY !== undefined ? { interactive: opts.isTTY } : {}),+ ...(opts.confirm ? { readLine: async ({ prompt }: { prompt: string }) => ({ kind: 'line' as const, text: (await opts.confirm!(prompt)) ? 'y' : 'n' }) } : {}),+ }),+ });+ return auth !== null;+}+export async function runMigrateEmbeddings(engine: BrainEngine,args: string[],@@ -1036,46 +1083,7 @@ export async function runMigrateEmbeddings(exit(0);}- // ── Consent gate (A4): effects paid + destructive. `spend.posture=tokenmax`- // covers only the paid part; the schema rebuild (existing vectors are- // dropped, retrieval is degraded until the re-embed finishes) still needs- // `--yes`. Spend stays bounded by the migration's own durable authorization- // (`--max-cost-usd` must cover the printed worst case), so the consent cap is- // not threaded into the run. No plan hash: the brain-wide target is fully- // named by the argv, and a resume re-runs the same command.- if (!flags.yes) {- const { resolveSpendPosture } = await import('../core/spend-posture.ts');- if (await resolveSpendPosture(engine) === 'tokenmax') {- serr(' [migrate] spend.posture=tokenmax: the cost estimate above is informational; the destructive rebuild still needs the user\'s approval.');- }- }- const priceNote = plan.price_known ? `about $${plan.est_cost_usd.toFixed(2)}` : 'an unpriced amount';- const worstCase = plan.worst_case_authorization.usd;- const auth = await consentGate({- command: 'migrate embeddings',- effects: ['paid', 'destructive'],- actor: 'agent',- what: `Move the brain's embeddings to ${flags.to}${flags.dim !== undefined ? ` (${flags.dim}d)` : ''}`,- why: `Re-embeds ${plan.chunks_to_embed} chunk(s), ${plan.facts_to_embed ?? 0} fact(s) and ${plan.takes_to_embed ?? 0} take(s) with ${flags.to} (${priceNote}) so search runs in the new model's vector space; pages and facts are kept.`,- risk: 'Rebuilds the embedding column in place: existing vectors are dropped and vector search is degraded until the re-embed finishes '- + `(a killed run resumes with the same command; status: ${EMBEDDING_MIGRATION_RECOVERY.status_command}). `- + `Spends up to the --max-cost-usd authorization${worstCase !== null ? ` (worst case $${worstCase.toFixed(2)})` : ''} with the target provider.`,- user_message: `Switch your brain's embeddings to ${flags.to}? It re-embeds ${plan.chunks_to_embed} chunk(s) for ${priceNote}`- + `${worstCase !== null ? ` (at most $${worstCase.toFixed(2)})` : ''}; search is degraded until it finishes. Your pages and facts are kept.`,- argv: ['gbrain', 'migrate', 'embeddings', ...args.filter(a => a !== '--yes')],- preview_argv: ['gbrain', 'migrate', 'embeddings', ...args.filter(a => a !== '--yes' && a !== '--json'), '--dry-run', '--json'],- est_usd: plan.price_known ? plan.est_cost_usd : null,- args,- }, {- json: flags.json,- env: engineConsentEnv(engine, {- configuredCapUsd: flags.maxCostUsd ?? 0,- note: () => {},- ...(opts.isTTY !== undefined ? { interactive: opts.isTTY } : {}),- ...(opts.confirm ? { readLine: async ({ prompt }: { prompt: string }) => ({ kind: 'line' as const, text: (await opts.confirm!(prompt)) ? 'y' : 'n' }) } : {}),- }),- });- if (!auth) return (opts.exit ?? ((value: number) => process.exit(value)))(currentExitCode());+ if (!(await migrateConsent(engine, args, flags, plan, opts))) return (opts.exit ?? ((value: number) => process.exit(value)))(currentExitCode());// ── Execute: locks → probe → apply → drain → reconcile → complete, all in// the shared orchestrator (identical semantics on the op path).diff --git a/src/core/bootstrap/harness-consent.ts b/src/core/bootstrap/harness-consent.tsnew file mode 100644index 0000000000..1a62b2b25f--- /dev/null+++ b/src/core/bootstrap/harness-consent.ts@@ -0,0 +1,48 @@+/**+ * Consent for `gbrain bootstrap harness` (agent operator wave C6). The user+ * decides: `--yes` is the approval; otherwise a TTY prompt (EOF/timeout =+ * decline) when a human can answer, and with no human at the terminal+ * nothing is written and the refusal (exit 3, consent payload) is printed.+ * The approved argv never repeats a `--token` value.+ */+import { consentGate } from '../consent-cli.ts';+import type { HarnessFlags } from './harness.ts';++export interface HarnessConsentInput {+ flags: Pick<HarnessFlags, 'raw' | 'token' | 'tokenName' | 'yes' | 'json'>;+ url: string;+ /** Human list of the harnesses being wired, e.g. "Claude Code, Codex". */+ harnesses: string;+ skillsPolicy: 'follow' | 'memory-only';+ wireHooks: boolean;+ hookScope: string;+}++/** Resolves true when authorized; false after the refusal was printed. */+export async function askHarnessConsent(input: HarnessConsentInput, d: { isTTY: boolean; prompt: (q: string) => Promise<string> }): Promise<boolean> {+ const { flags, url, harnesses, wireHooks, hookScope } = input;+ const argv = ['gbrain', 'bootstrap', 'harness'];+ for (let i = 0; i < flags.raw.length; i++) {+ const a = flags.raw[i]!;+ if (a === '--yes') continue;+ if (a === '--token') { i++; continue; }+ argv.push(a);+ }+ const scopes = input.skillsPolicy === 'follow' ? 'read, write, skills_member_self' : 'read, write';+ const auth = await consentGate({+ command: 'bootstrap harness',+ effects: flags.token === undefined ? ['persistent_install', 'credentials'] : ['persistent_install'],+ actor: 'agent',+ what: `Wire ${harnesses} to the gbrain serve at ${url}`,+ why: 'Registers the brain\'s memory tools (and the session hooks) in the agent harness so new sessions recall from and save to this brain.',+ risk: `${flags.token === undefined ? `Mints a bearer token "${flags.tokenName}" with scopes ${scopes} and stores it in the harness config. ` : 'Stores the supplied token in the harness config (pass the same --token again). '}`+ + `Changes the harness configuration persistently${wireHooks ? `, including session hooks (${hookScope})` : ''}. Undo: gbrain bootstrap harness --remove.`,+ user_message: `Connect ${harnesses} to your brain at ${url}? It adds gbrain's memory tools${wireHooks ? ' and session hooks' : ''} to the harness configuration; gbrain bootstrap harness --remove undoes it.`,+ argv,+ args: flags.yes ? ['--yes'] : [],+ }, {+ json: flags.json,+ env: { interactive: d.isTTY, readLine: async ({ prompt }) => ({ kind: 'line', text: (await d.prompt(prompt)).trim() }) },+ });+ return auth !== null;+}diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex ed7ccb0c9e..b097b2bd34 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -41,7 +41,7 @@*/import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';-import { consentGate } from '../consent-cli.ts';+import { askHarnessConsent } from './harness-consent.ts';import { CONFIRMATION_REQUIRED_EXIT_CODE } from '../exit-codes.ts';import { dirname, join, resolve } from 'node:path';import { randomUUID } from 'node:crypto';@@ -994,33 +994,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P...(instructionsPaths.length > 0 ? { instructionsPaths } : {}),});d.log(consent);- // A4/C6: the user decides. --yes is the approval; otherwise a TTY prompt- // (EOF/timeout = decline), and with no human at the terminal nothing is- // written and the run exits 3 with the consent payload.const harnesses = [wireClaude ? 'Claude Code' : null, wireCodex ? 'Codex' : null, wireOpencode ? 'opencode' : null].filter(Boolean).join(', ');- const approvedArgv = ['gbrain', 'bootstrap', 'harness'];- for (let i = 0; i < flags.raw.length; i++) {- const a = flags.raw[i]!;- if (a === '--yes') continue;- if (a === '--token') { i++; continue; }- approvedArgv.push(a);- }- const auth = await consentGate({- command: 'bootstrap harness',- effects: flags.token === undefined ? ['persistent_install', 'credentials'] : ['persistent_install'],- actor: 'agent',- what: `Wire ${harnesses} to the gbrain serve at ${url}`,- why: 'Registers the brain\'s memory tools (and the session hooks) in the agent harness so new sessions recall from and save to this brain.',- risk: `${flags.token === undefined ? `Mints a bearer token "${flags.tokenName}" with scopes ${skillsPolicy === 'follow' ? 'read, write, skills_member_self' : 'read, write'} and stores it in the harness config. ` : 'Stores the supplied token in the harness config (pass the same --token again). '}`- + `Changes the harness configuration persistently${wireHooks ? `, including session hooks (${hookScope})` : ''}. Undo: gbrain bootstrap harness --remove.`,- user_message: `Connect ${harnesses} to your brain at ${url}? It adds gbrain's memory tools${wireHooks ? ' and session hooks' : ''} to the harness configuration; gbrain bootstrap harness --remove undoes it.`,- argv: approvedArgv,- args: flags.yes ? ['--yes'] : [],- }, {- json: flags.json,- env: { interactive: d.isTTY, readLine: async ({ prompt }) => ({ kind: 'line', text: (await d.prompt(prompt)).trim() }) },- });- if (!auth) return CONFIRMATION_REQUIRED_EXIT_CODE;+ if (!(await askHarnessConsent({ flags, url, harnesses, skillsPolicy, wireHooks, hookScope }, d))) return CONFIRMATION_REQUIRED_EXIT_CODE;// Prior receipt: carries the previous minted token for post-wire rotation// [C7], and the prior hook-scope for the user-XOR-project exclusivity checkdiff --git a/src/core/brainstorm/orchestrator.ts b/src/core/brainstorm/orchestrator.tsindex 325893341a..fce12c6fc4 100644--- a/src/core/brainstorm/orchestrator.ts+++ b/src/core/brainstorm/orchestrator.ts@@ -609,8 +609,7 @@ async function _runBrainstormInner(profile,model: modelStr,skip: opts.skipCostPreview === true,- stderrWrite: stderr,- capUsd: opts.maxCostUsd ?? 5,+ stderrWrite: stderr, capUsd: opts.maxCostUsd ?? 5,});if (aborted) {throw new Error('brainstorm: aborted before run (Ctrl-C during cost preview window)');