This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: bun-standalone-executable-mmap-memory-guardrail

Bun 1.2 Standalone Executable Immutable Mmap Asset and Memory Protection

Bun 1.2 standalone executables (bun build --compile) map embedded static assets, bundled dependencies, and runtime bytecode into read-only virtual memory regions. Mutating these memory-mapped buffers in-place or attempting write operations against internal virtual paths triggers segmentation faults or tampering vulnerabilities. Systems must enforce explicit copy-on-write strategies for asset transformations and maintain strictly immutable virtual memory invariants across binary execution lifecycles.

Prohibited Anti-Pattern: Mutating memory-mapped binary asset buffers or attempting in-place writes against virtual executable boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Standalone Executable Immutable Mmap Asset and Memory Protection - Bun 1.2 standalone executables (bun build --compile) map embedded static assets, bundled dependencies, and runtime bytecode into read-only virtual memory regions. Mutating these memory-mapped buffers in-place or attempting write operations against internal virtual paths triggers segmentation faults or tampering vulnerabilities. Systems must enforce explicit copy-on-write strategies for asset transformations and maintain strictly immutable virtual memory invariants across binary execution lifecycles.
globs: src/**/*.{ts,tsx,js}, scripts/**/*.{ts,sh}, build/**/*.{ts,js}, Dockerfile, .github/workflows/**/*.{yml,yaml}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-standalone-executable-mmap-memory-guardrail"
---

# Bun 1.2 Standalone Executable Immutable Mmap Asset and Memory Protection

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Mutating memory-mapped binary asset buffers or attempting in-place writes against virtual executable boundaries

## System Constraints
You are a Principal Software Architect enforcing Bun 1.2 Standalone Executable Memory Safety. In Bun standalone binaries generated via `bun build --compile`, bundled dependencies and embedded files reside in read-only virtual memory mappings backed by the binary itself. You must strictly forbid any in-place mutation of memory-mapped buffers (Buffer, ArrayBuffer, Uint8Array) derived from embedded assets or modules. Enforce defensive copy-on-write semantics for mutable data transformations, ensure asset extraction directs only to strictly permissioned volatile filesystem storage, and verify executable binary integrity flags in CI/CD build scripts.

## Strict Guidelines
- Engineers MUST ALWAYS treat ArrayBuffers or TypedArrays originating from embedded assets (`import ... with { type: 'file' }` or Bun file references inside compiled binaries) as immutable read-only buffers.
- Engineers MUST NEVER perform in-place byte writes (e.g., `buf.writeUInt32LE()`, direct index assignment `view[0] = ...`) on virtual memory-mapped buffers sourced from the compiled executable binary.
- Engineers MUST explicitly clone mapped memory into fresh heap allocations using `.slice()` or `new Uint8Array(source.length)` when mutation or transformation is required.
- Code SHOULD verify whether the runtime context is a standalone executable via `process.isBun` and inspection of binary boundaries before performing filesystem writes adjacent to `process.execPath`.
- Services MUST route runtime file mutations or temporary state modifications to an isolated external storage directory (e.g., `os.tmpdir()`) rather than attempting to write to the embedded bundle's virtual filesystem paths.
- CI/CD build pipelines MUST compile Bun 1.2 binaries with explicit target flags (e.g., `--target=bun-linux-x64-modern`), strip unnecessary symbols without compromising mapped ELF/Mach-O sections, and enforce strict execution permissions (`chmod 0555`) to eliminate executable modification.

## Bad vs Good Implementations
### Unsafe In-Place Mutation of Memory-Mapped Executable Asset Buffer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In a Bun standalone compiled binary, assets imported as files are embedded in the executable's read-only binary data section. `file.arrayBuffer()` references or maps directly into this immutable memory. Attempting to write into the resulting `Buffer` view triggers a memory protection fault (SIGSEGV) because the underlying virtual memory pages are mapped with PROT_READ.
```typescript
import configAsset from "./embedded-manifest.json" with { type: "file" };

export async function patchManifestHeader(version: number): Promise<Buffer> {
  // Anti-pattern: Fetching the asset creates an mmap view backed by the read-only executable section.
  const file = Bun.file(configAsset);
  const arrayBuffer = await file.arrayBuffer();
  const buffer = Buffer.from(arrayBuffer);

  // DANGER: Mutating virtual memory-mapped executable segments directly triggers SIGSEGV
  // or causes runtime undefined behavior in standalone Bun 1.2 binaries.
  buffer.writeUInt32BE(version, 0);

  return buffer;
}
```

#### Production Standard (Correct)
> **Standard**: By explicitly copying the bytes from the mmap-backed read-only source buffer into a newly allocated `Uint8Array` on the V8/JSC heap, the application completely decouples mutable state from the immutable binary memory mapping, ensuring absolute memory safety and invariant stability.
```typescript
import configAsset from "./embedded-manifest.json" with { type: "file" };

export async function patchManifestHeader(version: number): Promise<Uint8Array> {
  const file = Bun.file(configAsset);
  const sourceBuffer = await file.arrayBuffer();

  // Copy-On-Write (COW): Allocate fresh heap memory decoupled from read-only mmap backing.
  const mutableClone = new Uint8Array(sourceBuffer.byteLength);
  mutableClone.set(new Uint8Array(sourceBuffer));

  // Safe: Mutation operates strictly inside user-space heap allocation.
  const view = new DataView(mutableClone.buffer, mutableClone.byteOffset, mutableClone.byteLength);
  view.setUint32(0, version, false); // Big-endian write

  return mutableClone;
}
```

