npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@fractalcode/fractal-claw

v0.1.0

Published

Fractal Code — Constitutional programming framework for safe AI agent execution

Readme

FractalClaw — Constitutional AI Code Generation

FractalClaw Demo

Fractal Code is a constitutional framework for building software. Every component is a typed cell — Transformer, Reactor, Keeper, or Channel — bound by a universal contract that enforces identity, input/output schemas, health reporting, lineage provenance, and a structural signature. Cells compose through Channels, never through direct references. The structure is fractal: a single function and a distributed system of 10,000 components present the same contract.

FractalClaw is a program built inside Fractal Code — governed by the same constitution it enforces on others. It is itself composed of Fractal Code cells, and its job is to generate, validate, execute, and trace multi-cell Fractal Code architectures using an LLM.

OpenClaw (145K+ GitHub stars) has documented security problems: malicious skills exfiltrate data, inject prompts, and escalate privileges. The root cause is zero structural governance — skills are text files loaded with full trust.

FractalClaw demonstrates that Fractal Code solves this by rebuilding OpenClaw's skill system on constitutional architecture, catching every documented attack vector — while also providing a full AI-driven generation pipeline for building correct, auditable systems from scratch.

Installation

npm install -g @fractal-code/fractalclaw

Or use without installing:

npx fractalclaw scan ./my-skills/

Quick Start

# Generate a single .fc cell from a plain-English prompt (requires ANTHROPIC_API_KEY)
npx fractalclaw build reverser --prompt "reverse the input string"

# Generate a multi-cell system automatically
npx fractalclaw build signal-pipeline --prompt "validate, classify, and log signals"

# Execute the generated system
npx fractalclaw pipeline ./fractalclaw/signal-pipeline/

# Scan a directory for constitutional violations
npx fractalclaw scan ./my-skills/

# Create a new skill from template
npx fractalclaw init my-skill

# Compute and write the structural signature
npx fractalclaw sign -w my-skill.transformer.fc

# Deep verification of a single file
npx fractalclaw verify my-skill.transformer.fc

# Validate, compile, and execute a single cell in the void environment
npx fractalclaw run my-skill.transformer.fc --input '"hello"'

# Verify a file's lineage via Merkle proof
npx fractalclaw verify-lineage my-skill.transformer.fc

Developer Workflow

Autonomous single-cell: build → run

# 1. Generate, validate, and sign in one step
npx fractalclaw build weather-lookup \
  --prompt "Look up the weather for a given city name and return a summary"

# 2. Execute it
npx fractalclaw run fractalclaw/weather-lookup/weather-lookup.transformer.fc --input '"London"'

Autonomous multi-cell: build → pipeline

# 1. Generate a full multi-cell architecture
npx fractalclaw build alert-system \
  --prompt "Ingest sensor readings, classify anomalies, and emit structured alerts"

# 2. Execute the pipeline end-to-end
npx fractalclaw pipeline ./fractalclaw/alert-system/ --input '{"sensor": "temp", "value": 42}'

Autonomous with semantic tests: build --tests → run

# 1. Write a test suite (JSON array of input/expected pairs)
echo '[
  { "input": "hello", "expected": "olleh" },
  { "input": "world", "expected": "dlrow" }
]' > reverser-tests.json

# 2. Generate, auto-verify quality gates (with self-heal if needed), run tests, validate, and sign
npx fractalclaw build reverser \
  --prompt "reverse the input string" \
  --tests reverser-tests.json

# 3. Execute it
npx fractalclaw run fractalclaw/reverser/reverser.transformer.fc --input '"hello"'

Manual: init → edit → sign → scan → run

# 1. Create a new skill from template
npx fractalclaw init weather-lookup

# 2. Edit the file — fill in identity, contract, lineage, and logic
#    (use your editor)

# 3. Seal it with a structural signature
npx fractalclaw sign -w weather-lookup.transformer.fc

# 4. Verify everything passes
npx fractalclaw scan .

# 5. Execute it
npx fractalclaw run weather-lookup.transformer.fc --input '"London"'

Commands

fractalclaw build <name>

Primary entry point. Generates a named system from a plain-English prompt. Auto-routes to orchestrate for single-cell outputs or architect for multi-cell architectures — based on the LLM's analysis of the prompt.

Requires the ANTHROPIC_API_KEY environment variable to be set.

fractalclaw build reverser --prompt "reverse the input string"
fractalclaw build alert-system --prompt "validate, classify, and alert on signals"
fractalclaw build my-system --prompt "..." --model claude-sonnet-4-20250514
fractalclaw build reverser --prompt "reverse the input string" --tests tests.json

Output (single-cell route):

═══════════════════════════════════════════════════════
  FractalClaw — Build
