Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(files): file_register and file_verify on engines opened from settings (Wave C)

garrytan3455aa01fbcf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3979b187a2..d38c0829a3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A host that stores a file's bytes itself can now record and check them.** On an engine opened from settings, `file_register` records the files row for an object the host already wrote at the path `file_upload` would use, after reading it back and matching its size and SHA-256, and `file_verify` lists which rows still have their object or re-hashes one. Both use the engine's own `settings.storage` (local, s3 or supabase, with an optional key `prefix` so brains sharing a bucket never see each other's objects), never the process storage config. A brain the CLI or a server opens is unchanged: there both refuse `embedded_engine_required`, and neither is ever an MCP tool. Contributed by @bradgessler (#8457).
+
+### Itemized changes
+
+- `src/core/ops/files.ts`: `file_register` accepts only the upload layout path (`<page_slug>/<filename>`, or `unsorted/<first 8 hash chars>-<filename>`), refuses `page_not_found` for a page the caller's read policy hides (member access and privacy, the private-pages hatch included), and records nothing unless the stored object matches. Registering the same path again updates its row.
+- A store that does not answer is the new `store_unavailable` code, never a file reported missing and never a row recorded.
+- `openEngine` refuses `engine_settings_invalid` for a `storage` setting missing a value its backend needs (so no backend falls back to a default path or environment credentials), an unknown field or a malformed prefix; `embeddedSettings()` reads back `hasSecret` instead of the secret.
+- `src/core/storage/local.ts` and `s3.ts` stream an object's size and SHA-256 (`hashObject`); other backends hash one download.
+- `test/file-register.test.ts`: real PGLite engines and a real local store; the unreachable store is a closed local port.
+
## [0.60.564.0] - 2026-11-03
**A brain opened from settings brings its own AI providers.** `settings.ai` names the providers an embedded engine may call, with their keys and base URLs as values, and the models it uses for chat, expansion and reranking. Its embed, chat and rerank calls go only there, never to a key in the process environment, `~/.gbrain/config.json` or the process-wide gateway, so two brains in one process never spend each other's keys or see each other's cached query vectors. A call to a provider the settings don't name refuses `engine_scope_missing` and sends nothing. While such an engine is open, an AI call made outside any engine's scope refuses the same way unless the host configured a process gateway. Each engine's chat usage lands in its own database. Keys never show up in errors, logs, doctor output or `embeddedSettings()`, also for a call still in flight when the engine disconnects. Every other engine, and the CLI, keeps the process gateway exactly as before. Contributed by @bradgessler (#8456, #8085).
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 0615493878..4a4429abe9 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -773,12 +773,13 @@ working directory:
key, the config file or the process gateway. An unnamed provider refuses `engine_scope_missing` and nothing is
sent. Operations and persistence consumers run in their engine's scope; a host calling core directly wraps it in
`withEngineScope(engine, fn)`.
-- **Read back.** `embeddedSettings(engine)` returns a frozen copy without the writer credential or provider keys.
+- **Read back.** `embeddedSettings(engine)` returns a frozen copy without the writer credential, provider keys or storage secret.
- **Close.** `disconnect()` closes the engine for good and drops its settings, even while a reconnect is in flight
(any pool that reconnect builds is ended). A later `connect()` or `reconnect()` refuses `engine_closed`; call
- `openEngine` again instead. File storage (backend and object prefix) is not a setting yet (Wave C).
+ `openEngine` again instead.
+- **Files.** `settings.storage` (local, s3 or supabase; optional key `prefix`) backs `file_register` and `file_verify`.
-Still process-wide: file storage, transcription, the AI call log and timeouts, `GBRAIN_*` tuning variables (pool lifetime,
+Still process-wide: file_upload's storage, transcription, the AI call log and timeouts, `GBRAIN_*` tuning variables (pool lifetime,
connect and session timeouts, `GBRAIN_PREPARE`, `GBRAIN_DIRECT_POOL_SIZE`, `GBRAIN_DISABLE_DIRECT_POOL`,
`GBRAIN_RLS_SCOPE_BINDING`, the PGLite close watchdog), `PG*` TLS and tuning
variables, the connection-events audit log, and operation-level
diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsv
index 8f31522fd8..c401fc3b9c 100644
--- a/docs/architecture/managed-mutating-writers.tsv
+++ b/docs/architecture/managed-mutating-writers.tsv
@@ -38,6 +38,7 @@ op sync_brain coordinator Managed sync admits each changed file through the coor
op put_raw_data no_canonical_write raw_data side table; not guarded canonical content.
op log_ingest no_canonical_write ingest_log audit rows only.
op file_upload no_canonical_write File storage objects and their index rows, confined to the upload root.
+op file_register no_canonical_write A files index row for an object an embedded host already stored at the upload layout path.
op submit_job no_canonical_write Queues a minion job; its handler owns any write and its own boundary.
op cancel_job no_canonical_write Minion queue state only.
op retry_job no_canonical_write Minion queue state only.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index dc573caf52..814abe55a0 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1343,6 +1343,16 @@ More: [docs/guides/repair.md#embed-backfill-stalled](../../docs/guides/repair.md
More: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)
+### embedded_engine_required
+
+<a id="embedded_engine_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| An operation that serves an embedding host (file_register, file_verify) was called on an engine the CLI or a server opened, so it did nothing. | These operations trust a host that stores bytes itself; a brain opened the usual way stores files through file_upload, so the operations stay off there and its behavior is unchanged. | Upload with gbrain files upload and check with gbrain files verify, or call it on an engine opened from settings. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)
+
### embedding_auth_failed
<a id="embedding_auth_failed"></a>
@@ -4491,6 +4501,16 @@ Reasons: `database_contention`.
Override: reason `database_contention`: retryable, exit 1, retryable.
+### store_unavailable
+
+<a id="store_unavailable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The object store an engine opened from settings names did not answer a file check (file_register, file_verify), so nothing was recorded and no file was reported missing. | A failed read says nothing about whether the object exists; reporting it missing could lead a host to re-upload or delete a file that is still there. | Check the store named in settings.storage (its endpoint, bucket and keys), then call again. | agent | `repeat the read that failed` | 1 | yes |
+
+More: [docs/ENGINES.md#opening-an-engine-from-settings-experimental](../../docs/ENGINES.md#opening-an-engine-from-settings-experimental)
+
### strict_requires_managed
<a id="strict_requires_managed"></a>
diff --git a/llms-full.txt b/llms-full.txt
index b0612b2a95..1c33fa95d6 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6220,12 +6220,13 @@ working directory:
key, the config file or the process gateway. An unnamed provider refuses `engine_scope_missing` and nothing is
sent. Operations and persistence consumers run in their engine's scope; a host calling core directly wraps it in
`withEngineScope(engine, fn)`.
-- **Read back.** `embeddedSettings(engine)` returns a frozen copy without the writer credential or provider keys.
+- **Read back.** `embeddedSettings(engine)` returns a frozen copy without the writer credential, provider keys or storage secret.
- **Close.** `disconnect()` closes the engine for good and drops its settings, even while a reconnect is in flight
(any pool that reconnect builds is ended). A later `connect()` or `reconnect()` refuses `engine_closed`; call
- `openEngine` again instead. File storage (backend and object prefix) is not a setting yet (Wave C).
+ `openEngine` again instead.
+- **Files.** `settings.storage` (local, s3 or supabase; optional key `prefix`) backs `file_register` and `file_verify`.
-Still process-wide: file storage, transcription, the AI call log and timeouts, `GBRAIN_*` tuning variables (pool lifetime,
+Still process-wide: file_upload's storage, transcription, the AI call log and timeouts, `GBRAIN_*` tuning variables (pool lifetime,
connect and session timeouts, `GBRAIN_PREPARE`, `GBRAIN_DIRECT_POOL_SIZE`, `GBRAIN_DISABLE_DIRECT_POOL`,
`GBRAIN_RLS_SCOPE_BINDING`, the PGLite close watchdog), `PG*` TLS and tuning
variables, the connection-events audit log, and operation-level
diff --git a/plugin/README.md b/plugin/README.md
index e534a349a2..37e7466ed6 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -8,7 +8,7 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface full` — 185
+The plugin's MCP server runs `gbrain serve --surface full` — 187
operations, the same surface every stdio registration gbrain writes pins.
Every gbrain operation the bundled skills name is on it. A harness that caps
its tool count can narrow this machine's plugin surface with
diff --git a/src/core/embedded-engine.ts b/src/core/embedded-engine.ts
index 14acef6aa1..490aef2a1d 100644
--- a/src/core/embedded-engine.ts
+++ b/src/core/embedded-engine.ts
@@ -30,6 +30,25 @@ export interface EngineSettings {
* model is `embedding` above. Without it every AI call refuses `engine_scope_missing`; no process key is used.
*/
ai?: EngineAISettings;
+ /**
+ * The object store file_register and file_verify check, as values: `local` needs `localPath`, `s3` its bucket and
+ * keys, `supabase` its bucket, `projectUrl` and `serviceRoleKey`. Every object key is `<prefix>/<path>` when
+ * `prefix` is set, so brains sharing a bucket never see each other's objects; no prefix keeps today's keys.
+ */
+ storage?: EngineStorageSettings;
+}
+
+export interface EngineStorageSettings {
+ backend: 'local' | 's3' | 'supabase';
+ bucket?: string;
+ localPath?: string;
+ region?: string;
+ endpoint?: string;
+ accessKeyId?: string;
+ secretAccessKey?: string;
+ projectUrl?: string;
+ serviceRoleKey?: string;
+ prefix?: string;
}
export interface EngineAISettings {
@@ -39,9 +58,10 @@ export interface EngineAISettings {
/** The settings `embeddedSettings` returns: everything the host passed except the writer credential and the provider keys. */
type DeepReadonly<T> = { readonly [K in keyof T]: DeepReadonly<T[K]> };
-export type EmbeddedSettingsView = DeepReadonly<Omit<EngineSettings, 'writer' | 'ai'> & {
+export type EmbeddedSettingsView = DeepReadonly<Omit<EngineSettings, 'writer' | 'ai' | 'storage'> & {
writer?: { id: string; lane: 'cli' | 'stdio' };
ai?: { providers: Record<string, { baseUrl?: string; hasApiKey: boolean }>; models?: EngineAISettings['models'] };
+ storage?: Omit<EngineStorageSettings, 'secretAccessKey' | 'serviceRoleKey'> & { hasSecret: boolean };
}>;
interface EmbeddedRecord {
@@ -125,11 +145,12 @@ export function embeddedSettingsRecord(engine: object): EngineSettings | undefin
export function embeddedSettings(engine: object): EmbeddedSettingsView | undefined {
const settings = embeddedSettingsRecord(engine);
if (!settings) return undefined;
- const { writer, ai, ...rest } = settings;
+ const { writer, ai, storage, ...rest } = settings;
const providers = ai && Object.fromEntries(Object.entries(ai.providers)
.map(([id, p]) => [id, { ...(p.baseUrl ? { baseUrl: p.baseUrl } : {}), hasApiKey: !!p.apiKey }]));
const view = structuredClone({ ...rest, ...(writer ? { writer: { id: writer.id, lane: writer.lane } } : {}),
- ...(ai ? { ai: { providers: providers!, ...(ai.models ? { models: { ...ai.models } } : {}) } } : {}) });
+ ...(ai ? { ai: { providers: providers!, ...(ai.models ? { models: { ...ai.models } } : {}) } } : {}),
+ ...(storage ? { storage: (({ secretAccessKey, serviceRoleKey, ...open }) => ({ ...open, hasSecret: !!(secretAccessKey || serviceRoleKey) }))(storage) } : {}) });
const freeze = (value: unknown): void => {
if (!value || typeof value !== 'object' || Object.isFrozen(value)) return;
Object.freeze(value);
diff --git a/src/core/engine-open.ts b/src/core/engine-open.ts
index e6f6205695..db3fb88522 100644
--- a/src/core/engine-open.ts
+++ b/src/core/engine-open.ts
@@ -7,12 +7,12 @@ import type { BrainEngine } from './engine.ts';
import type { EngineConfig } from './types.ts';
import { opError } from './ops/contract.ts';
import { createEngine } from './engine-factory.ts';
-import { connectionUrlProblem, markEmbeddedEngine, releaseEmbeddedEngine, type EngineAISettings, type EngineSettings } from './embedded-engine.ts';
+import { connectionUrlProblem, markEmbeddedEngine, releaseEmbeddedEngine, type EngineAISettings, type EngineSettings, type EngineStorageSettings } from './embedded-engine.ts';
import { assertLocalWriterValue, setEngineHostId } from './persistence/identity.ts';
import { engineProviderProblem, recipeKeyEnv, sharedProviderEnvConflict } from './ai/engine-gateway.ts';
import { getRecipe } from './ai/recipes/index.ts';
-export type { EngineAISettings, EngineSettings, EmbeddedSettingsView } from './embedded-engine.ts';
+export type { EngineAISettings, EngineSettings, EngineStorageSettings, EmbeddedSettingsView } from './embedded-engine.ts';
export { embeddedSettings, isEmbeddedEngine, processHasEmbeddedEngines } from './embedded-engine.ts';
export { withEngineScope } from './engine-scope.ts';
export { hostIdFor } from './persistence/identity.ts';
@@ -27,6 +27,23 @@ const text = (value: unknown) => typeof value === 'string' && value.length > 0;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const AI_MODELS = ['chat', 'expansion', 'reranker'];
+const STORAGE_NEEDS: Record<string, readonly (keyof EngineStorageSettings)[]> = {
+ local: ['localPath'], s3: ['bucket', 'accessKeyId', 'secretAccessKey'], supabase: ['bucket', 'projectUrl', 'serviceRoleKey'],
+};
+const STORAGE_FIELDS = new Set(['backend', 'bucket', 'localPath', 'region', 'endpoint', 'accessKeyId', 'secretAccessKey', 'projectUrl', 'serviceRoleKey', 'prefix']);
+const PREFIX = /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*$/i;
+
+/** Every value the backend needs is given, so no backend falls back to a default path or reads credentials from the environment. */
+function checkStorage(storage: EngineStorageSettings): void {
+ const needs = storage && typeof storage === 'object' ? STORAGE_NEEDS[storage.backend] : undefined;
+ if (!needs) throw invalid('storage.backend', "storage is { backend: 'local' | 's3' | 'supabase', ... }.");
+ const extra = Object.keys(storage).find(field => !STORAGE_FIELDS.has(field));
+ if (extra) throw invalid(`storage.${extra}`, `storage takes ${[...STORAGE_FIELDS].join(', ')}.`);
+ const missing = needs.find(field => !text(storage[field]));
+ if (missing) throw invalid(`storage.${missing}`, `A ${storage.backend} store needs ${needs.join(', ')}.`);
+ if (storage.prefix !== undefined && !PREFIX.test(storage.prefix)) throw invalid('storage.prefix', 'prefix is one or more slash-separated segments of letters, digits, - and _.');
+}
+
/** Names the setting that is wrong, never a key: a key's value is never part of a refusal. */
function checkAI(ai: EngineAISettings): void {
if (!ai || typeof ai !== 'object' || !ai.providers || typeof ai.providers !== 'object') {
@@ -84,6 +101,7 @@ function checkSettings(settings: EngineSettings): void {
throw invalid('embedding', 'embedding is { model, dimensions } with a model name and a positive whole width.');
}
if (settings.ai !== undefined) checkAI(settings.ai);
+ if (settings.storage !== undefined) checkStorage(settings.storage);
}
/**
@@ -112,6 +130,7 @@ export async function openEngine(settings: EngineSettings): Promise<BrainEngine>
...(settings.writer ? { writer: { ...settings.writer } } : {}),
...(settings.embedding ? { embedding: { ...settings.embedding } } : {}),
...(settings.pglite ? { pglite: { ...settings.pglite } } : {}),
+ ...(settings.storage ? { storage: { ...settings.storage } } : {}),
...(settings.ai ? { ai: {
providers: Object.fromEntries(Object.entries(settings.ai.providers).map(([id, provider]) => [id, { ...provider }])),
...(settings.ai.models ? { models: { ...settings.ai.models } } : {}),
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 566633a0db..3da633c901 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -302,6 +302,7 @@ export const CODES = {
embedding_width_mismatch: { class: 'caller', summary: "The embedding model cannot produce the width of the brain's vector column; nothing was changed." },
embedded_core_required: { class: 'caller', summary: "openEngine (gbrain/engine-open) was called without embedded_core: true, so no engine was opened.", why: 'Opening an engine from settings alone is an experimental embedding surface that is off by default; a host opts in explicitly so no existing caller changes behavior.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass embedded_core: true in the settings; the CLI, gbrain serve and mounts open brains through their own connect path and need nothing.' },
engine_embedding_mismatch: { class: 'host_only', actor: 'user', summary: "An engine opened from settings names an embedding model or width that differs from the one its database already records, so initSchema changed nothing.", why: 'The vector column has one width and the brain one embedding model; seeding another over it would make every stored and future embedding unreadable. Changing it is an explicit re-embed the user decides on.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: "Pass the database's recorded model and width in settings.embedding, or read the recorded identity with gbrain migrate embeddings --status on the brain host and preview a migration from there.", fix: { argv: ['gbrain', 'migrate', 'embeddings', '--status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: "Read-only: reports the brain's recorded embedding model and width and what a migration would change." } },
+ embedded_engine_required: { class: 'caller', summary: "An operation that serves an embedding host (file_register, file_verify) was called on an engine the CLI or a server opened, so it did nothing.", why: 'These operations trust a host that stores bytes itself; a brain opened the usual way stores files through file_upload, so the operations stay off there and its behavior is unchanged.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Upload with gbrain files upload and check with gbrain files verify, or call it on an engine opened from settings.' },
engine_closed: { class: 'caller', summary: 'An engine opened from settings was disconnected, which closes it for good, so connect() and reconnect() refuse and nothing was reopened.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Call openEngine again with the settings to open a new engine.' },
engine_host_missing: { class: 'caller', summary: "An engine opened from settings has no host identity, so nothing that needs one ran and no host.json was created.", why: 'An embedded engine publishes and claims work under the host id its host gave at open; minting a host.json under the home directory instead would tie its writes to whatever process happens to share that directory.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass host: { id: <uuid> } to openEngine; keep the same id for the same host across restarts.' },
engine_scope_missing: { class: 'caller', summary: "An engine opened from settings made an AI call (embed, chat, expansion or rerank) through a provider its settings.ai does not name, or a call ran outside any engine scope in a process holding such engines, so nothing was sent.", why: "An embedded engine's AI calls reach only the providers and keys its host passed as values. Falling back to a process.env key, ~/.gbrain/config.json or the process-wide gateway would spend another brain's key and send this brain's text where its host never pointed it.", docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass the provider in settings.ai.providers (apiKey, and baseUrl when it is not the default) to openEngine, or point settings.ai.models (or settings.embedding) at a provider the engine has.' },
@@ -732,6 +733,7 @@ export const CODES = {
stable_channel_unresolved: { class: 'unavailable', reasons: ['unreadable', 'no_stable', 'no_release_tag'], summary: "`gbrain upgrade --channel stable` (or `self_upgrade.channel stable`) could not name the stable release: the repository's tags could not be read, no release has been promoted to stable yet, or the `stable` tag does not share a commit with a `v<version>` release tag. Nothing was changed.", why: "The stable channel installs only a release a maintainer promoted after the production-shaped soak passed on its exact tree; without that answer it installs nothing rather than guess.", docs: 'docs/guides/upgrades-auto-update.md#stable-channel', suggestion: 'Retry later, or upgrade on the latest channel with `gbrain upgrade --channel latest`.' },
stale_unavailable: { class: 'unavailable', summary: "No complete, current authorized shared-skills view is available; cached shared skills stay unused.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ store_unavailable: { class: 'retryable', summary: "The object store an engine opened from settings names did not answer a file check (file_register, file_verify), so nothing was recorded and no file was reported missing.", why: 'A failed read says nothing about whether the object exists; reporting it missing could lead a host to re-upload or delete a file that is still there.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: "Check the store named in settings.storage (its endpoint, bucket and keys), then call again." },
storage_error: { class: 'server', summary: "Reading or writing durable storage failed.",
reasons: ['database_contention'], reason_overrides: { database_contention: { class: 'retryable' } },
why: "Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `reason: database_contention`: a write admission that deadlocks, serialization failures, lock timeouts or statement timeouts kept refusing for its whole retry budget; no receipt was confirmed, so the same request_id is safe to retry once the contention clears. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path.",
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index bd7b700761..99f83e35d1 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -79,7 +79,7 @@ const OP_AREAS: Record<string, string> = {
log_ingest: 'ingest', get_ingest_log: 'ingest',
get_usage: 'admin',
// files (localOnly)
- file_list: 'files', file_upload: 'files', file_url: 'files',
+ file_list: 'files', file_upload: 'files', file_url: 'files', file_register: 'files', file_verify: 'files',
// jobs (Minions + agent lane)
submit_job: 'jobs', get_job: 'jobs', wait_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',
retry_job: 'jobs', get_job_progress: 'jobs', pause_job: 'jobs',
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 46a02e2444..20c53aac3f 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -144,6 +144,8 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"file_list": [load_files, "filesOperations"],
"file_upload": [load_files, "filesOperations"],
"file_url": [load_files, "filesOperations"],
+ "file_register": [load_files, "filesOperations"],
+ "file_verify": [load_files, "filesOperations"],
"submit_job": [load_jobs, "jobsOperations"],
"get_job": [load_jobs, "jobsOperations"],
"wait_job": [load_jobs, "jobsOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index e650f0cdcb..8db565957b 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -3683,6 +3683,81 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"localOnly": true,
"area": "files"
},
+ {
+ "name": "file_register",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Record the files row for an object the host already stored at the path file_upload would use (<page_slug>/<filename>, or unsorted/<first 8 hash chars>-<filename>), after reading it back and matching its size and SHA-256. Use when an embedded host writes bytes to storage itself. Runs only on an engine opened from settings; registering the same path again updates its row.",
+ "params": {
+ "storage_path": {
+ "type": "string",
+ "required": true,
+ "description": "Where the host stored the object; must be the file_upload layout for page_slug, filename and content_hash"
+ },
+ "filename": {
+ "type": "string",
+ "required": true
+ },
+ "content_hash": {
+ "type": "string",
+ "required": true,
+ "description": "SHA-256 of the bytes, 64 lowercase hex characters"
+ },
+ "size_bytes": {
+ "type": "integer",
+ "required": true,
+ "minimum": 0
+ },
+ "page_slug": {
+ "type": "string",
+ "description": "Page the file belongs to"
+ },
+ "mime_type": {
+ "type": "string"
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "files",
+ "upload",
+ "<file>",
+ "--page",
+ "<page_slug>"
+ ]
+ },
+ "area": "files"
+ },
+ {
+ "name": "file_verify",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Check files rows against the storage backend. Without storage_path, lists up to 100 rows (optionally one page's) with whether each object is present; with it, reads that object back and says whether its size and SHA-256 match the row. Runs only on an engine opened from settings. A backend that fails the check is store_unavailable, never a file reported missing.",
+ "params": {
+ "storage_path": {
+ "type": "string",
+ "description": "Read back and hash this one object"
+ },
+ "slug": {
+ "type": "string",
+ "description": "List only this page's files"
+ }
+ },
+ "scope": "admin",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "files",
+ "verify"
+ ]
+ },
+ "area": "files"
+ },
{
"name": "submit_job",
"idempotent": false,
diff --git a/src/core/ops/files.ts b/src/core/ops/files.ts
index 7d8bdb0c14..8854328f83 100644
--- a/src/core/ops/files.ts
+++ b/src/core/ops/files.ts
@@ -11,6 +11,7 @@ import { hostFix, readFix } from './op-fix.ts';
import { validateFilename, validatePageSlug, validateUploadPath } from './context.ts';
import { privatePagesFilterForCaller, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { hookSessionCwd } from '../session-cwd.ts';
+import { embeddedSettingsRecord, isEmbeddedEngine } from '../embedded-engine.ts';
// --- File Operations ---
@@ -214,6 +215,121 @@ const file_url: Operation = {
},
};
+/** file_register and file_verify serve a host that stores bytes itself: they run only on an engine opened from settings, against its settings.storage. */
+async function embeddedStorage(ctx: OperationContext, op: string) {
+ if (!isEmbeddedEngine(ctx.engine)) throw opError('embedded_engine_required', `${op} runs only on an engine an embedding host opened from settings (embedded_core: true).`,
+ 'On a brain the CLI opens, upload the file with gbrain files upload and check it with gbrain files verify.');
+ const settings = embeddedSettingsRecord(ctx.engine)?.storage;
+ if (!settings) throw opError('storage_error', `This engine was opened with no settings.storage, so ${op} cannot check any stored object.`,
+ 'Open the engine with storage (local | s3 | supabase, with its values) in its settings; the process storage config is never used for an engine opened from settings. Nothing was recorded.');
+ const { createStorage, prefixedStorage } = await import('../storage.ts');
+ const { prefix, ...config } = settings;
+ try { return prefixedStorage(await createStorage({ bucket: '', ...config }), prefix); } catch (error) { throw storeUnavailable(op, error); }
+}
+
+function storeUnavailable(op: string, error: unknown) {
+ return opError('store_unavailable', `${op} could not ask the storage backend: ${error instanceof Error ? error.message : String(error)}`,
+ 'The backend did not answer, so nothing is known about the object and nothing was recorded or reported missing. Check the backend with gbrain doctor --json, then call again.');
+}
+
+/** The path file_upload stores a file under; file_register accepts no other, so a registered row only names what an upload could have written. */
+function uploadLayoutPath(pageSlug: string | null, filename: string, hash: string): string {
+ return pageSlug ? `${pageSlug}/${filename}` : `unsorted/${hash.slice(0, 8)}-${filename}`;
+}
+
+async function pageReadable(ctx: OperationContext, slug: string): Promise<boolean> {
+ const rows = await ctx.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages fp WHERE fp.slug = $1
+ AND ${await resolveExcludePrivatePages(ctx.engine, ctx.remote) ? `NOT ${privatePagesFilterForCaller('fp')}` : 'FALSE'}`, [slug]);
+ return rows[0]!.n === 0;
+}
+
+const file_register: Operation = {
+ name: 'file_register',
+ idempotent: true,
+ outputRedaction: 'no_stored_text',
+ description: 'Record the files row for an object the host already stored at the path file_upload would use (<page_slug>/<filename>, or unsorted/<first 8 hash chars>-<filename>), after reading it back and matching its size and SHA-256. Use when an embedded host writes bytes to storage itself. Runs only on an engine opened from settings; registering the same path again updates its row.',
+ params: {
+ storage_path: { type: 'string', required: true, description: 'Where the host stored the object; must be the file_upload layout for page_slug, filename and content_hash' },
+ filename: { type: 'string', required: true },
+ content_hash: { type: 'string', required: true, description: 'SHA-256 of the bytes, 64 lowercase hex characters' },
+ size_bytes: { type: 'integer', required: true, minimum: 0 },
+ page_slug: { type: 'string', description: 'Page the file belongs to' },
+ mime_type: { type: 'string' },
+ },
+ mutating: true,
+ scope: 'admin',
+ localOnly: true,
+ cliOnly: { argv: ['gbrain', 'files', 'upload', '<file>', '--page', '<page_slug>'] },
+ handler: async (ctx, p) => {
+ const storage = await embeddedStorage(ctx, 'file_register');
+ const filename = p.filename as string, hash = p.content_hash as string, size = p.size_bytes as number;
+ const pageSlug = (p.page_slug as string | undefined) || null;
+ validateFilename(filename);
+ if (pageSlug) validatePageSlug(pageSlug);
+ if (!/^[0-9a-f]{64}$/.test(hash)) throw opError('invalid_params', 'content_hash must be the SHA-256 of the bytes as 64 lowercase hex characters.', 'Hash the stored bytes with SHA-256 and pass the hex digest.');
+ if (!Number.isSafeInteger(size) || size < 0) throw opError('invalid_params', 'size_bytes must be a whole number of bytes.', 'Pass the stored object\'s size in bytes.');
+ const storagePath = uploadLayoutPath(pageSlug, filename, hash);
+ if (p.storage_path !== storagePath) throw opError('invalid_params', `storage_path must be ${storagePath} for this page, filename and hash.`,
+ `Store the object at ${storagePath} (the path file_upload uses) and register that path. Nothing was recorded.`);
+ if (pageSlug && !await pageReadable(ctx, pageSlug)) throw opError('page_not_found', `No page '${pageSlug}' is visible to this caller.`, 'Attach the file to a page this caller can read. Nothing was recorded.');
+ const existing = await ctx.engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM files f WHERE f.storage_path = $1 AND NOT (${await fileReadableSql(ctx)})`, [storagePath]);
+ if (existing[0]!.n > 0) throw opError('page_not_found', `The file at ${storagePath} belongs to a page this caller cannot read.`, 'Nothing was recorded.');
+ if (ctx.dryRun) return { dry_run: true, action: 'file_register', storage_path: storagePath };
+ const { hashStoredObject } = await import('../storage.ts');
+ let stored: { size: number; sha256: string } | null;
+ try { stored = await storage.exists(storagePath) ? await hashStoredObject(storage, storagePath) : null; }
+ catch (error) { throw storeUnavailable('file_register', error); }
+ if (!stored) throw opError('storage_error', `The storage backend has no object at ${storagePath}, so no row was recorded.`, 'Store the bytes at that path first, then register it.');
+ if (stored.size !== size || stored.sha256 !== hash) throw opError('storage_error', `The object at ${storagePath} does not match size_bytes and content_hash, so no row was recorded.`,
+ `The stored object is ${stored.size} bytes with SHA-256 ${stored.sha256}. Register the values of the bytes actually stored.`);
+ const { executeRawJsonb, FILES_METADATA_MERGE_SQL } = await import('../sql-query.ts');
+ await executeRawJsonb(ctx.engine,
+ `INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
+ VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)
+ ON CONFLICT (storage_path) DO UPDATE SET
+ content_hash = EXCLUDED.content_hash,
+ size_bytes = EXCLUDED.size_bytes,
+ mime_type = EXCLUDED.mime_type,
+ ${FILES_METADATA_MERGE_SQL}`,
+ [pageSlug, filename, storagePath, (p.mime_type as string | undefined) ?? null, size, hash],
+ [{ storage: embeddedSettingsRecord(ctx.engine)!.storage!.backend }]);
+ return { status: 'registered', storage_path: storagePath, size_bytes: size };
+ },
+};
+
+const file_verify: Operation = {
+ name: 'file_verify',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: 'no_stored_text',
+ description: `Check files rows against the storage backend. Without storage_path, lists up to ${FILE_LIST_LIMIT} rows (optionally one page's) with whether each object is present; with it, reads that object back and says whether its size and SHA-256 match the row. Runs only on an engine opened from settings. A backend that fails the check is store_unavailable, never a file reported missing.`,
+ params: {
+ storage_path: { type: 'string', description: 'Read back and hash this one object' },
+ slug: { type: 'string', description: 'List only this page\'s files' },
+ },
+ scope: 'admin',
+ localOnly: true,
+ cliOnly: { argv: ['gbrain', 'files', 'verify'] },
+ handler: async (ctx, p) => {
+ const storage = await embeddedStorage(ctx, 'file_verify');
+ const readable = await fileReadableSql(ctx);
+ if (p.storage_path !== undefined) {
+ const rows = await ctx.engine.executeRaw<{ size_bytes: unknown; content_hash: string }>(`SELECT size_bytes, content_hash FROM files f WHERE f.storage_path = $1 AND ${readable}`, [p.storage_path as string]);
+ if (rows.length === 0) throw opError('storage_error', `File not found: ${p.storage_path}`, 'No file row this caller can read has that storage_path. List them with file_verify and no storage_path.');
+ const { hashStoredObject } = await import('../storage.ts');
+ let stored: { size: number; sha256: string } | null;
+ try { stored = await storage.exists(p.storage_path as string) ? await hashStoredObject(storage, p.storage_path as string) : null; }
+ catch (error) { throw storeUnavailable('file_verify', error); }
+ return { storage_path: p.storage_path, present: stored !== null,
+ size_matches: stored !== null && stored.size === Number(rows[0]!.size_bytes), hash_matches: stored !== null && stored.sha256 === rows[0]!.content_hash };
+ }
+ const slug = p.slug as string | undefined;
+ const rows = await ctx.engine.executeRaw<{ storage_path: string; page_slug: string | null }>(`SELECT storage_path, page_slug FROM files f
+ WHERE (${slug === undefined ? 'TRUE' : 'f.page_slug = $2'}) AND ${readable} ORDER BY storage_path LIMIT $1`, slug === undefined ? [FILE_LIST_LIMIT] : [FILE_LIST_LIMIT, slug]);
+ try { return await Promise.all(rows.map(async row => ({ ...row, present: await storage.exists(row.storage_path) }))); }
+ catch (error) { throw storeUnavailable('file_verify', error); }
+ },
+};
// Ops in EXACTLY the canonical `operations` array order.
-export const filesOperations: Operation[] = [file_list, file_upload, file_url];
+export const filesOperations: Operation[] = [file_list, file_upload, file_url, file_register, file_verify];
diff --git a/src/core/storage.ts b/src/core/storage.ts
index facb0acd80..9dd8b28ed9 100644
--- a/src/core/storage.ts
+++ b/src/core/storage.ts
@@ -21,6 +21,8 @@ export interface StorageBackend {
exists(path: string): Promise<boolean>;
list(prefix: string): Promise<string[]>;
getUrl(path: string): Promise<string>;
+ /** Size and SHA-256 of a stored object, streamed; a backend without it is hashed from one download (hashStoredObject). */
+ hashObject?(path: string): Promise<{ size: number; sha256: string }>;
}
export interface StorageConfig {
@@ -76,6 +78,28 @@ export function hashStorageFile(filePath: string): string {
}
}
+/** `backend` with every object key under `<prefix>/`; list() returns keys without it. No prefix returns `backend` itself. */
+export function prefixedStorage(backend: StorageBackend, prefix: string | undefined): StorageBackend {
+ if (!prefix) return backend;
+ const key = (path: string) => `${prefix}/${path}`;
+ return {
+ upload: (path, data, mime) => backend.upload(key(path), data, mime),
+ uploadFile: (path, filePath, mime, sha256) => backend.uploadFile(key(path), filePath, mime, sha256),
+ download: path => backend.download(key(path)),
+ delete: path => backend.delete(key(path)),
+ exists: path => backend.exists(key(path)),
+ list: async listPrefix => (await backend.list(key(listPrefix))).map(path => path.slice(prefix.length + 1)),
+ getUrl: path => backend.getUrl(key(path)),
+ ...(backend.hashObject ? { hashObject: (path: string) => backend.hashObject!(key(path)) } : {}),
+ };
+}
+
+export async function hashStoredObject(storage: StorageBackend, path: string): Promise<{ size: number; sha256: string }> {
+ if (storage.hashObject) return storage.hashObject(path);
+ const bytes = await storage.download(path);
+ return { size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
+}
+
/** Upload a file under the hash the caller recorded; a file that changed since then is refused before it is published. */
export async function uploadUnchangedFile(storage: StorageBackend, path: string, filePath: string, sha256: string, mime?: string): Promise<void> {
await storage.uploadFile(path, filePath, mime, sha256);
diff --git a/src/core/storage/local.ts b/src/core/storage/local.ts
index a7cef5614f..7791d3272a 100644
--- a/src/core/storage/local.ts
+++ b/src/core/storage/local.ts
@@ -80,6 +80,13 @@ export class LocalStorage implements StorageBackend {
return results;
}
+ async hashObject(path: string): Promise<{ size: number; sha256: string }> {
+ const hash = createHash('sha256');
+ let size = 0;
+ for await (const chunk of createReadStream(this.contained(path))) { hash.update(chunk); size += chunk.length; }
+ return { size, sha256: hash.digest('hex') };
+ }
+
async getUrl(path: string): Promise<string> {
return `file://${this.contained(path)}`;
}
diff --git a/src/core/storage/s3.ts b/src/core/storage/s3.ts
index 19fe90d9c0..a178ac03b5 100644
--- a/src/core/storage/s3.ts
+++ b/src/core/storage/s3.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto';
import { open } from 'fs/promises';
import {
S3Client,
@@ -131,6 +132,15 @@ export class S3Storage implements StorageBackend {
return Buffer.from(await res.Body.transformToByteArray());
}
+ async hashObject(path: string): Promise<{ size: number; sha256: string }> {
+ const res = await this.client.send(new GetObjectCommand({ Bucket: this.bucket, Key: path }));
+ if (!res.Body) throw new Error(`S3 download returned empty body: ${path}`);
+ const hash = createHash('sha256');
+ let size = 0;
+ for await (const chunk of res.Body as AsyncIterable<Uint8Array>) { hash.update(chunk); size += chunk.length; }
+ return { size, sha256: hash.digest('hex') };
+ }
+
async delete(path: string): Promise<void> {
await this.client.send(new DeleteObjectCommand({
Bucket: this.bucket,
diff --git a/test/file-register.test.ts b/test/file-register.test.ts
new file mode 100644
index 0000000000..c4356fa2af
--- /dev/null
+++ b/test/file-register.test.ts
@@ -0,0 +1,228 @@
+/**
+ * GBRA-283 Wave C: file_register and file_verify, for an embedding host that stores a file's bytes itself.
+ * Contributed by @bradgessler (#8457); rewritten on master. Real PGLite engines and a real local storage backend.
+ */
+import { afterAll, afterEach, describe, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { embeddedSettings, openEngine, type EngineSettings, type EngineStorageSettings } from '../src/core/engine-open.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { isCallable } from '../src/core/ops/callable.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const root = mkdtempSync(join(tmpdir(), 'gbrain-file-register-'));
+const storageRoot = join(root, 'store');
+const storage: EngineStorageSettings = { backend: 'local', localPath: storageRoot };
+const unreachable: EngineStorageSettings = { backend: 's3', bucket: 'test', endpoint: 'http://127.0.0.1:1', region: 'us-east-1', accessKeyId: 'test-key', secretAccessKey: 'test-secret' };
+const settings = (over: Partial<EngineSettings> = {}): EngineSettings => ({ embedded_core: true, engine: 'pglite', database: {}, host: { id: randomUUID() }, embedding: { model: 'openai:text-embedding-3-small', dimensions: 1536 }, storage, ...over });
+const ctxFor = (engine: BrainEngine, over: Partial<OperationContext> = {}): OperationContext => ({
+ engine, config: {}, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: false, ...over,
+} as unknown as OperationContext);
+const run = (op: string, ctx: OperationContext, params: Record<string, unknown>) => operationsByName[op]!.handler(ctx, params);
+const failure = async (work: () => Promise<unknown>) => {
+ try { await work(); return null; } catch (error) { return error as Error & { code?: string }; }
+};
+const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');
+function store(path: string, bytes: Buffer): void {
+ mkdirSync(dirname(join(storageRoot, path)), { recursive: true });
+ writeFileSync(join(storageRoot, path), bytes);
+}
+const fileRows = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM files'))[0]!.n);
+
+const engines: BrainEngine[] = [];
+async function embedded(over: Partial<EngineSettings> = {}): Promise<BrainEngine> {
+ const engine = await openEngine(settings(over));
+ await engine.initSchema();
+ engines.push(engine);
+ return engine;
+}
+afterEach(async () => {
+ await Promise.all(engines.splice(0).map(engine => engine.disconnect()));
+ rmSync(storageRoot, { recursive: true, force: true });
+ __resetPrivateVisibilityCacheForTests();
+});
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('file_register', () => {
+ test('records one row for an object stored at the file_upload path, and registering again updates it', async () => {
+ const engine = await embedded();
+ const bytes = Buffer.from('report bytes');
+ store('notes/plan/report.pdf', bytes);
+ const params = { storage_path: 'notes/plan/report.pdf', filename: 'report.pdf', page_slug: 'notes/plan', content_hash: sha(bytes), size_bytes: bytes.length, mime_type: 'application/pdf' };
+ expect(await run('file_register', ctxFor(engine), params)).toEqual({ status: 'registered', storage_path: 'notes/plan/report.pdf', size_bytes: bytes.length });
+ const next = Buffer.from('report bytes, revised');
+ store('notes/plan/report.pdf', next);
+ await run('file_register', ctxFor(engine), { ...params, content_hash: sha(next), size_bytes: next.length });
+ const rows = await engine.executeRaw<{ page_slug: string; content_hash: string; size_bytes: unknown }>('SELECT page_slug, content_hash, size_bytes FROM files');
+ expect(rows.map(r => ({ ...r, size_bytes: Number(r.size_bytes) }))).toEqual([{ page_slug: 'notes/plan', content_hash: sha(next), size_bytes: next.length }]);
+ });
+
+ test('refuses a path other than the file_upload layout, a missing or different object and bad inputs, recording nothing', async () => {
+ const engine = await embedded();
+ const bytes = Buffer.from('loose bytes');
+ const hash = sha(bytes);
+ store(`unsorted/${hash.slice(0, 8)}-scan.png`, bytes);
+ store('elsewhere/scan.png', bytes);
+ const base = { storage_path: `unsorted/${hash.slice(0, 8)}-scan.png`, filename: 'scan.png', content_hash: hash, size_bytes: bytes.length };
+ const cases: Array<[Record<string, unknown>, string, OperationContext?]> = [
+ [{ ...base, storage_path: 'elsewhere/scan.png' }, 'invalid_params'],
+ [{ ...base, storage_path: '../outside/scan.png' }, 'invalid_params'],
+ [{ ...base, content_hash: 'A'.repeat(64) }, 'invalid_params'],
+ [{ ...base, size_bytes: 1.5 }, 'invalid_params'],
+ [{ ...base, filename: '../scan.png' }, 'invalid_params'],
+ [{ ...base, size_bytes: bytes.length + 1 }, 'storage_error'],
+ [{ ...base, filename: 'other.png', storage_path: `unsorted/${hash.slice(0, 8)}-other.png` }, 'storage_error'],
+ ];
+ for (const [params, code, ctx] of cases) expect([params, (await failure(() => run('file_register', ctx ?? ctxFor(engine), params)))?.code]).toEqual([params, code]);
+ expect(await fileRows(engine)).toBe(0);
+ await run('file_register', ctxFor(engine), base);
+ expect(await fileRows(engine)).toBe(1);
+ });
+
+ test('an engine opened without settings.storage refuses even when the process has a storage config', async () => {
+ const engine = await embedded({ storage: undefined });
+ const bytes = Buffer.from('loose bytes');
+ store(`unsorted/${sha(bytes).slice(0, 8)}-scan.png`, bytes);
+ const params = { storage_path: `unsorted/${sha(bytes).slice(0, 8)}-scan.png`, filename: 'scan.png', content_hash: sha(bytes), size_bytes: bytes.length };
+ const ctx = ctxFor(engine, { config: { storage } } as never);
+ expect((await failure(() => run('file_register', ctx, params)))?.code).toBe('storage_error');
+ expect((await failure(() => run('file_verify', ctx, {})))?.code).toBe('storage_error');
+ expect(await fileRows(engine)).toBe(0);
+ });
+
+ test('two brains sharing one store under different prefixes see only their own objects', async () => {
+ const a = await embedded({ storage: { ...storage, prefix: 'brain-a' } });
+ const b = await embedded({ storage: { ...storage, prefix: 'brain-b' } });
+ const bytes = Buffer.from('brain a bytes');
+ store('brain-a/notes/plan/a.txt', bytes);
+ const params = { storage_path: 'notes/plan/a.txt', filename: 'a.txt', page_slug: 'notes/plan', content_hash: sha(bytes), size_bytes: bytes.length };
+ await run('file_register', ctxFor(a), params);
+ expect((await failure(() => run('file_register', ctxFor(b), params)))?.code).toBe('storage_error');
+ expect(await fileRows(b)).toBe(0);
+ expect(await run('file_verify', ctxFor(a), { storage_path: 'notes/plan/a.txt' })).toEqual({ storage_path: 'notes/plan/a.txt', present: true, size_matches: true, hash_matches: true });
+ });
+
+ test('a store that cannot be reached is store_unavailable and records nothing', async () => {
+ const engine = await embedded({ storage: unreachable });
+ const bytes = Buffer.from('x');
+ const error = await failure(() => run('file_register', ctxFor(engine), { storage_path: `unsorted/${sha(bytes).slice(0, 8)}-a.txt`, filename: 'a.txt', content_hash: sha(bytes), size_bytes: 1 }));
+ expect(error?.code).toBe('store_unavailable');
+ expect(await fileRows(engine)).toBe(0);
+ await engine.executeRaw(`INSERT INTO files (filename, storage_path, content_hash, size_bytes) VALUES ('a.txt', 'unsorted/a.txt', $1, 1)`, [sha(bytes)]);
+ for (const params of [{}, { storage_path: 'unsorted/a.txt' }]) expect((await failure(() => run('file_verify', ctxFor(engine), params)))?.code).toBe('store_unavailable');
+ });
+});
+
+describe('settings.storage', () => {
+ test('openEngine refuses a store missing a value it needs, an unknown backend, field or prefix, and the view hides its secret', async () => {
+ const cases: Array<[unknown, string]> = [
+ [{ backend: 'nope' }, 'storage.backend'], [{ backend: 'local' }, 'storage.localPath'],
+ [{ backend: 's3', bucket: 'b', accessKeyId: 'k' }, 'storage.secretAccessKey'], [{ backend: 'supabase', bucket: 'b', projectUrl: 'https://x.example' }, 'storage.serviceRoleKey'],
+ [{ ...storage, region2: 'x' }, 'storage.region2'], [{ ...storage, prefix: '../a' }, 'storage.prefix'], [{ ...storage, prefix: 'a/' }, 'storage.prefix'],
+ ];
+ for (const [given, setting] of cases) {
+ const error = await failure(() => openEngine(settings({ storage: given as EngineStorageSettings })));
+ expect([setting, error?.code, error?.message]).toEqual([setting, 'engine_settings_invalid', `The ${setting} setting is invalid.`]);
+ }
+ const engine = await embedded({ storage: unreachable });
+ expect(embeddedSettings(engine)!.storage).toEqual({ backend: 's3', bucket: 'test', endpoint: 'http://127.0.0.1:1', region: 'us-east-1', accessKeyId: 'test-key', hasSecret: true });
+ expect(JSON.stringify(embeddedSettings(engine))).not.toContain('test-secret');
+ });
+});
+
+describe('hashing a stored object', () => {
+ test('S3 streams the object body into its size and SHA-256', async () => {
+ const { S3Storage } = await import('../src/core/storage/s3.ts');
+ const parts = [Buffer.from('first part, '), Buffer.from('second part')];
+ const client = { send: async () => ({ Body: (async function* () { yield* parts; })() }) };
+ const s3 = new S3Storage({ backend: 's3', bucket: 'test' }, client as never);
+ expect(await s3.hashObject('a/b.txt')).toEqual({ size: 23, sha256: sha(Buffer.concat(parts)) });
+ });
+});
+
+describe('file_verify', () => {
+ test('lists presence per row, reads one object back, and notices bytes changed underneath', async () => {
+ const engine = await embedded();
+ const a = Buffer.from('alpha'), b = Buffer.from('bravo');
+ store('notes/plan/a.txt', a);
+ store('notes/plan/b.txt', b);
+ for (const [name, bytes] of [['a.txt', a], ['b.txt', b]] as const) {
+ await run('file_register', ctxFor(engine), { storage_path: `notes/plan/${name}`, filename: name, page_slug: 'notes/plan', content_hash: sha(bytes), size_bytes: bytes.length });
+ }
+ rmSync(join(storageRoot, 'notes/plan/b.txt'));
+ expect(await run('file_verify', ctxFor(engine), { slug: 'notes/plan' })).toEqual([
+ { storage_path: 'notes/plan/a.txt', page_slug: 'notes/plan', present: true },
+ { storage_path: 'notes/plan/b.txt', page_slug: 'notes/plan', present: false },
+ ]);
+ expect(await run('file_verify', ctxFor(engine), { storage_path: 'notes/plan/a.txt' })).toEqual({ storage_path: 'notes/plan/a.txt', present: true, size_matches: true, hash_matches: true });
+ store('notes/plan/a.txt', Buffer.from('ALPHA'));
+ expect(await run('file_verify', ctxFor(engine), { storage_path: 'notes/plan/a.txt' })).toEqual({ storage_path: 'notes/plan/a.txt', present: true, size_matches: true, hash_matches: false });
+ });
+});
+
+describe('who may call them', () => {
+ test('an engine the CLI opens refuses both with embedded_engine_required and records nothing', async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ try {
+ const bytes = Buffer.from('cli');
+ store(`unsorted/${sha(bytes).slice(0, 8)}-c.txt`, bytes);
+ for (const [op, params] of [['file_register', { storage_path: `unsorted/${sha(bytes).slice(0, 8)}-c.txt`, filename: 'c.txt', content_hash: sha(bytes), size_bytes: 3 }], ['file_verify', {}]] as const) {
+ expect((await failure(() => run(op, ctxFor(engine), params)))?.code).toBe('embedded_engine_required');
+ }
+ expect(await fileRows(engine)).toBe(0);
+ } finally {
+ await engine.disconnect();
+ }
+ });
+
+ test('neither is listed or callable over MCP, stdio included', async () => {
+ const engine = await embedded();
+ for (const op of ['file_register', 'file_verify']) {
+ for (const transport of ['stdio', 'http'] as const) expect(isCallable(operationsByName[op]!, { transport, surface: 'full', scopes: ['admin'], publishGates: {} })).toBe(false);
+ const result = await dispatchToolCall(engine, op, {}, { remote: true, transport: 'stdio' } as never);
+ expect(result.isError).toBe(true);
+ expect(await fileRows(engine)).toBe(0);
+ }
+ });
+
+ test('a caller under the read policy cannot attach to, replace or see a file on a page it cannot read; a local caller can', async () => {
+ const engine = await embedded();
+ await importFromContent(engine, 'notes/secret', ['---', 'type: note', 'title: Secret', 'visibility: private', '---', '# Secret', '', 'Private body.'].join('\n'));
+ const bytes = Buffer.from('secret attachment');
+ store('notes/secret/s.txt', bytes);
+ const params = { storage_path: 'notes/secret/s.txt', filename: 's.txt', page_slug: 'notes/secret', content_hash: sha(bytes), size_bytes: bytes.length };
+ const remote = ctxFor(engine, { remote: true });
+ expect((await failure(() => run('file_register', remote, params)))?.code).toBe('page_not_found');
+ expect(await fileRows(engine)).toBe(0);
+ await run('file_register', ctxFor(engine), params);
+ expect((await failure(() => run('file_register', remote, params)))?.code).toBe('page_not_found');
+ expect(await run('file_verify', remote, {})).toEqual([]);
+ expect((await failure(() => run('file_verify', remote, { storage_path: 'notes/secret/s.txt' })))?.code).toBe('storage_error');
+ expect(await run('file_verify', ctxFor(engine), {})).toEqual([{ storage_path: 'notes/secret/s.txt', page_slug: 'notes/secret', present: true }]);
+ });
+
+ test('a page naming its readers stays closed to an unlisted remote caller even with the private-pages hatch open', async () => {
+ const engine = await embedded();
+ await importFromContent(engine, 'notes/members', ['---', 'type: note', 'title: Members', 'readable_by: [alice-example]', '---', '# Members', '', 'Member body.'].join('\n'));
+ const bytes = Buffer.from('member attachment');
+ store('notes/members/m.txt', bytes);
+ const params = { storage_path: 'notes/members/m.txt', filename: 'm.txt', page_slug: 'notes/members', content_hash: sha(bytes), size_bytes: bytes.length };
+ await withEnv({ GBRAIN_REMOTE_PRIVATE_PAGES: '1' }, async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const remote = ctxFor(engine, { remote: true });
+ expect((await failure(() => run('file_register', remote, params)))?.code).toBe('page_not_found');
+ await run('file_register', ctxFor(engine), params);
+ expect(await run('file_verify', remote, { slug: 'notes/members' })).toEqual([]);
+ expect((await failure(() => run('file_verify', remote, { storage_path: 'notes/members/m.txt' })))?.code).toBe('storage_error');
+ });
+ });
+});
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index a6bd83ffc0..cddfacd14f 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 268798,
- "stdoutSha256": "7e8ad692baa54268f6f79bf3109bfb03bf6c29119f65624e8847aff30963f591",
+ "stdoutBytes": 271352,
+ "stdoutSha256": "3b86f387e3b0e1804aa1a99b97d49d939c69fee5be7861b6ed4fcb7084b3d4a6",
"toolNames": [
"remember",
"entity",
@@ -90,6 +90,8 @@
"file_list",
"file_upload",
"file_url",
+ "file_register",
+ "file_verify",
"submit_job",
"get_job",
"wait_job",
@@ -4292,6 +4294,82 @@
},
"scope": "admin"
},
+ {
+ "description": "Record the files row for an object the host already stored at the path file_upload would use (<page_slug>/<filename>, or unsorted/<first 8 hash chars>-<filename>), after reading it back and matching its size and SHA-256. Use when an embedded host writes bytes to storage itself. Runs only on an engine opened from settings; registering the same path again updates its row.",
+ "idempotent": true,
+ "local_only": true,
+ "mutating": true,
+ "name": "file_register",
+ "parameters": {
+ "content_hash": "string",
+ "filename": "string",
+ "mime_type": "string?",
+ "page_slug": "string?",
+ "size_bytes": "integer",
+ "storage_path": "string"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "content_hash": {
+ "description": "SHA-256 of the bytes, 64 lowercase hex characters",
+ "type": "string"
+ },
+ "filename": {
+ "type": "string"
+ },
+ "mime_type": {
+ "type": "string"
+ },
+ "page_slug": {
+ "description": "Page the file belongs to",
+ "type": "string"
+ },
+ "size_bytes": {
+ "type": "integer"
+ },
+ "storage_path": {
+ "description": "Where the host stored the object; must be the file_upload layout for page_slug, filename and content_hash",
+ "type": "string"
+ }
+ },
+ "required": [
+ "storage_path",
+ "filename",
+ "content_hash",
+ "size_bytes"
+ ],
+ "type": "object"
+ },
+ "scope": "admin"
+ },
+ {
+ "description": "Check files rows against the storage backend. Without storage_path, lists up to 100 rows (optionally one page's) with whether each object is present; with it, reads that object back and says whether its size and SHA-256 match the row. Runs only on an engine opened from settings. A backend that fails the check is store_unavailable, never a file reported missing.",
+ "idempotent": true,
+ "local_only": true,
+ "mutating": false,
+ "name": "file_verify",
+ "parameters": {
+ "slug": "string?",
+ "storage_path": "string?"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "slug": {
+ "description": "List only this page's files",
+ "type": "string"
+ },
+ "storage_path": {
+ "description": "Read back and hash this one object",
+ "type": "string"
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "scope": "admin"
+ },
{
"description": "Submit a background job. Remote callers may submit sync, import, lint or lint-fix for their authenticated filesystem source. Other kinds require local CLI or a dedicated operation.",
"idempotent": false,
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index f19a7f679a..e321e36a54 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -4433,7 +4433,7 @@
"kind": "type",
"name": "EmbeddedSettingsView",
"signature": [
- "{ readonly pglite?: DeepReadonly<{ shared_buffers?: string; } | undefined>; readonly host: DeepReadonly<{ id: string; }>; readonly database: DeepReadonly<{ url?: string; directUrl?: string; path?: string; }>; readonly embedding?: DeepReadonly<{ model: string; dimensions: number; } | undefined>; readonly embedded_core: DeepReadonly<boolean>; readonly engine: DeepReadonly<\"postgres\" | \"pglite\">; readonly pool?: DeepReadonly<{ max?: number; } | undefined>; readonly keyword_statement_timeout_ms?: number | undefined; readonly writer?: DeepReadonly<{ id: string; lane: \"cli\" | \"stdio\"; } | undefined>; readonly ai?: DeepReadonly<{ providers: Record<string, { baseUrl?: string; hasApiKey: boolean; }>; models?: EngineAISettings[\"models\"]; } | undefined>; }"
+ "{ readonly pglite?: DeepReadonly<{ shared_buffers?: string; } | undefined>; readonly host: DeepReadonly<{ id: string; }>; readonly database: DeepReadonly<{ url?: string; directUrl?: string; path?: string; }>; readonly embedding?: DeepReadonly<{ model: string; dimensions: number; } | undefined>; readonly embedded_core: DeepReadonly<boolean>; readonly engine: DeepReadonly<\"postgres\" | \"pglite\">; readonly pool?: DeepReadonly<{ max?: number; } | undefined>; readonly keyword_statement_timeout_ms?: number | undefined; readonly writer?: DeepReadonly<{ id: string; lane: \"cli\" | \"stdio\"; } | undefined>; readonly ai?: DeepReadonly<{ providers: Record<string, { baseUrl?: string; hasApiKey: boolean; }>; models?: EngineAISettings[\"models\"]; } | undefined>; readonly storage?: DeepReadonly<(Omit<EngineStorageSettings, \"secretAccessKey\" | \"serviceRoleKey\"> & { hasSecret: boolean; }) | undefined>; }"
]
},
{
@@ -4456,10 +4456,27 @@
"keyword_statement_timeout_ms?: number | undefined",
"pglite?: { shared_buffers?: string; } | undefined",
"pool?: { max?: number; } | undefined",
+ "storage?: EngineStorageSettings | undefined",
"writer?: { id: string; credential: string; lane: \"cli\" | \"stdio\"; } | undefined"
],
"name": "EngineSettings"
},
+ {
+ "kind": "interface",
+ "members": [
+ "accessKeyId?: string | undefined",
+ "backend: \"local\" | \"s3\" | \"supabase\"",
+ "bucket?: string | undefined",
+ "endpoint?: string | undefined",
+ "localPath?: string | undefined",
+ "prefix?: string | undefined",
+ "projectUrl?: string | undefined",
+ "region?: string | undefined",
+ "secretAccessKey?: string | undefined",
+ "serviceRoleKey?: string | undefined"
+ ],
+ "name": "EngineStorageSettings"
+ },
{
"kind": "function",
"name": "embeddedSettings",
@@ -6794,7 +6811,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"write_quota_exhausted\" | \"write_quota_insufficient\" | \"write_capacity_backpressure\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"page_body_segmented\" | \"revision_changed\" | \"tail_changed\" | \"write_outcome_unknown\" | \"write_interrupted\" | \"connection_inherited_read_only\" | \"owner_marker_missing\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"absent_from_worktree\" | \"access_command_failed\" | \"access_member_disabled\" | \"on_behalf_of_invalid_audience\" | \"on_behalf_of_unknown_member\" | \"on_behalf_of_not_permitted\" | \"actor_not_attested\" | \"actor_unlinked\" | \"on_behalf_of_in_arguments\" | \"access_policy_invalid\" | \"access_policy_pending\" | \"access_policy_widening_held\" | \"access_policy_store_mismatch\" | \"access_rule_invalid\" | \"access_member_id_retired\" | \"access_member_invalid\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"admission_paused\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"atom_drain_incomplete\" | \"atom_drain_no_progress\" | \"atom_drain_provider_failure\" | \"autopilot_job_owned_by_other_brain\" | \"body_staging_expired\" | \"budget_below_recent_runtime\" | \"backup_dump_failed\" | \"backup_too_large\" | \"belief_coverage_required\" | \"belief_stale_preparation\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_cleanup_pending\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"coverage_from\" | \"coverage_gap\" | \"clock_mismatch\" | \"extract_write_lost\" | \"item_failures_systemic\" | \"known_as_of_unproven\" | \"cache_quota_exceeded\" | \"calendar_unreadable\" | \"capacity_paused\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_not_found\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"commit_lock_busy\" | \"commit_paths_invalid\" | \"commit_prestaged_paths\" | \"commit_outside_source_root\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"connector_access_denied\" | \"connector_auth_required\" | \"connector_binding_missing\" | \"connector_item_too_large\" | \"connector_response_too_large\" | \"connector_shape_drift\" | \"chunkless_pages_healable\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_null_bytes\" | \"content_rejected\" | \"continuation_unproven\" | \"corpus_chat_unavailable\" | \"corpus_window_backoff\" | \"corpus_window_dead_lettered\" | \"convergence_read_failed\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cursor_incarnation_retired\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"deleted_page_chunks_overdue\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_holder_stalled\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"doctor_tier_unavailable\" | \"effect_not_failed\" | \"embed_backfill_stalled\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_identity_unqualified\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_state_unknown\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"embedded_core_required\" | \"engine_embedding_mismatch\" | \"embedded_engine_required\" | \"engine_closed\" | \"engine_host_missing\" | \"engine_scope_missing\" | \"engine_settings_invalid\" | \"engine_graduated\" | \"entity_types_unavailable\" | \"eval_suite_unwired\" | \"explicit_tasks_conflict\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"fact_withdrawn\" | \"fact_rows_collide\" | \"fence_row_changed\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_database_drift\" | \"fix_not_writable\" | \"file_drift\" | \"file_drift_mixed_selection\" | \"file_drift_state_required\" | \"file_removed_during_scan\" | \"file_unreadable\" | \"file_wins_rewrite\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"reserved_frontmatter_key\" | \"generation_fenced\" | \"generation_held\" | \"generation_live_conflict\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"ghost_mass_delete_refused\" | \"notifier_stalled\" | \"origin_twin_mass_merge_refused\" | \"ghost_storage_unknown\" | \"git_branch_unborn\" | \"git_durability_not_enabled\" | \"git_checkout_required\" | \"git_worktree_link_broken\" | \"hosted_repo_refused\" | \"git_detached_head\" | \"git_index_conflict\" | \"git_index_locked\" | \"git_index_stale\" | \"git_target_pending\" | \"git_operation_in_progress\" | \"git_push_unavailable\" | \"git_target_changed\" | \"git_target_ignored\" | \"git_target_unsafe\" | \"git_unavailable\" | \"git_object_missing\" | \"git_conversion_blocked\" | \"git_conversion_incomplete\" | \"git_home_required\" | \"git_private_commit_refused\" | \"git_protocol_required\" | \"git_lfs_not_enabled\" | \"gitlink_not_followed\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"grant_scope\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"head_blocked\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"integrate_conflict\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"ipc_path_too_long\" | \"legacy_twin_mass_merge_refused\" | \"legacy_twins_storage_unknown\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"legacy_lock_removal_refused\" | \"link_cursor_invalid\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"managed_remedy_unavailable\" | \"merge_recommended\" | \"movement_unknown\" | \"managed_sync_flag_refused\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_declined\" | \"migration_failed\" | \"migration_host_work_pending\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_context_ceiling\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_converged\" | \"not_owner_host\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"page_body_rows_unreadable\" | \"page_projection_stale\" | \"page_shrink_refused\" | \"page_too_large_for_inline\" | \"parse_error\" | \"part_splits_code_point\" | \"part_too_large\" | \"frontmatter_alias_limit\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"path_not_utf8\" | \"pattern_claims_pending\" | \"patterns_min_interval\" | \"pending_verify\" | \"pending_writes\" | \"persistence_restart_required\" | \"pool_inflight_over_budget\" | \"deep_health_probe_failed\" | \"refresh_required\" | \"serve_self_exit_suppressed\" | \"serve_unhealthy_exit\" | \"persistence_write_stall\" | \"push_unconfirmed\" | \"schema_lock_blocked\" | \"pg_connection_recovery_failed\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"knock_on_exhausted\" | \"keyword_skipped_after_timeout\" | \"publication_pending\" | \"pull_blocked_local_changes\" | \"purge_blocked_pending_recovery\" | \"purge_lookup_timeout\" | \"purge_mirror_unwritable\" | \"question_not_found\" | \"question_owner_only\" | \"rank_entities_timeout\" | \"read_budget_exhausted\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"reconcile_host_required\" | \"reconcile_read_incomplete\" | \"recovery_prior_stage_unavailable\" | \"recovery_version_unsupported\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_lock_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"refresh_sync_timeout\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"rename_identity_unreadable\" | \"rename_reconcile_failed\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"restart_refused\" | \"restart_unverified\" | \"runtime_build_skew\" | \"reset_upstream_refused\" | \"resume_spec_mismatch\" | \"result_too_large\" | \"revision_unavailable\" | \"schema_owner_required\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"scorecard_group_by_local_only\" | \"search_offset_over_cap\" | \"segmented_mirror_writer_gate\" | \"serve_build_drift\" | \"serve_port_in_use\" | \"serve_status_only\" | \"settle_mismatch\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"hook_session_cwd\" | \"turn_hook_not_loaded\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"slug_page_mismatch\" | \"slug_root_mode_mismatch\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"sources_not_readable\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stable_channel_unresolved\" | \"stale_unavailable\" | \"state_mismatch\" | \"store_unavailable\" | \"strict_requires_managed\" | \"sync_anchor_relative\" | \"sync_not_applicable\" | \"sync_admission_restricted\" | \"sync_deadline_stalled\" | \"sync_drain_lease_held\" | \"content_receipt_stale\" | \"sync_first_run_in_progress\" | \"sync_no_successful_sync\" | \"sync_cursor_replaced\" | \"sync_pass_superseded\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"readable_by_invalid\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"transcript_source_mismatch\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_database_path\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"unsupported_path\" | \"upload_expired\" | \"upload_not_found\" | \"upload_protected_content\" | \"upload_too_many_parts\" | \"upstream\" | \"upstream_diverged\" | \"upstream_rewritten\" | \"upstream_unknown\" | \"vector_prewarm_extension_missing\" | \"vector_prewarm_unsupported_engine\" | \"vector_prewarm_wont_fit\" | \"verification_failed\" | \"visibility_noncanonical\" | \"visibility_not_applied\" | \"withdrawal_capacity\" | \"withdrawal_mirror_failed\" | \"withdrawal_mirror_pending\" | \"withdrawal_provenance\" | \"write_capacity_low\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.ts
index b6f7776c4e..f123e4fb5d 100644
--- a/test/operations-coverage-ledger.test.ts
+++ b/test/operations-coverage-ledger.test.ts
@@ -116,6 +116,8 @@ const LEDGER: Record<string, string> = {
file_list: 'test/file-upload-engine-context.test.ts',
file_upload: 'test/file-upload-engine-context.test.ts',
file_url: 'test/file-upload-engine-context.test.ts',
+ file_register: 'test/file-register.test.ts',
+ file_verify: 'test/file-register.test.ts',
submit_job: 'test/submit-queue-state.test.ts',
get_job: 'test/jobs-ops-token-redaction.test.ts',
list_jobs: 'test/jobs-ops-token-redaction.test.ts',
diff --git a/test/operations-trust-boundary.test.ts b/test/operations-trust-boundary.test.ts
index f40a88ea20..bb649ab230 100644
--- a/test/operations-trust-boundary.test.ts
+++ b/test/operations-trust-boundary.test.ts
@@ -235,8 +235,10 @@ describe('mcpOperations filter — localOnly ops are excluded from the HTTP-expo
'entity_identity_unlink',
'extraction_review',
'file_list',
+ 'file_register',
'file_upload',
'file_url',
+ 'file_verify',
'get_recent_transcripts',
'get_skill_retention',
'import_skill_proposal',
@@ -574,7 +576,7 @@ describe('ops-module system-access containment — top-level fs/child_process im
// one of the memory verbs from src/core/verbs.ts — nothing else.
expect(opsFiles).toContain('files.ts');
expect(opsFiles).toContain('jobs.ts');
- expect(await contributedOps('files.ts')).toEqual(['file_list', 'file_upload', 'file_url']);
+ expect(await contributedOps('files.ts')).toEqual(['file_list', 'file_register', 'file_upload', 'file_url', 'file_verify']);
expect(await contributedOps('jobs.ts')).toContain('submit_job');
const attributed = new Set<string>(verbOperations.map(op => op.name));