Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(storage): refuse a file that changed during its upload; keep plain-write modes for local objects
garrytan14a8bcb3671f
diff --git a/src/commands/files.ts b/src/commands/files.tsindex 559f6a24bb..9f62be4d10 100644--- a/src/commands/files.ts+++ b/src/commands/files.ts@@ -3,7 +3,7 @@ import { readFileSync, readdirSync, statSync, lstatSync, existsSync, writeFileSyimport { join, relative, extname, basename, dirname, resolve } from 'path';import { createHash } from 'crypto';import type { BrainEngine } from '../core/engine.ts';-import { hashStorageFile, type StorageBackend, type StorageConfig } from '../core/storage.ts';+import { hashStorageFile, uploadUnchangedFile, type StorageBackend, type StorageConfig } from '../core/storage.ts';import { sqlQueryForEngine, executeRawJsonb, FILES_METADATA_MERGE_SQL } from '../core/sql-query.ts';import { humanSize } from '../core/file-resolver.ts';import { createProgress } from '../core/progress.ts';@@ -202,7 +202,7 @@ async function uploadFile(engine: BrainEngine, args: string[]) {const method = stat.size >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';console.log(`Uploading ${humanSize(stat.size)} via ${method}...`);- await storage.uploadFile(storagePath, filePath, mimeType || undefined);+ await uploadUnchangedFile(storage, storagePath, filePath, stat, mimeType || undefined);// files.metadata is JSONB — bind a real object via executeRawJsonb instead// of casting a string into ::jsonb (the #2339 double-encode class).@@ -347,7 +347,7 @@ async function uploadRaw(engine: BrainEngine, args: string[]) {const method = stat.size >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';console.error(`Uploading ${humanSize(stat.size)} via ${method}...`);- await storage.uploadFile(storagePath, filePath, mimeType || undefined);+ await uploadUnchangedFile(storage, storagePath, filePath, stat, mimeType || undefined);// Create .redirect.yaml pointer in the brain repolet pointerPath: string | null = null;@@ -449,11 +449,11 @@ async function syncFiles(engine: BrainEngine, dir?: string) {progress.tick(1);+ const stat = statSync(filePath);const hash = fileHash(filePath);const filename = basename(filePath);const storagePath = relativePath.replace(/\\/g, '/');const mimeType = getMimeType(filePath);- const stat = statSync(filePath);const sql = sqlQueryForEngine(engine);const existing = await sql`SELECT id FROM files WHERE content_hash = ${hash} AND storage_path = ${storagePath}`;@@ -467,7 +467,7 @@ async function syncFiles(engine: BrainEngine, dir?: string) {const pageSlug = pathParts.length > 1 ? pathParts.slice(0, -1).join('/') : null;// Actually put the bytes in storage before recording them as stored.- await storage.uploadFile(storagePath, filePath, mimeType || undefined);+ await uploadUnchangedFile(storage, storagePath, filePath, stat, mimeType || undefined);// files.metadata is JSONB — bind a real object via executeRawJsonb instead// of casting a string into ::jsonb (the #2339 double-encode class).diff --git a/src/core/ops/files.ts b/src/core/ops/files.tsindex 632605f326..032a1906ac 100644--- a/src/core/ops/files.ts+++ b/src/core/ops/files.ts@@ -62,7 +62,7 @@ const file_upload: Operation = {const { statSync } = await import('fs');const { basename, extname } = await import('path');- const { hashStorageFile } = await import('../storage.ts');+ const { hashStorageFile, uploadUnchangedFile } = await import('../storage.ts');const filePath = p.path as string;const pageSlug = (p.page_slug as string) || null;@@ -127,7 +127,7 @@ const file_upload: Operation = {}try {- await storage.uploadFile(storagePath, filePath, mimeType || undefined);+ await uploadUnchangedFile(storage, storagePath, filePath, stat, mimeType || undefined);} catch (uploadErr) {throw opError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,'Nothing was recorded. Check the storage backend (credentials, bucket, disk) with `gbrain doctor --json`, then upload again; the upload is keyed by content hash, so repeating it is safe.');diff --git a/src/core/storage.ts b/src/core/storage.tsindex 22afcf9706..b5c6acd09c 100644--- a/src/core/storage.ts+++ b/src/core/storage.ts@@ -1,4 +1,4 @@-import { closeSync, openSync, readSync } from 'fs';+import { closeSync, openSync, readSync, statSync, type Stats } from 'fs';import type { FileHandle } from 'fs/promises';import { createHash } from 'crypto';@@ -73,6 +73,18 @@ export function hashStorageFile(filePath: string): string {}}+/**+ * Upload a file whose hash the caller already computed, then refuse when the file changed since `before` was taken,+ * so a row is never recorded under a hash the stored bytes may not match.+ */+export async function uploadUnchangedFile(storage: StorageBackend, path: string, filePath: string, before: Stats, mime?: string): Promise<void> {+ await storage.uploadFile(path, filePath, mime);+ const after = statSync(filePath);+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) {+ throw new Error(`${filePath} changed during the upload, so its hash may not match the stored bytes; nothing was recorded. Upload it again once it stops changing.`);+ }+}+/** Read exactly `length` bytes at `position` into the start of `buffer`. */export async function readFileRange(file: FileHandle, buffer: Buffer, length: number, position: number): Promise<Buffer> {for (let filled = 0; filled < length;) {diff --git a/src/core/storage/local.ts b/src/core/storage/local.tsindex 378f89e0fe..cb0ffc82b2 100644--- a/src/core/storage/local.ts+++ b/src/core/storage/local.ts@@ -1,4 +1,5 @@-import { copyFileSync, readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, readdirSync, realpathSync } from 'fs';+import { createReadStream, createWriteStream, readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, readdirSync, realpathSync } from 'fs';+import { pipeline } from 'stream/promises';import { join, dirname, resolve } from 'path';import type { StorageBackend } from '../storage.ts';@@ -31,7 +32,7 @@ export class LocalStorage implements StorageBackend {async uploadFile(path: string, filePath: string, _mime?: string): Promise<void> {const full = this.contained(path);mkdirSync(dirname(full), { recursive: true });- copyFileSync(filePath, full);+ await pipeline(createReadStream(filePath), createWriteStream(full));}async download(path: string): Promise<Buffer> {diff --git a/test/storage-upload-file.test.ts b/test/storage-upload-file.test.tsindex 1d8fbdafe5..d5f2269019 100644--- a/test/storage-upload-file.test.ts+++ b/test/storage-upload-file.test.ts@@ -249,6 +249,23 @@ describe('local uploadFile (#7427)', () => {expect(sha256Of(join(storageDir, 'media/local-src.bin'))).toBe(sha256Of(src));rmSync(storageDir, { recursive: true, force: true });});++ test('a stored object gets the mode a plain write gives, not the source file\'s mode', async () => {+ const src = join(workDir, 'local-private.bin');+ writePatterned(src, MiB + 5);+ fs.chmodSync(src, 0o600);+ const storageDir = mkdtempSync(join(tmpdir(), 'gb-7427-local-mode-'));+ const reference = join(storageDir, 'reference.bin');+ writeFileSync(reference, 'x');+ const storage = new LocalStorage(storageDir);+ await storage.uploadFile('media/new.bin', src);+ expect(fs.statSync(join(storageDir, 'media/new.bin')).mode & 0o777).toBe(fs.statSync(reference).mode & 0o777);+ fs.chmodSync(join(storageDir, 'media/new.bin'), 0o644);+ await storage.uploadFile('media/new.bin', src);+ expect(fs.statSync(join(storageDir, 'media/new.bin')).mode & 0o777).toBe(0o644);+ expect(sha256Of(join(storageDir, 'media/new.bin'))).toBe(sha256Of(src));+ rmSync(storageDir, { recursive: true, force: true });+ });});describe('upload callers hash and upload from disk (#7427)', () => {@@ -281,6 +298,35 @@ describe('upload callers hash and upload from disk (#7427)', () => {rmSync(storageDir, { recursive: true, force: true });});+ test('a file that changes during the upload is refused and nothing is recorded', async () => {+ const storageDir = mkdtempSync(join(tmpdir(), 'gb-7427-changed-'));+ const src = join(workDir, 'op-changing.mp4');+ writePatterned(src, MiB + 7);+ const ctx = {+ engine,+ config: { engine: 'pglite', storage: { backend: 'local', bucket: 'b', localPath: storageDir } },+ logger: { info() {}, warn() {}, error() {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ } as never;+ const original = LocalStorage.prototype.uploadFile;+ const spy = spyOn(LocalStorage.prototype, 'uploadFile').mockImplementation(async function (this: LocalStorage, path: string, filePath: string, mime?: string) {+ fs.appendFileSync(filePath, 'edited while uploading');+ return original.call(this, path, filePath, mime);+ });+ try {+ await expect(operationsByName['file_upload'].handler(ctx, { path: src, page_slug: 'media/changing-example' }))+ .rejects.toThrow(/changed during the upload/);+ } finally {+ spy.mockRestore();+ }+ const rows = await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM files WHERE storage_path = 'media/changing-example/op-changing.mp4'");+ expect(Number(rows[0].n)).toBe(0);+ rmSync(storageDir, { recursive: true, force: true });+ });+test('gbrain files upload, upload-raw, sync and mirror never read the whole original', async () => {const home = mkdtempSync(join(tmpdir(), 'gb-7427-home-'));const storageDir = mkdtempSync(join(tmpdir(), 'gb-7427-cli-'));