═══════════════════════════════════════════════════════

  Name:   reverser
  Prompt: "reverse the input string"

  → Single-cell system detected
  ✅ Generated                     reverser.transformer.fc
  ✅ Constitutional scan           all checks passed
  ✅ Signed                        0xb28649ba1eb52b9a...
  ✅ Lineage recorded              root: 0x6f515a551afa548d...

  ✅ reverser is ready.
  Run it: npx fractalclaw run fractalclaw/reverser/reverser.transformer.fc --input '<json>'

═══════════════════════════════════════════════════════

Output (multi-cell route):

═══════════════════════════════════════════════════════
  FractalClaw — Build
═══════════════════════════════════════════════════════

  Name:   alert-system
  Prompt: "validate, classify, and alert on signals"

  → Multi-cell system detected
  ✅ Manifest generated            4 cells, 3 channels
  ✅ validate-signal               generated + signed
  ✅ classify-signal               generated + signed
  ✅ emit-alert                    generated + signed
  ✅ alert-system (parent)         generated + signed
  ✅ Lineage recorded              swarm root: 0x8f3a21...

  ✅ alert-system is ready.
  Run it: npx fractalclaw pipeline fractalclaw/alert-system/

═══════════════════════════════════════════════════════

Flags:

  • --prompt <text> (required) — Plain-English description of what the system should do
  • --model <model> — Anthropic model to use (default: claude-sonnet-4-20250514)
  • --tests <path> — Path to semantic test suite JSON file (single-cell only)
  • --yes — Auto-accept the Spec Negotiation Gate's proposed refinement without prompting. Use in CI pipelines, regression harnesses, or any non-interactive context where stdin is unavailable.

fractalclaw architect <name>

Power-user multi-cell generation. Designs a multi-cell Fractal Code architecture from a prompt, then orchestrates each cell individually and assembles a parent cell that wires them through Channels.

fractalclaw architect alert-system --prompt "validate, classify, and alert on signals"

Three-phase pipeline:

  1. Manifest — LLM designs the cell graph (cells + channels + routing)
  2. Orchestrate — Each cell generated, validated, and signed independently
  3. Parent — Orchestrating parent cell generated and signed; Swarm Merkle Root computed

Flags:

  • --prompt <text> (required)
  • --model <model> — Model for both manifest and cell generation

fractalclaw pipeline <directory>

Execute a multi-cell architecture end-to-end in the Void Environment. Reads the parent manifest, validates all children, performs a topological sort, and executes cells in dependency order.

fractalclaw pipeline ./fractalclaw/alert-system/
fractalclaw pipeline ./fractalclaw/alert-system/ --input '{"sensor": "temp", "value": 42}'

Output:

═══════════════════════════════════════════════════════
  FractalClaw — Pipeline
═══════════════════════════════════════════════════════

  Directory: ./fractalclaw/alert-system/
  Cells: 3 (topologically sorted)

  ✅ validate-signal               done  (12ms)
  ✅ classify-signal               done  (8ms)
  ✅ emit-alert                    done  (6ms)

  Output: { "alert": "ANOMALY", "severity": "HIGH", "sensor": "temp" }

═══════════════════════════════════════════════════════

Execution rules:

  • Channel-type cells are skipped (routing metadata only)
  • Keeper cells: set called with { state, data }, then get called for output
  • Fan-in merging: multiple upstream outputs merge as { cellName_output: value }
  • Fractal Folding: a master state ledger accumulates all cell outputs; each cell with a declared inputSchema receives exactly its declared keys sliced from the ledger — no implicit field leakage between cells

Flags:

  • --input <json> — JSON input to pass to the first cell (default: null)

fractalclaw scan [directory]

Scan .fc files for constitutional violations. Recursively walks all subdirectories.

fractalclaw scan .                    # Scan current directory (recursive)
fractalclaw scan ./demos/legitimate/  # Scan specific directory
fractalclaw scan . --no-recursive     # Top-level only
fractalclaw scan . --json             # JSON output (CI/CD integration)
fractalclaw scan . --verbose          # Show details for passing files

Output:

  ✅ PASS  weather-lookup        [Transformer]  sig:0xD32C...
  ❌ REJECTED  data-exfiltration
     → Principle III: fetch() detected — undeclared network access
     → Principle III: fs.readFileSync detected — filesystem side channel

Results: 1 passed | 1 rejected | 2 violations found

Exit code 0 if all pass, 1 if any rejected.

Flags:

  • --json — Output results as JSON (for CI/CD pipelines)
  • --verbose — Show all checks for passing files
  • --no-recursive — Disable directory recursion

fractalclaw sign <path>

Compute and verify structural signatures.

