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

Bun 1.2 Hermetic Standalone Binary Embedding & Cold-Start Isolation

Enforces immutable, zero-dependency standalone binary compilation via `bun build --compile` combined with embedded asset loading and deferred runtime evaluation. This guarantees sub-millisecond container cold starts and deterministic execution across ephemeral serverless fleets without relying on host-level Node.js runtimes or dynamic filesystem node_modules resolution.

Prohibited Anti-Pattern: Dynamic filesystem traversal and runtime node_modules resolution in production serverless containers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Hermetic Standalone Binary Embedding & Cold-Start Isolation - Enforces immutable, zero-dependency standalone binary compilation via `bun build --compile` combined with embedded asset loading and deferred runtime evaluation. This guarantees sub-millisecond container cold starts and deterministic execution across ephemeral serverless fleets without relying on host-level Node.js runtimes or dynamic filesystem node_modules resolution.
globs: Dockerfile, package.json, src/**/*.{ts,js,json}, build.ts, .github/workflows/*.yml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-hermetic-standalone-coldstart-guardrail"
---

# Bun 1.2 Hermetic Standalone Binary Embedding & Cold-Start Isolation

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Dynamic filesystem traversal and runtime node_modules resolution in production serverless containers

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Hermetic Standalone Binary Embedding & Cold-Start Isolation. Mandate invariants that eliminate runtime module resolution, strip dynamic file asset lookups, and ensure zero-dependency scratch/distroless deployments. Every binary target must compile with static asset imports (`with { type: 'file' }` or embedded buffer references) and enforce lazy initialization of expensive runtime drivers to achieve deterministic, sub-millisecond cold-start metrics.

## Strict Guidelines
- Engineers MUST ALWAYS compile production artifacts using `bun build --compile --minify --sourcemap=none --bytecode` into a single standalone executable.
- Engineers MUST NOT rely on external `node_modules` or dynamic `import()` filesystem lookups inside the container runtime environment.
- Static assets MUST be embedded directly at compile time using `import content from './asset.ext' with { type: 'file' }` or `import content from './asset.ext' with { type: 'text' }` rather than runtime `fs.readFile` paths.
- Services MUST defer heavyweight network handles, telemetry handshakes, and database pool warmups until the first request or utilize synchronous, non-blocking zero-allocation initialization patterns.
- Production container images MUST deploy on `FROM scratch` or Google Distroless static bases containing solely the single compiled Bun standalone binary and mandatory TLS CA certificates.
- Build scripts MUST pass the `--target=bun-linux-x64-modern` or `--target=bun-linux-arm64` flag explicitly to eliminate runtime arch-detection overhead.

## Bad vs Good Implementations
### Compiling Standalone Binary with Embedded Static Assets

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Runtime filesystem reads add blocking kernel syscalls during the serverless cold-start phase and require shipping source directories or configuration trees alongside the executable, violating hermetic binary isolation.
```typescript
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

// ANTI-PATTERN: Dynamic FS lookup causes cold-start disk I/O latency
// and breaks when executed in scratch/distroless environments lacking node_modules.
const configPath = resolve(process.cwd(), './config/schema.json');
const schemaRaw = readFileSync(configPath, 'utf-8');
const schema = JSON.parse(schemaRaw);

export function handleRequest() {
  return Response.json({ status: 'ok', schema });
}
```

#### Production Standard (Correct)
> **Standard**: Bun 1.2 import attributes bake JSON and file blobs directly into the binary's data segment, avoiding disk lookups, eliminating runtime JSON parsing overhead, and guaranteeing sub-millisecond startup times.
```typescript
import schema from '../config/schema.json' with { type: 'json' };

// PRODUCTION FIX: Compile-time embedded asset using Bun 1.2 import attributes.
// Statically embedded directly into the standalone binary data segment.
export function handleRequest(): Response {
  return Response.json({ status: 'ok', schema });
}
```

### Hermetic Container Build & Execution Definition

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Shipping the full source code and `bun install` state results in huge image sizes (100MB+), runtime dependency parsing, dynamic file scans, and high cold-start p99 latencies.
```dockerfile
# ANTI-PATTERN: Bloated container deploying runtime Node/Bun engines and node_modules
FROM oven/bun:1.2-alpine
WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --production
COPY src ./src
EXPOSE 3000
CMD ["bun", "run", "src/index.ts"]
```

#### Production Standard (Correct)
> **Standard**: The build generates an immutable, self-contained standalone binary with bytecode caching. Distroless minimal image footprint ensures zero dynamic resolution dependencies and instant, sub-millisecond invocation.
```dockerfile
# PRODUCTION FIX: Multi-stage build producing an immutable, single standalone binary
FROM oven/bun:1.2 AS builder
WORKDIR /build
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun build --compile --minify-whitespace --minify-syntax --target=bun-linux-x64-modern src/index.ts --outfile /build/server

FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=builder /build/server /app/server
USER nonroot:nonroot
EXPOSE 3000
ENTRYPOINT ["/app/server"]
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Hermetic Standalone Binary Embedding & Cold-Start Isolation

Bun 1.2 Hermetic Standalone Binary Embedding & Cold-Start Isolation defines an industrial-grade behavioral standard for devops engineering. Enforces immutable, zero-dependency standalone binary compilation via `bun build --compile` combined with embedded asset loading and deferred runtime evaluation. This guarantees sub-millisecond container cold starts and deterministic execution across ephemeral serverless fleets without relying on host-level Node.js runtimes or dynamic filesystem node_modules resolution. 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: Dynamic filesystem traversal and runtime node_modules resolution in production serverless containers 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 DriftDynamic filesystem traversal and runtime node_modules resolution in production serverless containersCritical
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 compile production artifacts using `bun build --compile --minify --sourcemap=none --bytecode` into a single standalone executable.

Engineers MUST ALWAYS compile production artifacts using `bun build --compile --minify --sourcemap=none --bytecode` into a single standalone executable.

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 NOT rely on external `node_modules` or dynamic `import()` filesystem lookups inside the container runtime environment.

Engineers MUST NOT rely on external `node_modules` or dynamic `import()` filesystem lookups inside the container runtime environment.

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

Static assets MUST be embedded directly at compile time using `import content from './asset.ext' with { type

Static assets MUST be embedded directly at compile time using `import content from './asset.ext' with { type: 'file' }` or `import content from './asset.ext' with { type: 'text' }` rather than runtime `fs.readFile` 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.
4

Services MUST defer heavyweight network handles, telemetry handshakes, and database pool warmups until the first request or utilize synchronous, non-blocking zero-allocation initialization patterns.

Services MUST defer heavyweight network handles, telemetry handshakes, and database pool warmups until the first request or utilize synchronous, non-blocking zero-allocation initialization patterns.

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

Production container images MUST deploy on `FROM scratch` or Google Distroless static bases containing solely the single compiled Bun standalone binary and mandatory TLS CA certificates.

Production container images MUST deploy on `FROM scratch` or Google Distroless static bases containing solely the single compiled Bun standalone binary and mandatory TLS CA certificates.

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

Build scripts MUST pass the `--target=bun-linux-x64-modern` or `--target=bun-linux-arm64` flag explicitly to eliminate runtime arch-detection overhead.

Build scripts MUST pass the `--target=bun-linux-x64-modern` or `--target=bun-linux-arm64` flag explicitly to eliminate runtime arch-detection overhead.

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 Hermetic Standalone Binary Embedding & Cold-Start Isolation critical for AI coding assistants?

Enforces immutable, zero-dependency standalone binary compilation via `bun build --compile` combined with embedded asset loading and deferred runtime evaluation. This guarantees sub-millisecond container cold starts and deterministic execution across ephemeral serverless fleets without relying on host-level Node.js runtimes or dynamic filesystem node_modules resolution. 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 (Dynamic filesystem traversal and runtime node_modules resolution in production serverless containers) 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