### Hardened Build Pipeline for Standalone Executable Deployment

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Compiling without deterministic targets or stripping write permissions on the generated binary leaves the executable open to in-place binary tampering and exposes executable sections to runtime corruption vulnerabilities.
```typescript
// scripts/build-binary.ts
import { $ } from "bun";

// Flawed: Compiles binary without target safety, leaves file writable, assumes local write-backs
await $`bun build ./src/index.ts --compile --outfile dist/service`;
console.log("Binary built at dist/service");
```

#### Production Standard (Correct)
> **Standard**: Specifying modern target architectures and programmatically restricting the compiled binary filesystem permissions to 0555 prevents accidental or malicious writes to the binary on disk, mirroring the virtual memory immutability invariants enforced in memory.
```typescript
// scripts/build-binary.ts
import { $ } from "bun";
import { chmodSync } from "node:fs";
import { resolve } from "node:path";

const outPath = resolve("dist/service");

// Enforce explicit target compilation, dead-code elimination, and embedded bytecode immutability
await $`bun build ./src/index.ts --compile --minify --target=bun-linux-x64-modern --outfile ${outPath}`;

// Enforce strict read-and-execute permissions (r-xr-xr-x / 0555) to guard binary boundary
chmodSync(outPath, 0o555);

console.log(`Hardened immutable binary generated at ${outPath} [0555]`);
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Standalone Executable Immutable Mmap Asset and Memory Protection

Bun 1.2 Standalone Executable Immutable Mmap Asset and Memory Protection defines an industrial-grade behavioral standard for devops engineering. Bun 1.2 standalone executables (bun build --compile) map embedded static assets, bundled dependencies, and runtime bytecode into read-only virtual memory regions. Mutating these memory-mapped buffers in-place or attempting write operations against internal virtual paths triggers segmentation faults or tampering vulnerabilities. Systems must enforce explicit copy-on-write strategies for asset transformations and maintain strictly immutable virtual memory invariants across binary execution lifecycles. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Mutating memory-mapped binary asset buffers or attempting in-place writes against virtual executable boundaries Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftMutating memory-mapped binary asset buffers or attempting in-place writes against virtual executable boundariesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS treat ArrayBuffers or TypedArrays originating from embedded assets (`import ... with { type

Engineers MUST ALWAYS treat ArrayBuffers or TypedArrays originating from embedded assets (`import ... with { type: 'file' }` or Bun file references inside compiled binaries) as immutable read-only buffers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NEVER perform in-place byte writes (e.g., `buf.writeUInt32LE()`, direct index assignment `view[0] = ...`) on virtual memory-mapped buffers sourced from the compiled executable binary.

Engineers MUST NEVER perform in-place byte writes (e.g., `buf.writeUInt32LE()`, direct index assignment `view[0] = ...`) on virtual memory-mapped buffers sourced from the compiled executable binary.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST explicitly clone mapped memory into fresh heap allocations using `.slice()` or `new Uint8Array(source.length)` when mutation or transformation is required.

Engineers MUST explicitly clone mapped memory into fresh heap allocations using `.slice()` or `new Uint8Array(source.length)` when mutation or transformation is required.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD verify whether the runtime context is a standalone executable via `process.isBun` and inspection of binary boundaries before performing filesystem writes adjacent to `process.execPath`.

Code SHOULD verify whether the runtime context is a standalone executable via `process.isBun` and inspection of binary boundaries before performing filesystem writes adjacent to `process.execPath`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST route runtime file mutations or temporary state modifications to an isolated external storage directory (e.g., `os.tmpdir()`) rather than attempting to write to the embedded bundle's virtual filesystem paths.

Services MUST route runtime file mutations or temporary state modifications to an isolated external storage directory (e.g., `os.tmpdir()`) rather than attempting to write to the embedded bundle's virtual filesystem paths.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

CI/CD build pipelines MUST compile Bun 1.2 binaries with explicit target flags (e.g., `--target=bun-linux-x64-modern`), strip unnecessary symbols without compromising mapped ELF/Mach-O sections, and enforce strict execution permissions (`chmod 0555`) to eliminate executable modification.

CI/CD build pipelines MUST compile Bun 1.2 binaries with explicit target flags (e.g., `--target=bun-linux-x64-modern`), strip unnecessary symbols without compromising mapped ELF/Mach-O sections, and enforce strict execution permissions (`chmod 0555`) to eliminate executable modification.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Bun 1.2 Standalone Executable Immutable Mmap Asset and Memory Protection critical for AI coding assistants?

Bun 1.2 standalone executables (bun build --compile) map embedded static assets, bundled dependencies, and runtime bytecode into read-only virtual memory regions. Mutating these memory-mapped buffers in-place or attempting write operations against internal virtual paths triggers segmentation faults or tampering vulnerabilities. Systems must enforce explicit copy-on-write strategies for asset transformations and maintain strictly immutable virtual memory invariants across binary execution lifecycles. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Mutating memory-mapped binary asset buffers or attempting in-place writes against virtual executable boundaries) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Bun