fractalclaw sign weather-lookup.transformer.fc       # Verify signature
fractalclaw sign weather-lookup.transformer.fc -w     # Compute and write
fractalclaw sign ./demos/                             # Check all files in directory

Output:

File: weather-lookup.transformer.fc
Computed signature: 0xd32c68e15aef69e3...
Current signature:  0xd32c68e15aef69e3...
Status: ✅ Signature is valid

Flags:

  • -w, --write — Write computed signature into the file(s)

fractalclaw init [name]

Create a new .fc skill template.

fractalclaw init my-skill     # Creates my-skill.transformer.fc
fractalclaw init              # Creates new-skill.transformer.fc

fractalclaw verify <file>

Deep verification of a single .fc file. Runs all 8 checks individually with detailed diagnostics.

fractalclaw verify weather-lookup.transformer.fc

Output:

Verifying: weather-lookup.transformer.fc

  ✅ YAML parsing                    valid structure
  ✅ Cell type                       Transformer (valid)
  ✅ Identity                        name, version, type present
  ✅ Contract                        input and output defined
  ✅ Circuit Breaker                 budget: 100, action: halt
  ✅ Intent Ledger                   all 4 fields present and non-empty
  ✅ Static analysis                 no banned patterns detected
  ✅ Structural Signature            declared matches computed

  Result: PASS — 8/8 checks passed

When checks fail, suggests fixes:

  ❌ Structural Signature            declared does not match computed
     → Declared:  0xDEADBEEFDEADBEEF...
     → Computed:  0xFE42159F563996CE...
     → Fix: run `npx fractalclaw sign -w` to update

fractalclaw run <file.fc>

End-to-end Constitutional Runtime. Validates a .fc file through all constitutional checks and static analysis, then compiles it to WebAssembly and executes it in the Void Environment — a zero-capability sandbox with no network, filesystem, clock, or entropy access.

Requires Javy CLI to be installed.

fractalclaw run greeter.transformer.fc --input '"World"'
fractalclaw run my-skill.transformer.fc --input '{"key": "value"}'
fractalclaw run my-skill.transformer.fc --input '{}' --timeout 10000 --memory 128

Output for a valid cell:

═══════════════════════════════════════════════════════
  FractalClaw — Constitutional Runtime
═══════════════════════════════════════════════════════

  File: greeter.transformer.fc

  ✅ Constitutional validation    8/8 checks passed
  ✅ Static analysis              no banned patterns
  ✅ Structural signature         verified
  ✅ Compiled to Wasm             1233.4kb, cached
  ✅ Executed in void             12ms, budget 100 → 99

  Output: "Hello, World! Welcome to Fractal Code."

═══════════════════════════════════════════════════════

Output for a malicious cell (blocked before compilation):

═══════════════════════════════════════════════════════
  FractalClaw — Constitutional Runtime
═══════════════════════════════════════════════════════

  File: data-exfiltration.transformer.fc

  ✅ Constitutional validation    8/8 checks passed
  ❌ Static analysis              2 violation(s)
     → Principle III: fetch() detected — undeclared network access
     → Principle III: fs.readFileSync detected — filesystem side channel

  ⛔ BLOCKED — skill rejected before compilation
  The void environment was never needed.

═══════════════════════════════════════════════════════

Flags:

  • --input <json> — JSON input to pass to the cell's logic
  • --timeout <ms> — Execution timeout in milliseconds (default: 5000)
  • --memory <mb> — Memory limit in megabytes (default: 64)

Exit code 0 on success, 1 if validation fails or execution errors.

fractalclaw orchestrate <filename.fc>

Power-user single-cell generation. Generate a .fc file from a plain-English prompt via an LLM, then validate and sign it through the constitutional pipeline. Generation is decoupled from execution — use fractalclaw run separately to execute the generated file.

Requires the ANTHROPIC_API_KEY environment variable to be set.

fractalclaw orchestrate reverser.transformer.fc --prompt "reverse the input string"
fractalclaw orchestrate counter.transformer.fc --prompt "count the words in the input"
fractalclaw orchestrate counter.transformer.fc --prompt "count words" --model claude-sonnet-4-20250514
fractalclaw orchestrate reverser.transformer.fc --prompt "reverse the input string" --tests tests.json

Output for a valid generation:

═══════════════════════════════════════════════════════
  FractalClaw — Orchestrator
═══════════════════════════════════════════════════════

  Prompt: "reverse the input string"
  Target: reverser.transformer.fc

  ✅ Generated                     312 tokens (claude-sonnet-4-20250514)
  ✅ Saved                         reverser.transformer.fc
  ✅ Constitutional scan           all checks passed
  ✅ Signed                        0xb28649ba1eb52b9a...
  ✅ Lineage recorded              root: 0x6f515a551afa548d...

  ✅ reverser.transformer.fc is ready.
  Run it: npx fractalclaw run reverser.transformer.fc --input '<json>'

