Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): B10 backfill shared-skills catalog, policy, optimizer, setup and DB-only export refusals

garrytan02e6cc93ebd6
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 858a5fdeaf..949a686f9c 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -121,19 +121,13 @@ src/core/repair/extractor-facts.ts 2
src/core/repair/stale-atoms.ts 2
src/core/search/evidence-delivery.ts 1
src/core/shared-skills/adapter.ts 2
-src/core/shared-skills/catalog.ts 15
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-export.ts 25
src/core/shared-skills/migration-projection.ts 2
src/core/shared-skills/migration.ts 8
-src/core/shared-skills/optimizer.ts 18
-src/core/shared-skills/policy.ts 16
src/core/shared-skills/retention.ts 7
-src/core/shared-skills/setup-files.ts 11
src/core/shared-skills/setup-source-policy.ts 2
-src/core/shared-skills/setup.ts 14
src/core/skill-catalog.ts 9
src/core/skillpack/brain-resident-locate.ts 12
src/core/skillpack/shared-brain-bridge.ts 7
diff --git a/src/core/shared-skills/catalog.ts b/src/core/shared-skills/catalog.ts
index 188acf62e0..46dd323c77 100644
--- a/src/core/shared-skills/catalog.ts
+++ b/src/core/shared-skills/catalog.ts
@@ -1,5 +1,7 @@
import { createCipheriv, createDecipheriv, createHmac, randomBytes } from 'node:crypto';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { hostFix } from '../ops/op-fix.ts';
+import { catalogFix, skillHeadFix } from './fixes.ts';
import { sourceScopeOpts } from '../ops/context.ts';
import { stableJson } from '../persistence/digest.ts';
import { approvedFiles, authorizeSkillRead, legacySharedSkillPolicy, normalizePolicy, publicationEnabled, readSharedSkillPolicy, skillPrincipal } from './policy.ts';
@@ -10,14 +12,15 @@ import { SHARED_SKILL_LIMITS, type SharedSkillDetail, type SharedSkillKey, type
export function qualifiedSkillId(key: SharedSkillKey): string {
return `skill:${[key.brain_id, key.source_id, key.source_incarnation, key.pack_id, key.name].map(encodeURIComponent).join(':')}`;
}
+const QUALIFIED_ID_HINT = 'Pass qualified_id exactly as list_skills (schema_version 2) returned it; it is an opaque, URL-encoded key, never built by hand.';
export function parseQualifiedSkillId(value: string): SharedSkillKey {
const parts = value.split(':');
- if (parts.length !== 6 || parts.shift() !== 'skill') throw new OperationError('invalid_params', 'Invalid qualified skill key.');
+ if (parts.length !== 6 || parts.shift() !== 'skill') throw opError('invalid_params', 'Invalid qualified skill key.', QUALIFIED_ID_HINT, { fix: catalogFix() });
try {
const [brain_id, source_id, source_incarnation, pack_id, name] = parts.map(decodeURIComponent);
skillName(pack_id, 'pack_id'); skillName(name);
return { brain_id, source_id, source_incarnation, pack_id, name };
- } catch { throw new OperationError('invalid_params', 'Invalid qualified skill key.'); }
+ } catch { throw opError('invalid_params', 'Invalid qualified skill key.', QUALIFIED_ID_HINT, { fix: catalogFix() }); }
}
async function identity(ctx: OperationContext) {
const [row] = await ctx.engine.executeRaw<{ brain_id: string; token_secret: string; serving_epoch: string }>(
@@ -40,7 +43,10 @@ function decodeCursor(secret: string, value: string): { auth: string; view: stri
const decipher = createDecipheriv('aes-256-gcm', Buffer.from(secret, 'hex'), data.subarray(0, 12), { authTagLength: 16 });
decipher.setAuthTag(data.subarray(12, 28));
return JSON.parse(Buffer.concat([decipher.update(data.subarray(28)), decipher.final()]).toString());
- } catch { throw new OperationError('full_resync_required', 'The catalog cursor is invalid or expired.'); }
+ } catch {
+ throw opError('full_resync_required', 'The catalog cursor is invalid or expired.',
+ 'Restart enumeration: call list_skills with schema_version 2 and no cursor, and replace every page read so far with the new snapshot.', { fix: catalogFix() });
+ }
}
async function readSnapshot(ctx: OperationContext, selector: SharedSkillSelector = {}) {
const ids = sourceScopeOpts(ctx);
@@ -54,10 +60,17 @@ async function readSnapshot(ctx: OperationContext, selector: SharedSkillSelector
AND ($7::boolean=false OR COALESCE((h.metadata->>'private')::boolean,false)=false)
ORDER BY h.source_id,h.source_incarnation,h.pack_id,h.name LIMIT $2`,
[sourceIds, SHARED_SKILL_LIMITS.catalogSkills + 1, selector.source_id ?? null, selector.source_incarnation ?? null, selector.pack_id ?? null, selector.name ?? null, ctx.remote !== false]);
- if (rows.length > SHARED_SKILL_LIMITS.catalogSkills) throw new OperationError('catalog_unavailable', 'The authorized catalog exceeds its bounded snapshot limit.');
+ if (rows.length > SHARED_SKILL_LIMITS.catalogSkills) {
+ throw opError('catalog_unavailable', 'The authorized catalog exceeds its bounded snapshot limit.',
+ `More than ${SHARED_SKILL_LIMITS.catalogSkills} skills match; narrow the request to one source with source_id (and pack_id or name where known).`);
+ }
const brain = await identity(ctx);
const enabled = await publicationEnabled(ctx);
- if (ctx.remote !== false && !enabled) throw new OperationError('permission_denied', 'Shared skills are not published by this brain.');
+ if (ctx.remote !== false && !enabled) {
+ throw opError('permission_denied', 'Shared skills are not published by this brain.',
+ 'The brain owner has not enabled mcp.publish_skills, so connections like this one see no shared skills. Ask the user whether the owner wants to publish them; only the brain host can turn it on.',
+ { fix: hostFix(ctx, ['gbrain', 'config', 'set', 'mcp.publish_skills', 'true'], 'Publishes the owner-approved shared skills to authenticated MCP connections; each source\'s publication policy still limits what they see.', { consent: ['egress'] }) });
+ }
const principal = skillPrincipal(ctx);
const { sharedSkillToolAccess } = await import('./tool-access.ts');
const availableTools = new Set(await sharedSkillToolAccess(ctx));
@@ -94,14 +107,18 @@ export async function listSharedSkills(ctx: OperationContext, params: { limit?:
return catalogRead(ctx, 'list_skills', async active => {
const snapshot = await readSnapshot(active, { source_id: params.source_id });
const limit = params.limit ?? 50;
- if (!Number.isInteger(limit) || limit < 1 || limit > SHARED_SKILL_LIMITS.pageSize) throw new OperationError('invalid_params', 'Catalog limit must be 1-100.');
+ if (!Number.isInteger(limit) || limit < 1 || limit > SHARED_SKILL_LIMITS.pageSize) {
+ throw opError('invalid_params', 'Catalog limit must be 1-100.', `Pass limit as a whole number from 1 to ${SHARED_SKILL_LIMITS.pageSize}, or omit it for 50.`);
+ }
const skills = params.source_id ? snapshot.skills.filter(s => s.source_id === params.source_id) : snapshot.skills;
const view = opaque(snapshot.brain.token_secret, { view: snapshot.view, source: params.source_id ?? null });
let offset = 0;
if (params.cursor) {
const cursor = decodeCursor(snapshot.brain.token_secret, params.cursor);
if (cursor.auth !== snapshot.auth || cursor.view !== view || cursor.limit !== limit || cursor.expires < Date.now() || !Number.isSafeInteger(cursor.offset) || cursor.offset < 0) {
- throw new OperationError('full_resync_required', 'The authorized catalog changed; restart enumeration.');
+ throw opError('full_resync_required', 'The authorized catalog changed; restart enumeration.',
+ 'The catalog or this connection\'s grant changed since the cursor was issued (or it expired after 15 minutes). Restart with list_skills schema_version 2, the same limit and no cursor, and replace every page read so far.',
+ { fix: catalogFix(params.source_id) });
}
offset = cursor.offset;
}
@@ -112,14 +129,21 @@ export async function listSharedSkills(ctx: OperationContext, params: { limit?:
}
function selectSkill(skills: SharedSkillSummary[], params: SharedSkillSelector): SharedSkillSummary {
const supplied: SharedSkillSelector = params.qualified_id ? parseQualifiedSkillId(params.qualified_id) : params;
- if (!supplied.name) throw new OperationError('invalid_params', 'name or qualified_id is required.');
+ if (!supplied.name) {
+ throw opError('invalid_params', 'name or qualified_id is required.',
+ 'Pass the qualified_id list_skills (schema_version 2) returned, or name with pack_id and source_id.', { fix: catalogFix(params.source_id) });
+ }
skillName(supplied.name);
if (params.qualified_id && Object.entries(supplied).some(([key, value]) => params[key as keyof SharedSkillSelector] !== undefined && params[key as keyof SharedSkillSelector] !== value)) {
- throw new OperationError('invalid_params', 'Qualified key disagrees with selector fields.');
+ throw opError('invalid_params', 'Qualified key disagrees with selector fields.',
+ 'Pass qualified_id alone, or selector fields (source_id, source_incarnation, pack_id, name) that match it; drop the conflicting fields.');
}
const matches = skills.filter(skill => ['brain_id', 'source_id', 'source_incarnation', 'pack_id', 'name'].every(key =>
supplied[key as keyof SharedSkillSelector] === undefined || supplied[key as keyof SharedSkillSelector] === skill[key as keyof SharedSkillSummary]));
- if (!matches.length) throw new OperationError('skill_not_found', 'No authorized published skill matches this key.');
+ if (!matches.length) {
+ throw opError('skill_not_found', 'No authorized published skill matches this key.',
+ 'No published skill this connection may read matches the selector. List the catalog for the exact name, pack_id and source_id.', { fix: catalogFix(supplied.source_id) });
+ }
if (matches.length > 1) throw new OperationError('ambiguous_skill', 'This name belongs to multiple authorized sources.', 'Use a qualified_id from list_skills schema_version=2.');
return matches[0];
}
@@ -128,15 +152,26 @@ async function detail(active: OperationContext, params: SharedSkillSelector) {
const snapshot = await readSnapshot(active, selector);
const selected = selectSkill(snapshot.skills, params);
const revision = params.revision ?? selected.revision;
- if (typeof revision !== 'string' || !/^[0-9a-f-]{36}$/i.test(revision)) throw new OperationError('invalid_params', 'Invalid skill revision.');
+ if (typeof revision !== 'string' || !/^[0-9a-f-]{36}$/i.test(revision)) {
+ throw opError('invalid_params', 'Invalid skill revision.', 'Pass revision as the UUID list_skills or get_skill returned, or omit it for the current head.',
+ { fix: skillHeadFix(selected.source_id, selected.pack_id, selected.name) });
+ }
const [row] = await active.engine.executeRaw<StoredSkillRevision>(`SELECT * FROM shared_skill_revisions
WHERE source_id=$1 AND source_incarnation=$2::uuid AND pack_id=$3 AND name=$4 AND revision=$5::uuid AND NOT deleted`,
[selected.source_id, selected.source_incarnation, selected.pack_id, selected.name, revision]);
- if (!row || active.remote !== false && row.metadata.private) throw new OperationError('revision_unavailable', 'The exact authorized revision is unavailable.');
+ if (!row || active.remote !== false && row.metadata.private) {
+ throw opError('revision_unavailable', 'The exact authorized revision is unavailable.',
+ `That revision of ${selected.pack_id}/${selected.name} was deleted, pruned or is private. Read the current head instead (omit revision).`,
+ { fix: skillHeadFix(selected.source_id, selected.pack_id, selected.name) });
+ }
const { epoch, policy } = await readSharedSkillPolicy(active.engine, selected.source_id, selected.source_incarnation, snapshot.enabled);
const files = approvedFiles(row.files, policy, snapshot.principal);
const main = files.find(f => f.path === `skills/${selected.name}/SKILL.md`);
- if (!main) throw new OperationError('skill_not_found', 'This skill is not published to the current audience.');
+ if (!main) {
+ throw opError('skill_not_found', 'This skill is not published to the current audience.',
+ `${selected.pack_id}/${selected.name}'s SKILL.md is not approved for this connection's audience under source ${selected.source_id}'s policy; only the publisher can change that.`,
+ { fix: catalogFix(selected.source_id) });
+ }
const visible = new Set(files.map(f => f.path));
const complete = files.length === row.files.length && files.every(f => f.depends_on.every(d => visible.has(d)));
const { file_policy: _filePolicy, ...metadata } = row.metadata;
@@ -157,11 +192,19 @@ export async function getSharedSkill(ctx: OperationContext, params: SharedSkillS
}
export async function getSharedSkillAsset(ctx: OperationContext, params: SharedSkillSelector & { path: string }) {
return catalogRead(ctx, 'get_skill_asset', async active => {
- if (!params.revision) throw new OperationError('invalid_params', 'Asset reads require the exact approved revision.');
+ if (!params.revision) {
+ throw opError('invalid_params', 'Asset reads require the exact approved revision.',
+ 'Pass revision from get_skill (schema_version 2) for this skill; asset reads never follow the moving head.',
+ params.source_id && params.pack_id && params.name ? { fix: skillHeadFix(params.source_id, params.pack_id, params.name) } : {});
+ }
skillPath(params.path);
const { result, files } = await detail(active, params);
const file = files.find(f => f.path === params.path);
- if (!file) throw new OperationError('skill_asset_not_found', 'The requested file is not in the approved revision manifest.');
+ if (!file) {
+ throw opError('skill_asset_not_found', 'The requested file is not in the approved revision manifest.',
+ `Request one of the paths in the files list get_skill returns for revision ${result.revision} of ${result.pack_id}/${result.name}; other paths are not approved for this connection.`,
+ { fix: skillHeadFix(result.source_id, result.pack_id, result.name, result.revision) });
+ }
return { schema_version: 2 as const, brain_id: result.brain_id, source_id: result.source_id, source_incarnation: result.source_incarnation,
pack_id: result.pack_id, name: result.name, revision: result.revision, path: file.path,
encoding: 'base64' as const, content: file.content, sha256: file.sha256, size: file.size, media_type: file.media_type };
diff --git a/src/core/shared-skills/fixes.ts b/src/core/shared-skills/fixes.ts
new file mode 100644
index 0000000000..60268854fc
--- /dev/null
+++ b/src/core/shared-skills/fixes.ts
@@ -0,0 +1,34 @@
+/**
+ * Agent contract v1 (B10): the read-only next steps shared-skill refusals
+ * point at. Plain `Action` builders; `command`/`next` are rendered per caller.
+ */
+import type { Action } from '../agent-output.ts';
+import { readFix } from '../ops/op-fix.ts';
+
+/** Reads one skill (its current head, or an exact revision) with its revision and file manifest. */
+export function skillHeadFix(sourceId: string, packId: string, name: string, revision?: string): Action {
+ const at = revision ? ['--revision', revision] : [];
+ return readFix(revision
+ ? `Reads revision ${revision} of ${packId}/${name} on source ${sourceId} with its approved file manifest.`
+ : `Reads the current head revision of ${packId}/${name} on source ${sourceId}; resubmit against it with a new request_id.`, {
+ argv: ['gbrain', 'skill', '--schema-version', '2', '--source-id', sourceId, '--pack-id', packId, '--name', name, ...at],
+ mcp: { tool: 'get_skill', arguments: { schema_version: 2, source_id: sourceId, pack_id: packId, name, ...(revision ? { revision } : {}) } },
+ });
+}
+
+/** Lists the authorized shared-skill catalog (one source when known) with qualified ids, incarnations and head revisions. */
+export function catalogFix(sourceId?: string): Action {
+ const scope = sourceId ? ['--source-id', sourceId] : [];
+ return readFix(`Lists ${sourceId ? `source ${sourceId}'s` : 'the authorized'} shared skills with their qualified_id, source_incarnation, pack_id and head revisions.`, {
+ argv: ['gbrain', 'skills', '--schema-version', '2', ...scope],
+ mcp: { tool: 'list_skills', arguments: { schema_version: 2, ...(sourceId ? { source_id: sourceId } : {}) } },
+ });
+}
+
+/** Reads a source's publication policy and epoch (the review step before set_skill_policy). */
+export function policyFix(sourceId: string): Action {
+ return readFix(`Shows source ${sourceId}'s owner-approved publication policy and its epoch; widening it is the publisher's decision (set_skill_policy), never the editor's.`, {
+ argv: ['gbrain', 'skill-policy', '--source-id', sourceId],
+ mcp: { tool: 'get_skill_policy', arguments: { source_id: sourceId } },
+ });
+}
diff --git a/src/core/shared-skills/migration-export.ts b/src/core/shared-skills/migration-export.ts
index 1a68245ba8..7af39032f0 100644
--- a/src/core/shared-skills/migration-export.ts
+++ b/src/core/shared-skills/migration-export.ts
@@ -2,7 +2,9 @@ import { randomUUID } from 'node:crypto';
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync } from 'node:fs';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
-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 type { Action } from '../agent-output.ts';
import { parseMarkdown, serializeMarkdown } from '../markdown.ts';
import { stableJson } from '../persistence/digest.ts';
import { acquireNativeLock } from '../persistence/native-lock.ts';
@@ -52,10 +54,16 @@ export interface DatabaseContentExportReceipt {
schema_policy?: { schema: ApprovedSchemaIdentity; source_config_sha256: string };
}
+function exportPreviewFix(root: string, sourceId: string, why: string): Action {
+ return readFix(why, { argv: ['gbrain', 'apply-migrations', '--migration', '0.53.0', '--export-db-only', '--content-root', root, '--export-source', sourceId, '--dry-run', '--json'] });
+}
+const SOURCES_FIX = readFix('Lists the registered sources and whether each is archived.', { argv: ['gbrain', 'sources', 'list', '--json'] });
+
function exportPath(page: Page): string {
const path = page.source_path ?? `${page.slug}.md`;
if (path.length > 1024 || !path.endsWith('.md') || isAbsolute(path) || path.normalize('NFC') !== path || /[\\:\x00-\x1f\x7f]/.test(path) || path.split('/').some(part => !part || part === '.' || part === '..' || part.startsWith('.')) || /^(skills|\.git|\.gbrain)(\/|$)/i.test(path)) {
- throw new OperationError('unsupported_export_data', 'An unsafe, reserved or non-Markdown source path requires a format-specific export.');
+ throw opError('unsupported_export_data', 'An unsafe, reserved or non-Markdown source path requires a format-specific export.',
+ `Page ${page.slug} stays database-only: its source path must be a plain relative .md path outside skills/, .git and .gbrain to be exported as Markdown.`);
}
return path;
}
@@ -63,21 +71,31 @@ function exportPath(page: Page): string {
async function exportInventory(engine: BrainEngine, sourceId: string) {
const activePack = await loadActivePackForEngine(engine, { sourceId, remote: false });
const [source] = await engine.executeRaw<{ config: unknown; incarnation: string }>('SELECT config,incarnation FROM sources WHERE id=$1 AND NOT archived', [sourceId]);
- if (!source) throw new OperationError('source_changed', 'The export source is no longer active.');
+ if (!source) {
+ throw opError('source_changed', 'The export source is no longer active.',
+ `Source ${sourceId} was archived or removed, so nothing was exported or bound. Choose an active source for the export.`, { fix: SOURCES_FIX });
+ }
const schemaPolicy = { schema: approvedSchemaIdentity(activePack), source_config_sha256: setupHash(stableJson({ config: source.config, incarnation: source.incarnation })) };
const files: Record<string, string> = {}, conflicts: DatabaseContentExportReceipt['conflicts'] = [];
const pages = await engine.listPages({ sourceId, limit: 5001, sort: 'slug' });
- if (pages.length > 5000) throw new OperationError('export_limit', 'This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export.');
+ if (pages.length > 5000) {
+ throw opError('export_limit', 'This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export.',
+ `Source ${sourceId} has more than 5,000 active pages, so nothing was exported. Ask the user whether to split the source or run a reviewed bulk export instead.`);
+ }
let bytes = 0;
const names = new Set<string>();
for (const page of pages) {
try {
const path = exportPath(page);
- if (names.has(path.toLowerCase())) throw new OperationError('unsupported_export_data', 'Canonical paths collide after case normalization.');
+ if (names.has(path.toLowerCase())) {
+ throw opError('unsupported_export_data', 'Canonical paths collide after case normalization.',
+ `Page ${page.slug} exports to a path that differs from another page's only by letter case; rename one of them so the export also works on case-insensitive filesystems.`);
+ }
names.add(path.toLowerCase());
const tags = await engine.getTags(page.slug, { sourceId });
if (page.frontmatter.type !== undefined && page.frontmatter.type !== page.type || page.frontmatter.title !== undefined && page.frontmatter.title !== page.title) {
- throw new OperationError('unsupported_export_data', 'Stored frontmatter disagrees with the authoritative page title or type.');
+ throw opError('unsupported_export_data', 'Stored frontmatter disagrees with the authoritative page title or type.',
+ `Rewrite page ${page.slug} so its frontmatter title and type match the page's title and type, then preview the export again.`);
}
const frontmatter = { ...page.frontmatter, slug: page.slug, tags };
const content = serializeMarkdown(frontmatter, page.compiled_truth, page.timeline, { type: page.type, title: page.title, tags });
@@ -88,20 +106,30 @@ async function exportInventory(engine: BrainEngine, sourceId: string) {
parsed.compiled_truth !== page.compiled_truth || parsed.timeline !== page.timeline ||
stableJson([...parsed.tags].sort()) !== stableJson([...tags].sort()) ||
stableJson(parsed.frontmatter) !== stableJson(expectedFrontmatter)) {
- throw new OperationError('unsupported_export_data', 'The existing Markdown parser cannot round-trip this page without changing its fields.');
+ throw opError('unsupported_export_data', 'The existing Markdown parser cannot round-trip this page without changing its fields.',
+ `Page ${page.slug} would change when written as Markdown and parsed back, so it stays database-only; simplify its fields and preview the export again if it must become a file.`);
}
await assertExportProjectionRoundtrip(engine, parsed, page.id, sourceId);
files[path] = content;
const raw = await engine.getRawData(page.slug, undefined, { sourceId, includeDeleted: true });
if (raw.length) {
const data = Object.fromEntries(raw.map(row => [row.source, row.data]));
- if (Object.keys(data).length !== raw.length) throw new OperationError('unsupported_export_data', 'Raw-data sidecar keys are ambiguous.');
+ if (Object.keys(data).length !== raw.length) {
+ throw opError('unsupported_export_data', 'Raw-data sidecar keys are ambiguous.',
+ `Page ${page.slug} has several raw-data rows under one source key, so it stays database-only until they are merged.`);
+ }
const sidecar = JSON.stringify(data, null, 2) + '\n';
- if (stableJson(JSON.parse(sidecar)) !== stableJson(data)) throw new OperationError('unsupported_export_data', 'Raw data cannot round-trip through JSON.');
+ if (stableJson(JSON.parse(sidecar)) !== stableJson(data)) {
+ throw opError('unsupported_export_data', 'Raw data cannot round-trip through JSON.',
+ `Page ${page.slug}'s raw data changes when serialized as JSON, so it stays database-only.`);
+ }
files[join(dirname(path), '.raw', path.split('/').at(-1)!.slice(0, -3) + '.json')] = sidecar;
}
bytes += Buffer.byteLength(content) + raw.reduce((sum, row) => sum + Buffer.byteLength(JSON.stringify(row.data)), 0);
- if (Buffer.byteLength(content) > 5_000_000 || bytes > 64 * 1024 * 1024) throw new OperationError('export_limit', 'The canonical export exceeds its 5 MB page or 64 MiB source bound.');
+ if (Buffer.byteLength(content) > 5_000_000 || bytes > 64 * 1024 * 1024) {
+ throw opError('export_limit', 'The canonical export exceeds its 5 MB page or 64 MiB source bound.',
+ `Page ${page.slug} pushed the export past 5 MB for one page or 64 MiB for the source; split large pages or leave them database-only, then preview the export again.`);
+ }
} catch (error) {
conflicts.push({ slug: page.slug, reason: error instanceof OperationError ? error.message : 'This page cannot be exported losslessly.' });
}
@@ -115,15 +143,24 @@ function verifyFiles(root: string, hashes: Record<string, string>, exact = false
const absolute = join(root, path);
checkedContentRoot(dirname(absolute));
const stat = lstatSync(absolute);
- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || setupHash(readFileSync(absolute)) !== hash) throw new OperationError('local_conflict', 'An exported file was changed; no file or database row will be replaced.');
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || setupHash(readFileSync(absolute)) !== hash) {
+ throw opError('local_conflict', 'An exported file was changed; no file or database row will be replaced.',
+ `${path} under ${root} no longer matches the bytes the export wrote. Keep the directory, ask the user whether that edit should be kept, and restore the exported bytes before resuming the same export.`);
+ }
}
if (exact) {
const visit = (directory: string, prefix: string) => {
for (const name of readdirSync(directory)) {
const path = prefix ? `${prefix}/${name}` : name, stat = lstatSync(join(directory, name));
- if (stat.isSymbolicLink()) throw new OperationError('local_conflict', 'An export directory contains an unexpected symlink.');
+ if (stat.isSymbolicLink()) {
+ throw opError('local_conflict', 'An export directory contains an unexpected symlink.',
+ `Remove the symlink ${path} from ${root} (the export never writes links), then resume the same export.`);
+ }
if (stat.isDirectory()) visit(join(directory, name), path);
- else if (!hashes[path]) throw new OperationError('local_conflict', 'An export directory contains unowned files; it will not be adopted.');
+ else if (!hashes[path]) {
+ throw opError('local_conflict', 'An export directory contains unowned files; it will not be adopted.',
+ `${path} in ${root} was not written by this export. Ask the user where it belongs and move it out, then resume the same export.`);
+ }
}
};
visit(root, '');
@@ -131,27 +168,53 @@ function verifyFiles(root: string, hashes: Record<string, string>, exact = false
}
export async function exportDatabaseContent(ctx: OperationContext, options: DatabaseContentExportOptions): Promise<DatabaseContentExportReceipt> {
- if (ctx.remote !== false) throw new OperationError('permission_denied', 'DB-only export is a trusted host action.');
+ if (ctx.remote !== false) {
+ throw hostOnlyError(ctx, 'permission_denied', 'DB-only export is a trusted host action.',
+ ['gbrain', 'apply-migrations', '--migration', '0.53.0', '--export-db-only', '--content-root', options.root, '--export-source', options.sourceId, '--dry-run', '--json'],
+ `Previews the database-only export of source ${options.sourceId}; only the brain host's CLI writes and binds the exported files.`);
+ }
const root = checkedContentRoot(options.root);
const [brain] = await ctx.engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
const [source] = await ctx.engine.executeRaw<{ incarnation: string; local_path: string | null }>('SELECT incarnation,local_path FROM sources WHERE id=$1 AND NOT archived', [options.sourceId]);
- if (!brain || !source) throw new OperationError('source_changed', 'The selected brain/source is not active.');
+ if (!brain || !source) {
+ throw opError('source_changed', 'The selected brain/source is not active.',
+ `Source ${options.sourceId} is archived or not registered, or this brain has no persistence identity yet; pass an active source with --export-source.`, { fix: SOURCES_FIX });
+ }
await assertPackagedSkillSource(ctx.engine, options.sourceId);
if (!options.dryRun && options.confirmQuiesced && ((await ctx.engine.executeRaw(
'SELECT id FROM gbrain_cycle_locks WHERE $1::uuid IS NULL OR acquisition_token IS DISTINCT FROM $1::uuid LIMIT 1',
[options.ownLeaseToken ?? null])).length ||
(await ctx.engine.executeRaw("SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1")).length)) {
- throw new OperationError('writer_not_quiesced', 'Active maintenance locks or durable writes remain; finish or recover them before exporting.');
+ throw opError('writer_not_quiesced', 'Active maintenance locks or durable writes remain; finish or recover them before exporting.',
+ `Stop memory and file writers and old skill servers, let queued or recovering writes settle (the command in fix shows them for source ${options.sourceId}), then run the export again with --confirm-quiesced. Nothing was exported.`,
+ { fix: readFix(`Shows source ${options.sourceId}'s writer, queued requests and pending recovery.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', options.sourceId, '--json'] }) });
}
const key = `shared_skills.export.v1.${options.sourceId}.${source.incarnation}`;
const saved = await ctx.engine.getConfig(key);
let prior: DatabaseContentExportReceipt | null = null;
- try { if (saved) prior = JSON.parse(saved); } catch { throw new OperationError('local_conflict', 'The export checkpoint is malformed.'); }
- if (prior && (prior.version !== 1 || prior.root !== root || prior.brain_id !== brain.brain_id || prior.source_incarnation !== source.incarnation)) throw new OperationError('local_conflict', 'The export checkpoint targets a different root or identity.');
- if (prior?.root_identity && !existsSync(root)) throw new OperationError('local_conflict', 'The verified exported root is missing. Restore it; migration will not silently create a replacement.');
+ try { if (saved) prior = JSON.parse(saved); } catch {
+ throw opError('local_conflict', 'The export checkpoint is malformed.',
+ `The saved export checkpoint for source ${options.sourceId} (config key ${key}) is not valid JSON, so nothing was exported. Show it to the user and ask how to proceed before changing it.`,
+ { fix: readFix('Prints the saved export checkpoint.', { argv: ['gbrain', 'config', 'get', key] }) });
+ }
+ if (prior && (prior.version !== 1 || prior.root !== root || prior.brain_id !== brain.brain_id || prior.source_incarnation !== source.incarnation)) {
+ throw opError('local_conflict', 'The export checkpoint targets a different root or identity.',
+ `An earlier export of source ${options.sourceId} is checkpointed for another root or source incarnation; resume it with its own --content-root, or ask the user to settle it before starting a new one.`,
+ typeof prior.root === 'string' ? { fix: exportPreviewFix(prior.root, options.sourceId, `Previews the checkpointed export of source ${options.sourceId} at its original root.`) } : {});
+ }
+ if (prior?.root_identity && !existsSync(root)) {
+ throw opError('local_conflict', 'The verified exported root is missing. Restore it; migration will not silently create a replacement.',
+ `Restore ${root} from the user's copy of the verified export, then resume the same export; gbrain never recreates it silently.`);
+ }
const fallback = options.sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null;
- if ((source.local_path || fallback) && (!prior || resolve(source.local_path || fallback!) !== root)) throw new OperationError('local_conflict', 'The source already has a canonical root; this export never moves it.');
- if (existsSync(root) && !prior) throw new OperationError('local_conflict', 'Choose an absent export destination; existing directories are never overwritten.');
+ if ((source.local_path || fallback) && (!prior || resolve(source.local_path || fallback!) !== root)) {
+ throw opError('local_conflict', 'The source already has a canonical root; this export never moves it.',
+ `Source ${options.sourceId} already has a canonical checkout, so it needs no database-only export; the export only creates a root for sources that have none.`);
+ }
+ if (existsSync(root) && !prior) {
+ throw opError('local_conflict', 'Choose an absent export destination; existing directories are never overwritten.',
+ `${root} already exists; pass --content-root a path that does not exist yet (the export creates it).`);
+ }
const inventory = await exportInventory(ctx.engine, options.sourceId);
const hashes = Object.fromEntries(Object.entries(inventory.files).map(([path, content]) => [path, setupHash(content)]));
const receipt: DatabaseContentExportReceipt = prior ?? {
@@ -173,7 +236,11 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Data
return receipt;
}
const lock = await acquireNativeLock(gbrainPath('persistence', 'locks', `export-${brain.brain_id}-${source.incarnation}.lock`), { timeoutMs: 1000 });
- if (!lock) throw new OperationError('writer_lock_unavailable', 'Another export is using this source checkpoint.');
+ if (!lock) {
+ throw opError('writer_lock_unavailable', 'Another export is using this source checkpoint.',
+ `Another export of source ${options.sourceId} holds its checkpoint lock. Wait for it to finish and preview the checkpoint before starting again; nothing was written by this run.`,
+ { fix: exportPreviewFix(root, options.sourceId, `Shows the checkpointed export state of source ${options.sourceId} without writing.`) });
+ }
try {
await ctx.engine.setConfig(key, JSON.stringify(receipt));
if (!existsSync(root)) {
@@ -191,21 +258,35 @@ export async function exportDatabaseContent(ctx: OperationContext, options: Data
}
verifyFiles(receipt.staging_root, hashes, true);
const enclosing = spawnSync('git', ['-C', receipt.staging_root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });
- if (enclosing.status === 0) throw new OperationError('local_conflict', 'The export would claim an enclosing Git worktree. Choose a destination outside existing repositories.');
+ if (enclosing.status === 0) {
+ throw opError('local_conflict', 'The export would claim an enclosing Git worktree. Choose a destination outside existing repositories.',
+ `${root} lies inside an existing Git worktree; pass --content-root a path outside any repository.`);
+ }
const current = await exportInventory(ctx.engine, options.sourceId);
- if (current.conflicts.length || stableJson(current.schemaPolicy) !== stableJson(receipt.schema_policy) || !sameInventory(hashes, Object.fromEntries(Object.entries(current.files).map(([path, content]) => [path, setupHash(content)])))) throw new OperationError('local_conflict', 'The database content, source schema or ingestion policy changed while exporting; writers were not quiesced.');
+ if (current.conflicts.length || stableJson(current.schemaPolicy) !== stableJson(receipt.schema_policy) || !sameInventory(hashes, Object.fromEntries(Object.entries(current.files).map(([path, content]) => [path, setupHash(content)])))) {
+ throw opError('local_conflict', 'The database content, source schema or ingestion policy changed while exporting; writers were not quiesced.',
+ `Source ${options.sourceId} changed while it was being exported, so nothing was bound. Stop every writer, then preview the checkpointed export before resuming it.`,
+ { fix: exportPreviewFix(root, options.sourceId, `Shows what changed since the export checkpoint of source ${options.sourceId}, without writing.`) });
+ }
renameSync(receipt.staging_root, root);
flushTopologyDirectory(dirname(root));
}
verifyFiles(root, hashes, receipt.stage === 'inventory');
const stat = statSync(root);
- if (receipt.root_identity && (receipt.root_identity.device !== stat.dev || receipt.root_identity.inode !== stat.ino)) throw new OperationError('local_conflict', 'The exported root was replaced after validation.');
+ if (receipt.root_identity && (receipt.root_identity.device !== stat.dev || receipt.root_identity.inode !== stat.ino)) {
+ throw opError('local_conflict', 'The exported root was replaced after validation.',
+ `${root} is a different directory from the one the export validated, so nothing was bound. Restore the validated directory, or ask the user how to proceed.`);
+ }
receipt.root_identity = { device: stat.dev, inode: stat.ino };
receipt.stage = 'exported'; receipt.status = 'action_required';
await ctx.engine.setConfig(key, JSON.stringify(receipt));
await assertPackagedSkillSource(ctx.engine, options.sourceId);
const verified = await exportInventory(ctx.engine, options.sourceId);
- if (verified.conflicts.length || stableJson(verified.schemaPolicy) !== stableJson(receipt.schema_policy) || !sameInventory(hashes, Object.fromEntries(Object.entries(verified.files).map(([path, content]) => [path, setupHash(content)])))) throw new OperationError('local_conflict', 'The database content, source schema or ingestion policy changed before source binding.');
+ if (verified.conflicts.length || stableJson(verified.schemaPolicy) !== stableJson(receipt.schema_policy) || !sameInventory(hashes, Object.fromEntries(Object.entries(verified.files).map(([path, content]) => [path, setupHash(content)])))) {
+ throw opError('local_conflict', 'The database content, source schema or ingestion policy changed before source binding.',
+ `Source ${options.sourceId} changed after its files were exported, so the export root was not bound. Stop every writer, then preview the checkpointed export before resuming it.`,
+ { fix: exportPreviewFix(root, options.sourceId, `Shows what changed since the export checkpoint of source ${options.sourceId}, without writing.`) });
+ }
await registerLocalWriter(ctx.engine, 'cli');
assertTopologyCommitted(await runManagedSourceLifecycle(ctx.engine, { operation: 'claim', sourceId: options.sourceId, path: root,
expectedIncarnation: source.incarnation, requestId: receipt.request_id }));
diff --git a/src/core/shared-skills/optimizer.ts b/src/core/shared-skills/optimizer.ts
index d57bfd6d14..e91cb5db42 100644
--- a/src/core/shared-skills/optimizer.ts
+++ b/src/core/shared-skills/optimizer.ts
@@ -2,7 +2,9 @@ import { randomUUID } from 'node:crypto';
import { chmodSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
import { dirname, join, relative, resolve, sep } from 'node:path';
import { configDir } from '../config.ts';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { hostFix } from '../ops/op-fix.ts';
+import { skillHeadFix } from './fixes.ts';
import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';
import { getWriteRequest } from '../persistence/journal.ts';
import { submissionAuthority } from '../persistence/authority.ts';
@@ -22,14 +24,25 @@ import { SHARED_SKILL_LIMITS, type StoredSkillRevision } from './model.ts';
import { approvedFiles, assertSkillCapability, assertStoredSkillCapability, authorizeSkillRead, publicationEnabled, readSharedSkillPolicy, skillPrincipal } from './policy.ts';
import { submitSharedSkillMutation } from './publication.ts';
+const EVAL_INPUT_HINT = `Keep each benchmark and held-out file under ${SHARED_SKILL_LIMITS.bundleBytes} bytes (trim or sample the tasks); nothing ran and nothing was spent.`;
+
export async function sharedOptimizerSkillsDir(ctx: OperationContext, sourceId: string, incarnation: string): Promise<string> {
- if (ctx.remote !== false && (ctx.auth?.sourceId ?? ctx.sourceId) !== sourceId) throw new OperationError('permission_denied', 'The selected optimizer source is outside the caller grant.');
+ if (ctx.remote !== false && (ctx.auth?.sourceId ?? ctx.sourceId) !== sourceId) {
+ throw opError('permission_denied', 'The selected optimizer source is outside the caller grant.',
+ `This connection's grant is bound to a different source than ${sourceId}; optimize a skill from the granted source, or ask the brain host's operator to grant ${sourceId}.`);
+ }
const binding = await getWorktreeBinding(ctx.engine, sourceId);
+ const ownerFix = { fix: hostFix(ctx, ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'],
+ `Shows source ${sourceId}'s designated canonical owner and binding; optimization runs only on that host.`) };
if (!binding || binding.source_incarnation !== incarnation || binding.state !== 'active' || binding.owner_host_id !== localHostId() || !binding.local_path) {
- throw new OperationError('owner_unavailable', 'Shared optimization must run on the active canonical owner.');
+ throw opError('owner_unavailable', 'Shared optimization must run on the active canonical owner.',
+ `Source ${sourceId}'s skills are optimized only on its active canonical owner host, and this host is not it (or the binding is inactive). Nothing ran and nothing was spent; run the optimization there.`, ownerFix);
}
const root = resolve(binding.local_path, binding.relative_path);
- if (realpathSync(root) !== root) throw new OperationError('local_conflict', 'The canonical source root contains a symlink.');
+ if (realpathSync(root) !== root) {
+ throw opError('local_conflict', 'The canonical source root contains a symlink.',
+ `Source ${sourceId}'s registered checkout resolves through a symlink; the brain host's operator re-registers it at its real path before optimization can run.`, ownerFix);
+ }
return join(root, 'skills');
}
@@ -39,11 +52,16 @@ async function authorize(ctx: OperationContext, opts: SkillOptOpts): Promise<voi
if (ctx.remote !== false) {
active = await authorizeSkillRead(ctx, 'run_skillopt');
if (!hasScope(active.auth?.scopes ?? [], 'admin') || !active.auth?.allowedOperations?.includes('run_skillopt')) {
- throw new OperationError('permission_denied', 'Shared optimization requires current admin and an explicit run_skillopt operation grant.');
+ throw opError('permission_denied', 'Shared optimization requires current admin and an explicit run_skillopt operation grant.',
+ 'This connection needs admin scope and run_skillopt in its allowed operations. Ask the brain host\'s operator to grant both; nothing ran and nothing was spent.');
}
let allowed: unknown;
try { allowed = JSON.parse(await ctx.engine.getConfig('skillopt.allowed_skills') ?? '[]'); } catch { allowed = []; }
- if (!Array.isArray(allowed) || !allowed.includes(opts.skillName)) throw new OperationError('permission_denied', 'The skill is not in skillopt.allowed_skills.');
+ if (!Array.isArray(allowed) || !allowed.includes(opts.skillName)) {
+ throw opError('permission_denied', 'The skill is not in skillopt.allowed_skills.',
+ `Remote optimization is limited to the skills listed in skillopt.allowed_skills, and ${opts.skillName} is not one of them. Ask the user whether the brain host's operator should add it; nothing ran and nothing was spent.`,
+ { fix: hostFix(ctx, ['gbrain', 'config', 'get', 'skillopt.allowed_skills'], 'Shows which skills remote callers may optimize; adding one is the operator\'s decision.') });
+ }
}
assertSkillCapability(active, 'skill_editor', 'put_skill');
await initializeLocalPersistence(active);
@@ -54,7 +72,8 @@ async function authorize(ctx: OperationContext, opts: SkillOptOpts): Promise<voi
function lintCandidate(before: string, after: string): void {
const original = splitFrontmatter(before), candidate = splitFrontmatter(after);
if (!candidate.body.trim() || after.includes('\0') || before.slice(0, original.bodyStart) !== after.slice(0, candidate.bodyStart)) {
- throw new OperationError('skill_candidate_invalid', 'The optimized candidate changed protected frontmatter or has an empty/invalid body.');
+ throw opError('skill_candidate_invalid', 'The optimized candidate changed protected frontmatter or has an empty/invalid body.',
+ 'The optimizer\'s candidate was not published; the retained proposal (named in detail) shows what it produced. Ask the user before running the paid optimization again.');
}
let fence: { character: string; length: number } | null = null;
for (const line of candidate.body.split('\n')) {
@@ -63,17 +82,24 @@ function lintCandidate(before: string, after: string): void {
if (!fence) fence = { character: match[1][0], length: match[1].length };
else if (match[1][0] === fence.character && match[1].length >= fence.length && !match[2].trim()) fence = null;
}
- if (fence) throw new OperationError('skill_candidate_invalid', 'The optimized candidate contains an unclosed Markdown code fence.');
+ if (fence) {
+ throw opError('skill_candidate_invalid', 'The optimized candidate contains an unclosed Markdown code fence.',
+ 'The optimizer\'s candidate was not published; the retained proposal (named in detail) shows the unclosed fence. Ask the user before running the paid optimization again.');
+ }
}
export async function optimizeSharedSkill(opts: SkillOptOpts, run: (opts: SkillOptOpts) => Promise<RunSkillOptResult>): Promise<RunSkillOptResult> {
const target = opts.sharedSkill;
const ctx = opts.operationContext && target ? { ...opts.operationContext, sourceId: target.source_id } : undefined;
- if (!ctx || ctx.engine !== opts.engine || !target) throw new OperationError('permission_denied', 'Shared optimization requires the original operation context.');
+ if (!ctx || ctx.engine !== opts.engine || !target) {
+ throw opError('permission_denied', 'Shared optimization requires the original operation context.',
+ 'Start shared-skill optimization through the run_skillopt operation (or gbrain skillopt) so its grant and target travel with it; nothing ran and nothing was spent.');
+ }
skillName(opts.skillName); skillName(target.pack_id, 'pack_id');
requireUuid(target.source_incarnation); requireUuid(target.expected_revision); requireUuid(target.request_id);
if (opts.resumeRunId || opts.writeCapture || opts.disableValidationGate || opts.optimizerMode || opts.reflectMode) {
- throw new OperationError('invalid_params', 'Shared optimization does not permit legacy resume, write capture, or evaluation ablations.');
+ throw opError('invalid_params', 'Shared optimization does not permit legacy resume, write capture, or evaluation ablations.',
+ 'Drop the resume run id, write capture, validation-gate and optimizer/reflect mode overrides, then start the optimization again; shared skills always run the full gated evaluation.');
}
await authorize(ctx, opts);
if (await getWriteRequest(ctx.engine, await requestPrincipalForContext(ctx), target.request_id)) {
@@ -81,17 +107,28 @@ export async function optimizeSharedSkill(opts: SkillOptOpts, run: (opts: SkillO
`Read get_write_request with request_id=${target.request_id}; do not rerun paid optimization to poll a publication.`);
}
const skillsDir = await sharedOptimizerSkillsDir(ctx, target.source_id, target.source_incarnation);
- if (realpathSync(opts.skillsDir) !== realpathSync(skillsDir)) throw new OperationError('source_changed', 'The optimizer directory does not match the selected canonical source.');
+ if (realpathSync(opts.skillsDir) !== realpathSync(skillsDir)) {
+ throw opError('source_changed', 'The optimizer directory does not match the selected canonical source.',
+ `Point the optimizer at source ${target.source_id}'s canonical skills directory (${skillsDir}), or omit the directory override; nothing ran and nothing was spent.`);
+ }
const selector = { source_id: target.source_id, source_incarnation: target.source_incarnation, pack_id: target.pack_id, name: opts.skillName };
const skill = await getSharedSkill(ctx, selector);
- if (skill.revision !== target.expected_revision) throw new OperationError('revision_conflict', 'The selected skill changed before optimization.');
- if (skill.delivery !== 'complete') throw new OperationError('approval_required', 'Optimization requires the complete owner-approved dependency closure.');
+ const headFix = { fix: skillHeadFix(target.source_id, target.pack_id, opts.skillName) };
+ if (skill.revision !== target.expected_revision) {
+ throw opError('revision_conflict', 'The selected skill changed before optimization.',
+ `${target.pack_id}/${opts.skillName} moved to a new revision before optimization started; nothing ran and nothing was spent. Read the current revision and start again with it as expected_revision and a new request_id.`, headFix);
+ }
+ if (skill.delivery !== 'complete') {
+ throw opError('approval_required', 'Optimization requires the complete owner-approved dependency closure.',
+ `Part of ${target.pack_id}/${opts.skillName}'s files is not approved for this connection, so the optimizer cannot see the whole skill. Only the publisher can widen source ${target.source_id}'s policy; nothing ran.`, headFix);
+ }
const [stored] = await ctx.engine.executeRaw<StoredSkillRevision>(`SELECT * FROM shared_skill_revisions
WHERE source_id=$1 AND source_incarnation=$2::uuid AND pack_id=$3 AND name=$4 AND revision=$5::uuid AND NOT deleted`,
[target.source_id, target.source_incarnation, target.pack_id, opts.skillName, target.expected_revision]);
const policy = await readSharedSkillPolicy(ctx.engine, target.source_id, target.source_incarnation, await publicationEnabled(ctx));
if (!stored || approvedFiles(stored.files, policy.policy, skillPrincipal(ctx)).length !== stored.files.length) {
- throw new OperationError('approval_required', 'The original complete skill closure is no longer approved.');
+ throw opError('approval_required', 'The original complete skill closure is no longer approved.',
+ `Revision ${target.expected_revision} of ${target.pack_id}/${opts.skillName} is gone or no longer fully approved under source ${target.source_id}'s policy; nothing ran. Read the current revision before starting again.`, headFix);
}
const files = normalizeSkillFiles(opts.skillName, stored.files.map(file => ({ ...file, encoding: 'base64' })));
const evaluationInputs: Buffer[] = [];
@@ -103,23 +140,29 @@ export async function optimizeSharedSkill(opts: SkillOptOpts, run: (opts: SkillO
bytes = Buffer.from(asset.content, 'base64');
const sealed = files.find(file => file.path === path);
if (!sealed || asset.sha256 !== sealed.sha256 || sha256(bytes) !== sealed.sha256 || bytes.length !== asset.size) {
- throw new OperationError('revision_unavailable', 'The evaluation input does not match the selected approved skill revision.');
+ throw opError('revision_unavailable', 'The evaluation input does not match the selected approved skill revision.',
+ `Use a benchmark or held-out file that is part of revision ${target.expected_revision} of ${target.pack_id}/${opts.skillName} (get_skill lists its files); nothing ran.`,
+ { fix: skillHeadFix(target.source_id, target.pack_id, opts.skillName, target.expected_revision) });
}
} else {
- if (lstatSync(realpathSync(input)).size > SHARED_SKILL_LIMITS.bundleBytes) throw new OperationError('invalid_params', 'The evaluation input exceeds the bounded staging size.');
+ if (lstatSync(realpathSync(input)).size > SHARED_SKILL_LIMITS.bundleBytes) throw opError('invalid_params', 'The evaluation input exceeds the bounded staging size.', EVAL_INPUT_HINT);
bytes = readFileSync(input);
}
- if (bytes.length > SHARED_SKILL_LIMITS.bundleBytes) throw new OperationError('invalid_params', 'The evaluation input exceeds the bounded staging size.');
+ if (bytes.length > SHARED_SKILL_LIMITS.bundleBytes) throw opError('invalid_params', 'The evaluation input exceeds the bounded staging size.', EVAL_INPUT_HINT);
evaluationInputs.push(bytes);
}
const canonicalFile = join(skillsDir, opts.skillName, 'SKILL.md');
for (const file of files) {
const path = join(dirname(skillsDir), file.path), stat = lstatSync(path);
if (!stat.isFile() || stat.nlink !== 1 || realpathSync(path) !== path || sha256(readFileSync(path)) !== file.sha256) {
- throw new OperationError('local_conflict', 'Canonical skill bytes differ from the selected approved revision.');
+ throw opError('local_conflict', 'Canonical skill bytes differ from the selected approved revision.',
+ `${file.path} in source ${target.source_id}'s checkout differs from revision ${target.expected_revision}, so the checkout has unpublished edits. Restore the published bytes, or publish the edit through import_skill_proposal, before optimizing; nothing ran.`);
}
}
- if (!opts.force && getWorkingTreeStatusForFile(canonicalFile) === 'dirty') throw new OperationError('dirty_tree', 'Commit or stash canonical skill edits before optimization.');
+ if (!opts.force && getWorkingTreeStatusForFile(canonicalFile) === 'dirty') {
+ throw opError('dirty_tree', 'Commit or stash canonical skill edits before optimization.',
+ `${canonicalFile} has uncommitted Git changes. Ask the user whether to commit or stash them, then start the optimization again; nothing ran and nothing was spent.`);
+ }
const bundled = getBundledSkillContext(skillsDir, opts.skillName);
const mutate = shouldMutateSkillFile(bundled, opts).mutate;
const proposalId = randomUUID(), root = join(configDir(), 'skillopt-proposals', proposalId);
diff --git a/src/core/shared-skills/policy.ts b/src/core/shared-skills/policy.ts
index 0eb8a59b6a..8e73e578f2 100644
--- a/src/core/shared-skills/policy.ts
+++ b/src/core/shared-skills/policy.ts
@@ -1,5 +1,8 @@
import { randomUUID } from 'node:crypto';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { opError, type OperationContext } from '../ops/contract.ts';
+import { readFix, scopeDeniedError } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
+import { policyFix } from './fixes.ts';
import { sourceScopeOpts } from '../ops/context.ts';
import { hasScope } from '../scope.ts';
import { currentVerifiedLocalWriter, type LocalGrant } from '../persistence/identity.ts';
@@ -9,11 +12,28 @@ import type { SqlEngine, WriteAuthority } from '../persistence/model.ts';
import { stringList } from './manifest.ts';
import type { SharedSkillPolicy, SkillFileClass, StoredSkillFile } from './model.ts';
+const SOURCES_FIX = readFix('Lists the registered sources and whether each is archived.', {
+ argv: ['gbrain', 'sources', 'list', '--json'], mcp: { tool: 'sources_list', arguments: {} },
+});
+/** The host-side grant listing for a principal kind: the local writer registrations, or the OAuth clients and tokens. */
+function grantFix(kind: string | undefined, why: string): Action {
+ const local = kind === 'local_stdio' || kind === 'local_cli';
+ const argv = local ? ['gbrain', 'auth', 'local-writer', 'list', '--json'] : ['gbrain', 'auth', 'clients', '--json'];
+ if (kind === 'local_cli') return readFix(why, { argv });
+ return {
+ argv, consent: [], actor: local ? 'user' : 'host_admin', why, requires_exclusive: false,
+ user_message: local
+ ? 'This gbrain connection is missing access it needs. Please review its registration by running the command shown in a terminal on this machine.'
+ : 'This gbrain connection is missing access it needs. Please ask whoever runs the gbrain server to review its grant with the command shown.',
+ };
+}
+
export function skillPrincipal(ctx: OperationContext): string {
const p = ctx.auth?.principal ?? currentVerifiedLocalWriter()?.principal;
if (p) return `${p.kind}:${p.id}`;
if (ctx.remote === false) return 'local_cli';
- throw new OperationError('permission_denied', 'A verified principal is required for shared skills.');
+ throw opError('permission_denied', 'A verified principal is required for shared skills.',
+ 'Connect through an authenticated MCP client (OAuth client or access token), or use the gbrain CLI on the brain host; shared skills apply per-principal grants, so anonymous connections are refused.');
}
function intersect(original: string[], live: string[]): string[] { return original.filter(v => live.includes(v)); }
export async function authorizeSkillRead(ctx: OperationContext, operation: string): Promise<OperationContext> {
@@ -29,7 +49,9 @@ export async function authorizeSkillRead(ctx: OperationContext, operation: strin
auth.allowedOperations != null && !auth.allowedOperations.includes(operation)) ||
[verified.grant, row.grant_ceiling].some(grant => !hasScope(grant.scopes, 'read') ||
grant.operations !== null && !grant.operations.includes(operation))) {
- throw new OperationError('permission_denied', 'The local reader grant excludes this operation.');
+ throw opError('permission_denied', 'The local reader grant excludes this operation.',
+ `This local connection's registration no longer allows ${operation} (it needs read scope and the operation in its grant). The user reviews the registration in a terminal on this machine.`,
+ { fix: grantFix('local_stdio', `Shows the local writer registrations and their grants; ${operation} needs read scope and the operation listed.`) });
}
const scope = sourceScopeOpts(ctx);
let ids = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : null);
@@ -47,7 +69,9 @@ export async function authorizeSkillRead(ctx: OperationContext, operation: strin
}
if (!auth || !auth.principal || auth.grantProjectionDegraded || auth.fenceProjectionDegraded || !hasScope(auth.scopes, 'read') ||
auth.allowedOperations != null && !auth.allowedOperations.includes(operation) || auth.effectiveSurface === 'verbs') {
- throw new OperationError('permission_denied', 'The current grant does not permit shared skill discovery.');
+ throw opError('permission_denied', 'The current grant does not permit shared skill discovery.',
+ `${operation} needs read scope, the operation in this connection's allowed list and the full tool surface (not verbs). Ask the brain host's operator to review this connection's grant.`,
+ { fix: grantFix(auth?.principal?.kind, `Shows each client's scopes and allowed operations; ${operation} needs read scope and the operation listed.`) });
}
let liveSources: string[];
let liveScopes = auth.scopes;
@@ -57,7 +81,9 @@ export async function authorizeSkillRead(ctx: OperationContext, operation: strin
const [row] = await ctx.engine.executeRaw<{ scope: string; source_id: string; federated_read: string[] | null; allowed_operations: string[] | null; grant_revision: number }>(
'SELECT scope,source_id,federated_read,allowed_operations,grant_revision FROM oauth_clients WHERE client_id=$1 AND deleted_at IS NULL', [auth.principal.id]);
if (!row || !hasScope(row.scope.split(/\s+/), 'read') || row.allowed_operations != null && !row.allowed_operations.includes(operation)) {
- throw new OperationError('permission_denied', 'The shared skill reader grant was revoked or narrowed.');
+ throw opError('permission_denied', 'The shared skill reader grant was revoked or narrowed.',
+ `Client ${auth.principal.id} was deleted or no longer allows ${operation}. Ask the brain host's operator to restore its grant, then reconnect.`,
+ { fix: grantFix('oauth_client', `Shows whether client ${auth.principal.id} still exists and which operations it allows.`) });
}
liveSources = [...new Set([row.source_id, ...(row.federated_read ?? [])])].filter(Boolean);
liveScopes = auth.scopes.filter(scope => hasScope(row.scope.split(/\s+/), scope));
@@ -67,11 +93,23 @@ export async function authorizeSkillRead(ctx: OperationContext, operation: strin
const [row] = await ctx.engine.executeRaw<Record<string, unknown>>(
'SELECT * FROM access_tokens WHERE id=$1 AND revoked_at IS NULL', [auth.principal.id]);
const tokenGrant = row ? grantFromTokenRow(row) : undefined;
- if (!tokenGrant || !hasScope(tokenGrant.scopes, 'read')) throw new OperationError('permission_denied', 'The shared skill reader token was revoked.');
- if (tokenGrant.permissionsMalformed) throw new OperationError('permission_denied', 'Invalid reader projection.');
+ if (!tokenGrant || !hasScope(tokenGrant.scopes, 'read')) {
+ throw opError('permission_denied', 'The shared skill reader token was revoked.',
+ 'This access token was revoked or lost read scope. Ask the brain host\'s operator for a current token, then reconnect with it.',
+ { fix: grantFix('legacy_token', 'Shows the active tokens and clients with their scopes.') });
+ }
+ if (tokenGrant.permissionsMalformed) {
+ throw opError('permission_denied', 'Invalid reader projection.',
+ 'This access token\'s stored permissions are malformed, so gbrain will not guess which sources it may read. Ask the brain host\'s operator to reissue the token.',
+ { fix: grantFix('legacy_token', 'Shows the active tokens and clients so the operator can reissue this one.') });
+ }
const parsed = authSourcesFromGrant(tokenGrant);
const currentOperations = tokenGrant.allowedOperations;
- if (currentOperations != null && !currentOperations.includes(operation)) throw new OperationError('permission_denied', 'The current legacy operation grant excludes this read.');
+ if (currentOperations != null && !currentOperations.includes(operation)) {
+ throw opError('permission_denied', 'The current legacy operation grant excludes this read.',
+ `This access token's allowed operations exclude ${operation}. Ask the brain host's operator to allow it, or connect with a token that does.`,
+ { fix: grantFix('legacy_token', `Shows each token's allowed operations; ${operation} must be listed.`) });
+ }
liveScopes = auth.scopes.filter(scope => hasScope(tokenGrant.scopes, scope));
liveOperations = auth.allowedOperations == null ? currentOperations : currentOperations == null ? auth.allowedOperations : intersect(auth.allowedOperations, currentOperations);
liveSources = parsed.allowedSources ?? [parsed.sourceId];
@@ -88,12 +126,18 @@ export function assertSkillCapability(ctx: OperationContext, capability: 'skill_
const operations = auth?.allowedOperations ?? local?.operations;
if (auth?.grantProjectionDegraded || auth?.fenceProjectionDegraded || !scopes.includes(capability) ||
!hasScope(scopes, capability === 'skill_publisher' ? 'admin' : 'write') || !operations?.includes(operation)) {
- throw new OperationError('permission_denied', `This operation requires explicit ${capability} authority and an operation grant.`);
+ throw scopeDeniedError({ op: operation, required: [capability, capability === 'skill_publisher' ? 'admin' : 'write'], auth,
+ transport: ctx.transport === 'http' ? 'http' : 'stdio', legacy_error: 'permission_denied',
+ message: `This operation requires explicit ${capability} authority and an operation grant.` });
}
}
export async function assertStoredSkillCapability(engine: SqlEngine, authority: WriteAuthority, capability: 'skill_editor' | 'skill_publisher', lock = false): Promise<void> {
if (!authority.remote && authority.principal.kind === 'local_cli') return;
- if (!authority.scopes.includes(capability)) throw new OperationError('permission_denied', `The accepted request lacks ${capability}.`);
+ if (!authority.scopes.includes(capability)) {
+ throw opError('permission_denied', `The accepted request lacks ${capability}.`,
+ `This request was accepted without ${capability}, so it cannot publish. Ask the brain host's operator to grant ${capability} to this connection, then submit a new request.`,
+ { fix: grantFix(authority.principal.kind, `Shows the grant of the principal that submitted the request; it needs ${capability}.`) });
+ }
const suffix = lock ? ' FOR SHARE' : '';
let scopes: string[] = [];
if (authority.principal.kind === 'oauth_client') {
@@ -106,7 +150,11 @@ export async function assertStoredSkillCapability(engine: SqlEngine, authority:
const [row] = await engine.executeRaw<{ grant_ceiling: { scopes: string[] } }>(`SELECT grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid AND revoked_at IS NULL${suffix}`, [authority.principal.id]);
scopes = row?.grant_ceiling?.scopes ?? [];
}
- if (!scopes.includes(capability) || !hasScope(scopes, capability === 'skill_publisher' ? 'admin' : 'write')) throw new OperationError('permission_denied', `The current grant lacks ${capability} or its base scope.`);
+ if (!scopes.includes(capability) || !hasScope(scopes, capability === 'skill_publisher' ? 'admin' : 'write')) {
+ throw opError('permission_denied', `The current grant lacks ${capability} or its base scope.`,
+ `The principal that submitted this request no longer holds ${capability} with ${capability === 'skill_publisher' ? 'admin' : 'write'} scope (it was revoked or narrowed). Ask the brain host's operator to restore the grant, then submit a new request.`,
+ { fix: grantFix(authority.principal.kind, `Shows the submitting principal's current grant; it needs ${capability}.`) });
+ }
}
export async function publicationEnabled(ctx: OperationContext): Promise<boolean> {
const value = await ctx.engine.getConfig('mcp.publish_skills');
@@ -117,7 +165,8 @@ export function normalizePolicy(value: unknown): SharedSkillPolicy {
const classes = stringList(p?.classes, 'classes');
if (!p || p.version !== 1 || typeof p.enabled !== 'boolean' || typeof p.allow_follow !== 'boolean' ||
classes.some(c => !['prose', 'reference', 'asset', 'script'].includes(c)) || p.enabled && !classes.includes('prose')) {
- throw new OperationError('invalid_params', 'A version 1 publication policy with explicit consent is required.');
+ throw opError('invalid_params', 'A version 1 publication policy with explicit consent is required.',
+ 'Pass policy as {"version": 1, "enabled": true or false, "allow_follow": true or false, "classes": a subset of prose, reference, asset and script (including prose when enabled), "audiences": [...], "requirements": [...]}.');
}
return { version: 1, enabled: p.enabled, allow_follow: p.allow_follow, classes: classes as SkillFileClass[],
audiences: stringList(p.audiences, 'audiences'), requirements: stringList(p.requirements, 'requirements') };
@@ -145,15 +194,22 @@ export async function setSharedSkillPolicy(ctx: OperationContext, sourceId: stri
await initializeLocalPersistence(ctx);
return ctx.engine.transaction(async tx => {
const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'Publication requires an active source.');
+ if (!source || source.archived) {
+ throw opError('source_changed', 'Publication requires an active source.',
+ `Source ${sourceId} is archived or not registered; approve a policy for an active source.`, { fix: SOURCES_FIX });
+ }
const authority = await submissionAuthority({ ...ctx, engine: tx }, 'set_skill_policy', sourceId, source.incarnation, 'skills');
await assertStoredSkillCapability(tx, authority, 'skill_publisher', true);
const existing = await readSharedSkillPolicy(tx, sourceId, source.incarnation, await publicationEnabled({ ...ctx, engine: tx }), true);
if (!['legacy-prose', 'consent-required'].includes(existing.epoch) && expectedEpoch === undefined) {
- throw new OperationError('revision_required', 'Review the current policy and supply its expected_policy_epoch before changing disclosure.');
+ throw opError('revision_required', 'Review the current policy and supply its expected_policy_epoch before changing disclosure.',
+ `Read source ${sourceId}'s current policy, review the change with the user, then pass its policy_epoch as expected_policy_epoch.`,
+ { fix: policyFix(sourceId) });
}
if (expectedEpoch !== undefined && expectedEpoch !== existing.epoch && !(expectedEpoch === null && existing.epoch.startsWith('legacy-')) && !(expectedEpoch === null && existing.epoch === 'consent-required')) {
- throw new OperationError('revision_conflict', 'Publication policy changed; review its current disclosure before approving.');
+ throw opError('revision_conflict', 'Publication policy changed; review its current disclosure before approving.',
+ `Source ${sourceId}'s policy changed since it was reviewed. Read it again, review the difference with the user, and pass the new policy_epoch.`,
+ { fix: policyFix(sourceId) });
}
const epoch = randomUUID();
await tx.executeRaw(`INSERT INTO shared_skill_policies(source_id,source_incarnation,epoch,policy) VALUES($1,$2::uuid,$3::uuid,$4::text::jsonb)
@@ -171,10 +227,15 @@ export async function getSharedSkillPolicy(ctx: OperationContext, sourceId: stri
const active = await authorizeSkillRead(ctx, 'get_skill_policy');
const scope = sourceScopeOpts(active);
if (scope.sourceIds ? !scope.sourceIds.includes(sourceId) : scope.sourceId && scope.sourceId !== sourceId) {
- throw new OperationError('permission_denied', 'The publication policy source is outside this grant.');
+ throw opError('permission_denied', 'The publication policy source is outside this grant.',
+ `This connection's grant does not cover source ${sourceId}. Read the policy of a granted source, or ask the brain host's operator to extend the grant.`,
+ { fix: grantFix(ctx.auth?.principal?.kind ?? (ctx.remote === false ? 'local_cli' : undefined), `Shows this connection's granted sources; ${sourceId} must be among them.`) });
}
const [source] = await ctx.engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 AND NOT archived', [sourceId]);
- if (!source) throw new OperationError('source_changed', 'The publication policy source is not active.');
+ if (!source) {
+ throw opError('source_changed', 'The publication policy source is not active.',
+ `Source ${sourceId} is archived or not registered.`, { fix: SOURCES_FIX });
+ }
if (ctx.remote !== false) {
const { submissionAuthority } = await import('../persistence/authority.ts');
const authority = await submissionAuthority(ctx, 'get_skill_policy', sourceId, source.incarnation, 'skills');
diff --git a/src/core/shared-skills/publication.ts b/src/core/shared-skills/publication.ts
index 766710e8d8..fd536223be 100644
--- a/src/core/shared-skills/publication.ts
+++ b/src/core/shared-skills/publication.ts
@@ -6,6 +6,7 @@ import type { GBrainConfig } from '../config.ts';
import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
import { hostFix, readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
+import { catalogFix, policyFix, skillHeadFix } from './fixes.ts';
import { enforceClientSlugFence, enforceSubagentSlugFence } from '../ops/context.ts';
import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from '../persistence/authority.ts';
import { admitWrite, assertReplayIntent, getWriteRequest, intentDigest } from '../persistence/journal.ts';
@@ -43,24 +44,6 @@ interface HostAdoption {
}
type SkillAuthority = WriteAuthority & { skillSlugsUsed?: string[]; skillAdoptionPreconditions?: Record<string, string | null>; skillAdoptionInventory?: Record<string, string | null> };
const DOCTOR_FIX = readFix('Shows the brain host\'s storage and catalog health so the inconsistency can be reported with evidence.', { argv: ['gbrain', 'doctor', '--json'] });
-function skillHeadFix(sourceId: string, packId: string, name: string): Action {
- return readFix(`Reads the current head revision of ${packId}/${name} on source ${sourceId}; resubmit against it with a new request_id.`, {
- argv: ['gbrain', 'skill', '--schema-version', '2', '--source-id', sourceId, '--pack-id', packId, '--name', name],
- mcp: { tool: 'get_skill', arguments: { schema_version: 2, source_id: sourceId, pack_id: packId, name } },
- });
-}
-function catalogFix(sourceId: string): Action {
- return readFix(`Lists source ${sourceId}'s current shared skills with their source_incarnation, pack_id and head revisions.`, {
- argv: ['gbrain', 'skills', '--schema-version', '2', '--source-id', sourceId],
- mcp: { tool: 'list_skills', arguments: { schema_version: 2, source_id: sourceId } },
- });
-}
-function policyFix(sourceId: string): Action {
- return readFix(`Shows source ${sourceId}'s owner-approved publication policy and its epoch; widening it is the publisher's decision (set_skill_policy), never the editor's.`, {
- argv: ['gbrain', 'skill-policy', '--source-id', sourceId],
- mcp: { tool: 'get_skill_policy', arguments: { source_id: sourceId } },
- });
-}
function ownerStatusFix(sourceId: string, ctx?: OperationContext): Action {
const argv = ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'];
const why = `Shows source ${sourceId}'s designated canonical owner, its binding and any pending recovery; claiming, moving or rebinding ownership is a deliberate operator decision.`;
diff --git a/src/core/shared-skills/setup-files.ts b/src/core/shared-skills/setup-files.ts
index 80c21d80b1..740fe42492 100644
--- a/src/core/shared-skills/setup-files.ts
+++ b/src/core/shared-skills/setup-files.ts
@@ -1,7 +1,7 @@
import { createHash } from 'node:crypto';
import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
-import { OperationError } from '../ops/contract.ts';
+import { opError, OperationError } from '../ops/contract.ts';
export const setupHash = (content: string | Uint8Array): string => createHash('sha256').update(content).digest('hex');
@@ -11,7 +11,10 @@ export function checkedContentRoot(path: string): string {
while (true) {
if (existsSync(current)) {
const stat = lstatSync(current);
- if (stat.isSymbolicLink() || !stat.isDirectory()) throw new OperationError('local_conflict', 'A content-root component is not a real directory.');
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
+ throw opError('local_conflict', 'A content-root component is not a real directory.',
+ `${current} is a symlink or a file, so ${root} cannot be a content root. Choose a path whose every parent is a real directory.`);
+ }
}
const parent = dirname(current);
if (parent === current) break;
@@ -36,35 +39,64 @@ export function inventorySkillpack(root: string): PackInventory | null {
const read = (path: string): string => {
const absolute = join(root, path);
const rel = relative(realpathSync(root), realpathSync(absolute));
- if (isAbsolute(rel) || rel === '..' || rel.startsWith('../')) throw new OperationError('local_conflict', 'A skillpack path escapes its source root.');
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('../')) {
+ throw opError('local_conflict', 'A skillpack path escapes its source root.',
+ `${path} resolves outside ${root}. Replace the link with the real files inside the pack (or drop the entry from skillpack.json), then run the migration again.`);
+ }
const stat = lstatSync(absolute);
- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 262144) throw new OperationError('local_conflict', 'A skillpack file is unsafe or exceeds the migration limit.');
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 262144) {
+ throw opError('local_conflict', 'A skillpack file is unsafe or exceeds the migration limit.',
+ `${path} in ${root} must be a regular, singly linked file of at most 262144 bytes; shrink, split or remove it, then run the migration again.`);
+ }
const data = readFileSync(absolute);
bytes += data.length;
- if (Object.keys(hashes).length >= 256 || bytes > 4 * 1024 * 1024) throw new OperationError('local_conflict', 'The skillpack exceeds the bounded migration inventory.');
+ if (Object.keys(hashes).length >= 256 || bytes > 4 * 1024 * 1024) {
+ throw opError('local_conflict', 'The skillpack exceeds the bounded migration inventory.',
+ `The pack in ${root} holds more than 255 files or 4 MiB; move large assets out of the declared skills and shared_deps, then run the migration again.`);
+ }
hashes[path] = setupHash(data);
return data.toString('utf8');
};
let manifest: { skills?: unknown; shared_deps?: unknown; excluded_from_install?: unknown };
try { manifest = JSON.parse(read('skillpack.json')); }
- catch (error) { if (error instanceof OperationError) throw error; throw new OperationError('local_conflict', 'The existing skillpack manifest is malformed.'); }
+ catch (error) {
+ if (error instanceof OperationError) throw error;
+ throw opError('local_conflict', 'The existing skillpack manifest is malformed.',
+ `${manifestPath} is not valid JSON. Fix or restore it from Git, then run the migration again.`);
+ }
if (!Array.isArray(manifest.skills) || manifest.skills.some(path => typeof path !== 'string' || !/^skills\/[a-z0-9][a-z0-9-]*$/.test(path))) {
- throw new OperationError('local_conflict', 'The existing skillpack has ambiguous skill paths.');
+ throw opError('local_conflict', 'The existing skillpack has ambiguous skill paths.',
+ `Make "skills" in ${manifestPath} a list of top-level skill directories with lowercase names (for example "skills/meeting-notes"), then run the migration again.`);
}
const names = (manifest.skills as string[]).map(path => path.slice(7));
- if (new Set(names).size !== names.length) throw new OperationError('local_conflict', 'The existing skillpack has duplicate skill names.');
+ if (new Set(names).size !== names.length) {
+ throw opError('local_conflict', 'The existing skillpack has duplicate skill names.',
+ `List each skill once in "skills" of ${manifestPath}, then run the migration again.`);
+ }
const visit = (path: string, depth: number): void => {
- if (++entries > 1024 || depth > 8 || path.includes('\\') || path.split('/').some(part => !part || part === '.' || part === '..') || isAbsolute(path)) throw new OperationError('local_conflict', 'The skillpack contains an unsafe dependency path.');
+ if (++entries > 1024 || depth > 8 || path.includes('\\') || path.split('/').some(part => !part || part === '.' || part === '..') || isAbsolute(path)) {
+ throw opError('local_conflict', 'The skillpack contains an unsafe dependency path.',
+ `Declared skill and shared_deps paths in ${manifestPath} must be relative forward-slash paths without empty, . or .. segments, at most 8 directories deep and 1024 entries in total; fix the manifest, then run the migration again.`);
+ }
const stat = lstatSync(join(root, path));
- if (stat.isSymbolicLink()) throw new OperationError('local_conflict', 'Skillpack migration does not follow symlinks.');
+ if (stat.isSymbolicLink()) {
+ throw opError('local_conflict', 'Skillpack migration does not follow symlinks.',
+ `${path} in ${root} is a symlink; replace it with the real file or directory, then run the migration again.`);
+ }
if (stat.isDirectory()) {
for (const name of readdirSync(join(root, path)).sort()) visit(`${path}/${name}`, depth + 1);
} else if (!hashes[path]) read(path);
};
for (const path of manifest.skills as string[]) visit(path, 0);
- if (manifest.shared_deps !== undefined && (!Array.isArray(manifest.shared_deps) || manifest.shared_deps.some(path => typeof path !== 'string'))) throw new OperationError('local_conflict', 'The skillpack dependency declaration is malformed.');
+ if (manifest.shared_deps !== undefined && (!Array.isArray(manifest.shared_deps) || manifest.shared_deps.some(path => typeof path !== 'string'))) {
+ throw opError('local_conflict', 'The skillpack dependency declaration is malformed.',
+ `Make "shared_deps" in ${manifestPath} a list of relative paths (or remove it), then run the migration again.`);
+ }
for (const path of (manifest.shared_deps ?? []) as string[]) visit(path, 0);
- if (manifest.excluded_from_install !== undefined && (!Array.isArray(manifest.excluded_from_install) || manifest.excluded_from_install.some(name => typeof name !== 'string'))) throw new OperationError('local_conflict', 'The skillpack exclusions are malformed.');
+ if (manifest.excluded_from_install !== undefined && (!Array.isArray(manifest.excluded_from_install) || manifest.excluded_from_install.some(name => typeof name !== 'string'))) {
+ throw opError('local_conflict', 'The skillpack exclusions are malformed.',
+ `Make "excluded_from_install" in ${manifestPath} a list of skill names (or remove it), then run the migration again.`);
+ }
return { hashes, names, excluded_from_install: (manifest.excluded_from_install ?? []) as string[] };
}
diff --git a/src/core/shared-skills/setup.ts b/src/core/shared-skills/setup.ts
index ae5d44e032..1cbf517fa8 100644
--- a/src/core/shared-skills/setup.ts
+++ b/src/core/shared-skills/setup.ts
@@ -2,7 +2,8 @@ import { existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
import { gbrainPath, isThinClient } from '../config.ts';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { opError, type OperationContext } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { claimWorktree, getWorktreeBinding } from '../persistence/ownership.ts';
import { activateSharedSkillPersistence } from '../persistence/skill-activation.ts';
import { checkedContentRoot } from './setup-files.ts';
@@ -50,7 +51,10 @@ export async function saveContentReceipt(ctx: OperationContext, receipt: SharedC
}
export async function setupSharedBrainContent(ctx: OperationContext, options: SharedContentOptions = {}): Promise<SharedContentReceipt> {
- if (ctx.remote !== false) throw new OperationError('permission_denied', 'Content-root setup requires the trusted local host.');
+ if (ctx.remote !== false) {
+ throw opError('permission_denied', 'Content-root setup requires the trusted local host.',
+ 'Content-root setup runs only from gbrain init on the brain host; a remote connection cannot create or choose content directories.');
+ }
const receipt: SharedContentReceipt = {
version: 1, brain_id: null, source_id: options.sourceId ?? ctx.sourceId ?? 'default', source_incarnation: null,
root: null, repository_kind: 'remote', backup: 'not_verified', status: 'action_required', stage: 'root', pending_actions: [], owned_root: false,
@@ -63,7 +67,11 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Sh
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');
const [source] = await ctx.engine.executeRaw<{ id: string; incarnation: string; local_path: string | null }>(
'SELECT id,incarnation,local_path FROM sources WHERE id=$1 AND NOT archived', [sourceId]);
- if (!brain || !source) throw new OperationError('source_changed', 'Content setup requires the persistent brain identity and an active selected source.');
+ if (!brain || !source) {
+ throw opError('source_changed', 'Content setup requires the persistent brain identity and an active selected source.',
+ `Source ${sourceId} is archived or not registered, or this brain has no persistence identity yet. Check the registered sources, then run gbrain init again for an active one.`,
+ { fix: readFix('Lists the registered sources and whether each is archived.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
+ }
receipt.brain_id = brain.brain_id;
receipt.source_id = sourceId;
receipt.source_incarnation = source.incarnation;
@@ -83,12 +91,25 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Sh
const saved = await ctx.engine.getConfig(key);
let prior: SharedContentReceipt | null = null;
if (saved) {
- try { prior = JSON.parse(saved); } catch { throw new OperationError('local_conflict', 'The content setup checkpoint is malformed.'); }
- if (prior?.version !== 1 || prior.brain_id !== brain.brain_id || prior.source_incarnation !== source.incarnation) throw new OperationError('local_conflict', 'The content setup checkpoint does not match this brain.');
+ const checkpointFix = { fix: readFix('Prints the saved content setup checkpoint.', { argv: ['gbrain', 'config', 'get', key] }) };
+ try { prior = JSON.parse(saved); } catch {
+ throw opError('local_conflict', 'The content setup checkpoint is malformed.',
+ `The saved content setup checkpoint for source ${sourceId} (config key ${key}) is not valid JSON. Show it to the user and ask how to proceed before changing it.`, checkpointFix);
+ }
+ if (prior?.version !== 1 || prior.brain_id !== brain.brain_id || prior.source_incarnation !== source.incarnation) {
+ throw opError('local_conflict', 'The content setup checkpoint does not match this brain.',
+ `The content setup checkpoint for source ${sourceId} (config key ${key}) belongs to another brain or source incarnation. Show it to the user and ask how to proceed before changing it.`, checkpointFix);
+ }
}
const existingRoot = source.local_path || (sourceId === 'default' ? await ctx.engine.getConfig('sync.repo_path') : null);
- if (options.root && existingRoot && resolve(options.root) !== resolve(existingRoot)) throw new OperationError('local_conflict', 'The selected source already has a different content root; use an explicit source rebind.');
- if (options.dbOnly && existingRoot) throw new OperationError('local_conflict', 'DB-only setup cannot detach an existing canonical source root. Preserve it or use an explicit topology migration.');
+ if (options.root && existingRoot && resolve(options.root) !== resolve(existingRoot)) {
+ throw opError('local_conflict', 'The selected source already has a different content root; use an explicit source rebind.',
+ `Source ${sourceId} already uses ${existingRoot}. Run gbrain init without --content-root to keep it; moving it is a deliberate rebind the user must approve.`);
+ }
+ if (options.dbOnly && existingRoot) {
+ throw opError('local_conflict', 'DB-only setup cannot detach an existing canonical source root. Preserve it or use an explicit topology migration.',
+ `Source ${sourceId} already has the canonical root ${existingRoot}; run gbrain init without --db-only to keep it.`);
+ }
if (options.dbOnly || !options.root && !existingRoot && prior?.repository_kind === 'db_only') {
receipt.repository_kind = 'db_only';
receipt.pending_actions = ['Memory remains available. Select a host canonical root and validate a full export/import round trip before shared publication.'];
@@ -109,13 +130,23 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Sh
const gitProbe = existsSync(join(root, '.git')) ? spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 }) : null;
receipt.repository_kind = gitProbe?.status === 0 && resolve(gitProbe.stdout.trim()) === root ? 'git' : 'content_directory';
const existed = existsSync(root);
- if (prior?.root && prior.root !== root) throw new OperationError('local_conflict', 'The canonical root changed after setup began.');
- if (existingRoot && !existed) throw new OperationError('local_conflict', 'The registered content root is missing; restore it rather than creating a replacement.');
- if (!existingRoot && existed && !prior && readdirSync(root).length > 0) throw new OperationError('local_conflict', 'The requested root contains unowned files; register an existing source explicitly instead.');
+ if (prior?.root && prior.root !== root) {
+ throw opError('local_conflict', 'The canonical root changed after setup began.',
+ `Content setup for source ${sourceId} began at ${prior.root}; resume it with --content-root ${prior.root}, or ask the user before abandoning that setup.`);
+ }
+ if (existingRoot && !existed) {
+ throw opError('local_conflict', 'The registered content root is missing; restore it rather than creating a replacement.',
+ `Source ${sourceId}'s registered root ${root} does not exist. Restore it (for example from its Git remote or backup), then run gbrain init again.`);
+ }
+ if (!existingRoot && existed && !prior && readdirSync(root).length > 0) {
+ throw opError('local_conflict', 'The requested root contains unowned files; register an existing source explicitly instead.',
+ `${root} already has files. Pass --content-root a new or empty directory, or register that directory as a source with gbrain sources add.`);
+ }
if (prior?.owned_root && existed) {
const stat = statSync(root);
if (prior.root_identity ? prior.root_identity.device !== stat.dev || prior.root_identity.inode !== stat.ino : readdirSync(root).length > 0) {
- throw new OperationError('local_conflict', 'The owned root changed or gained unverified files after setup was interrupted.');
+ throw opError('local_conflict', 'The owned root changed or gained unverified files after setup was interrupted.',
+ `${root} was replaced or gained files after content setup was interrupted, so setup stopped. Ask the user whether those files belong there before resuming gbrain init.`);
}
receipt.root_identity = { device: stat.dev, inode: stat.ino };
}
@@ -141,7 +172,10 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Sh
await saveContentReceipt(ctx, receipt);
}
if (options.git === 'init' && receipt.repository_kind !== 'git') {
- if (!receipt.owned_root || readdirSync(root).length !== 0) throw new OperationError('local_conflict', 'Git initialization is allowed only in a newly owned empty content directory.');
+ if (!receipt.owned_root || readdirSync(root).length !== 0) {
+ throw opError('local_conflict', 'Git initialization is allowed only in a newly owned empty content directory.',
+ `${root} is not a new empty directory gbrain created; run gbrain init without --git and initialize Git there yourself if the user wants it.`);
+ }
const git = spawnSync('git', ['init', '--quiet', root], { encoding: 'utf8', timeout: 15_000 });
if (!git.error && git.status === 0) receipt.repository_kind = 'git';
else receipt.pending_actions.push('Git initialization was unavailable; install Git and explicitly initialize this content directory later.');
@@ -149,7 +183,10 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Sh
if (receipt.repository_kind === 'content_directory' && !receipt.pending_actions.length) receipt.pending_actions.push('Optional: initialize Git explicitly; configure an off-host backup separately.');
if (receipt.owned_root && receipt.repository_kind === 'content_directory') {
const enclosing = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });
- if (enclosing.status === 0 && resolve(enclosing.stdout.trim()) !== root) throw new OperationError('local_conflict', 'The new content directory is inside another Git worktree. Choose a separate root or explicitly initialize Git here; setup will not claim its parent repository.');
+ if (enclosing.status === 0 && resolve(enclosing.stdout.trim()) !== root) {
+ throw opError('local_conflict', 'The new content directory is inside another Git worktree. Choose a separate root or explicitly initialize Git here; setup will not claim its parent repository.',
+ `${root} is inside the Git worktree ${enclosing.stdout.trim()}. Pass --content-root a path outside any repository, or add --git so the content directory gets its own repository.`);
+ }
}
if (!existingRoot) await ctx.engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2 AND incarnation=$3::uuid AND local_path IS NULL', [root, sourceId, source.incarnation]);
receipt.stage = 'owner';
@@ -166,7 +203,11 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Sh
}
let binding = await getWorktreeBinding(ctx.engine, sourceId);
if (!binding) binding = await claimWorktree(ctx.engine, sourceId, root);
- if (binding.state !== 'active' || !binding.owner_host_id) throw new OperationError('owner_unavailable', 'The canonical content owner is not active.');
+ if (binding.state !== 'active' || !binding.owner_host_id) {
+ throw opError('owner_unavailable', 'The canonical content owner is not active.',
+ `Source ${sourceId}'s canonical owner is ${binding.state}, so the packaged skills were not installed. Inspect the binding; activating or moving ownership is the user's decision.`,
+ { fix: readFix(`Shows source ${sourceId}'s owner binding and any pending recovery.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
+ }
if (!brain.skill_bundles_enabled) await activateSharedSkillPersistence(ctx.engine, { confirmQuiesced: true });
receipt.stage = 'pack';
await saveContentReceipt(ctx, receipt);
@@ -197,7 +238,10 @@ export async function installPackagedSharedSkills(ctx: OperationContext, sourceI
files: [{ path: `${path}/SKILL.md`, content: files[`${path}/SKILL.md`], file_class: 'prose' }],
})),
});
- if (result.receipts.some(receipt => (receipt.write_request as { state?: string } | undefined)?.state !== 'committed')) {
- throw new OperationError('publication_pending', 'The default pack was accepted but is not fully committed; rerun init to resume its durable requests.');
+ const pending = result.receipts.map(receipt => receipt.write_request as { state?: string; request_id?: string } | undefined).find(request => request?.state !== 'committed');
+ if (pending) {
+ throw opError('publication_pending', 'The default pack was accepted but is not fully committed; rerun init to resume its durable requests.',
+ `Inspect the accepted request${pending.request_id ? ` ${pending.request_id}` : ''} first; gbrain init resumes the same durable request (same request_id), so it never publishes the pack twice.`,
+ pending.request_id ? { fix: readFix('Shows whether the default pack publication committed, is still pending, or failed.', { argv: ['gbrain', 'write-request', '--', pending.request_id] }) } : {});
}
}