Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

skills: /review fixes — embed guard in verify, module-size ceiling, agent-contract-clean skills_failed, connect removal leaves another connection index, default run leaves an unrecorded index, decline clears on re-add, unreadable instruction file refuses, remove restores rule on strip failure, doctor launcher check on stale, root-safe chmod tests

garrytan67481d6e2ef3
diff --git a/scripts/generate-bundled-skills.ts b/scripts/generate-bundled-skills.ts
index 49a7c1ef70..81f98b17ca 100644
--- a/scripts/generate-bundled-skills.ts
+++ b/scripts/generate-bundled-skills.ts
@@ -2,7 +2,7 @@
/**
* Generate src/core/skills/bundled-skills.generated.ts: gbrain's bundled
* skills (the plugin lane, skills/plugin-lanes.json) embedded as text imports,
- * so the spring-loaded skill index and `get_skill bundled:true` work from a
+ * so the spring-loaded skill index and `gbrain bundled-skill` work from a
* compiled binary with no skills/ directory beside it.
*
* bun run scripts/generate-bundled-skills.ts write
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 53970c21e2..4649e3fb95 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -38,7 +38,7 @@ src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
src/core/config.ts 2009 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured)
src/core/persistence/sync-run.ts 1682 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives)
-src/core/bootstrap/harness.ts 2605 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts)
+src/core/bootstrap/harness.ts 2621 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments); +13 brain-first block lane: --no-instructions flag field + parse, opencodeAgentsPath dep (field + default) and the step-10b / remove call sites (logic lives in harness-brain-first.ts); +16 GBRA-194 skills index lane: --skill-loading flag field + parse, step-10b and remove call sites, skills_index JSON field and exit-code wiring (logic lives in harness-skills-index.ts and setup/skills-block.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts)
src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured)
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 9b10122ad5..89e4841726 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -68,6 +68,8 @@ CHECKS=(
"check:admin-build"
"check:wasm"
"check:pglite-embedded"
+ # gbrain's bundled skills survive bun build --compile byte-identical (GBRA-194).
+ "check:skills-embedded"
# HEIC + AVIF decoders survive bun build --compile (~0.6s: the smoketest
# bundles a handful of modules, not the CLI).
"check:image-decoders"
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index b5e2b60c87..5690b3a05c 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -75,14 +75,14 @@ import {
import type { CodexSetupEvent } from '../core/bootstrap/codex-hooks.ts';
import {
describeSkillsBlockOutcome,
+ InvalidSkillLoadingEnv,
isSkillLoading,
- priorSkillLoading,
indexLauncher,
readSkillLoadingLedger,
refreshSkillsIndexes,
removeSkillsBlock,
- resolveSkillLoading,
installerSkillsBlock,
+ SKILL_LOADING_ENV,
skillsOutcomeFailed,
type SkillLoading,
type SkillsBlockOutcome,
@@ -231,8 +231,8 @@ function parseFlags(args: string[]): SetupFlags | string {
if (workspace !== undefined && !workspace.startsWith('/') && !workspace.startsWith('~')) return '--workspace needs an absolute path';
const skillLoading = value('--skill-loading');
if (skillLoading !== undefined && !isSkillLoading(skillLoading)) return `unknown --skill-loading '${skillLoading}'; pass off or spring`;
- const envLoading = process.env.GBRAIN_SKILL_LOADING?.trim();
- if (skillLoading === undefined && envLoading && !isSkillLoading(envLoading)) return `GBRAIN_SKILL_LOADING='${envLoading}' is not a skill-loading mode; set it to off or spring, or unset it`;
+ const envLoading = process.env[SKILL_LOADING_ENV]?.trim();
+ if (skillLoading === undefined && envLoading && !isSkillLoading(envLoading)) return new InvalidSkillLoadingEnv(envLoading).message;
return {
harness: positionals[0],
dryRun: args.includes('--dry-run'),
diff --git a/src/core/harness/install.ts b/src/core/harness/install.ts
index b5a040f4f3..b09182f24b 100644
--- a/src/core/harness/install.ts
+++ b/src/core/harness/install.ts
@@ -19,8 +19,8 @@ import { installSharedSkillsConnection } from './shared-skills.ts';
import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';
import { harnessSharedSkillsRoot } from './status.ts';
import { gitChildEnv } from '../git-env.ts';
-import { brainFirstTargetAt, codexInstructionFile, installerBrainFirst, renderBrainFirstSnippet, resolveBrainFirstDecision, type BrainFirstHarness } from '../setup/brain-first.ts';
-import { indexLauncher, installerSkillsBlock, isSkillLoading, renderSkillsSnippet, resolveSkillLoading, skillsOutcomeFailed, type SkillLoading } from '../setup/skills-block.ts';
+import { brainFirstTargetAt, codexInstructionFile, installerBrainFirst, readBrainFirstLedger, renderBrainFirstSnippet, resolveBrainFirstDecision, type BrainFirstHarness } from '../setup/brain-first.ts';
+import { indexLauncher, inspectSkillsBlock, installerSkillsBlock, isSkillLoading, renderSkillsSnippet, resolveSkillLoading, skillsOutcomeFailed, type SkillLoading, type SkillsBlockOutcome } from '../setup/skills-block.ts';
export interface InstallOptions { harness: string; name?: string; root?: string; configPath?: string; remove?: boolean;
sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string; credentialsFile?: string; freshToken?: boolean;
@@ -180,24 +180,25 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst
const beside = instructionFileBeside(adapter.connection, configPath);
const instructions = installerBrainFirst({ target: brainFirstTargetAt(beside.harness, beside.path), access: { kind: 'mcp', server: name },
writer: `gbrain connect --harness ${adapter.id} --install`, instructions: opts.instructions, remove: opts.remove });
- const skills = installerSkillsBlock({ target: brainFirstTargetAt(beside.harness, beside.path), launcher: opts.gbrainBin ?? indexLauncher() ?? 'gbrain',
+ const keptForOther = opts.remove && readBrainFirstLedger().some((b) => b.harness === beside.harness && b.path === beside.path && b.status === 'installed' && b.access.kind === 'mcp' && b.access.server !== name);
+ const skills = keptForOther
+ ? { harness: beside.harness, path: beside.path, decision: { value: 'off', source: 'flag' }, action: 'skip', state_before: inspectSkillsBlock(beside.path).state, detail: `the skills index in ${beside.path} sits beside another connection's brain-first block, so removing \`${name}\` leaves it` } satisfies SkillsBlockOutcome
+ : installerSkillsBlock({ target: brainFirstTargetAt(beside.harness, beside.path), launcher: opts.gbrainBin ?? indexLauncher() ?? 'gbrain',
writer: `gbrain connect --harness ${adapter.id} --install`, brainFirstDeclined: instructions.decision.value === 'declined', skillLoading: opts.skillLoading, audience: 'downstream', remove: opts.remove });
- const skillsProblem = skillsOutcomeFailed(skills) ? `The skills index step did not finish: ${skills.detail}. Fix that, then re-run this command (the skills record is kept, so a re-run finishes it).` : undefined;
+ const skillsFailed = skillsOutcomeFailed(skills) ? { skills_failed: true } : {};
if (opts.remove) {
if (existsSync(receiptPath)) unlinkSync(receiptPath);
const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });
const pending = 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true;
- const next = pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.'
- : 'The client configuration was removed. Revoke the grant on the brain host if access should end.';
- return { ...common, status: 'removed', config_path: configPath, shared_skills, remote_membership_pending: pending, instructions, skills,
- ...(skillsProblem ? { skills_failed: true } : {}), next_action: skillsProblem ? `${skillsProblem} ${next}` : next };
+ return { ...common, status: 'removed', config_path: configPath, shared_skills, remote_membership_pending: pending, instructions, skills, ...skillsFailed,
+ next_action: pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.'
+ : 'The client configuration was removed. Revoke the grant on the brain host if access should end.' };
}
const nextReceipt = { ...common, entry_hash: ownedEntryHash(nativeEntry(configPath, adapter.connection, name), adapter.connection), status: 'installed',
...inlineTokenReceipt(c, adapter.id, name, configPath, adapter.reload, opts.credentialsFile) };
atomicWriteTextFile(receiptPath, `${JSON.stringify(nextReceipt, null, 2)}\n`, { forceMode: 0o600 });
const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });
- return { ...nextReceipt, shared_skills, instructions, skills, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true,
- ...(skillsProblem ? { skills_failed: true, next_action: `${skillsProblem} ${nextReceipt.next_action}` } : {}) };
+ return { ...nextReceipt, shared_skills, instructions, skills, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true, ...skillsFailed };
} finally { lock.release(); }
}
@@ -225,7 +226,7 @@ async function installThinClient(c: HarnessCredentials, opts: InstallOptions, co
const sourceCli = fileURLToPath(new URL('../../cli.ts', import.meta.url));
const launcher = join(root, 'bin', 'gbrain');
const brainFirst = resolveBrainFirstDecision(opts.instructions, prior.brain_first_instructions === 'declined' ? { status: 'declined' } : undefined).value;
- const skillLoading = brainFirst === 'declined' ? 'off' : resolveSkillLoading(opts.skillLoading, isSkillLoading(prior.skill_loading) ? { mode: prior.skill_loading } : undefined).value;
+ const skillLoading = opts.remove || brainFirst === 'declined' ? 'off' : resolveSkillLoading(opts.skillLoading, isSkillLoading(prior.skill_loading) ? { mode: prior.skill_loading } : undefined).value;
const rerun = `gbrain connect ${shellQuote(c.mcp_url)} --harness ${shellQuote(opts.harness)} --credentials-file <private-handoff-file> --root ${shellQuote(root)} --install`;
const skillsIndex = skillLoading === 'spring' ? renderSkillsSnippet(opts.harness, launcher, 'downstream', { refresh: rerun, optOut: `${rerun} --skill-loading off` }) : '';
const instructionsHead = `${brainFirst === 'declined' ? '' : renderBrainFirstSnippet(opts.harness, { kind: 'cli', launcher }, 're-run gbrain connect with --no-instructions')}${skillsIndex}`;
diff --git a/src/core/setup/skills-block.ts b/src/core/setup/skills-block.ts
index c80f1ea200..2869f5f259 100644
--- a/src/core/setup/skills-block.ts
+++ b/src/core/setup/skills-block.ts
@@ -229,18 +229,20 @@ function loaderRulePresent(settings: string, rule: string): boolean | undefined
}
}
+/** 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 || !existsSync(settings)) return false;
+ const present = loaderRulePresent(settings, rule);
+ if (present !== false) return false;
+ return true;
+}
+
/**
* Add the rule after the block is in place; returns the ownership to record,
* whether this call added it, and whether it stayed out because the user
* 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 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 || loaderRulePresent(settings, rule) === false;
-}
-
function grantLoader(harness: string, launcher: string, settings: string, prior: SkillLoadingLedgerEntry | undefined, regrant: boolean): { grant: Grant; added: boolean; declined: boolean } {
if (harness !== 'claude-code') return { grant: {}, added: false, declined: false };
const rule = loaderAllowRule(launcher);
@@ -250,11 +252,6 @@ function grantLoader(harness: string, launcher: string, settings: string, prior:
return { grant: { allow_rule: rule, allow_settings: settings, allow_owned: added || shared }, added, declined: false };
}
-/**
- * Remove a rule gbrain owns once no other recorded index uses it. Never
- * throws: `problem` says why the rule is still there, `removed` names the
- * rule when this call took it out of the settings.
- */
/** The owned rule revokeLoader would take out for this entry, or undefined when it has none to take or another index still uses it. Throws on an unreadable ledger. */
function revocableRule(entry: SkillLoadingLedgerEntry | undefined, keep?: { rule?: string; settings: string }): { rule: string; settings: string } | undefined {
if (!entry?.allow_rule || entry.allow_owned !== true) return undefined;
@@ -271,6 +268,11 @@ function plannedPermission(change: 'would_add' | 'would_remove', target: { rule:
return { permission: { ...target, change } };
}
+/**
+ * Remove a rule gbrain owns once no other recorded index uses it. Never
+ * throws: `problem` says why the rule is still there, `removed` names the
+ * rule when this call took it out of the settings.
+ */
function revokeLoader(entry: SkillLoadingLedgerEntry | undefined, keep?: { rule?: string; settings: string }): { removed?: { rule: string; settings: string }; problem?: string } {
if (!entry?.allow_rule || entry.allow_owned !== true) return {};
const rule = entry.allow_rule;
@@ -321,7 +323,13 @@ export type SkillsBlockState = 'no_file' | 'absent' | 'current' | 'stale' | 'dam
*/
export function inspectSkillsBlock(path: string, expected?: string): { state: SkillsBlockState; version?: number; catalog?: string } {
if (!existsSync(path)) return { state: 'no_file' };
- const probe = probeBlock(MARKERS, readFileSync(path, 'utf8'));
+ let text: string;
+ try {
+ text = readFileSync(path, 'utf8');
+ } catch {
+ return { state: 'damaged' };
+ }
+ const probe = probeBlock(MARKERS, text);
if (probe.state !== 'present') return { state: probe.state };
const interior = probe.interior ?? '';
const version = Number(/gbrain skills v(\d+)/.exec(interior)?.[1] ?? 0);
@@ -381,7 +389,7 @@ const message = (e: unknown) => (e instanceof Error ? e.message : String(e));
* outcome with a reason, and the file is left as it was unless the detail
* says otherwise.
*/
-export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience; verifyLauncher?: boolean; settingsPath?: string }): SkillsBlockOutcome {
+export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience; settingsPath?: string }): SkillsBlockOutcome {
const { target, launcher, decision } = opts;
const settings = opts.settingsPath ?? claudeUserSettingsPath();
const audience = opts.audience ?? 'owner';
@@ -412,6 +420,9 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stri
return out('preserve', `the skills markers in ${target.path} were hand-edited (duplicate, orphan or out of order); fix or delete them, then re-run`, { reason: 'damaged_markers' });
}
if (decision.value === 'off') {
+ if (decision.source === 'default' && !prior && (before.state === 'current' || before.state === 'stale')) {
+ return out('skip', `the skills index in ${target.path} is not in this gbrain's record (${skillLoadingLedgerPath()}); another gbrain home or install probably wrote it, so it is left as it is. Pass --skill-loading off to remove it from here`);
+ }
const revocation = opts.dryRun ? {} : revokeLoader(prior);
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' } }
@@ -439,14 +450,12 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stri
}
if (body === undefined) return out('preserve', `${tooLarge!.message}; ${target.path} was left as it was`, { reason: 'index_too_large' });
- if (opts.verifyLauncher !== false) {
- const served = launcherCatalog(launcher);
- if ('error' in served) return out('preserve', `${served.error}; ${target.path} was left as it was. Pass --gbrain-bin <absolute path of this gbrain>`, { reason: 'launcher_unusable' });
- if (served.catalog !== bundledCatalogId()) {
- return out('preserve', `${launcher} serves skill catalog ${served.catalog}, not this gbrain's ${bundledCatalogId()}, so the index would load other text than it lists; ${target.path} was left as it was. Pass --gbrain-bin <absolute path of this gbrain>, or upgrade that install`, { reason: 'launcher_catalog_mismatch' });
- }
+ const served = launcherCatalog(launcher);
+ if ('error' in served) return out('preserve', `${served.error}; ${target.path} was left as it was. Pass --gbrain-bin <absolute path of this gbrain>`, { reason: 'launcher_unusable' });
+ if (served.catalog !== bundledCatalogId()) {
+ return out('preserve', `${launcher} serves skill catalog ${served.catalog}, not this gbrain's ${bundledCatalogId()}, so the index would load other text than it lists; ${target.path} was left as it was. Pass --gbrain-bin <absolute path of this gbrain>, or upgrade that install`, { reason: 'launcher_catalog_mismatch' });
}
- if (target.harness === 'hermes' && (before.state === 'no_file' || readFileSync(target.path, 'utf8').trim() === '')) {
+ if (target.harness === 'hermes' && (before.state === 'no_file' || (() => { try { return readFileSync(target.path, 'utf8').trim() === ''; } catch { return true; } })())) {
return out('skip', `${target.path} is missing or empty, and Hermes uses a non-empty SOUL.md instead of its default identity; start Hermes once (it seeds SOUL.md) or write your identity there, then re-run`, { reason: 'hermes_soul_missing' });
}
const brainFirstCreated = readBrainFirstLedger().find((e) => e.harness === target.harness && e.path === target.path)?.created_file ?? false;
@@ -572,7 +581,8 @@ export function removeSkillsBlock(opts: { harness: string; path: string; dryRun:
if (deleteFile) unlinkSync(opts.path);
else writeUnlessChanged(opts.path, existing, false, stripped);
} catch (e) {
- return out('preserve', `${opts.path} could not be updated (${message(e)}); the skills index is still there`, { reason: 'write_failed' });
+ const left = revocation.removed ? undoUnrecorded({ path: opts.path, settings: revocation.removed.settings, restore: revocation.removed }) : [];
+ return out('preserve', `${opts.path} could not be updated (${message(e)}); the skills index is still there${left.length ? `, and gbrain could not put back ${revocation.removed!.rule} in ${revocation.removed!.settings}; add it back by hand` : ''}`, { reason: 'write_failed' });
}
}
try { dropLedger(opts.harness, opts.path); } catch (e) {
@@ -657,7 +667,7 @@ export function skillsIndexViews(): SkillsIndexView[] {
if (unreadable) return [{ harness: '*', path: skillLoadingLedgerPath(), state: 'ledger_unreadable', refresh: unreadable.detail }];
return [...readSkillLoadingLedger().filter((e) => e.mode === 'spring').map((e): SkillsIndexView => {
const state = inspectSkillsBlock(e.path).state;
- if (state === 'current' && e.launcher && isAbsolute(e.launcher) && !launcherRuns(e.launcher)) {
+ if ((state === 'current' || state === 'stale') && e.launcher && isAbsolute(e.launcher) && !launcherRuns(e.launcher)) {
return { harness: e.harness, path: e.path, state: 'launcher_missing', refresh: `${skillsRefreshCommand(e.harness)} --gbrain-bin <absolute path of gbrain>` };
}
return { harness: e.harness, path: e.path, state, refresh: skillsRefreshCommand(e.harness) };
diff --git a/test/skill-loading-lanes.test.ts b/test/skill-loading-lanes.test.ts
index ff73061dd4..d982ee0e90 100644
--- a/test/skill-loading-lanes.test.ts
+++ b/test/skill-loading-lanes.test.ts
@@ -32,6 +32,8 @@ const LAUNCHER = join(BIN_DIR, 'gbrain');
writeFileSync(LAUNCHER, '#!/bin/sh\nexec \'' + process.execPath + '\' --no-env-file \'' + CLI + '\' "$@"\n');
chmodSync(LAUNCHER, 0o755);
const roots: string[] = [];
+/** chmod-based failure probes cannot fail for root (the ci:local container). */
+const asRoot = process.getuid?.() === 0;
afterAll(() => { for (const r of [...roots, BIN_DIR]) rmSync(r, { recursive: true, force: true }); });
function box() {
const root = mkdtempSync(join(tmpdir(), 'gbrain-skill-lanes-'));
@@ -88,6 +90,20 @@ describe('connect --harness --install', () => {
});
}
+ test('removing one connection leaves the skills index beside another connection\'s brain-first block', async () => {
+ const b = box();
+ await withEnv(b.env, async () => {
+ const configPath = join(b.home, '.claude.json');
+ const file = join(b.home, '.claude', 'CLAUDE.md');
+ await installHarnessConnection(credentials, { harness: 'claude-code', configPath, name: 'conn-a', skillLoading: 'spring', gbrainBin: LAUNCHER });
+ await installHarnessConnection(credentials, { harness: 'claude-code', configPath, name: 'conn-b', gbrainBin: LAUNCHER });
+ const removed = await installHarnessConnection(credentials, { harness: 'claude-code', configPath, name: 'conn-a', remove: true }) as any;
+ expect(removed.skills.action).toBe('skip');
+ expect(read(file)).toContain(SKILLS_BLOCK_BEGIN);
+ expect(readSkillLoadingLedger()).toHaveLength(1);
+ });
+ });
+
test('a requested index that is not written is flagged in the result and its next_action', async () => {
const b = box();
await withEnv(b.env, async () => {
@@ -95,7 +111,7 @@ describe('connect --harness --install', () => {
const r = await installHarnessConnection(credentials, { harness: 'codex', configPath, skillLoading: 'spring', gbrainBin: join(b.root, 'missing', 'gbrain') }) as any;
expect(r.skills).toMatchObject({ action: 'preserve', reason: 'launcher_unusable' });
expect(r.skills_failed).toBe(true);
- expect(r.next_action).toContain('skills index step did not finish');
+ expect(r.next_action).not.toContain('skills');
});
});
@@ -339,7 +355,7 @@ describe('Claude Code loader rule', () => {
});
for (const how of ['off', 'remove'] as const) {
- test(`a settings write that fails during ${how} is a typed refusal that keeps the index and the record`, async () => {
+ test.skipIf(asRoot)(`a settings write that fails during ${how} is a typed refusal that keeps the index and the record`, async () => {
const b = box();
await withEnv(b.env, async () => {
const s = setup(b);
@@ -428,7 +444,7 @@ describe('Claude Code loader rule: refresh, dry-run, ledger failures', () => {
});
});
- test('a ledger write that fails undoes the block and the rule, so a retry and opt-out leave nothing behind', async () => {
+ test.skipIf(asRoot)('a ledger write that fails undoes the block and the rule, so a retry and opt-out leave nothing behind', async () => {
const b = box();
await withEnv(b.env, async () => {
const c = ctx(b);
@@ -475,7 +491,7 @@ describe('Claude Code loader rule: refresh, dry-run, ledger failures', () => {
});
}
- test('a ledger write that fails during a launcher change puts the old rule back, so a plain retry keeps it', async () => {
+ test.skipIf(asRoot)('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 });
@@ -538,6 +554,47 @@ describe('Claude Code loader rule: refresh, dry-run, ledger failures', () => {
});
});
+ test('another gbrain home\'s index is left alone by a default run here', async () => {
+ const b = box();
+ await withEnv(b.env, async () => {
+ const c = ctx(b);
+ c.run();
+ const written = read(c.target.path);
+ await withEnv({ GBRAIN_HOME: join(b.root, 'second-home') }, async () => {
+ expect(c.run({})).toMatchObject({ action: 'skip', decision: { source: 'default' } });
+ });
+ expect(read(c.target.path)).toBe(written);
+ expect(allowList(c.settings)).toEqual([c.rule]);
+ });
+ });
+
+ test('a rule the user adds back by hand clears the decline; a missing settings file is not a decline', async () => {
+ const b = box();
+ await withEnv(b.env, async () => {
+ const c = ctx(b);
+ c.run();
+ writeFileSync(c.settings, JSON.stringify({ permissions: { allow: [] } }));
+ c.run({});
+ expect(readSkillLoadingLedger()[0].allow_declined).toBe(true);
+ writeFileSync(c.settings, JSON.stringify({ permissions: { allow: [c.rule] } }));
+ expect(c.run({}).detail).not.toContain('will ask');
+ expect(readSkillLoadingLedger()[0].allow_declined).toBeUndefined();
+ rmSync(c.settings);
+ expect(c.run({}).detail).not.toContain('will ask');
+ expect(readSkillLoadingLedger()[0].allow_declined).toBeUndefined();
+ });
+ });
+
+ test('an instruction path gbrain cannot read is a refusal, never a throw', async () => {
+ const b = box();
+ await withEnv(b.env, async () => {
+ const dir = join(b.home, 'agents', 'AGENTS.md');
+ mkdirSync(dir, { recursive: true });
+ const o = installerSkillsBlock({ target: brainFirstTargetAt('opencode', dir), launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, skillLoading: 'spring' });
+ expect(o.action).toBe('preserve');
+ });
+ });
+
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);