═══════════════════════════════════════════════════════

Output with semantic tests:

═══════════════════════════════════════════════════════
  FractalClaw — Orchestrator
═══════════════════════════════════════════════════════

  Prompt: "reverse the input string"
  Target: reverser.transformer.fc
  Tests:  2 case(s)

  ✅ Generated                     312 tokens (claude-sonnet-4-20250514)
  ✅ Saved                         reverser.transformer.fc
  ✅ Constitutional scan           all checks passed
  ✅ Semantic review               approved
  ✅ Crash test                    4/4 inputs passed
  ❌ Semantic tests                1/2 failed
     → Input: "hello"
       Expected: "olleh"
       Actual:   "HELLO"

  ⛔ Tests failed — exiting with code 1

═══════════════════════════════════════════════════════

Output when the LLM generates malicious code (caught by the constitution):

  ✅ Generated                     285 tokens (claude-sonnet-4-20250514)
  ✅ Saved                         sneaky.transformer.fc
  ❌ Constitutional scan           2 violation(s)
     → Principle III: fetch() detected — undeclared network access
     → Principle III: process.env detected — undeclared external data

  ⛔ REJECTED — generated file failed constitutional validation
  The file has been saved for inspection but should not be executed.

Flags:

  • --prompt <text> (required) — Plain-English instructions for the LLM
  • --model <model> — Anthropic model to use (default: claude-sonnet-4-20250514)
  • --tests <path> — Path to semantic test suite JSON file (see below)

Pipeline: LLM generate → extract .fc from markdown → save → constitutional scan → semantic review → crash test → (repair loop if needed) → sign → record lineage → ready.

Pipeline with --tests: LLM generate → extract → save → scan → semantic review → crash test → (repair loop if needed) → run user tests → exit 1 on failure → sign → record lineage → ready.

Exit code 0 on success, 1 if validation or semantic tests fail after all retries.

Semantic Test Suite

The --tests flag runs user-provided test cases as a final verification gate after code generation is complete. If any test fails, the orchestrator exits immediately with code 1. Unlike the internal quality gates (Semantic Review and Crash Test), user-provided tests do not trigger an auto-repair loop — they are the acceptance criterion, not a debugging aid.

Test file format — a JSON array of { input, expected } pairs:

[
  { "input": "hello", "expected": "olleh" },
  { "input": "world", "expected": "dlrow" },
  { "input": "",      "expected": "" }
]

Input and expected values can be any JSON type — strings, numbers, objects, arrays. Comparison uses subset matching — only fields present in expected are checked against actual, so the generated code can include additional fields without failing the test.

Cryptographic binding: When tests are provided, the SHA-256 hash of the test suite JSON is injected into the .fc file's contract as test_suite_hash and included in the structural signature computation. This cryptographically locks the generated code to the exact test suite that validated it — any change to the tests invalidates the signature.

fractalclaw verify-lineage <file.fc>

Verify a .fc file's provenance by looking up its structural signature in the Merkle-backed lineage ledger and validating the inclusion proof against the stored root.

fractalclaw verify-lineage reverser.transformer.fc

Output:

Verifying lineage: reverser.transformer.fc

  Signature:  0xB28649BA1EB52B9A...
  Timestamp:  2026-02-24T13:51:26.123Z
  Model:      claude-sonnet-4-20250514
  Prompt:     0x9f3a2c1e... (SHA-256 of original prompt)
  Retries:    0
  Test hash:  0xA3F1C9E8B7D24560...

  ✅ Merkle proof verified
     Root:   0x6F515A551AFA548D...
     Depth:  3
     Index:  5 of 6 event(s)

  Result: PASS

When no lineage record exists:

  ❌ No lineage record found for this file's signature
  This file may not have been created via the orchestrator,
  or the lineage ledger may have been cleared.

Exit code 0 on pass, 1 on fail or missing record.

Lineage Ledger — Merkle-Backed Provenance

Every successful orchestration is recorded in an append-only ledger at .fractal/lineage.json. The ledger is backed by a SHA-256 Merkle tree with domain separation (0x00 for leaves, 0x01 for internal nodes), enabling cryptographic provenance verification via inclusion proofs.

Each lineage event records:

| Field | Description | |-------|-------------| | timestamp | ISO-8601 creation time | | promptHash | SHA-256 of the plain-English prompt given to the LLM | | test_suite_hash | SHA-256 of the test suite JSON (empty string if no tests) | | cell_signature | The file's structural signature | | parent_root | Merkle root before this event was appended | | model | LLM model used for generation | | retries | Number of self-healing repair attempts (0 = first try) |

