Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

shared skills: refresh a superseded enrollment epoch and converge rotation leaves (#5878)

garrytanbaf4abe31b56
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9e37799487..7631d61404 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -28,7 +28,7 @@ src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unl
src/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
-src/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics
+src/commands/bootstrap.ts 2120 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts)
src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry
src/commands/sources.ts 2013 ratchet +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts)
src/core/link-extraction.ts 2143 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note
@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 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)
src/core/config.ts 1813 ratchet +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
-src/core/bootstrap/harness.ts 2690 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); +16 #5893: rotation grant carry wiring (carry rules live in token-mint.ts carryLegacyGrant)
+src/core/bootstrap/harness.ts 2696 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); +16 #5893: rotation grant carry wiring (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.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 626 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
src/core/search/mode.ts 1527 ratchet +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
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index b74ac80022..056d822139 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -83,6 +83,7 @@ import {
type HarnessDeps,
type HarnessDetectOverrides,
} from '../core/bootstrap/harness.ts';
+import { refreshHarnessSkills } from '../core/bootstrap/harness-skills.ts';
import { claudeUserSettingsPath, codexConfigPath, opencodeConfigDir, opencodeGlobalConfigPath, opencodeProjectConfigPath } from '../core/bootstrap/host-specs.ts';
import {
opencodeEntryKind,
@@ -137,7 +138,7 @@ Subcommands (run \`gbrain bootstrap status\` first — it is the resume entrypoi
attach [--harness H] Machine two: adopt a cloned agent workspace.
harness [--harness claude-code|codex|opencode|all] [--url U | --port N] [--source ID]
[--token-name NAME | --token TOK] [--name MCPNAME] [--project DIR]...
- [--no-hooks] [--no-capture] [--force] [--status] [--remove] [--yes] [--json]
+ [--no-hooks] [--no-capture] [--force] [--status] [--remove] [--refresh-skills] [--yes] [--json]
Wire framework-spawned Claude Code / Codex / opencode
sessions to a RUNNING \`gbrain serve --http\` on this box
(#4043): scoped bearer token, user-scope MCP + headless
@@ -147,6 +148,9 @@ Subcommands (run \`gbrain bootstrap status\` first — it is the resume entrypoi
--source ID: the source the hooks + token bind to
(default: sources.default, else the sole populated
non-default source, else default).
+ --refresh-skills: re-join shared skills under the
+ recorded credential so the router adopts the current
+ enrollment epoch (no token rotation).
(--local is an accepted no-op alias.)
cloud-setup-script Print the paste-ready cloud environment setup
script (installs the gbrain binary into the
@@ -1744,6 +1748,7 @@ async function runHarness(rest: string[], home: string, runner: ExecRunner, dete
}
ensureHarnessHome(home);
return withLock(home, async () => {
+ if (flags.refreshSkills) return refreshHarnessSkills(deps);
if (flags.remove) {
const code = await removeHarness(flags, deps);
abortIfInjected('harness');
diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.ts
index e36d3f4049..7b874527fa 100644
--- a/src/commands/doctor/bootstrap-checks.ts
+++ b/src/commands/doctor/bootstrap-checks.ts
@@ -9,7 +9,7 @@ import { execFileSync } from 'child_process';
import type { BrainEngine } from '../../core/engine.ts';
import { LATEST_VERSION } from '../../core/migrate.ts';
// Agent-bootstrap doctor group (plan B2/B4/ENG-4 + one-live-serve note).
-import { readHarnessReceiptState, readReceipt } from '../../core/bootstrap/format.ts';
+import { readHarnessReceiptState, readReceipt, type HarnessReceipt } from '../../core/bootstrap/format.ts';
import { probeLivePgliteHolder, resolveBrainDataDir } from '../../core/bootstrap/uninstall.ts';
import { readRunbookStamp, hooksInstalled, listVerifyRuns } from '../../core/bootstrap/status.ts';
import { resolveGbrainHome } from '../../core/gbrain-home.ts';
@@ -24,6 +24,22 @@ import type { Check } from '../doctor.ts';
* `gbrain bootstrap` get ZERO checks from this group. Every probe is
* fail-soft: a broken telemetry file degrades to a warn, never a throw.
*/
+/** #5878: warn when a shared-skills receipt epoch differs from this brain's membership row; true when it pushed. */
+async function pushSupersededEnrollmentCheck(checks: Check[], engine: BrainEngine | null, hr: HarnessReceipt): Promise<boolean> {
+ if (!engine) return false;
+ const { supersededEnrollments, SKILLS_REFRESH_COMMAND, SKILLS_EPOCH_DOCS } = await import('../../core/bootstrap/harness-skills.ts');
+ const superseded = await supersededEnrollments(engine, hr).catch(() => []);
+ if (superseded.length === 0) return false;
+ checks.push({
+ name: 'bootstrap_harness_health',
+ status: 'warn',
+ message: `shared skills enrollment superseded: ${superseded.map(e => `${e.host} receipt epoch ${e.local_epoch}, server epoch ${e.server_epoch}${e.active ? '' : ' (inactive)'}`).join('; ')} ` +
+ `— sessions get membership_inactive. Fix: ${SKILLS_REFRESH_COMMAND} (${SKILLS_EPOCH_DOCS}).`,
+ details: { code: 'shared_skills_epoch_superseded', fix: SKILLS_REFRESH_COMMAND, docs: SKILLS_EPOCH_DOCS, enrollments: superseded },
+ });
+ return true;
+}
+
export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise<Check[]> {
const checks: Check[] = [];
let home: string;
@@ -143,7 +159,7 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise
status: 'fail',
message: `harness removal pending: host wiring removed but the minted token (id ${hr.token.id}) is not yet revoked — stop the serve and re-run \`gbrain bootstrap harness\` with the remove flag, or run \`gbrain auth revoke\` with the id flag.`,
});
- } else {
+ } else if (!(await pushSupersededEnrollmentCheck(checks, engine, hr))) {
try {
const base = hr.url.replace(/\/mcp$/, '');
const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(3000) });
diff --git a/src/core/bootstrap/harness-skills.ts b/src/core/bootstrap/harness-skills.ts
new file mode 100644
index 0000000000..036a65aef0
--- /dev/null
+++ b/src/core/bootstrap/harness-skills.ts
@@ -0,0 +1,101 @@
+/**
+ * #5878: shared-skills enrollment refresh for bootstrap-managed installations.
+ *
+ * `gbrain bootstrap harness --refresh-skills` re-runs the adapter's join for
+ * every live shared-skills entry on the harness receipt, under that entry's
+ * own stored credential and follow policy, so the local receipt and the
+ * native router adopt the server's current enrollment epoch (an MCP
+ * leave/join by the same principal moves the epoch on and leaves the router
+ * calling `sync_brain_skills` with a superseded one). No token is minted or
+ * revoked. `localEnrollment` is the one reader of the adapter receipt's
+ * epoch, shared with `--status` and doctor.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { readCredentials } from '../harness/credentials.ts';
+import { redactToken } from '../mcp-registration.ts';
+import type { BrainEngine } from '../engine.ts';
+import { readHarnessReceiptState, writeHarnessReceipt, type HarnessReceipt } from './format.ts';
+import { resolveHarnessDeps, type HarnessDeps } from './harness.ts';
+
+export const SKILLS_REFRESH_COMMAND = 'gbrain bootstrap harness --refresh-skills';
+export const SKILLS_EPOCH_DOCS = 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment';
+
+/** The adapter receipt's enrollment, or undefined when the entry never enrolled. */
+export function localEnrollment(root: string): { installation_id: string; enrollment_epoch: number } | undefined {
+ const path = join(root, 'shared-skills', 'receipt.json');
+ if (!existsSync(path)) return undefined;
+ try {
+ const receipt = JSON.parse(readFileSync(path, 'utf8')) as { installation_id?: unknown; enrollment_epoch?: unknown };
+ if (typeof receipt.installation_id !== 'string' || !Number.isSafeInteger(receipt.enrollment_epoch)) return undefined;
+ return { installation_id: receipt.installation_id, enrollment_epoch: receipt.enrollment_epoch as number };
+ } catch {
+ return undefined;
+ }
+}
+
+export async function refreshHarnessSkills(rawDeps: HarnessDeps): Promise<number> {
+ const d = resolveHarnessDeps(rawDeps);
+ const state = readHarnessReceiptState(d.gbrainHome);
+ if (state.state !== 'ok') {
+ d.logError(`no readable harness receipt (${state.state}); run \`gbrain bootstrap harness\` first.`);
+ return 1;
+ }
+ const receipt = state.receipt;
+ const entries = (receipt.shared_skills ?? []).filter(entry => !entry.status.startsWith('left') && localEnrollment(entry.root));
+ if (entries.length === 0) {
+ d.log('no shared-skills enrollment to refresh (skills policy follow enrolls on the next `gbrain bootstrap harness`).');
+ return 0;
+ }
+ let ok = true;
+ for (const entry of entries) {
+ const before = localEnrollment(entry.root)!.enrollment_epoch;
+ let token = '';
+ try {
+ const credentials = readCredentials(join(entry.root, 'credentials.json'));
+ token = credentials.access_token ?? '';
+ if (credentials.mcp_url !== entry.url) throw new Error('credential endpoint mismatch');
+ const result = await d.installSharedSkills(credentials, {
+ harness: entry.host, root: entry.root, name: entry.name, nativeSkillsDir: d.nativeSkillsDir(entry.host),
+ });
+ entry.status = result.status;
+ entry.reason = result.reason ? redactToken(result.reason, token) : undefined;
+ const after = localEnrollment(entry.root)?.enrollment_epoch ?? before;
+ const refreshed = ['restart_required', 'advisory_refresh'].includes(result.status);
+ ok = ok && refreshed;
+ const line = `shared skills (${entry.host}): enrollment epoch ${before}${after !== before ? ` -> ${after}` : ' (current)'}; ` +
+ `${result.status}${entry.reason ? ` — ${entry.reason}` : ''}. ${result.next_action ?? ''}`.trim();
+ (refreshed ? d.log : d.logError)(redactToken(line, token));
+ } catch (error) {
+ ok = false;
+ entry.status = 'pending';
+ entry.reason = 'shared_skills_unavailable';
+ d.logError(redactToken(`shared skills (${entry.host}): refresh failed (${error instanceof Error ? error.message : String(error)}); ` +
+ 'memory remains independent. Re-run `gbrain bootstrap harness` to re-enroll with a fresh credential.', token));
+ }
+ writeHarnessReceipt(d.gbrainHome, receipt);
+ }
+ return ok ? 0 : 1;
+}
+
+/**
+ * Doctor's comparison (read-only): live harness entries whose adapter receipt
+ * epoch differs from this brain's membership row, or whose membership is no
+ * longer active. Installations this brain does not hold are skipped.
+ */
+export async function supersededEnrollments(engine: Pick<BrainEngine, 'executeRaw'>, receipt: HarnessReceipt): Promise<Array<{
+ host: string; installation_id: string; local_epoch: number; server_epoch: number; active: boolean;
+}>> {
+ const out = [];
+ for (const entry of receipt.shared_skills ?? []) {
+ if (entry.status.startsWith('left')) continue;
+ const local = localEnrollment(entry.root);
+ if (!local) continue;
+ const [row] = await engine.executeRaw<{ epoch: number | string; active: boolean }>(
+ 'SELECT epoch, active FROM shared_skill_members WHERE installation_id = $1::uuid', [local.installation_id]);
+ if (row && (Number(row.epoch) !== local.enrollment_epoch || row.active !== true)) {
+ out.push({ host: entry.host, installation_id: local.installation_id, local_epoch: local.enrollment_epoch, server_epoch: Number(row.epoch), active: row.active === true });
+ }
+ }
+ return out;
+}
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 0857bbe95f..df4b106c48 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -71,6 +71,7 @@ import { carryLegacyGrant, mintLegacyToken, readActiveTokenPermissions, revokeLe
import { generateToken } from '../utils.ts';
import { readCredentials, writeCredentials, type HarnessCredentials } from '../harness/credentials.ts';
import { installSharedSkillsConnection, type SharedSkillsConnectionOptions } from '../harness/shared-skills.ts';
+import { localEnrollment, SKILLS_REFRESH_COMMAND } from './harness-skills.ts';
import { nativeSharedSkillsDirectory } from '../harness/native-router.ts';
import { sqlQueryForEngine } from '../sql-query.ts';
import { BootstrapError, acquireBootstrapLock } from './lock.ts';
@@ -154,6 +155,7 @@ export interface HarnessFlags {
force: boolean;
remove: boolean;
status: boolean;
+ refreshSkills: boolean;
yes: boolean;
json: boolean;
gbrainBin?: string;
@@ -173,6 +175,7 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {
force: false,
remove: false,
status: false,
+ refreshSkills: false,
yes: false,
json: false,
};
@@ -251,6 +254,7 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {
out.force = rest.includes('--force');
out.remove = rest.includes('--remove');
out.status = rest.includes('--status');
+ out.refreshSkills = rest.includes('--refresh-skills');
out.yes = rest.includes('--yes');
out.json = rest.includes('--json');
const bin = value('--gbrain-bin');
@@ -262,6 +266,7 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {
if (out.status && out.remove) {
out.error = out.error ?? 'pass --status OR --remove, not both';
}
+ if (out.refreshSkills && (out.status || out.remove)) out.error = out.error ?? 'pass --refresh-skills alone, not with --status or --remove';
// --user-hooks and --local are accepted, documented no-ops (script clarity).
// Unknown/typo'd flags never reach this parser through the CLI: cli.ts
// validates argv against CLI_FLAG_REGISTRY pre-dispatch and rejects them
@@ -332,7 +337,7 @@ export interface HarnessDeps {
logError?: (line: string) => void;
}
-function resolveDeps(deps: HarnessDeps): Required<Omit<HarnessDeps, 'gbrainBin'>> & { gbrainBin: string | null } {
+export function resolveHarnessDeps(deps: HarnessDeps): Required<Omit<HarnessDeps, 'gbrainBin'>> & { gbrainBin: string | null } {
return {
runner: deps.runner,
gbrainHome: deps.gbrainHome,
@@ -647,7 +652,7 @@ export function parseClaudeMcpGetUrl(out: string): ClaudeMcpGetInfo {
async function cleanupStalePriorTargets(
prior: HarnessReceipt,
receipt: HarnessReceipt,
- d: ReturnType<typeof resolveDeps>,
+ d: ReturnType<typeof resolveHarnessDeps>,
save: () => void,
): Promise<void> {
const planned = receipt.targets;
@@ -778,7 +783,7 @@ async function harnessOperationSnapshot(follow: boolean): Promise<string[]> {
async function leaveHarnessSkills(
entry: NonNullable<HarnessReceipt['shared_skills']>[number],
- d: ReturnType<typeof resolveDeps>,
+ d: ReturnType<typeof resolveHarnessDeps>,
): Promise<boolean> {
try {
if (entry.status === 'left' || entry.status === 'left_with_retained_files') return true;
@@ -838,7 +843,7 @@ function logAmbientPostureNotes(
}
export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Promise<number> {
- const d = resolveDeps(rawDeps);
+ const d = resolveHarnessDeps(rawDeps);
// stdout-for-data discipline: under --json, stdout carries ONLY the final
// JSON document; every prose/progress line flows to stderr (matching the
// statusHarness --json contract, so machine callers never scrape).
@@ -2010,7 +2015,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// ── Remove [C9/F2/C8] ───────────────────────────────────────────────────────
export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Promise<number> {
- const d = resolveDeps(rawDeps);
+ const d = resolveHarnessDeps(rawDeps);
const state = readHarnessReceiptState(d.gbrainHome);
if (state.state === 'absent') {
d.log('nothing harness-installed on this machine (no harness receipt).');
@@ -2298,7 +2303,7 @@ export function parseCodexBlockBearer(configText: string, expectedUrl?: string):
/** `bootstrap harness --status [--json]` — one screen of live health. */
export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Promise<number> {
- const d = resolveDeps(rawDeps);
+ const d = resolveHarnessDeps(rawDeps);
const state = readHarnessReceiptState(d.gbrainHome);
if (state.state === 'absent') {
if (flags.json) {
@@ -2493,7 +2498,8 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
d.log(serveLine);
d.log(tokenLine);
for (const entry of receipt.shared_skills ?? []) {
- d.log(` shared skills (${entry.host}): ${entry.status}${entry.reason ? ` — ${entry.reason}` : ''}; receipt evidence only, native activation unverified.`);
+ const epoch = localEnrollment(entry.root)?.enrollment_epoch;
+ d.log(` shared skills (${entry.host}): ${entry.status}${entry.reason ? ` — ${entry.reason}` : ''}${epoch === undefined ? '' : `; enrollment epoch ${epoch}`}; receipt evidence only, native activation unverified (stale epoch: ${SKILLS_REFRESH_COMMAND}).`);
if (entry.retained_files?.length) d.log(` edited files retained: ${entry.retained_files.join(', ')}`);
}
for (const t of liveTargets) {
diff --git a/src/core/shared-skills/adapter.ts b/src/core/shared-skills/adapter.ts
index bccacb839a..832e97f751 100644
--- a/src/core/shared-skills/adapter.ts
+++ b/src/core/shared-skills/adapter.ts
@@ -264,9 +264,14 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
receipt.remote_membership_pending = false;
delete receipt.remote_membership_reason;
} catch (error) {
- receipt.remote_membership_pending = true;
- receipt.remote_membership_reason = error instanceof OperationError ? error.code : 'remote_unavailable';
- receipt.next_action += ' Remote membership deactivation is pending; retry leave when the host can acknowledge it.';
+ if (error instanceof OperationError && error.code === 'membership_inactive') {
+ receipt.remote_membership_pending = false;
+ receipt.remote_membership_reason = 'superseded';
+ } else {
+ receipt.remote_membership_pending = true;
+ receipt.remote_membership_reason = error instanceof OperationError ? error.code : 'remote_unavailable';
+ receipt.next_action += ' Remote membership deactivation is pending; retry leave when the host can acknowledge it.';
+ }
}
save(receipt);
return receipt;
diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.ts
index e52ddbe822..2908185e61 100644
--- a/test/bootstrap-harness.serial.test.ts
+++ b/test/bootstrap-harness.serial.test.ts
@@ -216,6 +216,8 @@ describe('parseHarnessArgs', () => {
expect(parseHarnessArgs(['--source', 'Not Valid']).error).toMatch(/invalid --source/);
expect(parseHarnessArgs(['--source', '__all__']).error).toMatch(/invalid --source/);
expect(parseHarnessArgs(['--source', 'wiki']).source).toBe('wiki');
+ expect(parseHarnessArgs(['--refresh-skills']).refreshSkills).toBe(true);
+ expect(parseHarnessArgs(['--refresh-skills', '--status']).error).toMatch(/--refresh-skills alone/);
});
test('--project is repeatable and resolved', () => {
const f = parseHarnessArgs(['--project', '/a', '--project', '/b']);
diff --git a/test/harness-skills-epoch.test.ts b/test/harness-skills-epoch.test.ts
new file mode 100644
index 0000000000..13ad7b79c5
--- /dev/null
+++ b/test/harness-skills-epoch.test.ts
@@ -0,0 +1,71 @@
+/**
+ * #5878: a bootstrap-managed shared-skills installation converges after the
+ * same principal re-enrolls over MCP (leave_brain + join_brain moves the
+ * server epoch on), against the real membership server behind the legacy
+ * HTTP transport on PGLite (and on Postgres when DATABASE_URL is set).
+ *
+ * Protects: doctor's epoch comparison (`supersededEnrollments`) names the
+ * stale receipt; `gbrain bootstrap harness --refresh-skills`
+ * (`refreshHarnessSkills`) makes the receipt and the native router adopt the
+ * current epoch under the recorded credential; a local leave whose own epoch
+ * was superseded completes instead of staying `remote_membership_pending`
+ * forever (which blocked rotation from revoking the previous token).
+ * Regression it catches: the pre-fix adapter, where only `join` rewrote the
+ * receipt and `leave` treated `membership_inactive` as a pending retry.
+ */
+import { expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { call, withTransportFixture } from './fixtures/shared-skills-transports.ts';
+import { writeCredentials, type HarnessCredentials } from '../src/core/harness/credentials.ts';
+import { installSharedSkillsConnection } from '../src/core/harness/shared-skills.ts';
+import { writeHarnessReceipt, type HarnessReceipt } from '../src/core/bootstrap/format.ts';
+import { localEnrollment, refreshHarnessSkills, supersededEnrollments } from '../src/core/bootstrap/harness-skills.ts';
+
+test('re-enrollment over MCP is detected, refreshed in place and leaves converge', async () => {
+ await withTransportFixture(async f => {
+ await f.seed();
+ const peer = f.peers.reader;
+ const home = join(f.dir, 'gbrain-home');
+ const root = join(home, 'bootstrap', 'shared-skills', 'codex', randomUUID());
+ const nativeSkillsDir = join(f.dir, 'codex-skills');
+ const credentials: HarnessCredentials = { version: 1, mcp_url: f.url, issuer_url: f.url.replace(/\/mcp$/, ''),
+ client_id: peer.id, access_token: peer.token, shared_skills: { follow: true } };
+ writeCredentials(join(root, 'credentials.json'), credentials);
+ const installed = await installSharedSkillsConnection(credentials, { harness: 'codex', root, name: 'gbrain', nativeSkillsDir });
+ expect(installed.status).toBe('restart_required');
+ const first = localEnrollment(root)!;
+ const receipt = { harness_receipt_version: 1, created_at: new Date().toISOString(), created_by: 'test', url: f.url, source_id: 'default',
+ token: { name: 'bootstrap-harness', minted: false }, skills_policy: 'follow', harness_tokens: {}, targets: [],
+ shared_skills: [{ host: 'codex', root, name: 'gbrain', url: f.url, status: installed.status }] } as HarnessReceipt;
+ writeHarnessReceipt(home, receipt);
+ expect(await supersededEnrollments(f.engine, receipt)).toEqual([]);
+
+ await call(peer.client, 'leave_brain', { installation_id: first.installation_id, enrollment_epoch: first.enrollment_epoch });
+ const rejoined = await call<{ enrollment_epoch: number }>(peer.client, 'join_brain', { adapter: 'codex', follow_policy: { approved: true } });
+ expect(rejoined.enrollment_epoch).toBe(first.enrollment_epoch + 1);
+ await expect(call(peer.client, 'sync_brain_skills', { installation_id: first.installation_id, enrollment_epoch: first.enrollment_epoch }))
+ .rejects.toMatchObject({ code: 'membership_inactive' });
+ expect(await supersededEnrollments(f.engine, receipt)).toEqual([{ host: 'codex', installation_id: first.installation_id,
+ local_epoch: first.enrollment_epoch, server_epoch: rejoined.enrollment_epoch, active: true }]);
+
+ const output: string[] = [];
+ expect(await refreshHarnessSkills({ gbrainHome: home, runner: async () => ({ code: 0, stdout: '', stderr: '' }),
+ nativeSkillsDir: () => nativeSkillsDir, log: line => output.push(line), logError: line => output.push(line) })).toBe(0);
+ expect(output.join('\n')).toContain(`enrollment epoch ${first.enrollment_epoch} -> ${rejoined.enrollment_epoch}`);
+ expect(localEnrollment(root)).toEqual({ installation_id: first.installation_id, enrollment_epoch: rejoined.enrollment_epoch });
+ const adapterReceipt = JSON.parse(readFileSync(join(root, 'shared-skills', 'receipt.json'), 'utf8')) as { native_router_path: string };
+ expect(readFileSync(adapterReceipt.native_router_path, 'utf8')).toContain(`enrollment_epoch ${rejoined.enrollment_epoch}`);
+ expect(await supersededEnrollments(f.engine, receipt)).toEqual([]);
+ expect(output.join('\n')).not.toContain(peer.token);
+
+ await call(peer.client, 'leave_brain', { installation_id: first.installation_id, enrollment_epoch: rejoined.enrollment_epoch });
+ await call(peer.client, 'join_brain', { adapter: 'codex', follow_policy: { approved: true } });
+ const left = await installSharedSkillsConnection(credentials, { harness: 'codex', root, name: 'gbrain', nativeSkillsDir, remove: true }) as {
+ status: string; remote_membership_pending?: boolean; remote_membership_reason?: string };
+ expect(left.status).toBe('left');
+ expect(left.remote_membership_pending).toBe(false);
+ expect(left.remote_membership_reason).toBe('superseded');
+ }, process.env.DATABASE_URL);
+}, 180_000);