Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Lane D: fsync the before copy through a writable descriptor; name the file-content hash helpers apart from the body hash

garrytanc01ec1394587
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 87fddbd4f6..459ddfe066 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -32,7 +32,7 @@ import { withNoRepoWriteThroughWarning } from '../write-through.ts';
import { assertUnboundPublication, classifyUnboundPage, unboundWriteWarning } from './unbound-source.ts';
import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, restoreBeforeStage, upgradeRecoveryStaging, type RecoveryStagingFile } from './staging.ts';
import { assertManagedFilesystemWrite } from './filesystem-guard.ts';
-import { beforeStagePath, contentBytes, contentHash, hashDescriptor, hashFile, isStreamedContent, LARGE_FILE_MIN_BYTES, stageBeforeCopy, stageStreamedContent, type StreamedFileContent } from './large-file.ts';
+import { beforeStagePath, fileContentBytes, fileContentHash, hashDescriptor, hashFile, isStreamedContent, LARGE_FILE_MIN_BYTES, stageBeforeCopy, stageStreamedContent, type StreamedFileContent } from './large-file.ts';
import { bindPublicationTimeouts, publicationTransaction } from './publication-deadline.ts';
import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';
@@ -297,7 +297,7 @@ export function pageRecoveryRecord(row: WriteRequest, file: PageMutationFile, bi
const record: FileRecoveryRecord = {
version: 1, path: file.path, root: file.root,
before: before?.toString('base64') ?? null, beforeHash: before ? sha256(before) : null,
- afterHash: file.content === null ? null : contentHash(file.content),
+ afterHash: file.content === null ? null : fileContentHash(file.content),
mode: before ? statSync(file.path).mode & 0o7777 : null,
ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token!,
staging: {
@@ -305,7 +305,7 @@ export function pageRecoveryRecord(row: WriteRequest, file: PageMutationFile, bi
...(before === null ? {} : { restoration: recoveryStagingFile(file.path, before) }),
},
};
- const nextBytes = file.content === null ? 0 : contentBytes(file.content);
+ const nextBytes = file.content === null ? 0 : fileContentBytes(file.content);
const beforeBytes = before?.byteLength ?? 0;
return { record, bytes: Math.max(beforeBytes * 3 + nextBytes * 2, Buffer.byteLength(JSON.stringify(record)) + beforeBytes + nextBytes) + 4096 };
}
@@ -325,14 +325,14 @@ function largeRecoveryRecord(row: WriteRequest, file: PageMutationFile, binding:
try { prior = { ...hashDescriptor(fd), mode: fstatSync(fd).mode & 0o7777 }; } finally { closeSync(fd); }
const record: FileRecoveryRecord = {
version: 1, path: file.path, root: file.root, before: null, beforeHash: prior.hash,
- afterHash: file.content === null ? null : contentHash(file.content), mode: prior.mode,
+ afterHash: file.content === null ? null : fileContentHash(file.content), mode: prior.mode,
ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token!,
staging: {
...(file.content === null ? {} : { publication: publicationStage(file.path, file.content) }),
before: { path: beforeStagePath(file.path), hash: prior.hash, bytes: prior.bytes },
},
};
- const nextBytes = file.content === null ? 0 : contentBytes(file.content);
+ const nextBytes = file.content === null ? 0 : fileContentBytes(file.content);
return { record, bytes: Buffer.byteLength(JSON.stringify(record)) + prior.bytes + nextBytes + 4096 };
}
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index a5f2fbe1ec..e057227d6f 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -5,7 +5,7 @@ import type { PageSnapshot } from '../page-state/types.ts';
import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { PreparedMutation } from './coordinator.ts';
-import { contentHash } from './large-file.ts';
+import { fileContentHash } from './large-file.ts';
import { PARK_AFTER_FAILURES, REMOTE_AUTO_LINKS_KEY, REMOTE_MENTION_OPERATIONS, type EffectKind, type PersistenceEffect, type EffectRequest } from './effect-model.ts';
import type { SqlEngine, WriteRequest } from './model.ts';
import { recordChronicleDecision } from '../chronicle/ledger.ts';
@@ -42,7 +42,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
row.principal_kind === 'local_cli' ? { fix: readFix(`Reads request ${row.id}'s durable receipt, read-only.`, { argv: ['gbrain', 'write-request', '--', row.id] }) } : {});
const commit = prepared.file.commit;
queue('git', { relative_path: relative(binding.local_path, prepared.file.path).split(sep).join('/'),
- expected_hash: prepared.file.content === null ? null : contentHash(prepared.file.content),
+ expected_hash: prepared.file.content === null ? null : fileContentHash(prepared.file.content),
...(commit ? { commit_subject: commit.subject, commit_line: commit.line, ...(commit.trailer ? { commit_trailer: commit.trailer } : {}) } : {}) });
if (outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });
}
diff --git a/src/core/persistence/large-file.ts b/src/core/persistence/large-file.ts
index 8ec8777662..8cca9cab42 100644
--- a/src/core/persistence/large-file.ts
+++ b/src/core/persistence/large-file.ts
@@ -110,10 +110,10 @@ async function* pieces(source: AsyncIterable<string | Uint8Array>): AsyncIterabl
}
export function isStreamedContent(content: unknown): content is StreamedFileContent { return content instanceof StreamedFileContent; }
/** UTF-8 byte length of a file target's content. */
-export function contentBytes(content: string | Uint8Array | StreamedFileContent): number {
+export function fileContentBytes(content: string | Uint8Array | StreamedFileContent): number {
return isStreamedContent(content) ? content.bytes : typeof content === 'string' ? Buffer.byteLength(content) : content.byteLength;
}
-export function contentHash(content: string | Uint8Array | StreamedFileContent): string {
+export function fileContentHash(content: string | Uint8Array | StreamedFileContent): string {
return isStreamedContent(content) ? content.hash : sha256(content);
}
@@ -180,7 +180,7 @@ export function stageBeforeCopy(path: string, stage: RecoveryStagingFile, mode:
validateBeforeStagePath(path, stage.path);
copyFileSync(path, stage.path, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
let staged = false;
- const fd = openSync(stage.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ const fd = openSync(stage.path, constants.O_RDWR | (constants.O_NOFOLLOW ?? 0));
try {
if (mode !== null) fchmodSync(fd, mode);
const copy = hashDescriptor(fd);
diff --git a/src/core/persistence/noop-kernel.ts b/src/core/persistence/noop-kernel.ts
index 8cb6f00bf9..8f0b98d9b3 100644
--- a/src/core/persistence/noop-kernel.ts
+++ b/src/core/persistence/noop-kernel.ts
@@ -33,7 +33,7 @@ import { persistenceFileHash } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { belowSafeChunkFence, chunkGenerationFilter } from '../search/safe-chunks.ts';
-import { contentHash } from './large-file.ts';
+import { fileContentHash } from './large-file.ts';
export interface NoopKernelResult {
contentUnchanged: boolean;
@@ -91,7 +91,7 @@ export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>,
if (!input.databaseOnly) {
const file = prepared.file;
const onDisk = file && file.content !== null ? persistenceFileHash(file.path) : null;
- if (!file || file.content === null || onDisk !== contentHash(file.content)) {
+ if (!file || file.content === null || onDisk !== fileContentHash(file.content)) {
if (onDisk === null || !input.waive?.includes('canonical_file_differs')) return result('canonical_file_differs');
waived.push('canonical_file_differs');
}
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index cf8dabb8f0..cb05c7bd44 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -81,7 +81,7 @@ import { isFenceEditWrite, pageGateTrust, pageWriteTrust, recordAgentPageLowerin
import { suppliedTrustMarkerView } from '../trust/channel.ts';
import { gateField, gateInput } from '../trust/gate-outcomes.ts';
import { PUSH_SCAN_MAX_FILE_BYTES } from '../page-size-policy.ts';
-import { contentHash, FileBytes, isStreamedContent, LARGE_FILE_MIN_BYTES, StreamedFileContent } from './large-file.ts';
+import { fileContentHash, FileBytes, isStreamedContent, LARGE_FILE_MIN_BYTES, StreamedFileContent } from './large-file.ts';
const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,
@@ -241,9 +241,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
/** #6517: a delete whose file another live page of the source records owns no file; the census target and claimants are reported. */
sharedOrigin?: { onShared: (shared: SharedOrigin) => void } } = {}): Promise<PreparedMutation['file']> {
if (!row.worktree_id) return undefined;
- // A canonical file over the pre-push secret-scan cap would block every later push of the brain repo. A streamed file
- // (restore_page of a page over the single-string ceiling: the file a delete removed) is exempt: the push gate scans a
- // staged file over that cap in bounded windows (workspace-push.ts), and the database copy is the system of record.
+ // An in-memory canonical file over the 25 MiB push-scan cap is refused (only a page over the 24 MiB single-string
+ // ceiling renders one). That page's file is streamed instead (restore_page of a page whose body was not read back,
+ // large-file.ts), and the push gate scans a staged file over the cap in bounded windows (workspace-push.ts).
if (content !== null && !isStreamedContent(content) && Buffer.byteLength(content, 'utf-8') > PUSH_SCAN_MAX_FILE_BYTES) throw opError('request_too_large', 'The canonical file would exceed the pre-push secret-scan cap.',
`Nothing was written. The rendered file of ${row.slug} is over ${PUSH_SCAN_MAX_FILE_BYTES} bytes, which the pre-push secret scan cannot scan, so it would block every push of source ${row.source_id}. Keep the page under the 24 MiB page ceiling (docs/guides/memory-boundaries.md#large-pages).`);
// #6212: a legacy slug (admitted only to delete or restore its existing row) never owns a file: its recorded
@@ -330,7 +330,7 @@ async function compareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 's
{ detail: 'file_database_drift', fix: readFix(`Previews how page ${row.slug}'s canonical file and database copy reconcile; a preview never changes canonical content.`,
{ argv: ['gbrain', 'sources', 'reconcile', row.source_id, row.slug, '--brain', 'host', '--preview', ...adopt] }) });
}
- } else if (before && !snapshot && content !== null && beforeHash() !== contentHash(content)
+ } else if (before && !snapshot && content !== null && beforeHash() !== fileContentHash(content)
&& !(options.capture && beforeHash() === options.capture.hash)) {
throw await heldFileRefusal(engine, row, root, path, 'occupied', options.remote === true)
?? new OperationError('source_changed', 'An unindexed file already occupies the canonical page path.', 'Import the file before replacing it.');