How it works:

  1. After the orchestrator signs a .fc file, it appends a lineage event to the ledger
  2. The ledger recomputes the Merkle root over all event hashes
  3. Each event's parent_root creates a hash chain — any insertion, deletion, or reordering is detectable
  4. verify-lineage looks up a file's signature, retrieves its event, generates a Merkle inclusion proof, and verifies it against the stored root

Lineage recording is non-fatal — if it fails (e.g., read-only filesystem), orchestration still succeeds with a warning.

Generation Safety Gates

FractalClaw's generation pipeline enforces eight deterministic gates between the LLM and the runtime. Each gate can trigger retries; exhausted retries produce quarantine or a hard error with an explicit code.

All code generation prompts also include an explicit Void Sandbox Contract listing every banned API by name — Date.now(), new Date(), Math.random(), setTimeout, fetch(), process.env, eval(), etc. — so the LLM never attempts to use them. If time or entropy is genuinely needed, the prompt instructs the LLM to declare it as an inputSchema field and receive it from the caller instead.

Gate 1 — Spec Negotiation (SNG)

Fires before any code is generated. The LLM evaluates the prompt for ambiguity: under-specified output shape, free-form string outputs that can't be smoke-tested, missing quantitative thresholds.

If the spec is ambiguous, the orchestrator pauses:

⚠  Ambiguous specification detected

  Proposed clarification:
  "Calculate monthly loan payment given principalAmount (number), annualInterestRate
  (number, e.g. 0.07), and termInYears (number). Return { monthlyPayment: number }."

  Fields that needed clarification: output format, interest rate unit, term unit

  Accept this spec? (y/n):

Accepting rewrites the prompt and proceeds. Declining aborts. In API mode (serve), returns HTTP 400 with { error: "AMBIGUOUS_SPEC", proposedPrompt, fields }. Pass --yes to auto-accept in non-interactive contexts (CI, regression harnesses) — the enriched proposedPrompt is still used; only the stdin prompt is skipped.

Gate 2 — Schema Alignment

Fires after each cell is generated in a multi-cell pipeline. Computes the allowed field set — pipeline root inputs (always present in the State Ledger) plus all upstream cell output fields — and validates the generated cell's inputSchema keys against it. If a cell declares a field that isn't in either source — a common LLM hallucination — the cell is deleted and re-generated with an explicit constraint listing only the available fields.

This mirrors the runtime State Ledger exactly: masterLedger = { ...pipelineInput, ...cell1Output, ...cell2Output, ... }. A downstream cell can declare any field that was in the original pipeline input OR any upstream output — without upstream cells needing to redundantly pass those values through.

Flat Schema Contract: Because the Ledger uses shallow spread, all inter-cell output contracts must be flat top-level key-value pairs. Nested return objects (e.g., return { data: { id, name } }) are architecturally invalid — they make nested fields opaque to this gate and cause downstream cells to hallucinate access paths. A brace-depth–tracking extractor correctly identifies only top-level field names from the generated return statement. A build-time Flat Output Structure Guard detects nested return objects post-generation and forces a repair cycle before the cell is sealed.

Single-Responsibility Mandate: Each cell's code-generation prompt explicitly names which tasks belong to the other cells in the pipeline, preventing the LLM from "helpfully" computing downstream values in an upstream cell.

Manifest Completeness Check: After initial manifest generation, a keyword-based check detects concerns mentioned in the prompt (routing, notification, output/reporting) that have no corresponding cell. If a concern is missing, the manifest is repaired. The "output/reporting" concern only triggers on explicit reporting keywords (report, summary, respond, response) — not generic computation terms like "output" or "result" (e.g., "output net pay"), which would otherwise force a spurious emit/format cell into every computation pipeline.

Up to 2 retries. If alignment still fails: ERR_SCHEMA_MISMATCH.

⚠️  Schema mismatch on "calculate-payment" — mismatched: principalAmount, annualInterestRate (retry 1/2)

Gate 3 — Null Guard

Fires after code generation, before quality gates. Parses the generated cell's inputSchema for fields typed object|null or array|null, then inspects the logic body for guard patterns (if (!input.field), ?? ..., optional chaining). Missing guards cause a Tier 2 repair with an explicit null-guard instruction.

Up to 2 retries. Guards that are still missing after retries result in quarantine.

Gate 4 — QuickJS Compatibility

Fires after code generation, before quality gates. Scans the generated logic body for ES2021+ APIs that work in Node.js V8 but are absent in the QuickJS runtime used by Javy inside the Wasm sandbox. Without this gate, code can pass all build-time checks and silently crash at pipeline runtime with ReferenceError or TypeError.

APIs detected and their required substitutes:

