Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

agent contract: job authorization and persistence write-path refusals name their own next step

garrytan9b660ccef206
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 96ed1305e6..05a5f782c1 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -1,12 +1,4 @@
# shrink-only baseline for scripts/check-agent-contract.ts rule suggestionless-operation-error: path<TAB>count
src/commands/book-mirror.ts 1
-src/core/facts/backstop.ts 1
-src/core/minions/submission-authority.ts 1
-src/core/minions/tool-write-identity.ts 1
-src/core/page-state/import-guard.ts 1
-src/core/persistence/effect-facts.ts 3
-src/core/persistence/effect-journal.ts 1
-src/core/persistence/effect-targets.ts 2
src/core/search/evidence-delivery.ts 1
-src/core/source-local-reference-index.ts 2
src/mcp/dispatch.ts 1
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 787e83acba..584bcb74fc 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -301,8 +301,9 @@ export async function runFactsBackstop(
const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');
if (await managedPersistenceEnabled(ctx.engine)) {
if (mode !== 'inline') {
- const { OperationError } = await import('../ops/contract.ts');
- throw new OperationError('writer_coordinator_required', 'Managed page backstops must use the durable publication outbox.');
+ const { opError } = await import('../ops/contract.ts');
+ throw opError('writer_coordinator_required', 'Managed page backstops must use the durable publication outbox.',
+ `On a managed brain the publication outbox queues facts for ${parsedPage.slug ?? 'a page'}; a direct ${mode} backstop is a gbrain bug in its caller. The page write is unaffected. Report it with gbrain --version.`);
}
return { mode: 'inline', ...await runPipeline(parsedPage, ctx, ctx.abortSignal) };
}
diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.ts
index 1d2e961107..6ac0edb00b 100644
--- a/src/core/minions/submission-authority.ts
+++ b/src/core/minions/submission-authority.ts
@@ -4,7 +4,7 @@ import { createHash } from 'node:crypto';
import { realpathSync, statSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import type { AuthInfo, OperationContext } from '../ops/contract.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
import { catalogueError } from '../error-catalogue.ts';
import { STOP_PRODUCERS, legacyRecoveryHint, selectCommand } from './legacy-selection.ts';
import { normalizeSlugPrefix } from '../ops/context.ts';
@@ -50,8 +50,8 @@ export function currentJobSignal(): AbortSignal | undefined { return executionAu
export function withSubmissionAuthority<T>(authority: SubmissionAuthority, fn: () => T, signal?: AbortSignal): T {
return executionAuthority.run({ authority, signal }, fn);
}
-function deny(message: string): never {
- throw new OperationError('permission_denied', `Queued job authorization: ${message}`);
+function deny(message: string, suggestion: string): never {
+ throw opError('permission_denied', `Queued job authorization: ${message}`, suggestion);
}
function record(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === 'object' && !Array.isArray(value)
@@ -95,26 +95,32 @@ export function parseSubmissionAuthority(value: unknown): SubmissionAuthority |
}
export function assertSameAuthority(actual: unknown, expected: SubmissionAuthority): void {
const parsed = parseSubmissionAuthority(actual);
- if (!parsed || authorityDigest(parsed) !== authorityDigest(expected)) deny('coalescing across submission authorities is forbidden');
+ if (!parsed || authorityDigest(parsed) !== authorityDigest(expected)) deny('coalescing across submission authorities is forbidden',
+ 'A job with this idempotency key was queued under another principal or grant. Submit with a new idempotency key, or leave that job to its submitter.');
}
async function sourceBoundary(engine: BrainEngine, sourceId: string, jobName: RemoteJobName) {
const [source] = await engine.executeRaw<Record<string, unknown>>(
'SELECT id, local_path, config, archived, created_at FROM sources WHERE id = $1', [sourceId]);
if (!source || source.archived !== false || typeof source.local_path !== 'string' || !source.local_path) {
- deny('an active source with a registered filesystem root is required');
+ deny('an active source with a registered filesystem root is required',
+ `Source ${sourceId} must be active and registered with a directory on the brain host. The brain host operator checks it with gbrain sources list --json.`);
}
let config = source.config;
- if (typeof config === 'string') { try { config = JSON.parse(config); } catch { deny('malformed source config'); } }
- if (!record(config) || record(config)!.kind != null) deny('generic filesystem jobs require an ordinary filesystem source; use the dedicated connector endpoint');
+ if (typeof config === 'string') { try { config = JSON.parse(config); } catch { deny('malformed source config', `Source ${sourceId}'s stored config is not valid JSON on the brain host, so nothing was queued. The brain host operator inspects it with gbrain sources status ${sourceId} --json.`); } }
+ if (!record(config) || record(config)!.kind != null) deny('generic filesystem jobs require an ordinary filesystem source; use the dedicated connector endpoint',
+ `Source ${sourceId} is a connector source: the brain host syncs it with gbrain connectors (connector_sync), not through submit_job.`);
let canonicalRoot: string;
try {
canonicalRoot = realpathSync(source.local_path);
- if (!statSync(canonicalRoot).isDirectory()) deny('registered source root must be a directory');
- } catch { deny('registered source root is unavailable or is not a directory'); }
+ if (!statSync(canonicalRoot).isDirectory()) deny('registered source root must be a directory',
+ `Source ${sourceId}'s registered root is not a directory on the brain host. The brain host operator restores the checkout or re-points it with gbrain sources set-path.`);
+ } catch { deny('registered source root is unavailable or is not a directory',
+ `Source ${sourceId}'s registered root is missing on the brain host. The brain host operator restores the checkout or re-points it with gbrain sources set-path.`); }
let worktreeRoot: string | null = null;
try { worktreeRoot = realpathSync(discoverGitRoot(canonicalRoot)); }
- catch { if (jobName === 'sync') deny('remote sync requires an existing Git working tree; initialize or restore it locally'); }
+ catch { if (jobName === 'sync') deny('remote sync requires an existing Git working tree; initialize or restore it locally',
+ `Source ${sourceId}'s root is not inside a Git working tree, so sync has nothing to diff. Submit import for it instead, or have the brain host operator restore the checkout.`); }
return { canonicalRoot, worktreeRoot, sourceCreatedAt: new Date(source.created_at as string).toISOString() };
}
@@ -125,50 +131,58 @@ export async function assertCurrentRemoteJobPrincipal(engine: BrainEngine, autho
// No fallback projections: an incomplete auth schema cannot authorize background work.
const [row] = await engine.executeRaw<Record<string, unknown>>(
'SELECT client_id, deleted_at, scope, source_id, bound_slug_prefixes, surface, allowed_operations FROM oauth_clients WHERE client_id = $1', [principal.id]);
- if (!row || row.deleted_at != null) deny('OAuth client is missing or revoked');
+ if (!row || row.deleted_at != null) deny('OAuth client is missing or revoked', `OAuth client ${principal.id} was deleted or revoked, so this job does not run. Reconnect with a current client and submit a new job.`);
scopes = typeof row.scope === 'string' ? row.scope.split(/\s+/).filter(Boolean) : [];
sourceId = typeof row.source_id === 'string' ? row.source_id : undefined;
- if (row.bound_slug_prefixes != null) deny('bulk filesystem jobs are unavailable to slug-bound clients');
- if (row.surface != null && row.surface !== 'full') deny('current client surface does not permit generic jobs');
+ if (row.bound_slug_prefixes != null) deny('bulk filesystem jobs are unavailable to slug-bound clients',
+ `Client ${principal.id} is bound to slug prefixes, so it cannot run whole-source jobs. Use page writes, or ask the brain host operator for an unrestricted source grant.`);
+ if (row.surface != null && row.surface !== 'full') deny('current client surface does not permit generic jobs',
+ `Client ${principal.id} is on the ${String(row.surface)} surface; generic jobs need full. Ask the brain host operator to widen this client's surface, then submit a new job.`);
for (const operations of [grant.allowedOperations, row.allowed_operations]) {
if (operations != null && (!Array.isArray(operations) || !operations.every(op => typeof op === 'string') || !operations.includes('submit_job'))) {
- deny('original and current operation grants must authorize submit_job');
+ deny('original and current operation grants must authorize submit_job',
+ `Client ${principal.id}'s operation allowlist does not include submit_job. Ask the brain host operator to add it, then submit a new job.`);
}
}
} else {
const [row] = await engine.executeRaw<Record<string, unknown>>(
'SELECT * FROM access_tokens WHERE id = $1', [principal.id]);
- if (!row || row.revoked_at != null) deny('legacy token is missing or revoked');
+ if (!row || row.revoked_at != null) deny('legacy token is missing or revoked', `Legacy token ${principal.id} was revoked, so this job does not run. Reconnect with a current credential and submit a new job.`);
const tokenGrant = grantFromTokenRow(row);
- if (tokenGrant.permissionsMalformed) deny('malformed token permissions');
+ if (tokenGrant.permissionsMalformed) deny('malformed token permissions', `Legacy token ${principal.id}'s stored permissions cannot be read. Ask the brain host operator to reissue the credential, then submit a new job.`);
scopes = tokenGrant.scopes;
sourceId = authSourcesFromGrant(tokenGrant).sourceId;
}
if (!hasScope(grant.scopes, 'admin') || !hasScope(scopes, 'admin') || sourceId !== grant.sourceId) {
- deny('the original grant and current principal must both authorize this source and admin operation');
+ deny('the original grant and current principal must both authorize this source and admin operation',
+ `This job needs the admin scope on source ${grant.sourceId} both when submitted and now. Ask the brain host operator to grant it, then submit a new job.`);
}
}
export async function prepareRemoteJob(
ctx: OperationContext, name: string, input: unknown,
): Promise<{ data: Record<string, unknown>; authority: RemoteJobAuthority }> {
- if (!REMOTE_JOB_NAMES.includes(name as RemoteJobName)) deny('unsupported remote job; only sync, import, lint and lint-fix are available through remote submit_job');
+ if (!REMOTE_JOB_NAMES.includes(name as RemoteJobName)) deny('unsupported remote job; only sync, import, lint and lint-fix are available through remote submit_job',
+ `Remote submit_job queues sync, import, lint and lint-fix only. Use the dedicated operation for ${name} work, or ask the user to run it with the gbrain CLI on the brain host.`);
const principal = ctx.auth?.principal;
const sourceId = ctx.auth?.sourceId;
if (!principal || !sourceId || !isValidSourceId(sourceId) || ctx.sourceId !== sourceId || !hasScope(ctx.auth?.scopes ?? [], 'admin')) {
- deny('an authenticated persistent principal and scalar write source are required; use local CLI or a dedicated operation');
+ deny('an authenticated persistent principal and scalar write source are required; use local CLI or a dedicated operation',
+ 'Connect with a persistent OAuth client bound to one write source and holding the admin scope, or ask the user to run the job with the gbrain CLI on the brain host.');
}
- if (ctx.auth?.boundSlugPrefixes !== undefined || ctx.auth?.fenceProjectionDegraded) deny('bulk filesystem jobs require an unrestricted source grant');
+ if (ctx.auth?.boundSlugPrefixes !== undefined || ctx.auth?.fenceProjectionDegraded) deny('bulk filesystem jobs require an unrestricted source grant',
+ 'This connection is slug-bound (or its grant projection is degraded), so it cannot queue whole-source jobs. Use page writes, or ask the brain host operator for an unrestricted source grant.');
const raw = input === undefined ? {} : record(input);
- if (!raw) deny('job data must be an object');
+ if (!raw) deny('job data must be an object', 'Send data as a JSON object (for sync, {"noPull": true}), or omit it.');
const allowed = name === 'sync' ? ['pull', 'noPull'] : [];
- for (const key of Object.keys(raw)) if (!allowed.includes(key)) deny('unsupported remote job parameter');
- for (const key of allowed) if (raw[key] !== undefined && typeof raw[key] !== 'boolean') deny(`${key} must be a boolean`);
- if (raw.pull !== undefined && raw.noPull !== undefined) deny('supply only one of pull and noPull');
+ for (const key of Object.keys(raw)) if (!allowed.includes(key)) deny('unsupported remote job parameter', `Remove ${key}; remote ${name} accepts ${allowed.length ? allowed.join(' or ') : 'no data fields'}.`);
+ for (const key of allowed) if (raw[key] !== undefined && typeof raw[key] !== 'boolean') deny(`${key} must be a boolean`, `Send ${key} as true or false.`);
+ if (raw.pull !== undefined && raw.noPull !== undefined) deny('supply only one of pull and noPull', 'Send pull or noPull, not both.');
const boundary = await sourceBoundary(ctx.engine, sourceId, name as RemoteJobName);
const wholeWorktree = boundary.canonicalRoot === boundary.worktreeRoot;
const pull = raw.pull ?? (raw.noPull !== undefined ? !raw.noPull : wholeWorktree);
- if (name === 'sync' && pull && !wholeWorktree) deny('pull is unavailable for a source nested inside another Git working tree');
+ if (name === 'sync' && pull && !wholeWorktree) deny('pull is unavailable for a source nested inside another Git working tree',
+ `Source ${sourceId} sits inside a larger Git working tree, so it cannot pull. Submit sync with {"noPull": true}.`);
const data: Record<string, unknown> = name === 'sync'
? { repoPath: boundary.canonicalRoot, sourceId, noPull: !pull, noEmbed: true, noExtract: true, auto_embed_backfill: false }
: { dir: boundary.canonicalRoot, sourceId, ...(name === 'import' ? { noEmbed: true } : {}) };
@@ -186,7 +200,8 @@ const toolName = (name: string) => name.replace(/^(?:brain_|mcp__gbrain__)/, '')
async function assertCurrentAgent(engine: BrainEngine, a: RemoteAgentAuthority, data: Record<string, unknown>, jobId?: number): Promise<void> {
const [source] = await engine.executeRaw<Record<string, unknown>>('SELECT archived, created_at FROM sources WHERE id = $1', [a.grant.sourceId]);
- if (!source || source.archived !== false || new Date(source.created_at as string).toISOString() !== a.grant.sourceCreatedAt) deny('agent source is missing, archived, or was replaced');
+ if (!source || source.archived !== false || new Date(source.created_at as string).toISOString() !== a.grant.sourceCreatedAt) deny('agent source is missing, archived, or was replaced',
+ `Source ${a.grant.sourceId} was archived, removed or recreated after this agent job was accepted. Submit a new agent job against the current source.`);
if (data.__delegation_grant !== undefined) {
// Grant profiles reference the complete operation catalog. Filesystem
// writers need this module during catalog initialization; load the policy
@@ -196,7 +211,8 @@ async function assertCurrentAgent(engine: BrainEngine, a: RemoteAgentAuthority,
if (!submitted || submitted.clientId !== a.principal.id || submitted.sourceId !== a.grant.sourceId
|| authorityDigest(submitted.tools) !== authorityDigest(a.grant.allowedTools)
|| authorityDigest(submitted.slugPrefixes) !== authorityDigest(a.grant.allowedSlugPrefixes)
- || !hasScope(a.grant.scopes, 'agent')) deny('delegation snapshot differs from its accepted authority');
+ || !hasScope(a.grant.scopes, 'agent')) deny('delegation snapshot differs from its accepted authority',
+ 'The delegation snapshot in this job no longer matches its accepted grant, so it does not run. Submit a new agent job under the current grant.');
// Direct and delegated namespaces are independent. The current grant may
// narrow tools/paths, while the submitted snapshot remains the ceiling.
await effectiveDelegation(engine, submitted, jobId);
@@ -205,20 +221,26 @@ async function assertCurrentAgent(engine: BrainEngine, a: RemoteAgentAuthority,
// Preserve the older explicit authority shape for already accepted jobs.
const [row] = await engine.executeRaw<Record<string, unknown>>(
'SELECT deleted_at, scope, source_id, bound_tools, bound_source_id, bound_slug_prefixes FROM oauth_clients WHERE client_id = $1', [a.principal.id]);
- if (!row || row.deleted_at != null) deny('agent owner is missing or revoked');
+ if (!row || row.deleted_at != null) deny('agent owner is missing or revoked', `OAuth client ${a.principal.id}, which owns this agent job, was deleted or revoked. Reconnect with a current client and submit a new job.`);
const scopes = typeof row.scope === 'string' ? row.scope.split(/\s+/) : [];
- if (!hasScope(a.grant.scopes, 'agent') || !hasScope(scopes, 'agent')) deny('original and current grants must include agent scope');
- if (row.source_id !== a.grant.sourceId || (row.bound_source_id != null && row.bound_source_id !== a.grant.sourceId)) deny('agent source grant changed');
+ if (!hasScope(a.grant.scopes, 'agent') || !hasScope(scopes, 'agent')) deny('original and current grants must include agent scope',
+ `Client ${a.principal.id} does not hold the agent scope now (or did not at submission). Ask the brain host operator to grant it, then submit a new job.`);
+ if (row.source_id !== a.grant.sourceId || (row.bound_source_id != null && row.bound_source_id !== a.grant.sourceId)) deny('agent source grant changed',
+ `Client ${a.principal.id} is now bound to another source than ${a.grant.sourceId}. Submit a new agent job under the current grant.`);
if (!Array.isArray(row.bound_tools) || !row.bound_tools.length ||
- !row.bound_tools.every(t => typeof t === 'string' && t.length && !['file_list', 'file_url'].includes(toolName(t)))) deny('current agent tool binding is empty or unsupported');
+ !row.bound_tools.every(t => typeof t === 'string' && t.length && !['file_list', 'file_url'].includes(toolName(t)))) deny('current agent tool binding is empty or unsupported',
+ `Client ${a.principal.id} has no usable bound tools (file_list and file_url cannot be agent tools). Ask the brain host operator to bind the agent's tools, then submit a new job.`);
const tools = row.bound_tools.map(t => toolName(t as string));
- if (a.grant.allowedTools.some(t => !tools.includes(toolName(t)))) deny('accepted agent tools are outside the current binding');
+ if (a.grant.allowedTools.some(t => !tools.includes(toolName(t)))) deny('accepted agent tools are outside the current binding',
+ `Client ${a.principal.id} no longer allows ${a.grant.allowedTools.filter(t => !tools.includes(toolName(t))).join(', ')}. Submit a new agent job with tools from its current binding.`);
const prefixes = row.bound_slug_prefixes;
if (prefixes != null) {
- if (!Array.isArray(prefixes) || !prefixes.length || !prefixes.every(p => typeof p === 'string' && p.length) || !a.grant.allowedSlugPrefixes.length) deny('agent slug binding changed');
+ if (!Array.isArray(prefixes) || !prefixes.length || !prefixes.every(p => typeof p === 'string' && p.length) || !a.grant.allowedSlugPrefixes.length) deny('agent slug binding changed',
+ `Client ${a.principal.id}'s slug binding changed after this job was accepted. Submit a new agent job under the current binding.`);
for (const granted of a.grant.allowedSlugPrefixes) {
const requested = normalizeSlugPrefix(granted);
- if (!prefixes.some(p => { const base = normalizeSlugPrefix(p as string); return base && (base.endsWith('/') ? requested.startsWith(base) : requested === base || requested.startsWith(`${base}/`)); })) deny('accepted agent slug grant is outside the current binding');
+ if (!prefixes.some(p => { const base = normalizeSlugPrefix(p as string); return base && (base.endsWith('/') ? requested.startsWith(base) : requested === base || requested.startsWith(`${base}/`)); })) deny('accepted agent slug grant is outside the current binding',
+ `Slug prefix ${granted} is outside client ${a.principal.id}'s current binding. Submit a new agent job with prefixes inside it.`);
}
}
}
@@ -226,16 +248,17 @@ async function assertCurrentAgent(engine: BrainEngine, a: RemoteAgentAuthority,
export async function prepareRemoteAgent(ctx: OperationContext, data: Record<string, unknown>): Promise<RemoteAgentAuthority> {
const principal = ctx.auth?.principal;
if (principal?.kind !== 'oauth_client' || principal.id !== ctx.auth?.clientId || !hasScope(ctx.auth?.scopes ?? [], 'agent') ||
- typeof data.source_id !== 'string' || data.source_id !== ctx.auth?.sourceId || !isValidSourceId(data.source_id)) deny('submit_agent requires a verified OAuth principal and scalar source grant');
+ typeof data.source_id !== 'string' || data.source_id !== ctx.auth?.sourceId || !isValidSourceId(data.source_id)) deny('submit_agent requires a verified OAuth principal and scalar source grant',
+ 'submit_agent needs an OAuth client holding the agent scope and bound to the one source named in source_id. Ask the brain host operator for such a client, or ask the user to run gbrain agent run on the brain host.');
const [source] = await ctx.engine.executeRaw<Record<string, unknown>>('SELECT archived, created_at FROM sources WHERE id = $1', [data.source_id]);
- if (!source || source.archived !== false) deny('agent source must be active');
+ if (!source || source.archived !== false) deny('agent source must be active', `Source ${data.source_id} is archived or missing. Name an active source in source_id.`);
const authority: RemoteAgentAuthority = {
version: 1, kind: 'remote_agent', principal: { kind: 'oauth_client', id: principal.id },
grant: { scopes: [...ctx.auth!.scopes], sourceId: data.source_id, sourceCreatedAt: new Date(source.created_at as string).toISOString(),
allowedTools: [...data.allowed_tools as string[]], allowedSlugPrefixes: [...data.allowed_slug_prefixes as string[]] },
payloadHash: authorityDigest(data),
};
- if (!parseSubmissionAuthority(authority)) deny('invalid agent grant');
+ if (!parseSubmissionAuthority(authority)) deny('invalid agent grant', 'Send allowed_tools as a non-empty list of tool names and allowed_slug_prefixes as a list of strings.');
await assertCurrentAgent(ctx.engine, authority, data);
return authority;
}
@@ -243,18 +266,22 @@ export async function prepareRemoteAgent(ctx: OperationContext, data: Record<str
/** Runs in BOTH inline and isolated workers, immediately before the handler. */
export async function authorizeJobExecution(engine: BrainEngine, job: Pick<MinionJob, 'name' | 'data' | 'submission_authority'> & Partial<Pick<MinionJob, 'id'>>): Promise<SubmissionAuthority> {
const a = parseSubmissionAuthority(job.submission_authority);
- if (!a) deny('missing or unsupported submission authority; review locally with jobs authorize-legacy');
+ if (!a) deny('missing or unsupported submission authority; review locally with jobs authorize-legacy',
+ 'This queued job has no readable submission authority, so it does not run until reviewed. On the brain host, gbrain jobs authorize-legacy lists it for the user to approve or cancel.');
if (a.kind === 'application') return a;
if (a.kind === 'remote_agent') {
- if (job.name !== 'subagent' || authorityDigest(job.data) !== a.payloadHash) deny('agent payload differs from its accepted grant');
+ if (job.name !== 'subagent' || authorityDigest(job.data) !== a.payloadHash) deny('agent payload differs from its accepted grant',
+ 'This agent job\'s data changed after it was accepted, so it does not run. Submit a new agent job.');
await assertCurrentAgent(engine, a, job.data, job.id);
return a;
}
- if (job.name !== a.grant.jobName || authorityDigest(job.data) !== a.payloadHash) deny('job data or name differs from its accepted grant');
+ if (job.name !== a.grant.jobName || authorityDigest(job.data) !== a.payloadHash) deny('job data or name differs from its accepted grant',
+ `This ${job.name} job's data changed after it was accepted, so it does not run. Submit a new job.`);
await assertCurrentRemoteJobPrincipal(engine, a);
const boundary = await sourceBoundary(engine, a.grant.sourceId, a.grant.jobName);
for (const key of ['canonicalRoot', 'worktreeRoot', 'sourceCreatedAt'] as const) {
- if (boundary[key] !== a.grant[key]) deny('source registration or filesystem root changed; submit a new job');
+ if (boundary[key] !== a.grant[key]) deny('source registration or filesystem root changed; submit a new job',
+ `Source ${a.grant.sourceId}'s ${key} changed after this job was accepted. Submit a new job against the current registration.`);
}
return a;
}
@@ -263,9 +290,12 @@ export async function assertRemoteJobControl(ctx: OperationContext, job: MinionJ
if (ctx.remote === false) return;
const a = parseSubmissionAuthority(job.submission_authority);
if (!a || a.kind === 'application' || !ctx.auth?.principal ||
- authorityDigest(a.principal) !== authorityDigest(ctx.auth.principal)) deny('only the submitting principal may restart a generic remote job');
- if (overrides !== undefined && (!record(overrides) || Object.keys(overrides as object).length)) deny('replay overrides are unavailable remotely; submit a new job');
- if (!hasScope(ctx.auth.scopes, 'admin') || ctx.auth.sourceId !== a.grant.sourceId) deny('current request is outside the original grant');
+ authorityDigest(a.principal) !== authorityDigest(ctx.auth.principal)) deny('only the submitting principal may restart a generic remote job',
+ 'Only the principal that submitted this job can restart it. Submit a new job from this connection instead.');
+ if (overrides !== undefined && (!record(overrides) || Object.keys(overrides as object).length)) deny('replay overrides are unavailable remotely; submit a new job',
+ 'Restart the job without overrides, or submit a new job with the changed data.');
+ if (!hasScope(ctx.auth.scopes, 'admin') || ctx.auth.sourceId !== a.grant.sourceId) deny('current request is outside the original grant',
+ `Restarting needs the admin scope on source ${a.grant.sourceId}, which this connection lacks. Restart it from a connection holding that grant.`);
await authorizeJobExecution(ctx.engine, job);
}
diff --git a/src/core/minions/tool-write-identity.ts b/src/core/minions/tool-write-identity.ts
index 5b3775fcbe..5b5468b6a9 100644
--- a/src/core/minions/tool-write-identity.ts
+++ b/src/core/minions/tool-write-identity.ts
@@ -1,5 +1,6 @@
import { createHash } from 'node:crypto';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { isWriteReceipt } from '../persistence/types.ts';
import { isPersistenceIpcMutation } from '../persistence/ipc.ts';
@@ -18,7 +19,10 @@ export function assertToolWriteCommitted(output: unknown, toolName: string): voi
if (!isPersistenceIpcMutation(toolName.replace(/^brain_/, '')) || !isWriteReceipt(output) || output.state === 'committed') return;
const pending = ['queued', 'running', 'recovering'].includes(output.state);
const code = pending ? 'write_pending' : 'storage_error';
- const error = new OperationError(code, `Tool write ${output.request_id} is ${output.state}; inspect its durable receipt before retrying.`);
+ const error = opError(code, `Tool write ${output.request_id} is ${output.state}; inspect its durable receipt before retrying.`,
+ pending ? `The tool write is accepted and still ${output.state}; read its receipt until it is terminal. Do not repeat the tool call: the same request id replays it.`
+ : `The tool write ended ${output.state}; its receipt holds the recorded error. Read it before deciding whether a new write (with a new request id) is needed.`,
+ { fix: readFix(`Reads tool write ${output.request_id}'s durable receipt, read-only.`, { argv: ['gbrain', 'write-request', '--', output.request_id] }) });
error.writeRequest = output; error.writeError = code; throw error;
}
export function isPendingToolWrite(error: unknown): error is OperationError {
diff --git a/src/core/page-state/import-guard.ts b/src/core/page-state/import-guard.ts
index ded901b839..fb3acc3c3e 100644
--- a/src/core/page-state/import-guard.ts
+++ b/src/core/page-state/import-guard.ts
@@ -1,7 +1,8 @@
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
import type { ParsedPage } from '../import-file.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { stableJson } from '../persistence/digest.ts';
import { assertPageRevision, type PageSnapshot } from './types.ts';
@@ -10,7 +11,9 @@ export async function assertImportBase(tx: BrainEngine, slug: string, sourceId:
await tx.lockPageKeys([{ sourceId, slug }]);
const current = await tx.getPage(slug, { sourceId, includeDeleted: true });
if ((current?.id ?? null) !== (existing?.id ?? null)) {
- throw new OperationError('page_identity_changed', 'The imported page was deleted or recreated during preparation.');
+ throw opError('page_identity_changed', 'The imported page was deleted or recreated during preparation.',
+ `Page ${slug} in source ${sourceId} was deleted or recreated while its import was prepared, so the import did not write it. Read the page that holds the slug now, then import the file again.`,
+ { fix: readFix(`Shows which page holds ${slug} now and its revision.`, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId } } }) });
}
assertPageRevision(current ? { revision: current.knowledge_revision! } : null, existing ? { expectedRevision: existing.knowledge_revision } : {});
}
diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.ts
index ecd93bdc44..9397fca4c1 100644
--- a/src/core/persistence/effect-facts.ts
+++ b/src/core/persistence/effect-facts.ts
@@ -3,7 +3,8 @@ import type { ParsedPage } from '../import-file.ts';
import { isFactsBackstopEligible } from '../facts/eligibility.ts';
import { isFactsExtractionEnabled } from '../facts/extract.ts';
import { MinionQueue } from '../minions/queue.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { authorizeStoredRequest, authorizeWrite } from './authority.ts';
import { completeEffect } from './effect-journal.ts';
import { guardEffectSource } from './effect-recovery.ts';
@@ -15,17 +16,22 @@ export type FactsBackstopStatus = { queued: true } | { skipped: string };
export async function authorizeFactsBackstop(engine: BrainEngine, row: WriteRequest, lock = false): Promise<void> {
if (derivedExtractionSkip(row.authority) === 'slug_bound_client') {
- throw new OperationError('permission_denied', 'A confined writer cannot extract into unnamed entity pages.');
+ throw opError('permission_denied', 'A confined writer cannot extract into unnamed entity pages.',
+ `The write of ${row.slug} came from a slug-bound client, so facts are not extracted into entity pages outside its prefixes; the page itself is written. Widening that client's grant is the brain host operator's decision.`);
}
await authorizeStoredRequest(engine, row, lock);
await authorizeWrite(engine, row.authority, 'extract_facts', row.slug, lock);
// A grant may have become confined while the page itself remains in scope.
if (row.principal_kind === 'oauth_client') {
const [current] = await engine.executeRaw<{ bound_slug_prefixes: unknown }>('SELECT bound_slug_prefixes FROM oauth_clients WHERE client_id=$1', [row.principal_id]);
- if (current?.bound_slug_prefixes != null) throw new OperationError('permission_denied', 'The current writer grant is confined.');
+ if (current?.bound_slug_prefixes != null) throw opError('permission_denied', 'The current writer grant is confined.',
+ `OAuth client ${row.principal_id} is now bound to slug prefixes, so facts from ${row.slug} are not extracted; the page itself is written. Widening the grant is the brain host operator's decision.`,
+ { fix: readFix('Lists the OAuth clients with their bound slug prefixes, read-only.', { argv: ['gbrain', 'auth', 'clients', '--json'] }) });
} else if (row.principal_kind === 'local_cli' || row.principal_kind === 'local_stdio') {
const [current] = await engine.executeRaw<{ prefixes: unknown }>("SELECT grant_ceiling->'slugPrefixes' AS prefixes FROM persistence_local_writers WHERE id=$1::uuid", [row.principal_id]);
- if (current?.prefixes != null) throw new OperationError('permission_denied', 'The current writer grant is confined.');
+ if (current?.prefixes != null) throw opError('permission_denied', 'The current writer grant is confined.',
+ `Local writer ${row.principal_id} now has slug prefixes, so facts from ${row.slug} are not extracted; the page itself is written. Replacing the grant is the user's decision.`,
+ { fix: readFix('Lists the local writer registrations and their grants, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });
}
}
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index d1bd0bc2f0..b60a1ac1ec 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -2,7 +2,8 @@ import { randomUUID } from 'node:crypto';
import { relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { PageSnapshot } from '../page-state/types.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import type { PreparedMutation } from './coordinator.ts';
import { sha256 } from './digest.ts';
import { PARK_AFTER_FAILURES, type EffectKind, type PersistenceEffect, type EffectRequest } from './effect-model.ts';
@@ -28,7 +29,9 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
if (prepared?.file && row.worktree_id) {
const [binding] = await tx.executeRaw<{ local_path: string }>(`SELECT h.local_path FROM persistence_host_bindings h
JOIN persistence_worktrees w ON w.id=h.worktree_id AND w.owner_host_id=h.host_id WHERE w.id=$1::uuid`, [row.worktree_id]);
- if (!binding?.local_path) throw new OperationError('owner_unavailable', 'Cannot record the canonical Git target without its owner binding.');
+ if (!binding?.local_path) throw opError('owner_unavailable', 'Cannot record the canonical Git target without its owner binding.',
+ `Worktree ${row.worktree_id} of source ${row.source_id} has no host binding for its owner, so request ${row.id} could not record its Git target. Read the request's receipt; the owner host's binding is restored by its claim or transfer.`,
+ row.principal_kind === 'local_cli' ? { fix: readFix(`Reads request ${row.id}'s durable receipt, read-only.`, { argv: ['gbrain', 'write-request', '--', row.id] }) } : {});
await queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),
expected_hash: prepared.file.content === null ? null : sha256(prepared.file.content) });
if (outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });
diff --git a/src/core/persistence/effect-targets.ts b/src/core/persistence/effect-targets.ts
index b418bd1f15..029be71860 100644
--- a/src/core/persistence/effect-targets.ts
+++ b/src/core/persistence/effect-targets.ts
@@ -1,5 +1,6 @@
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { discoverWithdrawalTargets, withdrawalDiscoveryFailure, WITHDRAWAL_LIMITS, type WithdrawalClaim } from '../facts/withdrawal-discovery.ts';
import type { PersistenceEffect } from './effect-model.ts';
import { guardEffectSource } from './effect-recovery.ts';
@@ -38,7 +39,9 @@ export async function upgradeWithdrawalEffect(engine: BrainEngine, effect: Persi
WHERE r.id=$2::uuid ORDER BY w.visibility,w.fact_hash,w.subject`, [effect.source_id, effect.request_id]);
const claims = requested.length ? requested : await tx.executeRaw<WithdrawalClaim>(`SELECT visibility,fact_hash,subject FROM fact_withdrawals
WHERE source_id=$1 ORDER BY visibility,fact_hash,subject LIMIT $2`, [effect.source_id, WITHDRAWAL_LIMITS.targets + 1]);
- if (!claims.length) throw new OperationError('withdrawal_provenance', 'Legacy withdrawal intent has no verifiable ledger. Its queued work remains retained.');
+ if (!claims.length) throw opError('withdrawal_provenance', 'Legacy withdrawal intent has no verifiable ledger. Its queued work remains retained.',
+ `Request ${effect.request_id} withdrew a fact in source ${effect.source_id} before withdrawals were ledgered, so its targets cannot be rediscovered; the effect stays parked and nothing was rewritten. Show it to the user with the writer status; report it with gbrain --version if it should have a ledger.`,
+ { fix: readFix(`Shows source ${effect.source_id}'s parked effects, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', effect.source_id, '--json'] }) });
const discovered = await discoverWithdrawalTargets(tx, effect.source_id, claims).catch(withdrawalDiscoveryFailure);
const remaining = await tx.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id=$1 AND id=ANY($2::int[])
AND ($3::text IS NULL OR slug>$3)`, [effect.source_id, discovered.map(target => target.page_id), effect.data.after_slug ?? null]);
@@ -50,7 +53,9 @@ export async function upgradeWithdrawalEffect(engine: BrainEngine, effect: Persi
const [current] = await tx.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET data=(data-'source_scan'-'after_slug')||$3::text::jsonb,updated_at=now()
WHERE id=$1 AND execution_token IS NOT DISTINCT FROM $2::uuid AND recovery IS NULL RETURNING *`,
[effect.id, effect.execution_token, JSON.stringify(data)]);
- if (!current) throw new OperationError('write_claim_lost', 'The legacy withdrawal effect changed during discovery.');
+ if (!current) throw opError('write_claim_lost', 'The legacy withdrawal effect changed during discovery.',
+ `Another executor claimed or recovered effect ${effect.id} of request ${effect.request_id} while its targets were discovered; the owner picks it up on its next pass. Check the writer status before doing anything else.`,
+ { fix: readFix(`Shows source ${effect.source_id}'s effects and their owner, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', effect.source_id, '--json'] }) });
return current;
});
}
diff --git a/src/core/source-local-reference-index.ts b/src/core/source-local-reference-index.ts
index 193cb0b7bb..acdb912267 100644
--- a/src/core/source-local-reference-index.ts
+++ b/src/core/source-local-reference-index.ts
@@ -1,7 +1,7 @@
import { normalizeAlias, normalizeAliasList } from './search/alias-normalize.ts';
import { buildBasenameIndex, queryBasenameIndex, normalizeBasename, FRONTMATTER_LINK_MAP, type LinkExtractionPack } from './link-extraction.ts';
import { slugifyPath, slugifySegment } from './sync.ts';
-import { OperationError } from './ops/contract.ts';
+import { opError } from './ops/contract.ts';
export interface SourceLocalReferencePage {
slug: string;
@@ -10,7 +10,8 @@ export interface SourceLocalReferencePage {
}
export function buildSourceLocalReferenceIndex(pages: readonly SourceLocalReferencePage[]) {
- if (pages.length > 100_000) throw new OperationError('request_too_large', 'Reference metadata exceeds 100,000 pages; partition the source.');
+ if (pages.length > 100_000) throw opError('request_too_large', 'Reference metadata exceeds 100,000 pages; partition the source.',
+ `The source has ${pages.length} pages and reference resolution handles 100,000 per source. Split it into smaller sources; for a company import, inspect again with narrower --include and --exclude globs.`);
const slugs = new Map<string, string[]>();
const names = new Map<string, Set<string>>();
let bytes = 0;
@@ -18,7 +19,8 @@ export function buildSourceLocalReferenceIndex(pages: readonly SourceLocalRefere
for (const page of pages) {
const aliases = normalizeAliasList(page.aliases);
bytes += Buffer.byteLength(JSON.stringify([page.slug, page.title, aliases]));
- if (bytes > 16 * 1024 ** 2) throw new OperationError('request_too_large', 'Reference metadata exceeds 16 MiB; narrow the source.');
+ if (bytes > 16 * 1024 ** 2) throw opError('request_too_large', 'Reference metadata exceeds 16 MiB; narrow the source.',
+ 'The slugs, titles and aliases of this source exceed 16 MiB. Split it into smaller sources, or trim very long aliases; for a company import, inspect again with narrower --include and --exclude globs.');
const sameSlug = slugs.get(page.slug) ?? [];
sameSlug.push(page.slug);
slugs.set(page.slug, sameSlug);
diff --git a/test/import-revision-concurrency.test.ts b/test/import-revision-concurrency.test.ts
index a81189d6ec..3a43dacd42 100644
--- a/test/import-revision-concurrency.test.ts
+++ b/test/import-revision-concurrency.test.ts
@@ -72,7 +72,8 @@ test('absence guards reject create races and physical recreation of the same slu
const original = (await engine.getPage(slug, { sourceId }))!;
await engine.deletePage(slug, { sourceId });
await importFromContent(engine, slug, content('recreated'), { sourceId, noEmbed: true });
- await expect(engine.transaction(tx => assertImportBase(tx, slug, sourceId, original))).rejects.toMatchObject({ code: 'page_identity_changed' });
+ await expect(engine.transaction(tx => assertImportBase(tx, slug, sourceId, original))).rejects.toMatchObject({ code: 'page_identity_changed',
+ fix: { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId } } } });
expect((await engine.getPage(slug, { sourceId }))!.frontmatter.captured_at).toBe('recreated');
}
});
diff --git a/test/minions-submission-authority.test.ts b/test/minions-submission-authority.test.ts
index cea08d6707..bb68abd2bc 100644
--- a/test/minions-submission-authority.test.ts
+++ b/test/minions-submission-authority.test.ts
@@ -14,6 +14,7 @@ import { readSourceFileSync, writeSourceFileSync, withSourceFilesystemLock } fro
import { APPLICATION_AUTHORITY, assertNoUnreviewedJobs, assertRemoteJobControl, authorizeJobExecution, prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
import { withEnv } from './helpers/with-env.ts';
+import { caught, envelopeFor, expectFunnelSuggestions } from './helpers/agent-envelope.ts';
const sandbox = mkdtempSync(join(tmpdir(), 'gbrain-job-authority-'));
const root = join(sandbox, 'repo');
@@ -81,6 +82,18 @@ describe('generic remote job authority', () => {
await expect(prepareRemoteJob(ctx(), 'lint', {})).rejects.toThrow('registered filesystem root');
}));
+ test('every authorization refusal names its own next step; a nested pull names the noPull form', () => isolated(async () => {
+ expectFunnelSuggestions('src/core/minions/submission-authority.ts', 'deny', 38);
+ const unsupported = envelopeFor(await caught(() => prepareRemoteJob(ctx(), 'embed', {})), 'stdio');
+ expect(unsupported).toMatchObject({ code: 'permission_denied' });
+ expect(unsupported.suggestion).toContain('Use the dedicated operation for embed work');
+ const nested = join(root, 'nested-pull'); mkdirSync(nested, { recursive: true });
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [nested]);
+ try {
+ expect(envelopeFor(await caught(() => prepareRemoteJob(ctx(), 'sync', { pull: true })), 'http').suggestion).toContain('{"noPull": true}');
+ } finally { await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]); }
+ }));
+
test('nested source defaults no-pull and rejects explicit whole-worktree mutation', () => isolated(async () => {
const nested = join(root, 'nested'); mkdirSync(nested, { recursive: true });
await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [nested]);
diff --git a/test/persistence-facts-backstop.test.ts b/test/persistence-facts-backstop.test.ts
index bf18d7e65b..c8067bde6d 100644
--- a/test/persistence-facts-backstop.test.ts
+++ b/test/persistence-facts-backstop.test.ts
@@ -11,7 +11,7 @@ import { localHostId, registerLocalWriter } from '../src/core/persistence/identi
import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';
import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { claimPersistenceEffect, publicEffectsForRequest } from '../src/core/persistence/effect-journal.ts';
-import { dispatchFactsBackstopEffect, readFactsBackstopJobPage } from '../src/core/persistence/effect-facts.ts';
+import { authorizeFactsBackstop, dispatchFactsBackstopEffect, readFactsBackstopJobPage } from '../src/core/persistence/effect-facts.ts';
import type { WriteRequest } from '../src/core/persistence/model.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -127,3 +127,9 @@ test('confined writers and disabled extraction never receive a queued claim', ()
const disabled = await publishMutation(engine, updated.row, updated.prepared);
expect(disabled.outcome?.facts_backstop).toEqual({ skipped: 'extraction_disabled' });
}));
+
+test('a slug-bound writer\'s backstop refusal says the page was written and who widens the grant', async () => {
+ const row = { slug: 'notes/a', authority: { slugPrefixes: ['notes/'] } } as unknown as WriteRequest;
+ await expect(authorizeFactsBackstop(engine, row)).rejects.toMatchObject({ code: 'permission_denied',
+ suggestion: expect.stringContaining('the page itself is written') });
+});
diff --git a/test/source-local-reference-index.test.ts b/test/source-local-reference-index.test.ts
index 07eb9b1851..6221e2f887 100644
--- a/test/source-local-reference-index.test.ts
+++ b/test/source-local-reference-index.test.ts
@@ -23,3 +23,8 @@ test('source-local reference indexes enforce page and metadata bounds', () => {
expect(() => buildSourceLocalReferenceIndex(Array.from({ length: 100_001 }, () => ({ slug: 'notes/one', title: 'One' })))).toThrow('100,000');
expect(() => buildSourceLocalReferenceIndex([{ slug: 'notes/large', title: 'x'.repeat(16 * 1024 ** 2) }])).toThrow('16 MiB');
});
+
+test('an oversized source names its page count and how to split it', () => {
+ expect(() => buildSourceLocalReferenceIndex(Array.from({ length: 100_001 }, () => ({ slug: 'notes/one', title: 'One' }))))
+ .toThrow(expect.objectContaining({ code: 'request_too_large', suggestion: expect.stringContaining('The source has 100001 pages') }));
+});
diff --git a/test/tool-write-identity.test.ts b/test/tool-write-identity.test.ts
new file mode 100644
index 0000000000..212001c194
--- /dev/null
+++ b/test/tool-write-identity.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { assertToolWriteCommitted } from '../src/core/minions/tool-write-identity.ts';
+import { envelopeFor } from './helpers/agent-envelope.ts';
+
+const receipt = (state: string) => ({ request_id: randomUUID(), state, retry_after_ms: null });
+const refusal = (state: string) => { try { assertToolWriteCommitted(receipt(state), 'brain_put_page'); } catch (error) { return error; } throw new Error('accepted'); };
+
+describe('subagent tool writes that did not commit point at their durable receipt', () => {
+ test('a pending tool write reads its receipt and never repeats the call', () => {
+ const error = refusal('queued') as { writeRequest: { request_id: string } };
+ const env = envelopeFor(error);
+ expect(env).toMatchObject({ code: 'write_pending', fix: { argv: ['gbrain', 'write-request', '--', error.writeRequest.request_id], next: 'run' } });
+ expect(env.suggestion).toContain('Do not repeat the tool call');
+ });
+
+ test('a failed tool write reads the recorded error before any new write', () => {
+ expect(envelopeFor(refusal('failed')).suggestion).toContain('new request id');
+ });
+});