Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

agent contract: shared-skills refusals name their own next step

garrytanda2205472e94
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 52731e3155..f9d0ffea0e 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -273,6 +273,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| Reserved by MEMORY_VERBS v1; never returned. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |
+### cache_quota_exceeded
+
+<a id="cache_quota_exceeded"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Retained shared-skill revisions reached this installation's local cache quota. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+
### cancelled
<a id="cancelled"></a>
@@ -281,6 +291,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| The write was cancelled before it committed. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### catalog_capacity_exceeded
+
+<a id="catalog_capacity_exceeded"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The shared-skills catalog visible to this connection exceeds the delivery limits. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+
### catalog_unavailable
<a id="catalog_unavailable"></a>
@@ -761,6 +781,16 @@ More: [docs/guides/write-refusals.md#fetch_failed](../../docs/guides/write-refus
|---|---|---|---|---|---|---|
| The file is over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read), so it was not imported. | Size limits bound parsing, chunking and embedding cost. The same bytes refuse on every retry. | Split the file into smaller files, or leave it out of the source (sync.exclude), then sync or import again. | agent | `repeat the read that failed` | 1 | no |
+### follow_approval_required
+
+<a id="follow_approval_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Following a brain's shared skills needs the user's explicit follow approval. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately](../../docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately)
+
### frontmatter_slug_conflict
<a id="frontmatter_slug_conflict"></a>
@@ -897,6 +927,16 @@ More: [docs/guides/write-refusals.md#fetch_failed](../../docs/guides/write-refus
|---|---|---|---|---|---|---|
| The operation was interrupted by a signal before it finished. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 130 | no |
+### invalid_acknowledgment
+
+<a id="invalid_acknowledgment"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The shared-skills delivery acknowledgment does not match a batch issued to this enrollment. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+
### invalid_client
<a id="invalid_client"></a>
@@ -1057,6 +1097,26 @@ More: [docs/guides/repair.md#legacy-jobs-active](../../docs/guides/repair.md#leg
More: [docs/guides/write-refusals.md#managed_pull_skipped](../../docs/guides/write-refusals.md#managed_pull_skipped)
+### membership_inactive
+
+<a id="membership_inactive"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The shared-skills enrollment epoch was left or superseded. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment](../../docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment)
+
+### membership_not_found
+
+<a id="membership_not_found"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| This principal has no shared-skills membership with that installation id. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+
### method_not_allowed
<a id="method_not_allowed"></a>
@@ -1679,6 +1739,16 @@ Reasons: `lock_held`, `no_brain`, `config_unreadable`, `missing_brain`, `brain_u
|---|---|---|---|---|---|---|
| Retained skill revisions exceed this source storage budget. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### skill_unavailable
+
+<a id="skill_unavailable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The qualified shared skill is not in this installation's current authorized view. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+
### source_binding_required
<a id="source_binding_required"></a>
@@ -1759,6 +1829,16 @@ Reasons: `lock_held`, `no_brain`, `config_unreadable`, `missing_brain`, `brain_u
|---|---|---|---|---|---|---|
| Split unparseable. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### stale_unavailable
+
+<a id="stale_unavailable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| No complete, current authorized shared-skills view is available; cached shared skills stay unused. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)
+
### state_mismatch
<a id="state_mismatch"></a>
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 4b6b3ddec5..b1c27623fa 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -3,7 +3,6 @@ src/commands/book-mirror.ts 1
src/core/company-brain/policy.ts 2
src/core/company-brain/receipts.ts 1
src/core/facts/backstop.ts 1
-src/core/harness/native-router.ts 1
src/core/minions/submission-authority.ts 1
src/core/minions/tool-write-identity.ts 1
src/core/page-state/import-guard.ts 1
@@ -11,7 +10,5 @@ src/core/persistence/effect-facts.ts 3
src/core/persistence/effect-journal.ts 1
src/core/persistence/effect-targets.ts 2
src/core/search/evidence-delivery.ts 1
-src/core/shared-skills/adapter.ts 2
-src/core/shared-skills/membership.ts 1
src/core/source-local-reference-index.ts 2
src/mcp/dispatch.ts 1
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 02d15a8203..9d0ec6c1f6 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -75,7 +75,9 @@ export const CODES = {
bridge_ownership_conflict: { class: 'caller', summary: "The private local CLI registration is invalid." },
bucket_not_found: { class: 'unavailable', summary: "The configured storage bucket does not exist." },
budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },
+ cache_quota_exceeded: { class: 'caller', summary: "Retained shared-skill revisions reached this installation's local cache quota.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },
+ catalog_capacity_exceeded: { class: 'caller', summary: "The shared-skills catalog visible to this connection exceeds the delivery limits.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },
changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },
chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },
@@ -133,6 +135,7 @@ export const CODES = {
facts_payload_expired: { class: 'server', summary: "The accepted fact extraction failed and its retained payload has expired." },
fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },
file_too_large: { class: 'caller', summary: "The file is over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read), so it was not imported.", why: "Size limits bound parsing, chunking and embedding cost. The same bytes refuse on every retry.", suggestion: 'Split the file into smaller files, or leave it out of the source (sync.exclude), then sync or import again.' },
+ follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },
full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },
@@ -150,6 +153,7 @@ export const CODES = {
internal: { class: 'server', summary: "A memory verb failed on the server; this is not a caller mistake." },
internal_error: { class: 'server', summary: "The server failed while running the operation; this is not a caller mistake." },
interrupted: { class: 'server', summary: "The operation was interrupted by a signal before it finished.", exit: 130 },
+ invalid_acknowledgment: { class: 'caller', summary: "The shared-skills delivery acknowledgment does not match a batch issued to this enrollment.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
invalid_client: { class: 'caller', summary: "Google connect credential error: invalid client.", docs: 'docs/guides/google-connect.md#troubleshooting' },
invalid_connector_text: { class: 'caller', summary: "Invalid connector text." },
invalid_frontmatter: { class: 'caller', summary: "The file's YAML frontmatter cannot be read without guessing, so it was not imported.", why: "gbrain imports frontmatter it can read exactly (quoting an unquoted value at most). Guessing could store a wrong title, merge a duplicate, or read a protected key such as `visibility` as a broader value.", reasons: ['yaml_parse', 'needs_interpretation', 'ambiguous_identity_key', 'ambiguous_protected_key'], suggestion: 'Fix the named line in the file (one line per key, the whole value quoted), then commit and sync or import again.' },
@@ -168,6 +172,8 @@ export const CODES = {
local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },
lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },
managed_pull_skipped: { class: 'retryable', summary: "The managed pull was skipped." },
+ membership_inactive: { class: 'caller', summary: "The shared-skills enrollment epoch was left or superseded.", docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' },
+ membership_not_found: { class: 'caller', summary: "This principal has no shared-skills membership with that installation id.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },
migration_failed: { class: 'server', summary: "A migration orchestrator failed, so the migration chain stopped; finished migrations stay recorded.",
reasons: ['orchestrator_failed', 'orchestrator_threw', 'ledger_write_failed', 'preview_failed', 'schema_failed'] },
@@ -242,6 +248,7 @@ export const CODES = {
skill_candidate_invalid: { class: 'caller', summary: "The optimized candidate changed protected frontmatter or has an empty/invalid body." },
skill_not_found: { class: 'caller', summary: "No authorized published skill matches this key." },
skill_retention_capacity: { class: 'caller', summary: "Retained skill revisions exceed this source storage budget." },
+ skill_unavailable: { class: 'caller', summary: "The qualified shared skill is not in this installation's current authorized view.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
source_binding_required: { class: 'caller', summary: "A write needs an explicit source binding on this MCP server (--source-guard)." },
source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed." },
source_id_taken: { class: 'caller', summary: "This source already exists and does not match this exact admitted request." },
@@ -252,6 +259,7 @@ export const CODES = {
source_writeback_required: { class: 'host_only', summary: "Canonical preparation requires a source-content correction; this profile never writes repository files." },
split_bad_ratio: { class: 'caller', summary: "Split bad ratio." },
split_unparseable: { class: 'caller', summary: "Split unparseable." },
+ stale_unavailable: { class: 'unavailable', summary: "No complete, current authorized shared-skills view is available; cached shared skills stay unused.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
storage_error: { class: 'server', summary: "Reading or writing durable storage failed." },
sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own.", reasons: ['content_directory'] },
diff --git a/src/core/harness/native-router.ts b/src/core/harness/native-router.ts
index a1fb7ca592..7d11e37844 100644
--- a/src/core/harness/native-router.ts
+++ b/src/core/harness/native-router.ts
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
import { claudeUserSkillsDir, opencodeConfigDir } from '../bootstrap/host-specs.ts';
import { assertNoSymlinks, checkedRoot, confinedPath, privateWrite, sha256 } from '../agent-install/state.ts';
import { acquireNativeLock } from '../persistence/native-lock.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
import { harnessAdapter } from './registry.ts';
interface RouterIdentity { brain_id: string; installation_id: string; adapter: string }
@@ -32,24 +32,30 @@ export function nativeSharedSkillsDirectory(harness: string): string | null {
return null;
}
-function conflict(): never { throw new OperationError('local_conflict', 'The native shared-brain router is unowned, edited, or bound to another installation. Preserve it before retrying.'); }
+function conflict(suggestion: string): never {
+ throw opError('local_conflict', 'The native shared-brain router is unowned, edited, or bound to another installation. Preserve it before retrying.', suggestion,
+ { docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' });
+}
function readReceipt(root: string): NativeRouterReceipt | null {
const path = confinedPath(root, 'native-router.json');
if (!existsSync(path)) return null;
try {
const stat = lstatSync(path);
- if (!stat.isFile() || stat.size > 65_536) return conflict();
+ if (!stat.isFile() || stat.size > 65_536) return conflict(`${path} is not a regular receipt file. Copy it aside for the user; with it moved away, the next join or refresh records a new one.`);
const value = JSON.parse(readFileSync(path, 'utf8')) as NativeRouterReceipt;
- if (value.version !== 1 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.name) || !['prepared', 'installed', 'removed'].includes(value.state)) return conflict();
+ if (value.version !== 1 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.name) || !['prepared', 'installed', 'removed'].includes(value.state)) return conflict(`${path} is not a native-router receipt this gbrain wrote. Copy it aside for the user; with it moved away, the next join or refresh records a new one.`);
checkedRoot(value.skills_dir);
return value;
- } catch { return conflict(); }
+ } catch (error) {
+ if (error instanceof OperationError && error.code === 'local_conflict') throw error;
+ return conflict(`${path} is unreadable or names an unsafe skills directory. Copy it aside for the user; with it moved away, the next join or refresh records a new one.`);
+ }
}
function hashAt(path: string): string | null {
assertNoSymlinks(path);
if (!existsSync(path)) return null;
const stat = lstatSync(path);
- if (!stat.isFile() || stat.size > 256 * 1024) return conflict();
+ if (!stat.isFile() || stat.size > 256 * 1024) return conflict(`${path} is not the router file gbrain installed (a directory or an oversized file). Move it aside after the user confirms, then refresh.`);
return sha256(readFileSync(path));
}
export function recordedNativeSkillsDirectory(stateRoot: string): string | undefined {
@@ -58,11 +64,14 @@ export function recordedNativeSkillsDirectory(stateRoot: string): string | undef
function validate(plan: NativeRouterPlan): NativeRouterReceipt | null {
const prior = readReceipt(plan.state_root);
if (prior && (prior.name !== plan.name || prior.skills_dir !== plan.skills_dir || prior.brain_id !== plan.brain_id ||
- prior.installation_id !== plan.installation_id || prior.adapter !== plan.adapter)) return conflict();
+ prior.installation_id !== plan.installation_id || prior.adapter !== plan.adapter)) return conflict(
+ `${plan.state_root} already routes installation ${prior.installation_id} (${prior.adapter}) into ${prior.skills_dir}. Leave that installation first, or give this connection its own state directory.`);
const current = hashAt(plan.path);
const directory = confinedPath(plan.skills_dir, plan.name);
- if (!prior && existsSync(directory) && readdirSync(directory).length) return conflict();
- if (current !== null && (!prior || ![prior.owned_hash, prior.pending?.before, prior.pending?.after].includes(current))) return conflict();
+ if (!prior && existsSync(directory) && readdirSync(directory).length) return conflict(
+ `${directory} already holds files gbrain did not record. Have the user move that directory aside, then join again.`);
+ if (current !== null && (!prior || ![prior.owned_hash, prior.pending?.before, prior.pending?.after].includes(current))) return conflict(
+ `${plan.path} was edited after gbrain installed it. Show the user the edit; once they keep a copy and restore or remove the file, refresh again.`);
return prior;
}
@@ -70,7 +79,8 @@ export function prepareNativeRouter(input: RouterIdentity & { state_root: string
const state_root = checkedRoot(input.state_root);
const skills_dir = checkedRoot(input.skills_dir);
const name = `gbrain-shared-${sha256(JSON.stringify([input.brain_id, input.installation_id, input.adapter, input.connection_name])).slice(0, 24)}`;
- if (!input.content.startsWith('---\nname: gbrain-shared-router\n')) return conflict();
+ if (!input.content.startsWith('---\nname: gbrain-shared-router\n')) return conflict(
+ 'The router content does not start with the gbrain-shared-router frontmatter; this gbrain build produced an unexpected router. Report it with gbrain --version.');
const plan = { ...input, state_root, skills_dir, name, path: confinedPath(skills_dir, `${name}/SKILL.md`),
content: input.content.replace('name: gbrain-shared-router\n', `name: ${name}\n`) };
validate(plan);
@@ -81,7 +91,7 @@ export async function installNativeRouter(plan: NativeRouterPlan): Promise<{ pat
assertNoSymlinks(plan.skills_dir);
mkdirSync(plan.skills_dir, { recursive: true, mode: 0o700 });
const lock = await acquireNativeLock(confinedPath(plan.skills_dir, `.gbrain-${plan.name}.lock`), { timeoutMs: 5000 });
- if (!lock) return conflict();
+ if (!lock) return conflict(`Another install of this router holds ${confinedPath(plan.skills_dir, `.gbrain-${plan.name}.lock`)}. Wait for it to finish, then refresh again.`);
try {
const prior = validate(plan);
const after = sha256(plan.content);
diff --git a/src/core/shared-skills/adapter.ts b/src/core/shared-skills/adapter.ts
index 832e97f751..4210fe43d4 100644
--- a/src/core/shared-skills/adapter.ts
+++ b/src/core/shared-skills/adapter.ts
@@ -2,7 +2,8 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, lstatSync
import { isAbsolute, join } from 'node:path';
import { assertNoSymlinks, checkedRoot, confinedPath, privateWrite, sha256 } from '../agent-install/state.ts';
import { acquireNativeLock } from '../persistence/native-lock.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError, type OpErrorOpts } from '../ops/contract.ts';
+import type { RegistryCode } from '../error-registry.ts';
import { harnessAdapter } from '../harness/registry.ts';
import { installNativeRouter, prepareNativeRouter, recordedNativeSkillsDirectory, removeNativeRouter } from '../harness/native-router.ts';
import { SHARED_SKILLS_DELIVERY_LIMITS, sharedSkillKey, type FollowPolicy, type MembershipSnapshot, type SharedSkillIdentity } from './membership-types.ts';
@@ -44,21 +45,26 @@ interface SkillFile { path: string; sha256: string; size?: number; content?: str
interface SkillBundle extends SharedSkillIdentity { content?: string; body?: string; usable?: boolean; unavailable_requirements?: unknown[];
delivery?: 'complete' | 'prose_only'; files?: SkillFile[]; manifest?: { files: SkillFile[] } }
const MAX_BYTES = 32 * 1024 * 1024;
+const TROUBLESHOOT = 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover';
export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
const root = checkedRoot(options.root);
const adapter = harnessAdapter(options.adapter);
- if (options.launcher && (!isAbsolute(options.launcher) || /[\x00-\x1f]/.test(options.launcher))) throw new OperationError('invalid_params', 'The launcher must be an absolute installation-bound path.');
+ if (options.launcher && (!isAbsolute(options.launcher) || /[\x00-\x1f]/.test(options.launcher))) throw opError('invalid_params', 'The launcher must be an absolute installation-bound path.',
+ 'Record the launcher as the absolute path of this installation\'s own gbrain binary, with no control characters; reinstalling the harness wiring writes one.');
const receiptPath = join(root, 'receipt.json');
- const fail = (code: string, message: string): never => { throw new OperationError(code, message); };
+ const fail = (code: RegistryCode, message: string, suggestion: string, opts: OpErrorOpts = { docs: TROUBLESHOOT }): never => { throw opError(code, message, suggestion, opts); };
+ const refreshAgain = 'Refresh again for the current authorized view; keep cached shared skills unused until a refresh succeeds. Memory keeps working.';
const save = (receipt: SharedSkillsLocalReceipt) => privateWrite(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`);
function read(): SharedSkillsLocalReceipt | null {
assertNoSymlinks(receiptPath);
if (!existsSync(receiptPath)) return null;
let receipt: SharedSkillsLocalReceipt;
try { receipt = JSON.parse(readFileSync(receiptPath, 'utf8')); }
- catch { return fail('local_conflict', 'The shared-skills ownership receipt is unreadable. Preserve it before recovery.'); }
- if (receipt.format_version !== 1 || receipt.adapter !== adapter.id || !receipt.installation_id || !receipt.owned_files || !receipt.pending_files) fail('local_conflict', 'The cache belongs to a different or unknown installation.');
+ catch { return fail('local_conflict', 'The shared-skills ownership receipt is unreadable. Preserve it before recovery.',
+ `${receiptPath} is not valid JSON. Copy it aside for the user before anything rewrites it; following resumes after the user restores a valid receipt or clears ${root} and joins again.`); }
+ if (receipt.format_version !== 1 || receipt.adapter !== adapter.id || !receipt.installation_id || !receipt.owned_files || !receipt.pending_files) fail('local_conflict', 'The cache belongs to a different or unknown installation.',
+ `${receiptPath} was written for adapter ${String(receipt.adapter)}, not ${adapter.id}, or by an older format. Give this harness its own shared-skills directory, or leave from the installation that owns ${root}.`);
for (const path of [...Object.keys(receipt.owned_files), ...Object.keys(receipt.pending_files)]) confinedPath(root, path);
return receipt;
}
@@ -66,30 +72,37 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
const absolute = confinedPath(root, path);
if (!existsSync(absolute)) return null;
const stat = lstatSync(absolute);
- if (!stat.isFile() || stat.size > MAX_BYTES) return fail('local_conflict', 'A managed file has been replaced by a non-file or oversized file.');
+ if (!stat.isFile() || stat.size > MAX_BYTES) return fail('local_conflict', 'A managed file has been replaced by a non-file or oversized file.',
+ `${absolute} is no longer the file gbrain installed. Move it aside after the user confirms, then refresh; gbrain never overwrites it.`);
return sha256(readFileSync(absolute));
}
function preflight(receipt: SharedSkillsLocalReceipt, files: Map<string, Uint8Array | string>) {
for (const path of new Set([...Object.keys(receipt.owned_files), ...files.keys()])) {
const current = existingHash(path);
const pending = receipt.pending_files[path];
- if (current !== null && current !== receipt.owned_files[path] && current !== pending?.before && current !== pending?.after) fail('local_conflict', 'A managed artifact was edited; preserve it and resolve the native shadow copy before following updates.');
- if (current !== null && path.startsWith('revisions/') && files.has(path) && current !== sha256(files.get(path)!)) fail('local_conflict', 'An immutable revision cannot be rewritten in place.');
+ if (current !== null && current !== receipt.owned_files[path] && current !== pending?.before && current !== pending?.after) fail('local_conflict', 'A managed artifact was edited; preserve it and resolve the native shadow copy before following updates.',
+ `${confinedPath(root, path)} was edited after gbrain installed it. Show the user the edit; once they keep a copy elsewhere and restore or remove the file, refresh again. gbrain never overwrites edits.`);
+ if (current !== null && path.startsWith('revisions/') && files.has(path) && current !== sha256(files.get(path)!)) fail('local_conflict', 'An immutable revision cannot be rewritten in place.',
+ `${confinedPath(root, path)} differs from the published revision. Move it aside after the user confirms; the next refresh writes the published bytes again.`);
}
}
async function locked<T>(fn: () => Promise<T>): Promise<T> {
assertNoSymlinks(root);
mkdirSync(root, { recursive: true, mode: 0o700 });
const lock = await acquireNativeLock(join(root, 'adapter.lock'), { timeoutMs: 5000 });
- if (!lock) return fail('local_conflict', 'Another adapter update is in progress.');
+ if (!lock) return fail('local_conflict', 'Another adapter update is in progress.',
+ `Another join, refresh or leave of this installation holds ${join(root, 'adapter.lock')}. Wait for it to finish, then run this step again.`);
try { return await fn(); } finally { await lock.release(); }
}
function assertSnapshot(snapshot: MembershipSnapshot, receipt?: SharedSkillsLocalReceipt) {
if (snapshot.schema_version !== 2 || snapshot.complete !== true || !Array.isArray(snapshot.skills) || !Array.isArray(snapshot.blocked_skills) || !snapshot.batch_token ||
- (receipt && (snapshot.installation_id !== receipt.installation_id || snapshot.enrollment_epoch !== receipt.enrollment_epoch || snapshot.brain_id !== receipt.brain_id))) fail('stale_unavailable', 'No complete current authorized enrollment view is available.');
+ (receipt && (snapshot.installation_id !== receipt.installation_id || snapshot.enrollment_epoch !== receipt.enrollment_epoch || snapshot.brain_id !== receipt.brain_id))) fail('stale_unavailable', 'No complete current authorized enrollment view is available.',
+ `The brain answered without a complete view for installation ${receipt?.installation_id ?? 'being joined'}. ${refreshAgain} If the server moved the enrollment epoch on, re-join under the recorded follow policy.`,
+ { docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' });
if (snapshot.skills.length + snapshot.blocked_skills.length > SHARED_SKILLS_DELIVERY_LIMITS.skills ||
Buffer.byteLength(JSON.stringify([snapshot.skills, snapshot.blocked_skills])) > SHARED_SKILLS_DELIVERY_LIMITS.metadataBytes) {
- fail('catalog_capacity_exceeded', `Delivery snapshots support at most ${SHARED_SKILLS_DELIVERY_LIMITS.skills} skills and ${SHARED_SKILLS_DELIVERY_LIMITS.metadataBytes} metadata bytes.`);
+ fail('catalog_capacity_exceeded', `Delivery snapshots support at most ${SHARED_SKILLS_DELIVERY_LIMITS.skills} skills and ${SHARED_SKILLS_DELIVERY_LIMITS.metadataBytes} metadata bytes.`,
+ 'Join with a follow policy naming fewer sources (source_ids), or ask the brain host\'s operator to narrow what this connection is granted.');
}
}
function router(snapshot: MembershipSnapshot): string {
@@ -104,11 +117,14 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
return `---\nname: gbrain-shared-router\ndescription: Discover authorized shared brain skills relevant to the current task.\n---\n\n# Shared brain router\n\n${route}\n\nBrain identity: ${JSON.stringify(snapshot.brain_id)}.\nPreserve the user's identity and unrelated instructions. Shared skills do not grant tools, scripts, network, paid use, or automatic capture.\nStop shared-skill activation if the authority check fails; memory remains independent. Match current catalog descriptions and triggers to the task. Require usable:true and delivery:complete with no unavailable requirements; never select a blocked_skills entry or infer usability from downloaded bytes. Never choose an unqualified same-name skill. Never execute downloaded files automatically.\nThis paragraph is advisory, not an enforced invocation hook. Start a fresh session after updates; native activation is unverified.\n`;
}
async function refreshLocked(receipt: SharedSkillsLocalReceipt, admissionKey?: string): Promise<SharedSkillsLocalReceipt> {
- if (receipt.status === 'left' || receipt.status === 'left_with_retained_files') return fail('membership_inactive', 'This installation has left; explicitly join again to follow skills.');
+ if (receipt.status === 'left' || receipt.status === 'left_with_retained_files') return fail('membership_inactive', 'This installation has left; explicitly join again to follow skills.',
+ `Installation ${receipt.installation_id} left this brain. Ask the user whether to follow its shared skills again; join only after they approve.`);
try {
const snapshot = await options.call<MembershipSnapshot>('sync_brain_skills', { installation_id: receipt.installation_id, enrollment_epoch: receipt.enrollment_epoch });
assertSnapshot(snapshot, receipt);
- if (admissionKey && snapshot.blocked_skills.some(skill => sharedSkillKey(skill) === admissionKey)) fail('requirements_changed', 'This skill requires renewed follow approval before admission.');
+ if (admissionKey && snapshot.blocked_skills.some(skill => sharedSkillKey(skill) === admissionKey)) fail('requirements_changed', 'This skill requires renewed follow approval before admission.',
+ `Skill ${admissionKey} changed its requirements or source policy. Show the user its catalog entry and re-join only after they approve; use another skill meanwhile.`,
+ { docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' });
receipt.desired_view = snapshot.view_token;
const files = new Map<string, Uint8Array | string>();
const references: Record<string, { revision: string; files: Record<string, string> }> = {};
@@ -119,7 +135,8 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
const selector = { expected_brain_id: skill.brain_id, source_id: skill.source_id, source_incarnation: skill.source_incarnation,
pack_id: skill.pack_id, name: skill.name, revision: skill.revision };
const bundle = await options.call<SkillBundle>('get_skill', { ...selector, schema_version: 2 });
- if (sharedSkillKey(bundle) !== sharedSkillKey(skill) || bundle.revision !== skill.revision) fail('stale_unavailable', 'The fetched skill does not match the issued immutable revision.');
+ if (sharedSkillKey(bundle) !== sharedSkillKey(skill) || bundle.revision !== skill.revision) fail('stale_unavailable', 'The fetched skill does not match the issued immutable revision.',
+ `The server returned another revision than ${skill.revision} for ${sharedSkillKey(skill)}. ${refreshAgain}`);
if (skill.usable === false || bundle.usable !== true || bundle.delivery !== 'complete' ||
(Array.isArray(skill.unavailable_requirements) && skill.unavailable_requirements.length > 0) || bundle.unavailable_requirements?.length) {
blocked.push({ key: sharedSkillKey(skill), reason: 'requirements_changed' });
@@ -127,18 +144,22 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
continue;
}
const manifest = bundle.manifest?.files ?? bundle.files ?? [];
- if (!Array.isArray(manifest) || !manifest.length || manifest.length > 128) fail('stale_unavailable', 'The server did not return a bounded declared file manifest.');
+ if (!Array.isArray(manifest) || !manifest.length || manifest.length > 128) fail('stale_unavailable', 'The server did not return a bounded declared file manifest.',
+ `${sharedSkillKey(skill)} came with no file manifest or more than 128 files. Ask the brain host's operator to republish it with a declared manifest; the other skills and memory keep working.`);
const paths = new Set<string>();
const ref = { revision: skill.revision, files: {} as Record<string, string> };
for (const file of manifest) {
confinedPath(root, file.path);
- if (paths.has(file.path) || !/^[a-f0-9]{64}$/.test(file.sha256)) fail('stale_unavailable', 'The declared dependency manifest is invalid.');
+ if (paths.has(file.path) || !/^[a-f0-9]{64}$/.test(file.sha256)) fail('stale_unavailable', 'The declared dependency manifest is invalid.',
+ `${sharedSkillKey(skill)} lists ${file.path} twice or without a SHA-256 digest. Ask the brain host's operator to republish the skill; nothing from it was installed.`);
paths.add(file.path);
const asset = await options.call<{ content: string; encoding?: string; sha256?: string }>('get_skill_asset', { ...selector, path: file.path });
- if (typeof asset.content !== 'string' || !['utf8', 'base64', undefined].includes(asset.encoding)) fail('stale_unavailable', 'Unsupported asset encoding.');
+ if (typeof asset.content !== 'string' || !['utf8', 'base64', undefined].includes(asset.encoding)) fail('stale_unavailable', 'Unsupported asset encoding.',
+ `The server sent ${file.path} of ${sharedSkillKey(skill)} in an encoding other than utf8 or base64; the brain host likely runs another gbrain version. Ask its operator to upgrade, then refresh.`);
const bytes = Buffer.from(asset.content, asset.encoding === 'base64' ? 'base64' : 'utf8');
total += bytes.length;
- if (total > MAX_BYTES || bytes.length > 2 * 1024 * 1024 || sha256(bytes) !== file.sha256 || (file.size !== undefined && bytes.length !== file.size)) fail('stale_unavailable', 'The approved bundle exceeded its bounds or failed a hash check.');
+ if (total > MAX_BYTES || bytes.length > 2 * 1024 * 1024 || sha256(bytes) !== file.sha256 || (file.size !== undefined && bytes.length !== file.size)) fail('stale_unavailable', 'The approved bundle exceeded its bounds or failed a hash check.',
+ `${file.path} of ${sharedSkillKey(skill)} is over its size bound or does not match its declared hash, so nothing from it was installed. ${refreshAgain}`);
const cache = `revisions/${sha256(sharedSkillKey(skill))}/${sha256(skill.revision)}/${file.path}`;
files.set(cache, bytes); ref.files[file.path] = cache;
}
@@ -155,10 +176,12 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
for (const path of Object.keys(receipt.owned_files)) {
if (!files.has(path) && existsSync(confinedPath(root, path))) retainedBytes += lstatSync(confinedPath(root, path)).size;
}
- if (retainedBytes + total > MAX_BYTES) fail('cache_quota_exceeded', 'Retained immutable revisions reached the cache quota; leave after native sessions stop before clearing owned files.');
+ if (retainedBytes + total > MAX_BYTES) fail('cache_quota_exceeded', 'Retained immutable revisions reached the cache quota; leave after native sessions stop before clearing owned files.',
+ `${root} holds ${retainedBytes} bytes of older revisions. Once no harness session uses them, leave this installation (it removes unchanged owned files), then join again with the user's approval.`);
const confirm = await options.call<MembershipSnapshot>('sync_brain_skills', { installation_id: receipt.installation_id, enrollment_epoch: receipt.enrollment_epoch });
assertSnapshot(confirm, receipt);
- if (confirm.view_token !== snapshot.view_token) fail('stale_unavailable', 'Authority or revisions changed during download; retry against the new catalog.');
+ if (confirm.view_token !== snapshot.view_token) fail('stale_unavailable', 'Authority or revisions changed during download; retry against the new catalog.',
+ `The catalog changed while it downloaded. ${refreshAgain}`);
receipt.last_authority_check = new Date().toISOString();
for (const [path, bytes] of files) receipt.pending_files[path] = { before: existingHash(path), after: sha256(bytes) };
save(receipt);
@@ -170,7 +193,8 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
}
const pending = receipt.pending_files[path];
const current = existingHash(path);
- if (current !== pending.before && current !== pending.after) fail('local_conflict', 'An artifact changed during installation.');
+ if (current !== pending.before && current !== pending.after) fail('local_conflict', 'An artifact changed during installation.',
+ `Another writer changed ${confinedPath(root, path)} while gbrain installed it. Stop that writer, keep its version for the user, then refresh again.`);
if (current !== pending.after) privateWrite(confinedPath(root, path), bytes);
receipt.owned_files[path] = pending.after;
delete receipt.pending_files[path];
@@ -186,7 +210,8 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
const ack = await options.call<MembershipSnapshot>('sync_brain_skills', { installation_id: receipt.installation_id, enrollment_epoch: receipt.enrollment_epoch,
acknowledgment: { batch_token: snapshot.batch_token, view_token: snapshot.view_token, evidence: { stage: partiallyInstalled ? 'fetched' : 'installed', revisions: snapshot.skills.map(({ brain_id, source_id, source_incarnation, pack_id, name, revision }) => ({ brain_id, source_id, source_incarnation, pack_id, name, revision })) } } });
assertSnapshot(ack, receipt);
- if (ack.view_token !== snapshot.view_token) fail('stale_unavailable', 'A newer authorized catalog is pending; the historical install is not current.');
+ if (ack.view_token !== snapshot.view_token) fail('stale_unavailable', 'A newer authorized catalog is pending; the historical install is not current.',
+ `A newer catalog was published during the install. ${refreshAgain}`);
if (!partiallyInstalled) {
receipt.acknowledged_view = snapshot.view_token;
delete receipt.remote_membership_pending;
@@ -208,10 +233,12 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
status: read,
join: (follow_policy: FollowPolicy) => locked(async () => {
const prior = read();
- if (!prior && readdirSync(root).some(path => path !== 'adapter.lock')) fail('local_conflict', 'Refusing to adopt an unowned shared-skills directory.');
+ if (!prior && readdirSync(root).some(path => path !== 'adapter.lock')) fail('local_conflict', 'Refusing to adopt an unowned shared-skills directory.',
+ `${root} already holds files gbrain did not create. Join with an empty shared-skills directory, or have the user move those files aside first.`);
const snapshot = await options.call<MembershipSnapshot>('join_brain', { adapter: adapter.id, follow_policy });
assertSnapshot(snapshot);
- if (prior && (prior.brain_id !== snapshot.brain_id || prior.installation_id !== snapshot.installation_id)) fail('local_conflict', 'The cache belongs to another principal or brain.');
+ if (prior && (prior.brain_id !== snapshot.brain_id || prior.installation_id !== snapshot.installation_id)) fail('local_conflict', 'The cache belongs to another principal or brain.',
+ `${root} belongs to installation ${prior.installation_id} on brain ${prior.brain_id}. Leave that enrollment first, or give this connection its own shared-skills directory.`);
const receipt: SharedSkillsLocalReceipt = { ...prior, format_version: 1, adapter: adapter.id, brain_id: snapshot.brain_id, installation_id: snapshot.installation_id,
enrollment_epoch: snapshot.enrollment_epoch, status: 'joined', native: 'unverified', router_path: join(root, 'router', 'SKILL.md'), native_registration: 'unverified',
freshness: ['claude-code', 'codex', 'opencode'].includes(adapter.id) ? 'session_refresh' : 'advisory_refresh',
@@ -221,16 +248,21 @@ export function createSharedSkillsAdapter(options: SharedSkillsAdapterOptions) {
}),
refresh: () => locked(async () => {
const receipt = read();
- if (!receipt) return fail('membership_inactive', 'Enroll before syncing this installation.');
+ if (!receipt) return fail('membership_inactive', 'Enroll before syncing this installation.',
+ `No enrollment receipt exists in ${root}. Joining needs the user's follow approval; until then keep using memory only.`);
return refreshLocked(receipt);
}),
admit: (key: string) => locked(async () => {
const receipt = read();
- if (!receipt) return fail('membership_inactive', 'Enroll before using shared skills.');
+ if (!receipt) return fail('membership_inactive', 'Enroll before using shared skills.',
+ `No enrollment receipt exists in ${root}. Joining needs the user's follow approval; until then keep using memory only.`);
await refreshLocked(receipt, key);
- if (receipt.blocked_skills?.some(skill => skill.key === key)) fail('requirements_changed', 'This skill is blocked by current usability or dependency requirements.');
+ if (receipt.blocked_skills?.some(skill => skill.key === key)) fail('requirements_changed', 'This skill is blocked by current usability or dependency requirements.',
+ `Skill ${key} is blocked until its missing requirements or changed policy are approved. Show the user its blocked entry and use another skill meanwhile.`,
+ { docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' });
const reference = JSON.parse(readFileSync(confinedPath(root, 'active.json'), 'utf8'));
- if (!reference.skills[key]) return fail('skill_unavailable', 'This qualified skill is not in the current authorized view.');
+ if (!reference.skills[key]) return fail('skill_unavailable', 'This qualified skill is not in the current authorized view.',
+ `Skill ${key} is not in installation ${receipt.installation_id}'s current view. List the catalog again and pick a usable entry with its exact qualified id.`);
return { ...reference.skills[key], key, admission_view: reference.view_token, native_verified: false };
}),
leave: () => locked(async () => {
diff --git a/src/core/shared-skills/membership.ts b/src/core/shared-skills/membership.ts
index 28778ac6f1..181603579e 100644
--- a/src/core/shared-skills/membership.ts
+++ b/src/core/shared-skills/membership.ts
@@ -1,6 +1,8 @@
import { createHash, randomUUID } from 'node:crypto';
-import type { OperationContext } from '../ops/contract.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { OperationContext, OpErrorOpts } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { hostFix, readFix } from '../ops/op-fix.ts';
+import type { RegistryCode } from '../error-registry.ts';
import type { Principal } from '../persistence/model.ts';
import { harnessAdapter } from '../harness/registry.ts';
import { listSharedSkills } from './catalog.ts';
@@ -44,7 +46,12 @@ interface Batch {
}
const digest = (value: unknown) => createHash('sha256').update(stableJson(value)).digest('hex');
const revisionKey = (skill: SkillDeliveryEntry) => `${sharedSkillKey(skill)}@${skill.revision}`;
-const fail = (code: string, message: string): never => { throw new OperationError(code, message); };
+const fail = (code: RegistryCode, message: string, suggestion: string, opts: OpErrorOpts = {}): never => { throw opError(code, message, suggestion, opts); };
+const catalogFix = readFix('Lists the shared skills this connection can see now, read-only.',
+ { argv: ['gbrain', 'skills', '--schema-version', '2', '--json'], mcp: { tool: 'list_skills', arguments: { schema_version: 2 } } });
+const syncFix = (installationId: string, epoch: number) => readFix('Reads a fresh complete view and batch for this enrollment; no acknowledgment is recorded.',
+ { argv: ['gbrain', 'sync-brain-skills', '--installation-id', installationId, '--enrollment-epoch', String(epoch), '--json'],
+ mcp: { tool: 'sync_brain_skills', arguments: { installation_id: installationId, enrollment_epoch: epoch } } });
async function catalog(ctx: OperationContext): Promise<{ brain_id: string; view_token: string; skills: SkillDeliveryEntry[] }> {
let cursor: string | undefined;
@@ -55,24 +62,33 @@ async function catalog(ctx: OperationContext): Promise<{ brain_id: string; view_
for (let page = 0; page < Math.ceil(SHARED_SKILLS_DELIVERY_LIMITS.skills / 100); page++) {
const result = await listSharedSkills(ctx, { limit: 100, ...(cursor ? { cursor } : {}) });
if (result.schema_version !== 2 || !Array.isArray(result.skills) || (view !== undefined && result.view_token !== view)) {
- fail('catalog_unavailable', 'A complete bounded catalog is required; no local deletion or cursor advancement is safe.');
+ fail('catalog_unavailable', 'A complete bounded catalog is required; no local deletion or cursor advancement is safe.',
+ 'The catalog changed or came back incomplete while it was read, so nothing was delivered or deleted. Call sync_brain_skills again for a fresh complete view, and keep cached skills unused until it succeeds.',
+ { fix: catalogFix });
}
view = result.view_token; brain = result.brain_id;
skills.push(...result.skills.map(skill => ({ ...skill, brain_id: result.brain_id })) as SkillDeliveryEntry[]);
metadataBytes += Buffer.byteLength(JSON.stringify(result.skills));
if (skills.length > SHARED_SKILLS_DELIVERY_LIMITS.skills || metadataBytes > SHARED_SKILLS_DELIVERY_LIMITS.metadataBytes) {
- fail('catalog_capacity_exceeded', `Delivery snapshots support at most ${SHARED_SKILLS_DELIVERY_LIMITS.skills} skills and ${SHARED_SKILLS_DELIVERY_LIMITS.metadataBytes} metadata bytes. Narrow the authorized source view; existing delivery state was preserved.`);
+ fail('catalog_capacity_exceeded', `Delivery snapshots support at most ${SHARED_SKILLS_DELIVERY_LIMITS.skills} skills and ${SHARED_SKILLS_DELIVERY_LIMITS.metadataBytes} metadata bytes. Narrow the authorized source view; existing delivery state was preserved.`,
+ 'Follow fewer sources (follow_policy.source_ids) or ask the brain host\'s operator to narrow the sources this connection is granted; existing delivery state is unchanged.', { fix: catalogFix });
}
cursor = result.next_cursor;
if (!cursor) return { brain_id: brain, view_token: view, skills };
}
- return fail('catalog_capacity_exceeded', `Delivery snapshots support at most ${SHARED_SKILLS_DELIVERY_LIMITS.skills} skills. Narrow the authorized source view; existing delivery state was preserved.`);
+ return fail('catalog_capacity_exceeded', `Delivery snapshots support at most ${SHARED_SKILLS_DELIVERY_LIMITS.skills} skills. Narrow the authorized source view; existing delivery state was preserved.`,
+ 'Follow fewer sources (follow_policy.source_ids) or ask the brain host\'s operator to narrow the sources this connection is granted; existing delivery state is unchanged.', { fix: catalogFix });
}
-function normalizePolicy(policy: FollowPolicy): string[] | null {
- if (policy?.approved !== true) fail('follow_approval_required', 'Approve following this brain’s published skills or continue with memory only.');
+function normalizePolicy(policy: FollowPolicy, adapter: string): string[] | null {
+ if (policy?.approved !== true) fail('follow_approval_required', 'Approve following this brain’s published skills or continue with memory only.',
+ 'Ask the user whether this installation should follow the brain\'s published skills (their instructions get installed in the harness). Only after they agree, join with follow_policy {"approved": true}; otherwise keep using memory only.',
+ { fix: { argv: ['gbrain', 'join-brain', '--adapter', adapter, '--follow-policy', '{"approved":true}', '--json'],
+ mcp: { tool: 'join_brain', arguments: { adapter, follow_policy: { approved: true } } }, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false,
+ why: 'Enrolls this installation to follow approved shared skills; the user decides whether instructions are installed.' } });
if (policy.source_ids === undefined) return null;
- if (!Array.isArray(policy.source_ids) || policy.source_ids.length > 64 || policy.source_ids.some(s => typeof s !== 'string' || !s || s.length > 128)) fail('invalid_params', 'Invalid follow source list.');
+ if (!Array.isArray(policy.source_ids) || policy.source_ids.length > 64 || policy.source_ids.some(s => typeof s !== 'string' || !s || s.length > 128)) fail('invalid_params', 'Invalid follow source list.',
+ 'Send follow_policy.source_ids as up to 64 non-empty source ids of at most 128 characters each, or omit it to follow every source this connection can see.', { fix: catalogFix });
return [...new Set(policy.source_ids)].sort();
}
@@ -83,7 +99,8 @@ async function bindPolicy(ctx: OperationContext, sourceIds: string[] | null): Pr
const allowed = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : null);
const rows = await ctx.engine.executeRaw<{ id: string; incarnation: string }>(`SELECT id,incarnation FROM sources
WHERE NOT archived AND ($1::text[] IS NULL OR id=ANY($1::text[])) AND ($2::text[] IS NULL OR id=ANY($2::text[])) ORDER BY id LIMIT 65`, [allowed, sourceIds]);
- if (rows.length > 64) fail('invalid_params', 'Narrow the enrollment to at most 64 sources.');
+ if (rows.length > 64) fail('invalid_params', 'Narrow the enrollment to at most 64 sources.',
+ 'This connection can see more than 64 sources: name at most 64 of them in follow_policy.source_ids.', { fix: catalogFix });
const published = await publicationEnabled(ctx);
for (const source of rows) {
if (sourceIds && !sourceIds.includes(source.id)) continue;
@@ -109,17 +126,20 @@ function filtered(member: Member, skills: SkillDeliveryEntry[]) {
return { accepted, blocked };
}
+const notMember = 'Use the installation_id that join_brain returned to this same connection. With no enrollment yet, joining needs the user\'s follow approval first.';
async function ownMember(ctx: OperationContext, id: string, principal: Principal): Promise<Member> {
- if (typeof id !== 'string' || !/^[0-9a-f-]{36}$/i.test(id)) fail('membership_not_found', 'No active membership for this principal.');
+ if (typeof id !== 'string' || !/^[0-9a-f-]{36}$/i.test(id)) fail('membership_not_found', 'No active membership for this principal.', `installation_id must be a UUID. ${notMember}`);
const [member] = await ctx.engine.executeRaw<Member>(`SELECT * FROM shared_skill_members WHERE installation_id=$1::uuid
AND principal_kind=$2 AND principal_id=$3 FOR UPDATE`, [id, principal.kind, principal.id]);
- if (!member) fail('membership_not_found', 'No active membership for this principal.');
+ if (!member) fail('membership_not_found', 'No active membership for this principal.', `This connection has no membership ${id}. ${notMember}`);
return member;
}
async function issue(ctx: OperationContext, member: Member, authorityDigest: string, snapshot: Awaited<ReturnType<typeof catalog>>,
acknowledgment?: MembershipSnapshot['acknowledgment']): Promise<MembershipSnapshot> {
- if (snapshot.brain_id !== member.brain_id) fail('membership_inactive', 'The persistent brain identity changed; this enrollment cannot be reused.');
+ if (snapshot.brain_id !== member.brain_id) fail('membership_inactive', 'The persistent brain identity changed; this enrollment cannot be reused.',
+ `This brain now has identity ${snapshot.brain_id}, not the ${member.brain_id} installation ${member.installation_id} enrolled with. Leave locally, then join again after the user approves following this brain.`,
+ { docs: 'docs/guides/shared-brain-skills.md#recover-the-same-brain-identity' });
const { accepted, blocked } = filtered(member, snapshot.skills);
const view = digest([snapshot.view_token, member.epoch, member.follow_policy]);
const revisions = accepted.map(revisionKey).sort();
@@ -154,21 +174,25 @@ async function issue(ctx: OperationContext, member: Member, authorityDigest: str
}
export async function joinBrain(ctx: OperationContext, params: { adapter: string; follow_policy: FollowPolicy; installation_id?: never }): Promise<MembershipSnapshot> {
- if (params.installation_id !== undefined) fail('invalid_params', 'Installation identities are assigned by the server.');
+ if (params.installation_id !== undefined) fail('invalid_params', 'Installation identities are assigned by the server.',
+ 'Omit installation_id from join_brain; its result carries the server-assigned installation_id and enrollment_epoch.');
const adapter = harnessAdapter(params.adapter).id;
- const sourceIds = normalizePolicy(params.follow_policy);
+ const sourceIds = normalizePolicy(params.follow_policy, adapter);
await initializeLocalPersistence(ctx);
return ctx.engine.transaction(async engine => {
const tx = { ...ctx, engine };
const authority = await memberAuthority(tx, 'join_brain');
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1 FOR UPDATE');
- if (!brain) fail('catalog_unavailable', 'Persistent brain identity is unavailable.');
+ if (!brain) fail('catalog_unavailable', 'Persistent brain identity is unavailable.',
+ 'The brain host has not initialized its persistent identity, so nobody can enroll yet. The brain host\'s operator checks it with doctor.',
+ { fix: hostFix(ctx, ['gbrain', 'doctor', '--json'], 'Reports the brain\'s persistence identity and what initializes it.') });
const snapshot = await catalog(authority.ctx);
const [existing] = await engine.executeRaw<Member>('SELECT * FROM shared_skill_members WHERE principal_kind=$1 AND principal_id=$2 AND adapter=$3 FOR UPDATE', [authority.principal.kind, authority.principal.id, adapter]);
let member = existing;
if (member?.active) {
const prior = member.follow_policy.source_ids;
- if (prior && (!sourceIds || sourceIds.some(s => !prior.includes(s)))) fail('follow_approval_required', 'An active membership can only narrow its follow policy; leave and approve a new enrollment to widen it.');
+ if (prior && (!sourceIds || sourceIds.some(s => !prior.includes(s)))) fail('follow_approval_required', 'An active membership can only narrow its follow policy; leave and approve a new enrollment to widen it.',
+ `Installation ${member.installation_id} follows only ${prior.join(', ')}. To follow more, ask the user to approve the wider policy, then leave_brain and join_brain again with it.`);
if (JSON.stringify(prior) !== JSON.stringify(sourceIds)) {
member.follow_policy = { ...member.follow_policy, source_ids: sourceIds };
member.epoch = Number(member.epoch) + 1;
@@ -176,9 +200,11 @@ export async function joinBrain(ctx: OperationContext, params: { adapter: string
await engine.executeRaw(`UPDATE shared_skill_members SET follow_policy=$2::text::jsonb,epoch=$3,issued_sequence=0,acknowledged_sequence=0,desired_view=NULL,acknowledged_view=NULL WHERE installation_id=$1::uuid`, [member.installation_id, JSON.stringify(member.follow_policy), member.epoch]);
}
} else {
- if (member && new Date(member.join_window).getTime() > Date.now() - 3_600_000 && member.join_count >= 10) fail('rate_limited', 'Enrollment rate limit reached for this principal and adapter.');
+ if (member && new Date(member.join_window).getTime() > Date.now() - 3_600_000 && member.join_count >= 10) fail('rate_limited', 'Enrollment rate limit reached for this principal and adapter.',
+ `This connection joined ten times within an hour on adapter ${adapter}. Wait until ${new Date(new Date(member.join_window).getTime() + 3_600_000).toISOString()}, then join once.`);
const [count] = await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM shared_skill_members');
- if (!member && Number(count.n) >= 4096) fail('rate_limited', 'Brain membership quota reached.');
+ if (!member && Number(count.n) >= 4096) fail('rate_limited', 'Brain membership quota reached.',
+ 'The brain holds 4096 shared-skills memberships. Ask the brain host\'s operator to retire stale installations before this one joins.');
const policy = await bindPolicy(authority.ctx, sourceIds);
const id = member?.installation_id ?? randomUUID();
await engine.executeRaw(`INSERT INTO shared_skill_members(installation_id,principal_kind,principal_id,adapter,brain_id,follow_policy)
@@ -199,26 +225,37 @@ export async function syncBrain(ctx: OperationContext, params: { installation_id
const tx = { ...ctx, engine };
const authority = await memberAuthority(tx, 'sync_brain_skills');
const member = await ownMember(tx, params.installation_id, authority.principal);
- if (!member.active || Number(member.epoch) !== params.enrollment_epoch) fail('membership_inactive', 'Membership was left or superseded; delayed delivery cannot reactivate it.');
+ if (!member.active || Number(member.epoch) !== params.enrollment_epoch) fail('membership_inactive', 'Membership was left or superseded; delayed delivery cannot reactivate it.',
+ member.active ? `Installation ${member.installation_id} is at enrollment epoch ${member.epoch}, not ${params.enrollment_epoch}. Re-join under the recorded follow policy so the receipt and router adopt the current epoch; for bootstrap-managed wiring that is gbrain bootstrap harness --refresh-skills on the harness host.`
+ : `Installation ${member.installation_id} left this brain. Following again needs the user's follow approval and a new join; keep cached skills unused.`,
+ { docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' });
const snapshot = await catalog(authority.ctx);
let acknowledgment: MembershipSnapshot['acknowledgment'];
const ack = params.acknowledgment;
if (ack) {
if (!/^[0-9a-f-]{36}$/i.test(ack.batch_token) || Buffer.byteLength(JSON.stringify(ack)) > SHARED_SKILLS_DELIVERY_LIMITS.acknowledgmentBytes || !['installed', 'fetched'].includes(ack.evidence?.stage) ||
- !Array.isArray(ack.evidence?.revisions) || ack.evidence.revisions.length > SHARED_SKILLS_DELIVERY_LIMITS.skills) fail('invalid_acknowledgment', 'Invalid or oversized delivery acknowledgment.');
+ !Array.isArray(ack.evidence?.revisions) || ack.evidence.revisions.length > SHARED_SKILLS_DELIVERY_LIMITS.skills) fail('invalid_acknowledgment', 'Invalid or oversized delivery acknowledgment.',
+ `Send acknowledgment as {batch_token, view_token, evidence: {stage: "installed" or "fetched", revisions}} copied from the last sync_brain_skills result, within ${SHARED_SKILLS_DELIVERY_LIMITS.acknowledgmentBytes} bytes.`,
+ { fix: syncFix(member.installation_id, Number(member.epoch)) });
const [batch] = await engine.executeRaw<Batch>(`SELECT * FROM shared_skill_delivery_batches WHERE token=$1::uuid AND installation_id=$2::uuid AND epoch=$3
AND issued_at>=now()-interval '24 hours' FOR UPDATE`, [ack.batch_token, member.installation_id, member.epoch]);
if (!batch) throw new OperationError('acknowledgment_unavailable', 'This batch is unknown or outside the retained replay window.', 'Sync without acknowledgment to obtain a fresh batch, then verify installation before acknowledging it. No delivery state was advanced.');
- if (batch.view_token !== ack.view_token || batch.authority_digest !== authority.digest) fail('invalid_acknowledgment', 'The batch does not belong to this current authorized enrollment.');
+ if (batch.view_token !== ack.view_token || batch.authority_digest !== authority.digest) fail('invalid_acknowledgment', 'The batch does not belong to this current authorized enrollment.',
+ 'Authority or the view changed since that batch was issued. Sync without an acknowledgment for a fresh batch, install it, then acknowledge that batch_token and view_token.',
+ { fix: syncFix(member.installation_id, Number(member.epoch)) });
const revisions = ack.evidence.revisions.map(s => revisionKey(s as SkillDeliveryEntry)).sort();
- if (JSON.stringify(revisions) !== JSON.stringify(batch.revisions)) fail('invalid_acknowledgment', 'Only the complete issued revision set can be acknowledged.');
+ if (JSON.stringify(revisions) !== JSON.stringify(batch.revisions)) fail('invalid_acknowledgment', 'Only the complete issued revision set can be acknowledged.',
+ `List all ${batch.revisions.length} revisions the batch issued (the skills of that sync result) in evidence.revisions, not a subset or a different set.`);
if (ack.evidence.native && (ack.evidence.native.source !== 'self_report' || ack.evidence.stage !== 'installed' ||
!ack.evidence.revisions.some(s => s.revision === ack.evidence.native!.revision) ||
- ['adapter_version', 'host_version', 'session_id', 'revision'].some(k => typeof (ack.evidence.native as any)[k] !== 'string' || !(ack.evidence.native as any)[k].length || (ack.evidence.native as any)[k].length > 200))) fail('invalid_acknowledgment', 'Native evidence must identify its self-reported provenance and issued revision.');
+ ['adapter_version', 'host_version', 'session_id', 'revision'].some(k => typeof (ack.evidence.native as any)[k] !== 'string' || !(ack.evidence.native as any)[k].length || (ack.evidence.native as any)[k].length > 200))) fail('invalid_acknowledgment', 'Native evidence must identify its self-reported provenance and issued revision.',
+ 'Send evidence.native with source "self_report", stage "installed", one issued revision, and adapter_version, host_version, session_id and revision strings of 1-200 characters; or omit evidence.native.');
if (batch.acknowledged_at && digest(batch.evidence) === digest(ack.evidence)) {
acknowledgment = 'replayed';
} else {
- if (batch.acknowledged_at && !(batch.evidence?.stage === 'fetched' && ack.evidence.stage === 'installed')) fail('invalid_acknowledgment', 'A recorded acknowledgment may only advance from fetched to installed.');
+ if (batch.acknowledged_at && !(batch.evidence?.stage === 'fetched' && ack.evidence.stage === 'installed')) fail('invalid_acknowledgment', 'A recorded acknowledgment may only advance from fetched to installed.',
+ `This batch already has a ${String(batch.evidence?.stage)} acknowledgment. Resend that evidence unchanged, or sync again for a new batch.`,
+ { fix: syncFix(member.installation_id, Number(member.epoch)) });
await engine.executeRaw('UPDATE shared_skill_delivery_batches SET acknowledged_at=now(),evidence=$2::text::jsonb WHERE token=$1::uuid', [batch.token, JSON.stringify(ack.evidence)]);
const currentView = digest([snapshot.view_token, member.epoch, member.follow_policy]);
acknowledgment = batch.view_token === currentView && Number(batch.sequence) === Number(member.issued_sequence) ? 'recorded' : 'historical';
@@ -237,7 +274,9 @@ export async function leaveBrain(ctx: OperationContext, params: { installation_i
const tx = { ...ctx, engine };
const authority = await memberAuthority(tx, 'leave_brain');
const member = await ownMember(tx, params.installation_id, authority.principal);
- if (Number(member.epoch) !== params.enrollment_epoch) fail('membership_inactive', 'This enrollment epoch has already been superseded.');
+ if (Number(member.epoch) !== params.enrollment_epoch) fail('membership_inactive', 'This enrollment epoch has already been superseded.',
+ `Installation ${member.installation_id} is at enrollment epoch ${member.epoch}; a leave for epoch ${params.enrollment_epoch} cannot end the newer enrollment. Leave with the enrollment_epoch from the latest join_brain or sync_brain_skills result.`,
+ { docs: 'docs/guides/shared-brain-skills.md#membership-inactive-after-a-re-enrollment' });
await engine.executeRaw('UPDATE shared_skill_members SET active=false WHERE installation_id=$1::uuid', [member.installation_id]);
return { installation_id: member.installation_id, enrollment_epoch: Number(member.epoch), status: 'left',
native_harness_verified: false, local_cleanup: 'unverified', credentials_revoked: false };
diff --git a/test/shared-skills-refusal-envelopes.test.ts b/test/shared-skills-refusal-envelopes.test.ts
new file mode 100644
index 0000000000..9921901e4e
--- /dev/null
+++ b/test/shared-skills-refusal-envelopes.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { createSharedSkillsAdapter } from '../src/core/shared-skills/adapter.ts';
+import { joinBrain } from '../src/core/shared-skills/membership.ts';
+import { prepareNativeRouter } from '../src/core/harness/native-router.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { caught, envelopeFor, expectFunnelSuggestions } from './helpers/agent-envelope.ts';
+
+const roots: string[] = [];
+const temp = () => { const root = mkdtempSync(join(tmpdir(), 'gbrain-shared-refusals-')); roots.push(root); return root; };
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+const unreachable = async () => { throw new Error('no server call expected'); };
+
+describe('shared-skills refusals name their own next step', () => {
+ test('every fail() and conflict() call site carries a site-specific suggestion', () => {
+ expectFunnelSuggestions('src/core/shared-skills/adapter.ts', 'fail', 24);
+ expectFunnelSuggestions('src/core/shared-skills/membership.ts', 'fail', 20);
+ expectFunnelSuggestions('src/core/harness/native-router.ts', 'conflict', 8);
+ });
+
+ test('joining without follow approval asks the user before the join call, on MCP and the CLI', async () => {
+ const ctx = { remote: true, transport: 'stdio' } as OperationContext;
+ const error = await caught(() => joinBrain(ctx, { adapter: 'codex', follow_policy: { approved: false } as never }));
+ const mcp = envelopeFor(error, 'stdio', ['join_brain']);
+ expect(mcp).toMatchObject({ code: 'follow_approval_required', docs: expect.stringContaining('approve-publication-following-and-editing-separately'),
+ fix: { mcp: { tool: 'join_brain', arguments: { adapter: 'codex', follow_policy: { approved: true } } }, consent: ['persistent_install'], next: 'ask_user' } });
+ expect(envelopeFor(error).fix).toMatchObject({ argv: ['gbrain', 'join-brain', '--adapter', 'codex', '--follow-policy', '{"approved":true}', '--json'], next: 'ask_user' });
+ });
+
+ test('a refresh with no enrollment receipt names the state directory and the approval it needs', async () => {
+ const root = temp();
+ const error = await caught(() => createSharedSkillsAdapter({ call: unreachable, root, adapter: 'codex' }).refresh());
+ const env = envelopeFor(error);
+ expect(env).toMatchObject({ code: 'membership_inactive', docs: expect.stringContaining('docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover') });
+ expect(env.suggestion).toContain(root);
+ });
+
+ test('joining into a directory gbrain did not create names the directory and never adopts it', async () => {
+ const root = temp();
+ writeFileSync(join(root, 'notes.md'), 'user file');
+ const env = envelopeFor(await caught(() => createSharedSkillsAdapter({ call: unreachable, root, adapter: 'codex' }).join({ approved: true })));
+ expect(env.code).toBe('local_conflict');
+ expect(env.suggestion).toContain(`${root} already holds files gbrain did not create`);
+ });
+
+ test('an unexpected native router body is reported with the version', async () => {
+ const root = temp();
+ const env = envelopeFor(await caught(() => prepareNativeRouter({ brain_id: randomUUID(), installation_id: randomUUID(), adapter: 'codex',
+ state_root: join(root, 'state'), skills_dir: join(root, 'skills'), connection_name: 'gbrain', content: '# not a router' })));
+ expect(env).toMatchObject({ code: 'local_conflict', docs: expect.stringContaining('docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover') });
+ expect(env.suggestion).toContain('gbrain --version');
+ });
+});