| Incompatible (V8 only) | QuickJS-safe substitute | |---|---| | arr.at(-1) | arr[arr.length - 1] | | str.replaceAll(x, y) | str.replace(/x/g, y) | | Object.hasOwn(obj, k) | Object.prototype.hasOwnProperty.call(obj, k) | | structuredClone(v) | JSON.parse(JSON.stringify(v)) | | arr.findLast(fn) | [...arr].reverse().find(fn) | | arr.findLastIndex(fn) | [...arr].reverse().findIndex(fn) | | 1_000_000 (numeric separators) | 1000000 |

Up to 2 retries with an explicit mandate listing each violation and its safe substitute. Warnings and proceeds if retries are exhausted (smoke tests will surface any remaining crash).

  ⚠️  QuickJS gate: incompatible APIs [.replaceAll(), .at()] — retry 1/2
  ✅ QuickJS gate              ES2020-compatible code confirmed

Gate 5 — Enum Mandate (Output Type Rules)

A cross-cutting prompt-level instruction applied to all code generation and QA prompts. Guides the LLM to prefer categorical, testable output types over floating-point metrics:

  • string[] of SCREAMING_SNAKE_CASE constants for flag/issue lists (e.g., ["SENTENCE_LENGTH_ANOMALY"])
  • Short enum strings for categories (e.g., riskLevel: "HIGH_RISK" | "MEDIUM_RISK" | "LOW_RISK")
  • boolean for binary verdicts (e.g., isConsistent: true)
  • number only for exact counts, monetary amounts, or numerically-specified values

Float outputs that represent computed metrics (deviation scores, similarity ratios, complexity indices) are the primary cause of QA-code divergence — the QA LLM cannot predict them accurately and will quarantine correct code. The Enum Mandate prevents this design problem at the prompt level rather than patching it at test time.

Gate 6 — Semantic Review

Fires after code generation. A second LLM call plays the role of a senior software engineer reviewing the generated code against the original spec. It receives the full prompt and the generated .fc file and returns { approved: boolean, issues: string[] }.

If it rejects the code, the issues list (e.g., "Wrong discount rate: uses 0.15, spec says 0.10") is fed into the repair loop as the repair directive. If it approves, the crash test gate runs next.

Fails-open: if the review call fails or returns malformed JSON, the gate is skipped and generation continues.

  ✅ Semantic review   approved

or

  ❌ Semantic review   1 issue(s) — feeding into repair loop
     → Wrong discount rate: uses 0.15, spec says 0.10

Gate 7 — Crash Test

Fires after semantic review passes (skipped when semantic review already rejected — a repair is already pending). A crash input generator produces diverse input objects covering normal, boundary, and adversarial cases. Each input is executed against the generated logic in vm.runInNewContext. The gate asserts:

  1. No exception thrown — the code must not crash on any generated input
  2. Correct return type — if the cell's outputSchema declares named keys, the return value must be a non-null object (not a primitive or array)
  3. All declared fields present — every key named in outputSchema must appear in the returned object

No value assertions are made — correctness is the semantic review's responsibility; the crash test only verifies structural soundness and runtime stability.

If any input throws, the failing input and error message are fed into the repair loop as { type: "crash", input, error }.

Fails-open: if crash input generation fails or returns a non-array, the gate is skipped.

  ✅ Crash test   4/4 inputs passed

or

  ❌ Crash test   crash on input {"amount": null} — TypeError: Cannot read property 'toFixed' of null

Repair loop: When either Gate 6 or Gate 7 rejects the code, the orchestrator enters a repair loop (up to 3 retries). Each attempt rebuilds the cell via the LLM with the rejection reason as context, then re-runs both gates. If retries are exhausted, the cell is stamped quarantined: true.


Attack Vectors Caught

Direct Attacks

| Attack | How It Works | Caught By | Principle | |--------|-------------|-----------|-----------| | Data Exfiltration | fs.readFileSync + fetch() to external URL | Static scanner | III — Channel Isolation | | Prompt Injection | this.identity = {...} runtime mutation | Static scanner | II — Universal Contract | | Privilege Escalation | process.env + globalThis credential theft | Static scanner | III — Channel Isolation | | Supply Chain | Clean logic but forged signature | Signature verification | X — Structural Signature | | Stealth Network | WebSocket + XMLHttpRequest covert channels | Static scanner | III — Channel Isolation | | Budget Bomb | complexity_budget: 999999999999 | Budget sanity check | Circuit Breaker |

Obfuscation Bypasses

Attackers can try to hide banned keywords behind encoding tricks. The scanner detects these too:

