Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

skills: owner-only revoke blocking, rollback restores revoked rule (spring and off), ownership invariants in ledger validation, complete dry-run permission previews, bootstrap JSON status, user-owned deleted rule respected; flag registry scoping for bundled-skill

garrytan904a1f32bc5e
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 717ff0ab0a..a5b81018a4 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -420,6 +420,8 @@ function buildFlagArtifacts(root: string): { registry: Record<string, string[]>;
reindex: ['--type'],
upgrade: ['--type', '--aliases'],
'post-upgrade': ['--type', '--aliases'],
+ // bundled-skill's skill_not_found hint names setup's refresh command; it parses its own flags strictly.
+ 'bundled-skill': ['--skill-loading', '--skills-index-only', '--install'],
};
const consumes = (text: string, flag: string): boolean =>
new RegExp(`['"\`]${flag}['"\`]`).test(text);
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 5f457bdba8..040719a78b 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -2020,7 +2020,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
emitJson(
JSON.stringify(
{
- schema_version: 1, ...harnessOutcomeFields(pendingFix, allConfirmed && smokeOk),
+ schema_version: 1, ...harnessOutcomeFields(pendingFix, allConfirmed && smokeOk && !skillsIndexFailed),
...cleanupOutcomeFields(cleanup, !pendingFix && allConfirmed && smokeOk, flags.raw),
url,
engine: health.engine ?? null,
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 71c8576006..a494abc964 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -28,7 +28,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],
'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--keep-checkout', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-instructions', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skill-loading', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--probe', '--resume', '--save', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],
- 'bundled-skill': ['--asset', '--brain', '--help', '--json', '--skill-loading', '--skills-index-only', '--source'],
+ 'bundled-skill': ['--asset', '--brain', '--help', '--json', '--source'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
'calibration': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
@@ -51,7 +51,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--credentials-file', '--cursor', '--dataset', '--day', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-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', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -122,7 +122,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
- 'setup': ['--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--surface', '--token', '--url', '--workspace', '--yes'],
+ 'setup': ['--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--root', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--surface', '--token', '--url', '--workspace', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'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'],
diff --git a/src/core/setup/skills-block.ts b/src/core/setup/skills-block.ts
index 160823b315..c80f1ea200 100644
--- a/src/core/setup/skills-block.ts
+++ b/src/core/setup/skills-block.ts
@@ -177,6 +177,8 @@ function invalidLedgerField(e: SkillLoadingLedgerEntry): string | undefined {
if (e.audience !== undefined && e.audience !== 'owner' && e.audience !== 'downstream') return 'audience';
for (const k of ['catalog', 'launcher', 'allow_rule', 'allow_settings'] as const) if (optional(e[k], 'string')) return k;
for (const k of ['allow_owned', 'allow_declined'] as const) if (optional(e[k], 'boolean')) return k;
+ if ((e.allow_owned === true || e.allow_declined === true) && e.allow_rule === undefined) return 'allow_rule (ownership recorded without the rule)';
+ if (e.allow_owned === true && e.allow_declined === true) return 'allow_declined (both owned and declined)';
return undefined;
}
@@ -233,10 +235,10 @@ function loaderRulePresent(settings: string, rule: string): boolean | undefined
* removed the rule gbrain added (only an explicit --skill-loading spring adds
* it back). Throws when settings cannot be updated.
*/
-/** The recorded rule is this one and the user took it out after gbrain added it (or declined it before). */
+/** The recorded rule is this one and the user took it out since (whoever added it), or declined it before. */
function userRemovedRule(prior: SkillLoadingLedgerEntry | undefined, rule: string, settings: string): boolean {
if (prior?.allow_rule !== rule || ruleSettings(prior) !== settings) return false;
- return prior.allow_declined === true || (prior.allow_owned === true && loaderRulePresent(settings, rule) === false);
+ return prior.allow_declined === true || loaderRulePresent(settings, rule) === false;
}
function grantLoader(harness: string, launcher: string, settings: string, prior: SkillLoadingLedgerEntry | undefined, regrant: boolean): { grant: Grant; added: boolean; declined: boolean } {
@@ -259,8 +261,8 @@ function revocableRule(entry: SkillLoadingLedgerEntry | undefined, keep?: { rule
const rule = entry.allow_rule;
const settings = ruleSettings(entry);
if (keep && rule === keep.rule && settings === keep.settings) return undefined;
- const stillUsed = readSkillLoadingLedger().some((e) => e.mode === 'spring' && e.allow_rule === rule && ruleSettings(e) === settings && !(e.harness === entry.harness && e.path === entry.path));
- return stillUsed ? undefined : { rule, settings };
+ const stillOwned = readSkillLoadingLedger().some((e) => e.mode === 'spring' && e.allow_owned === true && e.allow_rule === rule && ruleSettings(e) === settings && !(e.harness === entry.harness && e.path === entry.path));
+ return stillOwned ? undefined : { rule, settings };
}
/** What --dry-run reports for the loader rule: the change a real run would make. */
@@ -342,6 +344,8 @@ export interface SkillsBlockOutcome {
reason?: SkillsBlockReason;
/** Claude Code: the loader rule this run added to (or removed from) the user settings. */
permission?: { rule: string; settings: string; change: 'added' | 'removed' | 'would_add' | 'would_remove' };
+ /** Claude Code: the previous launcher's rule a launcher change took out (or would). */
+ replaced_permission?: { rule: string; settings: string; change: 'removed' | 'would_remove' };
}
/**
@@ -412,8 +416,10 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stri
if (revocation.problem) return out('preserve', `${revocation.problem}; fix that, then re-run. ${target.path} was left as it was`, { reason: 'permission_update_failed' });
const revoked: Partial<SkillsBlockOutcome> = revocation.removed ? { permission: { ...revocation.removed, change: 'removed' } }
: opts.dryRun ? plannedPermission('would_remove', revocableRule(prior)) : {};
+ // The ledger still records the rule until the opt-out is recorded, so a failure puts it back and a re-run finishes cleanly.
+ const putBack = () => (revocation.removed && undoUnrecorded({ path: target.path, settings, restore: revocation.removed }).length ? `; gbrain also could not put back ${revocation.removed.rule} in ${revocation.removed.settings}, so add it back by hand before re-running` : '');
if (before.state === 'no_file' || before.state === 'absent') {
- try { record('off', false); } catch (e) { return out('preserve', `recording the opt-out failed: ${message(e)}`, { reason: 'write_failed' }); }
+ try { record('off', false); } catch (e) { return out('preserve', `recording the opt-out failed: ${message(e)}${putBack()}`, { reason: 'write_failed' }); }
return out('skip', `skill loading off: no skills index in ${target.path}`, revoked);
}
try {
@@ -424,10 +430,10 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stri
else writeUnlessChanged(target.path, existing, false, stripped);
}
} catch (e) {
- return out('preserve', `${target.path} could not be updated (${message(e)}); the skills index is still there`, { reason: 'write_failed' });
+ return out('preserve', `${target.path} could not be updated (${message(e)}); the skills index is still there${putBack()}`, { reason: 'write_failed' });
}
try { record('off', false); } catch (e) {
- return out('preserve', `the skills index was removed from ${target.path}, but recording the opt-out in ${skillLoadingLedgerPath()} failed (${message(e)}); re-run to record it`, { reason: 'recorded_partially' });
+ return out('preserve', `the skills index was removed from ${target.path}, but recording the opt-out in ${skillLoadingLedgerPath()} failed (${message(e)}); re-run to record it${putBack()}`, { reason: 'recorded_partially' });
}
return out('remove', `skills index from ${target.path}`, revoked);
}
@@ -466,8 +472,10 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stri
if (opts.dryRun) {
if (target.harness !== 'claude-code') return done;
const rule = loaderAllowRule(launcher);
- if (userRemovedRule(prior, rule, settings) && decision.source !== 'flag') return done;
- return { ...done, ...plannedPermission('would_add', { rule, settings }) };
+ const old = plannedPermission('would_remove', revocableRule(prior, { rule, settings })).permission;
+ const replacedPreview: Partial<SkillsBlockOutcome> = old ? { replaced_permission: { rule: old.rule, settings: old.settings, change: 'would_remove' } } : {};
+ if (userRemovedRule(prior, rule, settings) && decision.source !== 'flag') return { ...done, ...replacedPreview };
+ return { ...done, ...replacedPreview, ...plannedPermission('would_add', { rule, settings }) };
}
const priorGrant: Grant = prior?.allow_rule
? { allow_rule: prior.allow_rule, allow_settings: prior.allow_settings, allow_owned: prior.allow_owned, ...(prior.allow_declined ? { allow_declined: true } : {}) }
@@ -489,10 +497,11 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stri
try {
record('spring', createdFile, grant);
} catch (e) {
- const left = undoUnrecorded({ path: target.path, written, rule: added ? grant.allow_rule : undefined, settings });
+ const left = undoUnrecorded({ path: target.path, written, rule: added ? grant.allow_rule : undefined, settings, restore: replaced.removed });
if (left.length === 0) return out('preserve', `recording the skills index in ${skillLoadingLedgerPath()} failed (${message(e)}), so this run's changes were undone and nothing changed; fix that, then re-run`, { reason: 'write_failed' });
return out('preserve', `recording the skills index in ${skillLoadingLedgerPath()} failed (${message(e)}), and gbrain could not undo ${left.join(' and ')}; remove ${left.length > 1 ? 'them' : 'it'} by hand before re-running, because a re-run would take ${left.length > 1 ? 'them' : 'it'} for yours`, { reason: 'recorded_partially' });
}
+ if (replaced.removed) done.replaced_permission = { ...replaced.removed, change: 'removed' };
if (permissionProblem) return { ...done, action: 'preserve', detail: `${done.detail} (the index is in place; the permission step did not finish): ${permissionProblem}`, reason: 'permission_update_failed' };
if (declined) return { ...done, detail: `${done.detail}; the Claude Code rule ${rule} was removed from ${settings} after gbrain added it, so gbrain left it out and Claude Code will ask before each skill load (re-run with --skill-loading spring to add it again)` };
return added && grant.allow_rule ? { ...done, detail: `${done.detail}; Claude Code may now run ${grant.allow_rule}`, permission: { rule: grant.allow_rule, settings, change: 'added' } } : done;
@@ -503,8 +512,15 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stri
* file is left that the ledger does not know gbrain wrote. Returns what could
* not be undone.
*/
-function undoUnrecorded(opts: { path: string; written?: { before: string | null; after: string }; rule?: string; settings: string }): string[] {
+function undoUnrecorded(opts: { path: string; written?: { before: string | null; after: string }; rule?: string; settings: string; restore?: { rule: string; settings: string } }): string[] {
const left: string[] = [];
+ if (opts.restore) {
+ try {
+ addPermissionsAllowEntry(opts.restore.settings, opts.restore.rule);
+ } catch {
+ left.push(`the removal of the rule ${opts.restore.rule} from ${opts.restore.settings} (add it back)`);
+ }
+ }
if (opts.rule) {
try {
if (removePermissionsAllowEntry(opts.settings, opts.rule).notes.some((n) => n.startsWith('WARNING'))) left.push(`the rule ${opts.rule} in ${opts.settings}`);
@@ -571,7 +587,9 @@ export function removeSkillsBlock(opts: { harness: string; path: string; dryRun:
export function describeSkillsBlockOutcome(o: SkillsBlockOutcome, dryRun: boolean): string {
const how = o.decision.value === 'spring' ? 'turn off with --skill-loading off' : 'turn on with --skill-loading spring';
const tag = o.decision.source === 'unresolved' ? '' : ` [${o.decision.source}; ${how}]`;
- return ` ${(dryRun && o.action !== 'keep' && o.action !== 'skip' ? `would ${o.action}` : o.action).padEnd(8)} ${'skills'.padEnd(7)} ${o.detail}${tag}`;
+ const rule = (p: { rule: string; settings: string; change: string } | undefined) =>
+ p && p.change !== 'added' ? `; ${p.change.replace('_', ' ')} Claude Code permission ${p.rule} in ${p.settings}` : '';
+ return ` ${(dryRun && o.action !== 'keep' && o.action !== 'skip' ? `would ${o.action}` : o.action).padEnd(8)} ${'skills'.padEnd(7)} ${o.detail}${rule(o.replaced_permission)}${rule(o.permission)}${tag}`;
}
/**
@@ -682,7 +700,9 @@ export function refreshSkillsIndexes(harness: BrainFirstHarness, opts: { mode?:
const unreadable = ledgerProblem();
if (unreadable) return [unreadable];
const off = opts.mode === 'off';
- return readSkillLoadingLedger().filter((e) => e.harness === harness && (off || e.mode === 'spring')).map((e) => syncSkillsBlock({
+ const ledger = readSkillLoadingLedger();
+ const batch = ledger.filter((e) => e.harness === harness && (off || e.mode === 'spring'));
+ const outcomes = batch.map((e) => syncSkillsBlock({
target: brainFirstTargetAt(harness, e.path),
launcher: opts.launcher ?? e.launcher ?? indexLauncher() ?? 'gbrain',
audience: e.audience ?? 'owner',
@@ -690,4 +710,22 @@ export function refreshSkillsIndexes(harness: BrainFirstHarness, opts: { mode?:
writer: e.writer,
dryRun: opts.dryRun,
}));
+ if (!opts.dryRun || harness !== 'claude-code') return outcomes;
+ // Each row previewed alone sees the others still owning a shared rule. When the batch drops that rule from every
+ // row (an opt-out, or a launcher change), its last owner is the one that takes it out, so that row shows the removal.
+ const owners = (e: SkillLoadingLedgerEntry) => e.mode === 'spring' && e.allow_owned === true && e.allow_rule !== undefined;
+ const drops = (e: SkillLoadingLedgerEntry) => off || loaderAllowRule(opts.launcher ?? e.launcher ?? '') !== e.allow_rule;
+ const shown = (o: SkillsBlockOutcome, rule: string) => (off ? o.permission : o.replaced_permission)?.rule === rule;
+ batch.forEach((e, i) => {
+ if (!owners(e) || !drops(e) || outcomes.some((o) => shown(o, e.allow_rule!))) return;
+ const settings = ruleSettings(e);
+ const sameRule = (x: SkillLoadingLedgerEntry) => owners(x) && x.allow_rule === e.allow_rule && ruleSettings(x) === settings;
+ if (ledger.some((x) => sameRule(x) && (!batch.includes(x) || !drops(x)))) return;
+ if (batch.map((x, j) => (sameRule(x) ? j : -1)).filter((j) => j >= 0).pop() !== i) return;
+ const removal = plannedPermission('would_remove', { rule: e.allow_rule!, settings }).permission;
+ if (!removal) return;
+ if (off) outcomes[i]!.permission = removal;
+ else outcomes[i]!.replaced_permission = { rule: removal.rule, settings: removal.settings, change: 'would_remove' };
+ });
+ return outcomes;
}
diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.ts
index 9cb73772d2..19e12d2651 100644
--- a/test/bootstrap-harness.serial.test.ts
+++ b/test/bootstrap-harness.serial.test.ts
@@ -520,7 +520,8 @@ describe('skills index exit codes (GBRA-194)', () => {
const code = await applyHarness(flags(['--harness', 'claude-code', '--skill-loading', 'spring', '--json']), f.deps);
expect(code).toBe(1);
expect(f.err.join('\n')).toContain('skills index was not written');
- const doc = JSON.parse(f.out.filter(l => l.trim().startsWith('{')).join('\n') || '{}') as { skills_index?: Array<{ action: string; reason?: string }> };
+ const doc = JSON.parse(f.out.filter(l => l.trim().startsWith('{')).join('\n') || '{}') as { status?: string; skills_index?: Array<{ action: string; reason?: string }> };
+ expect(doc.status).toBe('failed');
expect(doc.skills_index?.[0]).toMatchObject({ action: 'preserve', reason: 'launcher_unusable' });
});
});
diff --git a/test/connect.test.ts b/test/connect.test.ts
index aa65dacfef..fbe334bcf4 100644
--- a/test/connect.test.ts
+++ b/test/connect.test.ts
@@ -508,7 +508,7 @@ function installDeps(over: Partial<ConnectDeps> = {}): ConnectDeps {
env: () => undefined, // tests control the env; real GBRAIN_REMOTE_TOKEN must not leak in
registerOAuthClient: () => ({ ok: true, clientId: 'gbrain_cl_minted', clientSecret: 'gbrain_cs_minted' }),
writeOpencodeRemoteEntry: (name) => ({ configPath: `/tmp/xdg/opencode/opencode.jsonc (${name})`, replacedPrior: false }),
- writeInstructions: (agent, name, optOut) => (optOut ? null : `write instructions brain-first block for ${agent} '${name}'`),
+ writeInstructions: (agent, name, optOut, skillLoading, gbrainBin) => (optOut ? null : `write instructions brain-first block for ${agent} '${name}'${skillLoading ? ` skill-loading=${skillLoading}` : ''}${gbrainBin ? ` gbrain-bin=${gbrainBin}` : ''}`),
...over,
};
}
@@ -525,6 +525,16 @@ describe('runConnect --install', () => {
expect(r.err.join('\n')).toContain(LEARN_INSTRUCTION);
});
+ test('--skill-loading and --gbrain-bin reach the instruction writer', async () => {
+ const seen: unknown[] = [];
+ const r = await runWithExitCapture(
+ ['https://brain.example.com/mcp', '--token', 'gbrain_tok', '--install', '--yes', '--skill-loading', 'spring', '--gbrain-bin', '/opt/alice-example/gbrain'],
+ installDeps({ writeInstructions: (agent, name, optOut, skillLoading, gbrainBin) => { seen.push([skillLoading, gbrainBin]); return null; } }),
+ );
+ expect(r.exitCode).toBeUndefined();
+ expect(seen).toEqual([['spring', '/opt/alice-example/gbrain']]);
+ });
+
test('probe failure warns + exits 1 + never echoes the token', async () => {
const r = await runWithExitCapture(
['https://brain.example.com/mcp', '--token', 'gbrain_secret', '--install', '--yes'],
diff --git a/test/skill-loading-lanes.test.ts b/test/skill-loading-lanes.test.ts
index eef936eda3..ff73061dd4 100644
--- a/test/skill-loading-lanes.test.ts
+++ b/test/skill-loading-lanes.test.ts
@@ -18,7 +18,7 @@ import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { withEnv } from './helpers/with-env.ts';
import { BRAIN_FIRST_END, brainFirstTargetAt } from '../src/core/setup/brain-first.ts';
-import { installerSkillsBlock, loaderAllowRule, readSkillLoadingLedger, refreshSkillsIndexes, skillsIndexViews, skillsOutcomeFailed, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END, type SkillsBlockOutcome } from '../src/core/setup/skills-block.ts';
+import { describeSkillsBlockOutcome, installerSkillsBlock, loaderAllowRule, readSkillLoadingLedger, refreshSkillsIndexes, skillsIndexViews, skillsOutcomeFailed, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END, type SkillsBlockOutcome } from '../src/core/setup/skills-block.ts';
import { removeHarnessBrainFirst, writeHarnessBrainFirst } from '../src/core/bootstrap/harness-brain-first.ts';
import { installHarnessConnection } from '../src/core/harness/install.ts';
import { removeHarnessSkillsIndex, writeHarnessSkillsIndex } from '../src/core/bootstrap/harness-skills-index.ts';
@@ -286,6 +286,20 @@ describe('Claude Code loader rule', () => {
});
});
+ test('a rule the user had before gbrain and then deleted is not added back by a remembered choice', async () => {
+ const b = box();
+ await withEnv(b.env, async () => {
+ const s = setup(b);
+ mkdirSync(dirname(s.settings), { recursive: true });
+ writeFileSync(s.settings, JSON.stringify({ permissions: { allow: [s.rule] } }));
+ s.spring(s.user);
+ writeFileSync(s.settings, JSON.stringify({ permissions: { allow: [] } }));
+ expect(s.spring(s.user, {}).detail).toContain('--skill-loading spring');
+ expect(allowList(s.settings)).toEqual([]);
+ expect(readSkillLoadingLedger()[0]).toMatchObject({ allow_owned: false, allow_declined: true });
+ });
+ });
+
test('a rule the user removed is not added back by a remembered choice, only by an explicit --skill-loading spring', async () => {
const b = box();
await withEnv(b.env, async () => {
@@ -439,6 +453,91 @@ describe('Claude Code loader rule: refresh, dry-run, ledger failures', () => {
});
});
+ for (const order of ['owner first', 'declined first'] as const) {
+ test(`decline on both indexes, explicit re-grant on one: the rule still comes out with the last removal (${order})`, async () => {
+ const b = box();
+ await withEnv(b.env, async () => {
+ const c = ctx(b);
+ const project = brainFirstTargetAt('claude-code', join(b.root, 'repo', 'CLAUDE.md'));
+ mkdirSync(dirname(project.path), { recursive: true });
+ const runProject = (extra: Record<string, unknown>) => installerSkillsBlock({ target: project, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, ...extra });
+ c.run();
+ runProject({ skillLoading: 'spring' });
+ writeFileSync(c.settings, JSON.stringify({ permissions: { allow: [] } }));
+ c.run({});
+ runProject({});
+ expect(readSkillLoadingLedger().every(e => e.allow_declined === true)).toBe(true);
+ expect(c.run().permission).toMatchObject({ change: 'added' });
+ if (order === 'owner first') { c.run({ remove: true }); runProject({ remove: true }); } else { runProject({ remove: true }); c.run({ remove: true }); }
+ expect(readSkillLoadingLedger()).toEqual([]);
+ expect(allowList(c.settings)).toEqual([]);
+ });
+ });
+ }
+
+ test('a ledger write that fails during a launcher change puts the old rule back, so a plain retry keeps it', async () => {
+ const b = box();
+ const other = join(b.root, 'other-install', 'gbrain');
+ mkdirSync(dirname(other), { recursive: true });
+ copyFileSync(LAUNCHER, other);
+ chmodSync(other, 0o755);
+ await withEnv(b.env, async () => {
+ const c = ctx(b);
+ c.run();
+ const dir = join(b.home, '.gbrain');
+ chmodSync(dir, 0o500);
+ let failed: SkillsBlockOutcome;
+ try {
+ failed = installerSkillsBlock({ target: c.target, launcher: other, writer: 'test', brainFirstDeclined: false, skillLoading: 'spring' });
+ } finally {
+ chmodSync(dir, 0o755);
+ }
+ expect(failed).toMatchObject({ action: 'preserve', reason: 'write_failed' });
+ expect(allowList(c.settings)).toEqual([c.rule]);
+ const retry = c.run({});
+ expect(retry.action).toBe('keep');
+ expect(readSkillLoadingLedger()[0]).toMatchObject({ allow_owned: true });
+ expect(readSkillLoadingLedger()[0].allow_declined).toBeUndefined();
+ });
+ });
+
+ test('a ledger row that claims ownership without its rule is refused', async () => {
+ const b = box();
+ await withEnv(b.env, async () => {
+ const c = ctx(b);
+ c.run();
+ const ledger = join(b.home, '.gbrain', 'skill-loading.json');
+ const doc = JSON.parse(read(ledger));
+ delete doc.entries[0].allow_rule;
+ writeFileSync(ledger, JSON.stringify(doc));
+ expect(c.run({ skillLoading: 'off' })).toMatchObject({ action: 'preserve', reason: 'ledger_unreadable' });
+ expect(allowList(c.settings)).toEqual([c.rule]);
+ });
+ });
+
+ test('dry-run previews are complete: human lines name the rule, a batch opt-out removes a shared rule once, a launcher change shows both rules', async () => {
+ const b = box();
+ const other = join(b.root, 'other-install', 'gbrain');
+ mkdirSync(dirname(other), { recursive: true });
+ copyFileSync(LAUNCHER, other);
+ chmodSync(other, 0o755);
+ await withEnv(b.env, async () => {
+ const c = ctx(b);
+ const preview = c.run({ skillLoading: 'spring', dryRun: true });
+ expect(describeSkillsBlockOutcome(preview, true)).toContain(`would add Claude Code permission ${c.rule} in ${c.settings}`);
+ c.run();
+ const project = brainFirstTargetAt('claude-code', join(b.root, 'repo', 'CLAUDE.md'));
+ mkdirSync(dirname(project.path), { recursive: true });
+ installerSkillsBlock({ target: project, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, skillLoading: 'spring' });
+ const batch = refreshSkillsIndexes('claude-code', { mode: 'off', dryRun: true });
+ expect(batch.filter(o => o.permission?.change === 'would_remove')).toHaveLength(1);
+ expect(allowList(c.settings)).toEqual([c.rule]);
+ const swap = refreshSkillsIndexes('claude-code', { launcher: other, dryRun: true });
+ expect(swap.some(o => o.permission?.change === 'would_add' && o.permission.rule === loaderAllowRule(other))).toBe(true);
+ expect(swap.filter(o => o.replaced_permission?.change === 'would_remove')).toHaveLength(1);
+ });
+ });
+
test('an explicit spring skipped for a reason the user must fix counts as failed; a remembered one does not', () => {
const base = { harness: 'hermes', path: '/home/alice-example/.hermes/SOUL.md', action: 'skip', state_before: 'no_file', detail: 'x', reason: 'hermes_soul_missing' } as const;
expect(skillsOutcomeFailed({ ...base, decision: { value: 'spring', source: 'flag' } })).toBe(true);