Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): B6 trusted-CLI refusals name the registration check; missing_source_scope fills the client id; error-codes doc regenerated
garrytane6f65a90dc68
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 71169002ba..5d3d18cb20 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1110,7 +1110,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| The page was deleted or replaced while the operation ran. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+| The page was deleted or replaced while the operation ran. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |### page_not_found@@ -1118,7 +1118,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| No page with that slug exists in the selected source. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+| No page with that slug exists in the selected source. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |### parse_error@@ -1420,7 +1420,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| The target changed since it was read; the expected revision no longer matches. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+| The target changed since it was read; the expected revision no longer matches. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |### revision_requireddiff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex c71de35166..7641be8fa6 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -54,7 +54,7 @@ src/core/ops/timeline.ts 3src/core/ops/transcripts.ts 1src/core/page-state/import-guard.ts 1src/core/persistence/activation.ts 5-src/core/persistence/administration.ts 6+src/core/persistence/administration.ts 4src/core/persistence/atom-maintenance.ts 23src/core/persistence/atom-retry.ts 8src/core/persistence/authority.ts 1@@ -77,14 +77,14 @@ src/core/persistence/effect-recovery.ts 11src/core/persistence/effect-retry.ts 12src/core/persistence/effect-targets.ts 2src/core/persistence/effects.ts 22-src/core/persistence/embed-facts-administration.ts 3+src/core/persistence/embed-facts-administration.ts 2src/core/persistence/embedding-settlement.ts 1src/core/persistence/facts-maintenance.ts 19src/core/persistence/facts-prepare.ts 13src/core/persistence/grandfather.ts 6src/core/persistence/identity.ts 9-src/core/persistence/import-mutations.ts 3-src/core/persistence/import-prepare.ts 22+src/core/persistence/import-mutations.ts 2+src/core/persistence/import-prepare.ts 21src/core/persistence/ipc.ts 9src/core/persistence/journal.ts 8src/core/persistence/limits.ts 1@@ -101,21 +101,21 @@ src/core/persistence/prepared-maintenance.ts 26src/core/persistence/projection-reindex.ts 7src/core/persistence/protected-takes.ts 2src/core/persistence/protocol.ts 1-src/core/persistence/provider.ts 4-src/core/persistence/reconcile-audit.ts 13+src/core/persistence/provider.ts 3+src/core/persistence/reconcile-audit.ts 12src/core/persistence/reconcile-backup.ts 17src/core/persistence/reconcile-merge.ts 13src/core/persistence/reconcile-prepare.ts 7src/core/persistence/reconcile-state.ts 11-src/core/persistence/reconcile.ts 11-src/core/persistence/reindex-administration.ts 5+src/core/persistence/reconcile.ts 10+src/core/persistence/reindex-administration.ts 4src/core/persistence/root-registry.ts 2src/core/persistence/semantic-pages.ts 3src/core/persistence/service.ts 5src/core/persistence/skill-activation.ts 1src/core/persistence/source-lifecycle.ts 25src/core/persistence/staging.ts 2-src/core/persistence/sync-administration.ts 2+src/core/persistence/sync-administration.ts 1src/core/persistence/sync-authority.ts 7src/core/persistence/sync-discovery.ts 20src/core/persistence/sync-origin.ts 3diff --git a/src/core/ops/op-fix.ts b/src/core/ops/op-fix.tsindex 3a781eb6a1..f700aa861b 100644--- a/src/core/ops/op-fix.ts+++ b/src/core/ops/op-fix.ts@@ -164,3 +164,22 @@ export function scopeDeniedError(opts: {},});}++/**+ * B6: a persistence administration path reached without the current trusted+ * CLI writer registration. The person at the brain host runs it from the+ * gbrain CLI; the fix reads the registration first (never re-registers).+ */+export function trustedCliRequired(message: string): OperationError {+ return opError('permission_denied', message,+ 'Run this from the gbrain CLI in a terminal on the brain host. It needs a current CLI writer registration: `gbrain auth local-writer list --json` shows it, and `gbrain auth local-writer register cli` creates one when none is active.',+ {+ reason: 'trusted_cli_required',+ fix: {+ argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], consent: [], actor: 'user',+ why: 'Administration paths run only under the brain host\'s trusted CLI registration; this shows whether one is active.',+ user_message: 'This gbrain maintenance step has to run from a terminal on the machine that hosts the brain. Please run the command shown there.',+ requires_exclusive: false,+ },+ });+}diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex bc203fc4bf..b6d846fd35 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -17,6 +17,7 @@ import { writerOnboardingPreflight } from './onboarding.ts';import { assertWriterAdminUnlocked, readWriterAdminLock, setWriterAdminLock } from './admin-lock.ts';import { listBlockingEffects } from './blocking-effects.ts';import { listWriterVersions } from './writer-versions.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';const invalid = (message: string) => new OperationError('invalid_params', message);function source(value: unknown): string {@@ -90,7 +91,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioif (operation === 'company_brain_preview') return { ...await runtime.previewCompanyBrain(engine, input) };return { ...await runtime.connectCompanyBrain(engine, input) };}- if (currentVerifiedLocalWriter()?.remote) throw new OperationError('permission_denied', 'Writer administration requires a trusted local CLI caller.');+ if (currentVerifiedLocalWriter()?.remote) throw trustedCliRequired('Writer administration requires a trusted local CLI caller.');if (operation === 'writer_lock' || operation === 'writer_unlock') {keys(params, []);return { ...await setWriterAdminLock(engine, operation === 'writer_lock') };@@ -101,7 +102,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatioif (operation === 'writer_extract_stale') {keys(params, ['source_id', 'dry_run']);const writer = currentVerifiedLocalWriter();- if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Stale extraction requires a trusted CLI registration.');+ if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw trustedCliRequired('Stale extraction requires a trusted CLI registration.');const { managedPersistenceEnabled } = await import('./ownership.ts');if (!await managedPersistenceEnabled(engine)) throw new OperationError('writer_coordinator_required', 'Owner-delegated stale extraction requires activated managed persistence.', WRITER_INSPECTION_HINT);return { ...await (await import('./links-maintenance.ts')).runManagedStaleExtraction(engine,diff --git a/src/core/persistence/embed-facts-administration.ts b/src/core/persistence/embed-facts-administration.tsindex b85f3ccd98..28be4b0f2d 100644--- a/src/core/persistence/embed-facts-administration.ts+++ b/src/core/persistence/embed-facts-administration.ts@@ -5,11 +5,12 @@ import { validateEmbedFactsOptions } from '../embed-facts-options.ts';import { OperationError } from '../ops/contract.ts';import { EmbeddingDisabledError } from '../embedding-dim-check.ts';import { currentVerifiedLocalWriter } from './identity.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';export async function runAuthenticatedFactEmbedding(engine: BrainEngine, params: Record<string, unknown>, selectedConfig: GBrainConfig | null = null): Promise<Record<string, unknown>> {const verified = currentVerifiedLocalWriter();if (!verified || verified.remote || verified.principal.kind !== 'local_cli') {- throw new OperationError('permission_denied', 'Fact embedding repair requires a current trusted CLI registration');+ throw trustedCliRequired('Fact embedding repair requires a current trusted CLI registration');}if (Object.keys(params).some(key => key !== 'options')) {throw new OperationError('invalid_params', 'Fact embedding repair requires typed options');diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex 6564eae0c5..cbc79c92e7 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -15,12 +15,13 @@ import { submissionAuthority } from './authority.ts';import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';import type { WorktreeBinding } from './ownership.ts';import type { PageSnapshot } from '../page-state/types.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';export async function importManagedFile(engine: BrainEngine, filePath: string, sourcePath: string,opts: { sourceId?: string; noEmbed?: boolean; activePack?: ImportPack; signal?: AbortSignal; slugRoot?: string } = {}): Promise<ImportResult> {const caller = currentSubmissionAuthority();if (caller && caller.kind !== 'application' || currentVerifiedLocalWriter()?.remote) {- throw new OperationError('permission_denied', 'Managed filesystem import requires the trusted local CLI.');+ throw trustedCliRequired('Managed filesystem import requires the trusted local CLI.');}opts.signal?.throwIfAborted();if (isImageFilePath(sourcePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL !== 'true') {diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex b0e9c706d0..a3060af394 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -22,6 +22,7 @@ import { prepareCanonicalProjections } from './canonical-projections.ts';import type { PreparedContentImport } from './prepared-import.ts';import type { PreparedMutation } from './coordinator.ts';import type { WriteRequest } from './model.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';export type ImportPack = { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };export interface ManagedImportIntent extends Record<string, unknown> {@@ -92,7 +93,7 @@ export async function assertImportPaths(engine: BrainEngine, sourceId: string, rexport async function prepareManagedImportMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {const p = row.intent as ManagedImportIntent | null;- if (row.authority.remote || row.principal_kind !== 'local_cli') throw new OperationError('permission_denied', 'Filesystem import requires a trusted local CLI writer.');+ if (row.authority.remote || row.principal_kind !== 'local_cli') throw trustedCliRequired('Filesystem import requires a trusted local CLI writer.');if (!p || p.kind !== 'managed_file_import' || typeof p.content !== 'string' || typeof p.inputPath !== 'string' || typeof p.sourcePath !== 'string') {throw new OperationError('invalid_params', 'The durable file import intent is incomplete.');}diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex cb09c7cd92..a531133164 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -13,6 +13,7 @@ import { runPersistenceAdministration } from './administration.ts';import { boundedWriteWaitMs } from './write-wait.ts';export { residentPersistenceConfig } from './local-client.ts';import { projectionBacklog } from '../page-state/projections.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';/** Resident lifecycle owns the consumer; each connection proves its own durable registration. */export async function createPersistenceIpcProvider(engine: BrainEngine, config: GBrainConfig): Promise<PersistenceIpcProvider> {@@ -67,7 +68,7 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:}), administer: request => withVerifiedLocalRegistration(engine, request.registration, async verified => {assertPersistenceAccepting(engine);if (request.brain_id !== brain.brain_id || verified.remote || verified.principal.kind !== 'local_cli') {- throw new OperationError('permission_denied', 'Local administration requires this brain’s current trusted CLI registration.');+ throw trustedCliRequired('Local administration requires this brain’s current trusted CLI registration.');}return runPersistenceAdministration(engine, request.operation, request.params, config);}) };diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.tsindex 202dd09814..162060af04 100644--- a/src/core/persistence/reconcile-audit.ts+++ b/src/core/persistence/reconcile-audit.ts@@ -11,6 +11,7 @@ import { submissionAuthority } from './authority.ts';import { currentVerifiedLocalWriter, existingLocalHostId, readLocalWriter, verifyLocalWriter } from './identity.ts';import { getWorktreeBinding } from './ownership.ts';import { prepareFileTarget } from './page-prepare.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';export interface ReconcileAuditReport extends Record<string, unknown> {source_id: string;@@ -83,7 +84,7 @@ export async function runReconcileAudit(engine: BrainEngine, params: Record<stri}const writer = currentVerifiedLocalWriter() ?? await verifyLocalWriter(engine, await readLocalWriter(engine, 'cli'));if (writer.remote || writer.principal.kind !== 'local_cli' || writer.grant.slugPrefixes !== null) {- throw new OperationError('permission_denied', 'A whole-source audit requires the existing trusted CLI grant without a slug-prefix restriction.');+ throw trustedCliRequired('A whole-source audit requires the existing trusted CLI grant without a slug-prefix restriction.');}if (!writer.grant.sourceIds.includes('*') && !writer.grant.sourceIds.includes(params.source_id)) {throw new OperationError('permission_denied', 'The current CLI grant excludes this source.');diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex 753fefb9f7..d894b9c529 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -16,13 +16,14 @@ import { assertReconcileOutputPath, assertReconcileSize, manageReconcileBackups,import type { LocalGrant } from './identity.ts';import { isTerminal } from './model.ts';import { serializePageToMarkdown } from '../markdown.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';export { assertReconcileOutputPath } from './reconcile-backup.ts';export type { ReconcileArtifact } from './reconcile-state.ts';async function authorize(engine: BrainEngine, sourceId: unknown, slug: unknown) {const verified = currentVerifiedLocalWriter();- if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Reconciliation requires a verified trusted local CLI caller.');+ if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw trustedCliRequired('Reconciliation requires a verified trusted local CLI caller.');if (typeof sourceId !== 'string' || !isValidSourceId(sourceId) || typeof slug !== 'string' || !slug) throw new OperationError('invalid_params', 'One explicit source ID and page slug are required.');validatePageSlug(slug);if (/[?*]/.test(slug)) throw new OperationError('invalid_params', 'Reconciliation requires an exact page slug, not a pattern.');diff --git a/src/core/persistence/reindex-administration.ts b/src/core/persistence/reindex-administration.tsindex fbc559ad39..6fecd9d1cd 100644--- a/src/core/persistence/reindex-administration.ts+++ b/src/core/persistence/reindex-administration.ts@@ -2,10 +2,11 @@ import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { currentVerifiedLocalWriter } from './identity.ts';import { runReindexCode, type ReindexCodeOpts } from '../../commands/reindex-code.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';export async function runAuthenticatedCodeReindex(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {const verified = currentVerifiedLocalWriter();- if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Code reindex requires a trusted CLI registration.');+ if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw trustedCliRequired('Code reindex requires a trusted CLI registration.');if (Object.keys(params).some(k => k !== 'options') || !params.options || typeof params.options !== 'object' || Array.isArray(params.options)) throw new OperationError('invalid_params', 'Code reindex requires typed options.');const options = params.options as Record<string, unknown>;const allowed = ['sourceId', 'dryRun', 'yes', 'json', 'force', 'noEmbed', 'workers', 'maxCostUsd'];diff --git a/src/core/persistence/sync-administration.ts b/src/core/persistence/sync-administration.tsindex f0028a1a72..e9f260fccc 100644--- a/src/core/persistence/sync-administration.ts+++ b/src/core/persistence/sync-administration.ts@@ -6,11 +6,12 @@ import { submissionAuthority } from './authority.ts';import type { OperationContext } from '../ops/contract.ts';import { validateSyncWireParams } from './sync-wire.ts';import { explicitSyncProcessing } from './sync-authority.ts';+import { trustedCliRequired } from '../ops/op-fix.ts';/** Private CLI transport: wire fields can never manufacture a trust lane. */export async function runAuthenticatedSyncSlice(engine: BrainEngine, params: Record<string,unknown>): Promise<Record<string,unknown>> {const verified=currentVerifiedLocalWriter();- if(!verified||verified.remote||verified.principal.kind!=='local_cli')throw new OperationError('permission_denied','Sync requires a current trusted CLI registration.');+ if(!verified||verified.remote||verified.principal.kind!=='local_cli')throw trustedCliRequired('Sync requires a current trusted CLI registration.');const wire=validateSyncWireParams(params);const sourceId=await resolveSourceId(engine,wire.options.sourceId??null,wire.cwd,{skipLocalSignals:true});const [source]=await engine.executeRaw<{incarnation:string;archived:boolean}>('SELECT incarnation,archived FROM sources WHERE id=$1',[sourceId]);diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex a7f7ce6112..116ddd9439 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -718,7 +718,7 @@ export async function dispatchToolCall(return errorResult(opError('missing_source_scope',`Remote tool call '${name}' carries no resolved sourceId; refusing the shared 'default' source fallback. Pass an explicit sourceId resolved from the caller's grant.`,viaClient- ? 'This connection has no source grant. The brain host operator binds one to this client (gbrain auth rescope-client <client_id> --source <id>), then the call works.'+ ? `This connection has no source grant. The brain host operator binds one to this client (gbrain auth rescope-client ${opts.auth!.clientId} --source <source-id>), then the call works.`: 'This MCP server resolved no source. Set GBRAIN_SOURCE to a registered source id in the environment that launches it, then restart it.',{ fix: hostFix({ remote: true, transport: viaClient ? 'http' : 'stdio' },viaClient ? ['gbrain', 'auth', 'clients', '--json'] : ['gbrain', 'sources', 'list'],diff --git a/test/op-fix.test.ts b/test/op-fix.test.tsindex cb78821ea5..6fac28d683 100644--- a/test/op-fix.test.ts+++ b/test/op-fix.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'bun:test';-import { hostFix, hostOnlyError, invalidParam, opTransport, paramUse, readFix } from '../src/core/ops/op-fix.ts';+import { hostFix, hostOnlyError, invalidParam, opTransport, paramUse, readFix, trustedCliRequired } from '../src/core/ops/op-fix.ts';import { renderAction, cliRenderContext, toAgentError } from '../src/core/agent-output.ts';const cli = { remote: false } as const;@@ -61,4 +61,10 @@ describe('op-fix builders', () => {expect(renderAction(f, cliRenderContext())).toMatchObject({ next: 'run', command: 'gbrain jobs list' });expect(renderAction(f, mcpRender('stdio', ['list_jobs']))).toMatchObject({ next: 'run', mcp: { tool: 'list_jobs' } });});++ test('trustedCliRequired reads the registration first and never re-registers', () => {+ const e = trustedCliRequired('Sync requires a current trusted CLI registration.');+ expect(e).toMatchObject({ code: 'permission_denied', reason: 'trusted_cli_required', message: 'Sync requires a current trusted CLI registration.' });+ expect(renderAction(e.fix!, cliRenderContext())).toMatchObject({ command: 'gbrain auth local-writer list --json', actor: 'user', next: 'tell_user_to_run' });+ });});