Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(files): refuse upload-raw on a managed worktree before creating anything (#5963)

garrytan2207aa134615
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 9332fcf4de..74ac3df8e1 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -25,6 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/sort-newest-first.ts` — single source of truth for the descending-lex sort that `gbrain import` and `gbrain sync` both apply. Mutates in place (Array.prototype.sort semantics), returns the same array reference for fluent chaining. Empty/single-element inputs short-circuit. Future ordering changes flip one line here instead of touching two CLI commands. Pinned by `test/sort-newest-first.test.ts` (descending order, mixed prefixes, empty, single-element, in-place-mutation contract).
- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Also exports `FILES_METADATA_MERGE_SQL`, the one `ON CONFLICT (storage_path)` merge fragment every files upsert (`src/commands/files.ts` x4, `src/core/ops/files.ts` `file_upload`) interpolates: it resets a non-object `files.metadata` to `{}` before the jsonb `||` merge, because `||` array-wraps a non-object left operand and would turn a legacy string-scalar row into `["{}", {...}]` that `gbrain repair-jsonb` can no longer see (pinned by `test/file-upload-fail-closed.test.ts`). Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.
+- `src/core/raw-file-upload.ts` — #5963 Part A: `managedRawUploadRefusal` is checked by `gbrain files upload-raw` (`src/commands/files.ts`) before any `mkdir`, so a git-storage upload into a managed canonical worktree refuses `writer_coordinator_required` (raw files are not coordinated in this release; fix: `gbrain files upload` with a storage backend) and creates nothing; `rawUploadRefusedFor` keeps `file_upload` (`src/core/ops/files.ts`) from suggesting upload-raw for such a page when no backend is configured.
- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml`, normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. `isDeclaredDbOnlySlug` matches a lowercase page slug against the declared db_only dirs case-insensitively; managed persistence uses it to publish those pages database-only. `hasUnresolvedDbOnlyDeclaration` detects a db_only key line that resolved no directory (unsupported syntax such as flow-style lists; an intentionally empty `db_only: []` is an accepted false positive); the sync baseline-commit guard refuses on it, and managed persistence turns a missing-file refusal into `storage_error`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 65950bd6e1..42acc29ae0 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -69,6 +69,7 @@ of making a duplicate.
| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |
| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
+| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. |
| <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. |
| <a id="reconcile-private-facts"></a>reconcile private facts | `permission_denied` | `gbrain sources reconcile --apply` (and its preview) found a `## Facts` row that would edit, renumber or change the visibility of a stored private fact, copy a stored private claim into a row under another visibility, or copy a stored private row's context (24 characters or longer) verbatim into a world row. A row is identified by its row number and claim, so a world row that only shares a private row's claim is not a private row and publishes. The refusal names the row number, never its text. It guards against verbatim copies only; reworded text is not detected, so it is not a confidentiality proof. Sources are not compared, because rows share provenance such as "Slack import". Nothing was written. | Read the stored page with the printed `gbrain get --source <id> -- <slug>`, keep the named row as stored in the file (or remove the copied text), then run a fresh `gbrain sources reconcile <id> <slug> --preview` and apply it. Change private facts with `remember` and `forget`. |
diff --git a/src/commands/files.ts b/src/commands/files.ts
index 73824acd4d..f9cf230d6e 100644
--- a/src/commands/files.ts
+++ b/src/commands/files.ts
@@ -299,6 +299,9 @@ async function uploadRaw(engine: BrainEngine, args: string[]) {
const dest = join(destDir, filename);
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- identity comparison only (skip self-copy when source already IS the dest); no fs path is derived from this expression
if (resolve(dest) !== resolve(filePath)) {
+ // #5963: refuse on a managed root before mkdir, so a refused upload leaves no empty .raw/ directory.
+ const refusal = (await import('../core/raw-file-upload.ts')).managedRawUploadRefusal(dest, filePath, pageSlug);
+ if (refusal) throw refusal;
mkdirSync(destDir, { recursive: true });
assertManagedFilesystemWrite(dest);
copyFileSync(filePath, dest);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index a73931bf75..93725278c9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -262,6 +262,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.0.0-wave11', text: 'A remote put_page or put_pages entry whose content has no Timeline section is now refused with `timeline_rows_would_be_removed` when it would delete the page\'s dated entries; keep the section (get_page include_content:true) or pass `drop_timeline: true`. A local `gbrain put` without an expected revision keeps those rows; an explicitly empty `## Timeline` still deletes them, and every write that deletes rows reports `timeline_rows_removed` (count and dates).' },
{ since: '0.0.0-wave11', text: '`gbrain repair failed-writes` now replays subagent and restricted-namespace writes (they were all refused "via subagent requires ctx.subagentId"), under the original writer\'s stored authority re-checked against its live grant; replayed writes are attributed to that original writer.' },
{ since: '0.0.0-wave11', text: 'Inline `[Source: ..., date]` citations no longer file an adjacent HTML comment (such as `<!-- AUTO:slack END -->`) as a timeline entry, and a timeline row carrying comment markup is never written back into a page (it would duplicate a section END marker); `gbrain repair timeline-comments --source <id>` previews and cleans rows and bullets stored before this release.' },
+ { since: '0.0.0-wave11', text: 'On a managed brain, `gbrain files upload-raw` of a small file now refuses before creating anything (it used to leave an empty `.raw/` directory); configure a storage backend and use `gbrain files upload <file> --page <slug>`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/ops/files.ts b/src/core/ops/files.ts
index 9ee354dbd3..9700bb2963 100644
--- a/src/core/ops/files.ts
+++ b/src/core/ops/files.ts
@@ -97,6 +97,10 @@ const file_upload: Operation = {
// lane (`gbrain files upload-raw --page <slug>`).
if (!ctx.config.storage) {
const slugOk = pageSlug !== null && /^[a-z0-9][a-z0-9._/-]*$/i.test(pageSlug);
+ // #5963: the git-tracked lane is refused on a managed worktree, so it is not offered there.
+ if (slugOk && await (await import('../raw-file-upload.ts')).rawUploadRefusedFor(ctx.engine, pageSlug!, ctx.sourceId ?? 'default')) throw opError('storage_error',
+ 'No storage backend configured — file_upload would record a files row with no stored bytes.',
+ 'Configure `storage` in your gbrain config (supabase | s3 | local), then upload again. This page lives in a managed canonical worktree, which does not accept raw files from outside the persistence coordinator, so a storage backend is the only way to store it.');
throw opError(
'storage_error',
'No storage backend configured — file_upload would record a files row with no stored bytes.',
diff --git a/src/core/raw-file-upload.ts b/src/core/raw-file-upload.ts
new file mode 100644
index 0000000000..d92482c615
--- /dev/null
+++ b/src/core/raw-file-upload.ts
@@ -0,0 +1,31 @@
+/**
+ * #5963 Part A: raw files are not coordinated on managed brains yet. A
+ * git-storage `gbrain files upload-raw` whose destination lies in a managed
+ * canonical worktree is refused before anything is created; a configured
+ * storage backend (`gbrain files upload`) is the working path.
+ */
+import type { BrainEngine } from './engine.ts';
+import { opError, type OperationError } from './ops/contract.ts';
+import { managedFilesystemRootFor } from './persistence/filesystem-guard.ts';
+
+export function managedRawUploadRefusal(dest: string, filePath: string, pageSlug: string): OperationError | null {
+ const managed = managedFilesystemRootFor(dest);
+ if (!managed) return null;
+ const error = opError('writer_coordinator_required',
+ `gbrain files upload-raw cannot bank ${filePath} next to ${pageSlug}: that path is in the managed canonical worktree ${managed.root}${managed.sourceId ? ` (source ${managed.sourceId})` : ''}. Nothing was created.`,
+ 'Store the file in a configured storage backend instead: configure `storage` (supabase | s3 | local) in the gbrain config, then run the command in fix. Starting a gbrain serve owner does not help.',
+ { why: 'Raw file uploads are not supported on a managed brain in this release: the persistence coordinator does not publish raw files yet, so the managed worktree refuses writes from outside it.',
+ docs: 'docs/guides/write-refusals.md#managed_raw_upload',
+ fix: { argv: ['gbrain', 'files', 'upload', filePath, '--page', pageSlug], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Uploads the file to the configured storage backend and links it to the page; it needs `storage` configured first.',
+ verify: { argv: ['gbrain', 'files', 'list', pageSlug] } } });
+ error.detail = `root=${managed.root} source=${managed.sourceId ?? 'unknown'} evidence=${managed.evidence}`;
+ return error;
+}
+
+/** True when a git-storage upload for this page would land in a managed worktree (so upload-raw is refused). */
+export async function rawUploadRefusedFor(engine: BrainEngine, pageSlug: string, sourceId: string): Promise<boolean> {
+ const { resolvePageWriteTarget } = await import('./write-through.ts');
+ const target = await resolvePageWriteTarget(engine, pageSlug, sourceId).catch(() => null);
+ return !!target?.ok && managedFilesystemRootFor(target.filePath) !== null;
+}
diff --git a/test/files-upload-raw-managed.test.ts b/test/files-upload-raw-managed.test.ts
new file mode 100644
index 0000000000..540592dca1
--- /dev/null
+++ b/test/files-upload-raw-managed.test.ts
@@ -0,0 +1,57 @@
+/**
+ * #5963 Part A: `gbrain files upload-raw` on a managed canonical worktree
+ * refuses before creating anything (no empty `.raw/` directory, no files row),
+ * and names `gbrain files upload` with a storage backend; `file_upload` with no
+ * backend stops pointing at upload-raw for a managed page.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError, operationsByName } from '../src/core/operations.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { refreshManagedFilesystemRoots } from '../src/core/persistence/filesystem-guard.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runFiles } from '../src/commands/files.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-upload-raw-managed-'));
+const fixtures = mkdtempSync(join(process.cwd(), '.gb-5963-fixtures-'));
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await disposePersistenceConsumer(engine); await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true }); rmSync(fixtures, { recursive: true, force: true });
+});
+
+test('upload-raw on a managed root refuses before any mkdir and leaves no files row', async () => {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ const sourceId = `raw-${randomUUID().slice(0, 8)}`;
+ const root = join(dir, sourceId); mkdirSync(root);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await refreshManagedFilesystemRoots(engine);
+ const doc = join(fixtures, 'doc.pdf');
+ writeFileSync(doc, '%PDF-1.4 example');
+ let error: unknown;
+ try { await runFiles(engine, ['upload-raw', doc, '--page', 'people/alice-example', '--source', sourceId]); } catch (e) { error = e; }
+ expect(error).toBeInstanceOf(OperationError);
+ const refusal = error as OperationError;
+ expect(refusal.code).toBe('writer_coordinator_required');
+ expect(refusal.why).toContain('not supported');
+ expect(refusal.fix?.argv).toEqual(['gbrain', 'files', 'upload', doc, '--page', 'people/alice-example']);
+ expect(existsSync(join(root, 'people', '.raw'))).toBe(false);
+ expect(await engine.executeRaw('SELECT 1 FROM files WHERE source_id=$1', [sourceId])).toEqual([]);
+
+ const upload = await operationsByName.file_upload.handler({ engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote: false, sourceId } as never, { path: doc, page_slug: 'people/alice-example' }).catch((e: unknown) => e as OperationError);
+ expect((upload as OperationError).code).toBe('storage_error');
+ expect((upload as OperationError).suggestion).not.toContain('upload-raw');
+ expect(JSON.stringify((upload as OperationError).fix ?? null)).not.toContain('upload-raw');
+ });
+}, 60_000);