Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sources shared-skills <id> on|off|status: the per-source shared-skills opt-out command
garrytan0c502202082b
diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 8a6b287d6e..13acfd1620 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -359,7 +359,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// top-level help's own SOURCES block promises `sources --help` as the place to find the long tail// (rename, default, attach, current, federate, set-cr-mode, webhook, harden, ...). That made the// pointer circular and those subcommands undiscoverable from the CLI in either direction.- { name: 'sources', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/sources.ts') },+ { name: 'sources', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, load: () => import('./commands/sources.ts') },// CLI_ONLY: Open-loop engine CLI (engine-bound; trusted-local op dispatch).{ name: 'waiting', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/waiting.ts') },{ name: 'loops', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/loops.ts') },diff --git a/src/commands/sources-shared-skills.ts b/src/commands/sources-shared-skills.tsnew file mode 100644index 0000000000..4c8c25a317--- /dev/null+++ b/src/commands/sources-shared-skills.ts@@ -0,0 +1,63 @@+/**+ * `gbrain sources shared-skills <id> on|off|status [--json]`: the per-source+ * shared-skills opt-out (`config.shared_skills`, refusal reason+ * `source_shared_skills_disabled`). `off` writes `config.shared_skills=false`;+ * `on` deletes the key and releases a parked oversized inventory. Every form+ * prints the configured value and the effective migration policy with its+ * reason, so a connector or external source that stays preserve_files or+ * explicit_pack_required explains itself.+ */+import type { BrainEngine } from '../core/engine.ts';+import { usageError } from '../cli/cli-error.ts';+import { readSharedSkillsSourceView, setSourceSharedSkills, sharedSkillsStatusLines, type SharedSkillsAction } from '../core/shared-skills/source-opt-out.ts';+import { SHARED_SKILLS_OPT_OUT_DOCS } from '../core/shared-skills/setup-source-policy.ts';++export const SOURCES_SHARED_SKILLS_HELP = `Usage: gbrain sources shared-skills <id> on|off|status [--json]++Choose whether the shared-skills migration may adopt this source's skillpack+(config.shared_skills; reason code source_shared_skills_disabled when off).++ status Print the configured value, the effective policy mode and its reason,+ and a parked oversized inventory with its next step. Read-only.+ off Opt the source out: the migration preserves its files.+ on Remove the opt-out (the default) and release a parked inventory so+ the next \`gbrain apply-migrations --migration 0.53.0 --yes\` run+ inventories it again. A connector or external source can still stay+ preserve_files or explicit_pack_required; status says why.++Runs only on the brain host. Docs: ${SHARED_SKILLS_OPT_OUT_DOCS}`;++const ACTIONS: readonly SharedSkillsAction[] = ['on', 'off', 'status'];++export async function runSourcesSharedSkills(engine: BrainEngine, args: string[]): Promise<void> {+ const json = args.includes('--json');+ const unknown = args.find(arg => arg.startsWith('-') && arg !== '--json');+ if (unknown) {+ throw usageError(`Unknown flag ${unknown} for sources shared-skills.`, 'Run `gbrain sources shared-skills --help` for the accepted forms.', {+ code: 'unknown_flag',+ fix: { argv: ['gbrain', 'sources', 'shared-skills', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'The help lists the accepted forms.' },+ });+ }+ const [id, action, ...extra] = args.filter(arg => !arg.startsWith('-'));+ if (!id || !ACTIONS.includes(action as SharedSkillsAction) || extra.length) {+ throw usageError(+ !id ? 'sources shared-skills needs a source id and on, off or status.' : `sources shared-skills needs exactly one of on, off or status after the source id${action ? `, not "${[action, ...extra].join(' ')}"` : ''}.`,+ 'Run `gbrain sources shared-skills <id> status` to read the current setting first.',+ { fix: id+ ? { argv: ['gbrain', 'sources', 'shared-skills', id, 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the current setting and effective policy, read-only.' }+ : { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the registered source ids, read-only.' } },+ );+ }+ const change = action === 'status' ? null : await setSourceSharedSkills({ engine, remote: false }, id, action === 'on');+ const result = change ?? await readSharedSkillsSourceView(engine, id);+ if (json) {+ console.log(JSON.stringify({ schema_version: 1, action, ...result }, null, 2));+ return;+ }+ if (change) {+ console.log(change.changed+ ? `Shared skills ${action} for source ${id}.${change.released_parked ? ' Released its parked inventory; run gbrain apply-migrations --migration 0.53.0 --yes to inventory it again.' : ''}`+ : `Shared skills were already ${action} for source ${id}; nothing changed.`);+ }+ for (const line of sharedSkillsStatusLines(result)) console.log(line);+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex a358a57f43..cddf4f66ff 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1246,6 +1246,8 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {const gitHolds = await statusView.readGitHoldStatuses(engine, sources.map(source => source.id));const drainMod = await import('../core/persistence/sync-drain.ts');const backlog = new Map((await drainMod.readManagedSyncBacklog(engine).catch(() => [])).map(b => [b.source_id, b]));+ const sharedSkillsView = await import('../core/shared-skills/source-opt-out.ts');+ const sharedSkills = new Map(await Promise.all(sources.map(async source => [source.id, await sharedSkillsView.readSharedSkillsSourceView(engine, source.id).catch(() => null)] as const)));if (json) {const enriched = metrics.map((m) => ({...m,@@ -1255,6 +1257,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {...(connectors.get(m.source_id) ? { connector: connectors.get(m.source_id) } : {}),...(backlog.get(m.source_id) ? { managed_backlog: backlog.get(m.source_id) } : {}),...(gitHolds.get(m.source_id) ? { git_holds: gitHolds.get(m.source_id) } : {}),+ ...(sharedSkills.get(m.source_id) ? { shared_skills: sharedSkills.get(m.source_id) } : {}),}));console.log(JSON.stringify({ schema_version: 1, sources: enriched }, null, 2));return;@@ -1295,6 +1298,7 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {for (const [sourceId, status] of connectors) for (const line of statusView.connectorStatusLines(sourceId, status)) console.log(line);for (const [sourceId, status] of gitHolds) for (const line of statusView.gitHoldStatusLines(sourceId, status)) console.log(line);for (const b of backlog.values()) console.log(` ${drainMod.formatManagedSyncBacklog(b)}`);+ for (const view of sharedSkills.values()) if (view && (only || view.configured === false || view.parked)) for (const line of sharedSkillsView.sharedSkillsStatusLines(view)) console.log(` ${line}`);for (const m of metrics) {const warns: string[] = [];if (!m.local_path) warns.push('no local_path');@@ -1859,6 +1863,10 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vconsole.log(SOURCES_WEBHOOK_HELP);return;}+ if (sub === 'shared-skills') {+ console.log((await import('./sources-shared-skills.ts')).SOURCES_SHARED_SKILLS_HELP);+ return;+ }printHelp();return;}@@ -1898,6 +1906,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase 'set-cr-mode': return runSetCrMode(engine, rest);// #4739 non-destructive local_path pointer repaircase 'set-path': { const { runSetPath } = await import('./sources-set-path.ts'); return runSetPath(engine, rest); }+ case 'shared-skills': { const { runSourcesSharedSkills } = await import('./sources-shared-skills.ts'); return runSourcesSharedSkills(engine, rest); }case 'retry-held': { const { runRetryHeld } = await import('./sources-retry-held.ts'); return runRetryHeld(engine, rest); }case 'audit': return runAudit(engine, rest);// v0.46 github-source demo (offline, privacy-clean fixtures)@@ -1988,6 +1997,8 @@ Subcommands:Re-attempt a connector source's held items, or re-screen a Git source's held files, on its next sync.Runs nothing now. Most Git holds re-screen by themselves (file changed ordeleted, newer gbrain); fix the files with gbrain repair frontmatter --source <id>.+ shared-skills <id> on|off|status [--json]+ Opt a source out of (or back into) shared-skills adoption; status explains its effective policy.set-path <id> --clear Clear a connector source's (google, github)stale local_path; takes no path.webhook <set|show|rotate|clear> <id> [options]diff --git a/src/commands/thin-client-routing.ts b/src/commands/thin-client-routing.tsindex 6487575ba9..bdcdc33888 100644--- a/src/commands/thin-client-routing.ts+++ b/src/commands/thin-client-routing.ts@@ -62,6 +62,18 @@ export async function routeThinClientCommand(const sub = args[0];const rest = args.slice(1);+ if (command === 'sources' && sub === 'shared-skills') {+ if (rest.includes('--help') || rest.includes('-h')) {+ console.log((await import('./sources-shared-skills.ts')).SOURCES_SHARED_SKILLS_HELP);+ return true;+ }+ const [id, action] = rest.filter(arg => !arg.startsWith('-'));+ if (!id || !/^[a-z0-9-]{1,32}$/.test(id)) return false;+ const { sharedSkillsRemoteRefusal } = await import('../core/shared-skills/source-opt-out.ts');+ const { exitCliError } = await import('../cli/cli-error.ts');+ exitCliError(sharedSkillsRemoteRefusal(id, action === 'on' || action === 'off' ? action : 'status'), 'sources');+ }+if (command === 'config') {const { tryRunConfigThinClient } = await import('./config.ts');return tryRunConfigThinClient(args);diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 0745c4407f..58af7a6374 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -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', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--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', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--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-common-dir', '--git-dir', '--git-path', '--group', '--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', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--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', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--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', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--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', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--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', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--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-common-dir', '--git-dir', '--git-path', '--group', '--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', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--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', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--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', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--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', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--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', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -107,7 +107,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--only', '--remediate', '--remediation-plan', '--scopes', '--skip', '--source', '--stale', '--yes'],'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--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', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],@@ -120,7 +120,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', '--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', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait', '--wait-drain', '--yes'],+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait', '--wait-drain', '--yes'],'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--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-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],diff --git a/src/core/shared-skills/setup-source-policy.ts b/src/core/shared-skills/setup-source-policy.tsindex af74df35fd..004f3f588e 100644--- a/src/core/shared-skills/setup-source-policy.ts+++ b/src/core/shared-skills/setup-source-policy.ts@@ -3,6 +3,8 @@ import { getCompanyBrainProfile } from '../company-brain/profile.ts';import { parseSourceConfig } from '../sources-load.ts';import { OperationError } from '../ops/contract.ts';+export const SHARED_SKILLS_OPT_OUT_DOCS = 'docs/guides/shared-brain-skills.md#choose-which-sources-adopt-shared-skills';+export type SharedSkillSourcePolicy =| { mode: 'content'; reason?: never }| { mode: 'explicit_pack_required' | 'preserve_files'; reason: string };@@ -17,23 +19,25 @@ export async function sharedSkillSourcePolicy(engine: BrainEngine, sourceId: str`Source ${sourceId} is archived or not registered; choose an active content source (gbrain sources list --json shows them).`);}const config = parseSourceConfig(source.config);- // A source can already decline adoption implicitly by being connector-managed- // or an unapproved external repo (below). Some sources have a working- // skill-delivery path entirely outside this migration (their own- // brain-resident skillpack served over MCP, or an external plugin install)- // and need an explicit way to decline too: `inventorySkillpack`'s fixed- // file-count/byte-size bound throws on any skillpack that exceeds it, and- // after enough consecutive failures the migration wedges permanently for- // that source, with no other way to opt out per source.+ // A source can decline adoption implicitly by being connector-managed or an+ // unapproved external repo (below), or explicitly with+ // `gbrain sources shared-skills <id> off` when it already delivers skills+ // another way (its own brain-resident skillpack over MCP, a plugin install).if (config.shared_skills === false) return { mode: 'preserve_files',- reason: 'source_shared_skills_disabled: this source opted out of shared-skills catalog adoption (config.shared_skills=false). Its existing skill-delivery path (e.g. list_brain_skillpack/get_skill, or an external plugin install) is unaffected; no files or grants were touched.' };+ reason: `source_shared_skills_disabled: this source opted out of shared-skills catalog adoption (config.shared_skills=false). Its existing skill-delivery path (e.g. list_brain_skillpack/get_skill, or an external plugin install) is unaffected; no files or grants were touched. Turn adoption back on with gbrain sources shared-skills ${sourceId} on (${SHARED_SKILLS_OPT_OUT_DOCS}).` };if (config.kind != null) return { mode: 'preserve_files',- reason: 'source_skill_adoption_required: this connector-managed source is not a shared-skill write target. Preserve its generated/imported files and put approved shared skills in a separate content source.' };+ reason: `source_skill_adoption_required: this connector-managed source is not a shared-skill write target. Preserve its generated/imported files and put approved shared skills in a separate content source. gbrain sources shared-skills ${sourceId} status explains it (${SHARED_SKILLS_OPT_OUT_DOCS}).` };if (config.remote_url != null || config.managed_clone === true) return { mode: 'explicit_pack_required',- reason: 'source_skill_adoption_required: this external repository has no explicit brain-resident skillpack approval. No packaged skills were added. Review an existing brain_resident:true manifest or use a separate owned content source.' };+ reason: `source_skill_adoption_required: this external repository has no explicit brain-resident skillpack approval. No packaged skills were added. Review an existing brain_resident:true manifest or use a separate owned content source. gbrain sources shared-skills ${sourceId} status explains it (${SHARED_SKILLS_OPT_OUT_DOCS}).` };return { mode: 'content' };}+/** The policy as the migration applies it: a policy that cannot be verified preserves files. */+export async function sharedSkillSourcePolicyOrPreserve(engine: BrainEngine, sourceId: string): Promise<SharedSkillSourcePolicy> {+ return sharedSkillSourcePolicy(engine, sourceId).catch(error => ({ mode: 'preserve_files' as const,+ reason: error instanceof OperationError ? `${error.code}: ${error.message}` : 'profile_incompatible: the source writeback policy could not be verified; no repository changes were attempted.' }));+}+export async function assertPackagedSkillSource(engine: BrainEngine, sourceId: string): Promise<void> {const policy = await sharedSkillSourcePolicy(engine, sourceId);if (policy.mode !== 'content') {diff --git a/src/core/shared-skills/source-opt-out.ts b/src/core/shared-skills/source-opt-out.tsnew file mode 100644index 0000000000..7db37dd106--- /dev/null+++ b/src/core/shared-skills/source-opt-out.ts@@ -0,0 +1,96 @@+import type { BrainEngine } from '../engine.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { parseSourceConfig } from '../sources-load.ts';+import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';+import { migrationCheckpointKey, parkedReason, type SharedSourceMigration, type SharedSourceParked } from './migration.ts';+import { SHARED_SKILLS_OPT_OUT_DOCS, sharedSkillSourcePolicyOrPreserve } from './setup-source-policy.ts';++export type SharedSkillsAction = 'on' | 'off' | 'status';++/** What `gbrain sources shared-skills <id> status`, `sources status` and doctor report for one source. */+export interface SharedSkillsSourceView {+ source_id: string;+ /** `config.shared_skills` as stored: false (opted out), true, or null (unset, the default: on). */+ configured: boolean | null;+ mode: 'content' | 'explicit_pack_required' | 'preserve_files';+ reason_code: string | null;+ reason: string | null;+ explanation: string;+ parked: (SharedSourceParked & { next_step: string }) | null;+}++const statusArgv = (sourceId: string) => ['gbrain', 'sources', 'shared-skills', sourceId, 'status', '--json'];++export function sharedSkillsNotFound(sourceId: string): OperationError {+ return opError('not_found', `Source "${sourceId}" was not found (or is archived).`, 'List the registered sources, then run sources shared-skills with one of their ids.',+ { fix: readFix('Lists the registered sources and their ids, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });+}++/** A remote caller (thin client or MCP) cannot change or read the host's source policy. */+export function sharedSkillsRemoteRefusal(sourceId: string, action: SharedSkillsAction): OperationError {+ const argv = ['gbrain', 'sources', 'shared-skills', sourceId, action];+ return opError('trusted_local_only', `sources shared-skills runs only from the trusted local CLI on the brain host.`,+ `Ask the brain host's operator to run \`${argv.join(' ')}\` on the brain host.`, {+ why: 'A source\'s shared-skills setting decides whether the host migration may write skills into that repository, so only the brain host can read or change it.',+ fix: { argv, consent: [], actor: 'host_admin', requires_exclusive: false, docs: SHARED_SKILLS_OPT_OUT_DOCS,+ why: 'Runs on the brain host, which owns the source configuration.', verify: { argv: statusArgv(sourceId) } },+ });+}++async function readRecord(engine: BrainEngine, sourceId: string, incarnation: string): Promise<SharedSourceMigration | null> {+ const raw = await engine.getConfig(migrationCheckpointKey(sourceId, incarnation));+ if (!raw) return null;+ try { return JSON.parse(raw) as SharedSourceMigration; } catch { return null; }+}++export async function readSharedSkillsSourceView(engine: BrainEngine, sourceId: string): Promise<SharedSkillsSourceView> {+ const [source] = await engine.executeRaw<{ config: unknown; incarnation: string }>('SELECT config,incarnation FROM sources WHERE id=$1 AND NOT archived', [sourceId]);+ if (!source) throw sharedSkillsNotFound(sourceId);+ const stored = parseSourceConfig(source.config).shared_skills;+ const configured = typeof stored === 'boolean' ? stored : null;+ const policy = await sharedSkillSourcePolicyOrPreserve(engine, sourceId);+ const reasonCode = policy.mode === 'content' ? null : policy.reason.split(':')[0]!;+ const record = await readRecord(engine, sourceId, source.incarnation);+ const parked = policy.mode !== 'preserve_files' && record?.parked ? { ...record.parked, next_step: parkedReason(sourceId, record.parked) } : null;+ const explanation = policy.mode === 'content'+ ? `Shared skills are on for ${sourceId}: the migration may inventory and adopt its skillpack. Opt out with gbrain sources shared-skills ${sourceId} off.`+ : configured === false+ ? `${sourceId} opted out with config.shared_skills=false, so the migration preserves its files. Turn adoption back on with gbrain sources shared-skills ${sourceId} on.`+ : `config.shared_skills is ${configured === null ? 'unset (on)' : 'true'}, but ${sourceId} stays ${policy.mode} because of ${reasonCode}; turning shared skills on cannot change that. ${policy.reason}`;+ return { source_id: sourceId, configured, mode: policy.mode, reason_code: reasonCode, reason: policy.mode === 'content' ? null : policy.reason, explanation, parked };+}++/** Human lines shared by `sources shared-skills` and `sources status`. */+export function sharedSkillsStatusLines(view: SharedSkillsSourceView): string[] {+ return [+ `${view.source_id}: config.shared_skills = ${view.configured === null ? 'unset (on)' : String(view.configured)}; effective policy ${view.mode}${view.reason_code ? ` (${view.reason_code})` : ''}`,+ ` ${view.explanation}`,+ ...(view.parked ? [` parked inventory since ${view.parked.parked_at} (${view.parked.limit}): ${view.parked.next_step}`] : []),+ ];+}++/**+ * `off` writes config.shared_skills=false. `on` deletes the key and releases a+ * parked inventory so the next migration run inventories the source again.+ * Trusted local CLI only.+ */+export async function setSourceSharedSkills(ctx: { engine: BrainEngine; remote: boolean }, sourceId: string, enabled: boolean): Promise<SharedSkillsSourceView & { changed: boolean; released_parked: boolean }> {+ if (ctx.remote !== false) throw sharedSkillsRemoteRefusal(sourceId, enabled ? 'on' : 'off');+ const before = await readSharedSkillsSourceView(ctx.engine, sourceId);+ await ctx.engine.executeRaw(enabled+ ? `UPDATE sources SET config = ${SOURCE_CONFIG_OBJECT_SQL} - 'shared_skills' WHERE id = $1 AND NOT archived`+ : `UPDATE sources SET config = ${SOURCE_CONFIG_OBJECT_SQL} || '{"shared_skills": false}'::jsonb WHERE id = $1 AND NOT archived`, [sourceId]);+ let released = false;+ if (enabled) {+ const [source] = await ctx.engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);+ const record = source ? await readRecord(ctx.engine, sourceId, source.incarnation) : null;+ if (source && record?.parked) {+ delete record.parked;+ await ctx.engine.setConfig(migrationCheckpointKey(sourceId, source.incarnation), JSON.stringify(record));+ released = true;+ }+ }+ const after = await readSharedSkillsSourceView(ctx.engine, sourceId);+ return { ...after, changed: before.configured !== after.configured || released, released_parked: released };+}diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex 0e604da5c5..5854eec413 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -1721,8 +1721,10 @@"unconditionalFor": []}],- "thinClient": "refuse",- "thinClientRoutedSubcommands": []+ "thinClient": "route-then-refuse",+ "thinClientRoutedSubcommands": [+ "shared-skills"+ ]},"status": {"hasSwitchCase": true,@@ -2130,6 +2132,9 @@"stats","tune"],+ "sources": [+ "shared-skills"+ ],"takes": ["list","search",