Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): B10 backfill shared-skills migration/retention, skill catalog and shared-brain bridge refusals

garrytan58103675365a
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 949a686f9c..ba156598de 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -125,12 +125,8 @@ src/core/shared-skills/compatibility.ts 2
src/core/shared-skills/membership-authority.ts 1
src/core/shared-skills/membership.ts 1
src/core/shared-skills/migration-projection.ts 2
-src/core/shared-skills/migration.ts 8
-src/core/shared-skills/retention.ts 7
src/core/shared-skills/setup-source-policy.ts 2
-src/core/skill-catalog.ts 9
src/core/skillpack/brain-resident-locate.ts 12
-src/core/skillpack/shared-brain-bridge.ts 7
src/core/skillpack/writer-guard.ts 1
src/core/source-local-reference-index.ts 2
src/mcp/dispatch.ts 1
diff --git a/src/core/shared-skills/migration.ts b/src/core/shared-skills/migration.ts
index c21acea640..3511769317 100644
--- a/src/core/shared-skills/migration.ts
+++ b/src/core/shared-skills/migration.ts
@@ -1,7 +1,8 @@
import { existsSync, readdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { isThinClient } from '../config.ts';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { getWorktreeBinding } from '../persistence/ownership.ts';
import { checkedContentRoot, inventorySkillpack, sameInventory, type PackInventory } from './setup-files.ts';
import { contentSetupKey, installPackagedSharedSkills, setupSharedBrainContent, type SharedContentReceipt } from './setup.ts';
@@ -49,7 +50,10 @@ export async function legacyPublication(ctx: OperationContext): Promise<Migratio
}
export async function runSharedSkillsMigration(ctx: OperationContext, options: { dryRun?: boolean } = {}): Promise<SharedMigrationReport> {
- if (ctx.remote !== false) throw new OperationError('permission_denied', 'Shared-skills migration requires the trusted local host.');
+ if (ctx.remote !== false) {
+ throw opError('permission_denied', 'Shared-skills migration requires the trusted local host.',
+ 'The shared-skills migration runs only from gbrain apply-migrations on the brain host; a remote connection cannot run it.');
+ }
const dryRun = options.dryRun ?? ctx.dryRun;
const report: SharedMigrationReport = { version: 1, brain_id: null, dry_run: dryRun, status: dryRun ? 'planned' : 'complete', sources: [], pending_actions: [], permission_changes: [] };
if (isThinClient(ctx.config)) {
@@ -59,7 +63,11 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
}
const [brain] = await ctx.engine.executeRaw<{ brain_id: string; enabled: boolean; skill_bundles_enabled: boolean }>(
'SELECT brain_id,enabled,skill_bundles_enabled FROM persistence_brain WHERE singleton=1');
- if (!brain) throw new OperationError('writer_not_initialized', 'Apply the shared-skills schema before migrating content.');
+ if (!brain) {
+ throw opError('writer_not_initialized', 'Apply the shared-skills schema before migrating content.',
+ 'This brain has no persistence identity yet, so the shared-skills schema is not applied. Preview the pending migrations with the command in fix, then apply them.',
+ { fix: readFix('Lists the pending schema migrations without applying them.', { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'] }) });
+ }
report.brain_id = brain.brain_id;
const publication = await legacyPublication(ctx);
const roots = await ctx.engine.executeRaw<{ id: string; incarnation: string; local_path: string | null }>('SELECT id,incarnation,local_path FROM sources WHERE NOT archived ORDER BY id');
@@ -71,7 +79,11 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
if (contentCheckpoint && !dryRun && sourcePolicy.mode === 'content') {
let content: SharedContentReceipt;
try { content = JSON.parse(contentCheckpoint); }
- catch { throw new OperationError('local_conflict', 'A content setup checkpoint is malformed; preserve it for review.'); }
+ catch {
+ throw opError('local_conflict', 'A content setup checkpoint is malformed; preserve it for review.',
+ `The content setup checkpoint for source ${source.id} is not valid JSON. Show it to the user and ask how to proceed; do not delete it.`,
+ { fix: readFix('Prints the saved content setup checkpoint.', { argv: ['gbrain', 'config', 'get', contentSetupKey(source.id, source.incarnation)] }) });
+ }
if (content.owned_root && content.stage !== 'complete') {
const resumed = await setupSharedBrainContent({ ...ctx, sourceId: source.id }, { sourceId: source.id });
if (resumed.root) source.local_path = resumed.root;
@@ -105,16 +117,23 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
try {
if (checkpoint) prior = JSON.parse(checkpoint);
row.root = checkedContentRoot(row.root);
- if (!existsSync(row.root)) throw new OperationError('local_conflict', 'The registered canonical root is missing.');
+ if (!existsSync(row.root)) {
+ throw opError('local_conflict', 'The registered canonical root is missing.',
+ `Source ${source.id}'s registered root ${row.root} does not exist. Restore it (from its Git remote or backup), then run the migration again.`);
+ }
row.inventory = inventorySkillpack(row.root);
- if (prior && (prior.source_incarnation !== source.incarnation || prior.root !== row.root)) throw new OperationError('local_conflict', 'The source root changed since migration inventory.');
+ if (prior && (prior.source_incarnation !== source.incarnation || prior.root !== row.root)) {
+ throw opError('local_conflict', 'The source root changed since migration inventory.',
+ `Source ${source.id} was recreated or moved since its migration inventory was taken; review the checkpoint with the user before continuing the migration.`);
+ }
if (prior?.inventory && (!row.inventory || !sameInventory(prior.inventory.hashes, row.inventory.hashes))) {
const original = { ...prior.inventory.hashes }, current = { ...row.inventory?.hashes };
delete original['skillpack.json']; delete current['skillpack.json'];
const [sealed] = await ctx.engine.executeRaw<{ manifest_hash: string }>('SELECT manifest_hash FROM shared_skill_packs WHERE source_id=$1 AND source_incarnation=$2::uuid', [source.id, source.incarnation]);
if (!row.inventory || !sameInventory(original, current) || sealed?.manifest_hash !== row.inventory.hashes['skillpack.json']) {
row.inventory = prior.inventory;
- throw new OperationError('local_conflict', 'Files changed since migration inventory; preserve edits and review the checkpoint before retrying.');
+ throw opError('local_conflict', 'Files changed since migration inventory; preserve edits and review the checkpoint before retrying.',
+ `Skill files under ${row.root} changed since the migration inventory. Keep the edits, review them with the user, then run the migration again.`);
}
}
} catch (error) {
@@ -157,7 +176,10 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
continue;
}
}
- if (!row.inventory) throw new OperationError('catalog_unavailable', 'Committed pack inventory could not be verified.');
+ if (!row.inventory) {
+ throw opError('catalog_unavailable', 'Committed pack inventory could not be verified.',
+ `Source ${source.id}'s pack inventory is missing, so its catalog adoption cannot be checked. Inspect the per-source stages with gbrain apply-migrations --migration 0.53.0 --dry-run --json.`);
+ }
if (!dryRun) {
try {
const [pack] = await ctx.engine.executeRaw<{ manifest_hash: string }>('SELECT manifest_hash FROM shared_skill_packs WHERE source_id=$1 AND source_incarnation=$2::uuid', [source.id, source.incarnation]);
@@ -169,7 +191,11 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
if (!complete) {
const { adoptSharedSkillpack } = await import('./catalog.ts');
const result = await adoptSharedSkillpack(ctx, source.id, { expected_hashes: row.inventory.hashes });
- if (result.receipts.some(receipt => (receipt.write_request as { state?: string } | undefined)?.state !== 'committed')) throw new OperationError('publication_pending', 'The catalog adoption is accepted but not fully committed. Retry the durable requests before marking this stage complete.');
+ const open = result.receipts.map(receipt => receipt.write_request as { state?: string; request_id?: string } | undefined).find(request => request?.state !== 'committed');
+ if (open) {
+ throw opError('publication_pending', 'The catalog adoption is accepted but not fully committed. Retry the durable requests before marking this stage complete.',
+ `Inspect request ${open.request_id ?? 'receipts'} first; rerunning the migration resumes the same durable request (same request_id), never a second adoption.`);
+ }
}
row.inventory = inventorySkillpack(row.root);
} catch (error) {
diff --git a/src/core/shared-skills/retention.ts b/src/core/shared-skills/retention.ts
index a7129b74e4..794fdf82cf 100644
--- a/src/core/shared-skills/retention.ts
+++ b/src/core/shared-skills/retention.ts
@@ -1,6 +1,8 @@
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { hostOnlyError, readFix } from '../ops/op-fix.ts';
+import { skillHeadFix } from './fixes.ts';
import { declarePersistenceProtocol } from '../persistence/protocol.ts';
import { withCoordinatedWrite } from '../persistence/context.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
@@ -118,9 +120,15 @@ export function assertSharedSkillRetentionCapacity(status: SkillRetentionCapacit
}
async function operatorSource(ctx: OperationContext, sourceId: string): Promise<string> {
- if (ctx.remote !== false) throw new OperationError('permission_denied', 'Revision retention is controlled by the trusted local brain operator.');
+ if (ctx.remote !== false) {
+ throw hostOnlyError(ctx, 'permission_denied', 'Revision retention is controlled by the trusted local brain operator.',
+ ['gbrain', 'skill-retention', '--source-id', sourceId], `Shows source ${sourceId}'s retained skill revisions, pins and storage capacity on the brain host.`);
+ }
const [source] = await ctx.engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);
- if (!source) throw new OperationError('source_changed', 'The retention source is unavailable.');
+ if (!source) {
+ throw opError('source_changed', 'The retention source is unavailable.', `Source ${sourceId} is not registered; pass a registered source.`,
+ { fix: readFix('Lists the registered sources.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
+ }
return source.incarnation;
}
export async function getSharedSkillRetention(ctx: OperationContext, sourceId = ctx.sourceId) {
@@ -133,7 +141,10 @@ export async function pruneSharedSkillRevisions(ctx: OperationContext, sourceId
return ctx.engine.transaction(async tx => {
await declarePersistenceProtocol(tx);
const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
- if (source?.incarnation !== incarnation) throw new OperationError('source_changed', 'The retention source changed.');
+ if (source?.incarnation !== incarnation) {
+ throw opError('source_changed', 'The retention source changed.',
+ `Source ${sourceId} was recreated or removed during pruning, so nothing was pruned. Inspect its retention again before pruning.`, { fix: readFix(`Shows source ${sourceId}'s current incarnation and retention state.`, { argv: ['gbrain', 'skill-retention', '--source-id', sourceId] }) });
+ }
return withCoordinatedWrite(tx, [sourceId], async () => {
const count = await pruneSharedSkillRevisionsInTransaction(tx, sourceId, incarnation);
return { ...await sharedSkillRetentionStatus(tx, sourceId, incarnation), pruned_revisions: count };
@@ -143,19 +154,32 @@ export async function pruneSharedSkillRevisions(ctx: OperationContext, sourceId
export async function retainSharedSkillRevision(ctx: OperationContext, params: { source_id?: string; source_incarnation: string; pack_id: string; name: string; revision: string; hours?: number }) {
const sourceId = params.source_id ?? ctx.sourceId;
const incarnation = await operatorSource(ctx, sourceId);
- if (params.source_incarnation !== incarnation) throw new OperationError('source_changed', 'The pin source incarnation changed.');
+ if (params.source_incarnation !== incarnation) {
+ throw opError('source_changed', 'The pin source incarnation changed.',
+ `Source ${sourceId} is at a different incarnation than the one supplied, so no pin was taken; revisions of a recreated source cannot be pinned. List the catalog again for the current revision.`, { fix: readFix(`Shows source ${sourceId}'s current incarnation and retention state.`, { argv: ['gbrain', 'skill-retention', '--source-id', sourceId] }) });
+ }
const pack = skillName(params.pack_id, 'pack_id'); const name = skillName(params.name); const revision = requireUuid(params.revision);
const hours = params.hours ?? SHARED_SKILL_RETENTION_LIMITS.pinHours;
- if (!Number.isFinite(hours) || hours <= 0 || hours > SHARED_SKILL_RETENTION_LIMITS.pinHours) throw new OperationError('invalid_params', 'Retention pins last more than zero and at most 24 hours.');
+ if (!Number.isFinite(hours) || hours <= 0 || hours > SHARED_SKILL_RETENTION_LIMITS.pinHours) {
+ throw opError('invalid_params', 'Retention pins last more than zero and at most 24 hours.',
+ `Pass hours as a number greater than 0 and at most ${SHARED_SKILL_RETENTION_LIMITS.pinHours}, or omit it for ${SHARED_SKILL_RETENTION_LIMITS.pinHours}.`);
+ }
await initializeLocalPersistence(ctx);
const principal = await requestPrincipalForContext(ctx);
return ctx.engine.transaction(async tx => {
await tx.executeRaw('SELECT singleton FROM shared_skill_state WHERE singleton=1 FOR UPDATE');
const existing = await tx.executeRaw(`SELECT revision FROM shared_skill_revisions
WHERE source_id=$1 AND source_incarnation=$2::uuid AND pack_id=$3 AND name=$4 AND revision=$5::uuid FOR KEY SHARE`, [sourceId, incarnation, pack, name, revision]);
- if (!existing.length) throw new OperationError('revision_unavailable', 'The exact revision is no longer retained.');
+ if (!existing.length) {
+ throw opError('revision_unavailable', 'The exact revision is no longer retained.',
+ `Revision ${revision} of ${pack}/${name} was already pruned, so it cannot be pinned. Pin the current head revision instead.`,
+ { fix: skillHeadFix(sourceId, pack, name) });
+ }
const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 FOR SHARE', [sourceId]);
- if (source?.incarnation !== incarnation) throw new OperationError('source_changed', 'The pin source changed.');
+ if (source?.incarnation !== incarnation) {
+ throw opError('source_changed', 'The pin source changed.',
+ `Source ${sourceId} was recreated while the pin was being taken, so no pin was taken. Inspect its retention again before pinning.`, { fix: readFix(`Shows source ${sourceId}'s current incarnation and retention state.`, { argv: ['gbrain', 'skill-retention', '--source-id', sourceId] }) });
+ }
const [count] = await tx.executeRaw<{ principal: number; source: number; brain: number }>(`SELECT COUNT(*) FILTER(WHERE principal_kind=$3 AND principal_id=$4)::int AS principal,
COUNT(*) FILTER(WHERE source_id=$1 AND source_incarnation=$2::uuid)::int AS source,COUNT(*)::int AS brain
FROM shared_skill_revision_leases WHERE lease_kind='pin' AND expires_at>now()`, [sourceId, incarnation, principal.kind, principal.id]);
diff --git a/src/core/skill-catalog.ts b/src/core/skill-catalog.ts
index 6431941ceb..428f7315d0 100644
--- a/src/core/skill-catalog.ts
+++ b/src/core/skill-catalog.ts
@@ -217,18 +217,20 @@ export function resolveSkillsDir(
// Path confinement (the security boundary)
// ---------------------------------------------------------------------------
+const SKILL_NAME_HINT = `Pass name exactly as list_skills returned it: a lookup key of at most ${MAX_SKILL_NAME_LEN} characters with no slashes, spaces or "..", never a path.`;
+
/** Validate the client-supplied skill name BEFORE any filesystem access. */
function assertSkillNameShape(name: unknown): asserts name is string {
if (typeof name !== 'string' || name.length === 0) {
- throw new OperationError('invalid_params', 'skill name must be a non-empty string');
+ throw new OperationError('invalid_params', 'skill name must be a non-empty string', SKILL_NAME_HINT);
}
if (name.length > MAX_SKILL_NAME_LEN) {
- throw new OperationError('invalid_params', `skill name exceeds ${MAX_SKILL_NAME_LEN} characters`);
+ throw new OperationError('invalid_params', `skill name exceeds ${MAX_SKILL_NAME_LEN} characters`, SKILL_NAME_HINT);
}
// No path separators, no traversal, no null byte. The name is a manifest
// LOOKUP KEY — it must never look like a path component.
if (/[/\\]|\.\.|/.test(name)) {
- throw new OperationError('invalid_params', `Invalid skill name: ${name}`);
+ throw new OperationError('invalid_params', `Invalid skill name: ${name}`, SKILL_NAME_HINT);
}
}
@@ -264,28 +266,31 @@ export function confineManifestPath(skillsDir: string, entry: ManifestEntry): st
try {
realRoot = realpathSync(skillsDir);
} catch {
- throw new OperationError('storage_error', `Cannot resolve skills dir: ${skillsDir}`);
+ throw new OperationError('storage_error', `Cannot resolve skills dir: ${skillsDir}`,
+ 'The skills directory on the brain host is missing or unreadable. The host\'s operator checks mcp.skills_dir (gbrain config get mcp.skills_dir) or unsets it so gbrain autodetects the directory.');
}
const candidate = join(realRoot, entry.path);
try {
realCandidate = realpathSync(candidate);
} catch {
- throw new OperationError('page_not_found', `Skill file not found: ${entry.name}`);
+ throw new OperationError('page_not_found', `Skill file not found: ${entry.name}`, `The skills manifest lists ${entry.name} but its SKILL.md is missing on the brain host. Call list_skills for the skills that are available; the host's operator restores the file or regenerates the manifest.`);
}
const rel = relative(realRoot, realCandidate);
if (rel.startsWith('..') || resolve(realRoot, rel) !== realCandidate) {
- throw new OperationError('invalid_params', `Skill path escapes skills dir: ${entry.name}`);
+ throw new OperationError('invalid_params', `Skill path escapes skills dir: ${entry.name}`,
+ `The manifest entry for ${entry.name} points outside the skills directory, so it is refused. Pick another skill from list_skills; the brain host's operator fixes the manifest.`);
}
let st;
try {
st = statSync(realCandidate);
} catch {
- throw new OperationError('page_not_found', `Skill file not found: ${entry.name}`);
+ throw new OperationError('page_not_found', `Skill file not found: ${entry.name}`, `The skills manifest lists ${entry.name} but its SKILL.md is missing on the brain host. Call list_skills for the skills that are available; the host's operator restores the file or regenerates the manifest.`);
}
if (!st.isFile() || basename(realCandidate) !== 'SKILL.md') {
throw new OperationError(
'invalid_params',
`Skill target is not a SKILL.md regular file: ${entry.name}`,
+ `The manifest entry for ${entry.name} does not point at a regular SKILL.md file, so it is refused. Pick another skill from list_skills; the brain host's operator fixes the manifest.`,
);
}
return realCandidate;
@@ -558,7 +563,8 @@ export function getSkillDetail(
}
const content = readFileSync(path, 'utf-8');
if (Buffer.byteLength(content, 'utf8') > MAX_SKILL_MD_BYTES) {
- throw new OperationError('payload_too_large', `Skill ${name} exceeds the size cap.`);
+ throw new OperationError('payload_too_large', `Skill ${name} exceeds the size cap.`,
+ `Skill ${name} is over ${MAX_SKILL_MD_BYTES} bytes, so it is not served. The brain host's operator can raise GBRAIN_MAX_SKILL_MD_BYTES if it is legitimately large.`);
}
const parsed = parseSkillFrontmatter(content);
diff --git a/src/core/skillpack/shared-brain-bridge.ts b/src/core/skillpack/shared-brain-bridge.ts
index ad97345d4c..242afca812 100644
--- a/src/core/skillpack/shared-brain-bridge.ts
+++ b/src/core/skillpack/shared-brain-bridge.ts
@@ -15,39 +15,50 @@ import { acquireBootstrapLock } from '../bootstrap/lock.ts';
import { assertLegacySkillFilesystemWrite } from './writer-guard.ts';
import { readPrivateText } from '../harness/credentials.ts';
import { harnessAdapter } from '../harness/registry.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError, OperationError } from '../ops/contract.ts';
async function bindBridgeTarget(engine: BrainEngine, brainId: string, adapter: string, root: string, follow: boolean): Promise<LocalRegistration> {
const registration = JSON.parse(readPrivateText(confinedPath(configDir(), `persistence/${brainId}.cli.json`), 65536)) as LocalRegistration;
if (registration.lane !== 'cli' || typeof registration.credential !== 'string' || !/^[a-f0-9-]{36}$/i.test(registration.id)) {
- throw new OperationError('bridge_ownership_conflict', 'The private local CLI registration is invalid.');
+ throw opError('bridge_ownership_conflict', 'The private local CLI registration is invalid.',
+ `The private CLI registration for brain ${brainId} is malformed, so no bridge was bound. Inspect the local writer registrations; re-registering is the user's decision.`,
+ { fix: { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], consent: [], actor: 'agent', why: 'Shows the local writer registrations and whether the CLI one is active.', requires_exclusive: false } });
}
let verified = false;
try { await verifyLocalWriter(engine, registration); verified = true; }
catch (error) { if (follow) throw error; }
const claimKey = `shared_skills.bridge_owner.v1.${registration.id}.${adapter}`;
const target = sha256(JSON.stringify([brainId, root]));
- const refuseIndependent = () => new OperationError('independent_principal_required',
- 'This local CLI principal already owns another source/destination for this harness. Reuse that bridge target; independent installations need separate private-handoff principals. Leaving does not release this binding.');
+ const refuseIndependent = () => opError('independent_principal_required',
+ 'This local CLI principal already owns another source/destination for this harness. Reuse that bridge target; independent installations need separate private-handoff principals. Leaving does not release this binding.',
+ `Install the ${adapter} bridge to the destination this CLI principal already owns, or give the second installation its own private-handoff principal; nothing was changed.`);
const existing = await engine.getConfig(claimKey);
if (existing !== null && existing !== undefined) {
if (existing !== target) throw refuseIndependent();
return registration;
}
- if (!verified) throw new OperationError('bridge_ownership_conflict', 'Restore writer access to verify legacy bridge ownership before attempting cleanup.');
+ if (!verified) {
+ throw opError('bridge_ownership_conflict', 'Restore writer access to verify legacy bridge ownership before attempting cleanup.',
+ 'The CLI writer registration could not be verified, so legacy bridge ownership cannot be checked; nothing was changed. Inspect the local writer registrations before trying again.',
+ { fix: { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], consent: [], actor: 'agent', why: 'Shows whether the CLI writer registration is active.', requires_exclusive: false } });
+ }
const [member] = await engine.executeRaw<{ installation_id: string }>(
"SELECT installation_id FROM shared_skill_members WHERE principal_kind='local_cli' AND principal_id=$1 AND adapter=$2", [registration.id, adapter]);
const readReceipt = (path: string) => {
const receipt = JSON.parse(readPrivateText(path, 4 * 1024 * 1024)) as { format_version: number; adapter: string; brain_id: string; installation_id: string };
if (receipt.format_version !== 1 || typeof receipt.adapter !== 'string' || typeof receipt.brain_id !== 'string' || typeof receipt.installation_id !== 'string') {
- throw new OperationError('bridge_ownership_conflict', 'Preserve the invalid legacy enrollment receipt before retrying.');
+ throw opError('bridge_ownership_conflict', 'Preserve the invalid legacy enrollment receipt before retrying.',
+ `${path} is not a valid legacy enrollment receipt. Keep it, show it to the user, and resolve which installation it belongs to before installing again; nothing was changed.`);
}
return receipt;
};
if (member) {
const parent = dirname(root);
const directories = existsSync(parent) ? readdirSync(parent).filter(name => /^[a-f0-9]{32}$/.test(name)) : [];
- if (directories.length > 4096) throw new OperationError('bridge_ownership_conflict', 'The legacy bridge inventory exceeds the ownership inspection limit.');
+ if (directories.length > 4096) {
+ throw opError('bridge_ownership_conflict', 'The legacy bridge inventory exceeds the ownership inspection limit.',
+ `${parent} holds more than 4096 legacy bridge directories, beyond what gbrain inspects. Ask the user to archive old copies there before installing again; nothing was changed.`);
+ }
const matching: string[] = [];
for (const directory of directories) {
const candidate = confinedPath(parent, `${directory}/shared-skills/receipt.json`);
@@ -55,11 +66,15 @@ async function bindBridgeTarget(engine: BrainEngine, brainId: string, adapter: s
const receipt = readReceipt(candidate);
if (receipt.brain_id === brainId && receipt.adapter === adapter && receipt.installation_id === member.installation_id) matching.push(join(parent, directory));
}
- if (matching.length !== 1) throw new OperationError('bridge_ownership_conflict',
- 'Existing membership has missing or multiple bridge receipts. No enrollment or native files were changed. Preserve and resolve all old copies before using separate private-handoff principals.');
+ if (matching.length !== 1) {
+ throw opError('bridge_ownership_conflict',
+ 'Existing membership has missing or multiple bridge receipts. No enrollment or native files were changed. Preserve and resolve all old copies before using separate private-handoff principals.',
+ `Found ${matching.length} bridge receipts for installation ${member.installation_id} under ${parent}. Show the user the copies and keep exactly one before installing again.`);
+ }
if (matching[0] !== root) throw refuseIndependent();
} else if (existsSync(confinedPath(root, 'shared-skills/receipt.json'))) {
- throw new OperationError('bridge_ownership_conflict', 'The existing bridge receipt does not belong to the current authenticated principal.');
+ throw opError('bridge_ownership_conflict', 'The existing bridge receipt does not belong to the current authenticated principal.',
+ `${root} already holds another principal's bridge receipt. Install to a different destination, or ask the user which installation should own this one; nothing was changed.`);
}
await engine.executeRaw('INSERT INTO config(key,value) VALUES($1,$2) ON CONFLICT(key) DO NOTHING', [claimKey, target]);
if (await engine.getConfig(claimKey) !== target) throw refuseIndependent();