| Attack | How It Works | Caught By | Principle | |--------|-------------|-----------|-----------| | Base64 Decode | atob('ZmV0Y2g=') hides fetch | Static scanner | III — Channel Isolation | | Base64 Encode | btoa(secrets) encodes data for exfiltration | Static scanner | III — Channel Isolation | | Buffer Base64 | Buffer.from(encoded, 'base64') Node-specific decode | Static scanner | III — Channel Isolation | | Function Template | Function(`return ...`) code injection via template literal | Static scanner | III — Channel Isolation | | Dynamic Require | require(variable) loads arbitrary modules | Static scanner | III — Channel Isolation | | Dynamic Import | import('./secret-module') loads modules at runtime | Static scanner | III — Channel Isolation | | Hex Escape | \x66\x65\x74\x63\x68 spells fetch char by char | Static scanner | III — Channel Isolation | | Unicode Escape | \u0066\u0065\u0074\u0063\u0068 spells fetch char by char | Static scanner | III — Channel Isolation |

Primitive Gateway — Intent-Yield Object Capability

The Void Environment gives cells zero host capabilities. But real programs need side effects. The Primitive Gateway solves this without breaking isolation: cells yield intents instead of executing side effects directly.

How It Works

  1. The cell's logic calls __yield("Log_Entry", "hello") — this writes a yield envelope to stdout and terminates
  2. The host parses the envelope, checks the capability manifest to authorize the primitive
  3. The host executes the primitive (e.g., appends "hello" to an in-memory log)
  4. The host re-invokes the cell with the original input, injecting the primitive's result
  5. The cell calls __getPrimitiveResult("Log_Entry") — finds the injected result — and completes normally

Inside the Cell

The Javy wrapper injects three helpers into every cell's scope:

| Helper | Purpose | |--------|---------| | __yield(primitive, payload) | Emit an intent to the host and terminate | | __getPrimitiveResult(primitive) | Read the result of a prior yield pass | | __primitiveResults | Array of all injected { primitive, result } pairs |

Example .fc Logic

logic:
  lang: "typescript"
  process: |
    const logResult = __getPrimitiveResult("Log_Entry");
    if (logResult === undefined) {
      __yield("Log_Entry", "Cell says: " + input);
      return null;
    }
    return "Logged successfully: " + input;

Pass 1: no prior result → yields Log_Entry → terminates. Pass 2: host injects result → cell reads it → returns final output.

Security Properties

  • No direct access: The cell cannot call console.log, fetch, or any host API. It can only yield an intent.
  • Capability-gated: The host checks a capability manifest before executing any primitive. Unauthorized primitives throw CapabilityDeniedError.
  • Multi-pass ceiling: Maximum 10 yield passes per execution to prevent infinite loops.
  • Auditable: Every primitive invocation is explicit in the cell's logic — no hidden side effects.

Level 0 Primitives

| Primitive | Host Behavior | Level | |-----------|--------------|-------| | Log_Entry | Appends a string to an in-memory array | 0 |

The capability manifest is currently hardcoded (all cells get Log_Entry). It will eventually be parsed from the .fc file's contract section so the human signature governs authorization.

The Key Insight

The security model operates at two stages:

Generation-time gates (catch problems before code reaches the runtime):

  • Spec Negotiation Gate catches ambiguous, untestable specs before any code is generated
  • Schema Alignment Gate catches inter-cell contract mismatches after generation, before integration
  • Flat Schema Contract enforces flat top-level output contracts; build-time guard detects and repairs nested return objects before they poison the upstream schema reported to downstream cells
  • Single-Responsibility Mandate explicitly tells each cell's code-gen agent which tasks belong to other cells, preventing upstream cells from computing downstream values
  • Manifest Completeness Check detects and repairs missing concerns; "output/reporting" only triggers on explicit reporting keywords, preventing spurious emit/format cells in computation pipelines
  • Null Guard Gate catches missing defensive guards before runtime
  • QuickJS Compatibility Gate catches ES2021+ APIs (.at(), .replaceAll(), Object.hasOwn(), structuredClone(), findLast(), numeric separators) that work in V8 but crash in the QuickJS Wasm runtime
  • Enum Mandate redirects LLM designs away from unpredictable float metrics toward testable categoricals
  • Semantic Review Gate has a second LLM pass review the generated code against the spec and reject with a structured issues list; mismatches trigger the repair loop
  • Crash Test Gate executes the generated code with diverse inputs in vm.runInNewContext and verifies no throw + correct output structure; failures trigger the repair loop

Runtime enforcement (catch problems at execution):

  • Signatures catch contract-level tampering (supply-chain attacks)
  • Static analysis catches implementation-level attacks (exfiltration, injection)
  • Void Environment enforces runtime isolation — compiled Wasm has zero host capabilities
  • Primitive Gateway mediates all side effects through authorized, auditable intents

Problems are caught at the earliest possible stage. A vague prompt never reaches code generation. A float-heavy output design gets redirected to categoricals. A hallucinated field name never reaches the runtime. A missing null guard never reaches runtime. After generation, a second LLM pass reviews the code against the spec and rejects anything that misimplements it — triggering a repair loop with structured feedback. Crash testing confirms the code is structurally sound before it is sealed. A cell with fetch() in its logic body is blocked at static analysis and never reaches the Wasm compiler. Even if a pattern somehow passed static analysis, the Void Environment denies all host access — no network, no filesystem, no real clock, no entropy.

Running the Tests

# fractalclaw (generation pipeline, gates, QA system)
cd fractalclaw
npm install && npm test

# runtime (Void Environment, Wasm executor, Primitive Gateway)
cd runtime
npm install && npm test

fractalclaw: 540 tests across 19 test files: regression tests for all 11 original patterns, tests for all 8 obfuscation patterns, false-positive checks for clean code, orchestrator tests (extractor, system prompt validation, subset matching, repair prompts, semantic review gate, crash test gate, repair loop integration, end-to-end with mock LLM, schema alignment helpers, null guard gate helpers, QuickJS compatibility gate helpers, system prompt mandate checks, extractLogicBody, semanticReview, generateCrashInputs, runCrashTest, Enum Mandate prompt content, Flat Output Contract mandate, extractReturnFields nested object handling), Merkle tree / lineage ledger tests (domain separation, tree construction, inclusion proofs, tampered proof detection, append-only ledger operations, signature lookup, proof generation and verification), build command routing tests, architect pipeline tests (Schema Alignment Gate integration, ERR_SCHEMA_MISMATCH), and pipeline executor tests.

runtime: 77 tests across 8 test files: unit tests for executeCell/compileCell guards and parseEnvelope branches, Primitive Gateway authorizer and registry (isAuthorized, getCapabilities, listPrimitives, Log_Entry handler), transpiler, Wasm wrapper, void environment, and integration tests (compile → execute → cache → Primitive Gateway round-trips).

Running the Demo

cd fractalclaw
npm install && npm run build && npm run demo

Project Structure

fractalclaw/
├── src/
│   ├── cli.ts                    # CLI entry point (commander)
│   ├── commands/
│   │   ├── build.ts              # build command — unified entry, auto-routes single vs multi-cell
│   │   ├── architect.ts          # architect command — multi-cell system generation
│   │   ├── pipeline.ts           # pipeline command — execute multi-cell architectures
│   │   ├── scan.ts               # scan command — batch constitutional scanning
│   │   ├── sign.ts               # sign command — signature management
│   │   ├── init.ts               # init command — template creation
│   │   ├── verify.ts             # verify command — deep single-file checks
│   │   ├── run.ts                # run command — validate, compile, execute in void
│   │   ├── orchestrate.ts        # orchestrate command — LLM generate, validate, sign
│   │   ├── serve.ts              # serve command — local HTTP API
│   │   └── verify-lineage.ts     # verify-lineage command — Merkle proof verification
│   ├── orchestrator.ts           # LLM adapters (Groq primary, Anthropic + Gemini failover), system prompts, .fc extractor, schema alignment + null guard helpers, extractLogicBody, semanticReview, generateCrashInputs, runCrashTest
│   ├── merkle-tree.ts            # SHA-256 Merkle tree with domain separation
│   ├── lineage-ledger.ts         # Append-only lineage ledger (.fractal/lineage.json)
│   ├── signer.ts                 # Structural signature computation
│   ├── skill-loader.ts           # Constitutional skill loading pipeline
│   ├── skill-scanner.ts          # Static analysis of logic bodies (19 patterns)
│   ├── skill-executor.ts         # Circuit breaker runtime enforcement demo
│   ├── demo.ts                   # Demo entry point
│   └── __tests__/
│       ├── scanner.test.ts             # 27 tests (regression + obfuscation + clean code)
│       ├── orchestrator.test.ts        # 48 tests (extractor + subset match + repair + semantic tests + e2e)
│       ├── merkle-lineage.test.ts      # 46 tests (Merkle tree + lineage ledger)
│       ├── build.test.ts               # build command routing and single/multi-cell dispatch
│       ├── architect.test.ts           # architect pipeline (manifest → orchestrate → parent)
│       ├── pipeline.test.ts            # pipeline executor (topological sort + keeper execution)
│       └── ...                         # additional integration and unit tests
├── demos/
│   ├── legitimate/               # 3 clean skills that pass all checks
│   ├── malicious/                # 6 attack skills, each caught by a different principle
│   └── obfuscated/               # 8 obfuscation bypass attempts, all caught
├── types/                        # JSON Schema definitions for skill contracts
├── spec/
│   └── skill-manifest.md         # How OpenClaw skills map to Fractal Cells
├── fractal.json
├── package.json
└── tsconfig.json

Related