Autopoietic Code Rewriting — Documentation

A complete reference for the Autopoietic Code Rewriting project: architecture, invariants, transformations, sandbox, deployer, tests, and current status.

Phase I complete. 118/118 tests passing at v0.2.0-implementation. No pilot has been executed. State restoration fidelity is deferred to Phase III.

Overview

Autopoietic Code Rewriting investigates the conditions under which a software system can modify its own source-code representation during runtime while preserving structural integrity, execution continuity, and behavioral consistency.

The initial scope is deliberately restricted to individual top-level Python functions, using LibCST for AST transformation and multiprocessing for logical execution isolation.

ProjectAutopoietic Code Rewriting Version0.2.0-implementation PhasePhase I — Verification Complete ScopeFunction-Level, Stateless, Python 3.11+ Tests118/118 passing LicenseMIT (code) · CC-BY-4.0 (docs)
"The ability to generate a modified program is separated from the ability to establish its admissibility."

Architecture

Six-Stage Pipeline

┌─────────────────────────────────────────────────────────┐
│  1. Extract      →  Load P₀, preserve source hash      │
│  2. Analyze      →  Build dependency graph, symbol table│
│  3. Transform    →  Produce candidate P₁ = T(P₀, θ)    │
│  4. Sandbox      →  Execute P₁ in isolated process      │
│  5. Verify       →  I_s ∧ I_t ∧ I_b + differential test │
│  6. Deploy       →  Atomic swap or rollback             │
└─────────────────────────────────────────────────────────┘

Four Operational Dimensions

DimensionQuestionEvaluation
IsolationCan candidate execution be separated from the parent?multiprocessing tests
VerificationDoes P₁ satisfy defined acceptance conditions?I_s ∧ I_t ∧ I_b
Transition IntegrityCan activation occur without partial deployment?atomic swap
RecoverabilityCan the previous state be restored?rollback + SRF (deferred)
No dimension guarantees another. Successful rollback does not imply complete state restoration. Structural validity does not imply behavioral equivalence. Each dimension is measured independently.

Invariants (S/T/B)

Layer I_s — Syntactic (S1–S6)

CodeConditionCheck
S1P₁ parses as valid Modulecst.parse_module
S2Exactly one top-level FunctionDefnode count
S3Function name unchangedname compare
S4Signature unchangedparams compare
S5No new decoratorsdecorator set
S6No new imports inside functionImport scan

Layer I_t — Structural (T1–T5)

CodeConditionCheck
T1Every used Name has a bindingscope analysis
T2No invalid dependency cyclesDFS cycle detection
T3No orphan variablesliveness diff
T4No new global statementsAST scan
T5Local call targets resolvesymbol table

Layer I_b — Behavioral (B1–B4)

CodeConditionCheck
B1Return values match over corpusdifferential test
B2Exceptions match over corpusdifferential test
B3stdout traces match over corpusdifferential test
B4No new side effectsruntime enforcement
B4 scope. Monkeypatching blocks a specific allowlist of side-effect entry points (open, os.system, subprocess.*, socket.socket, urllib.request.urlopen). It detects accidental side effects introduced by transformations. It is not a security sandbox against hostile code.

Decision Policy

Accept(P₁)     ⟺  I_s(P₁) ∧ I_t(P₁) ∧ I_b(P₁)
Reject(P₁)     ⟺  ¬I_s ∨ ¬I_t ∨ ¬I_b
Inconclusive   ≠  Accepted   # default to rejection when in doubt

Transformations

TransformationExampleInvariant Tested
Constant Folding2 + 3 → 5Syntactic + Behavioral
Algebraic Simplificationx * 1 → xStructural + Behavioral
Dead Branch Eliminationif False: ... → removedStructural
Local Variable Renamingy → z (scope-aware)Structural
Excluded in Phase I. Function signature changes · imports · closures · decorators · cross-function dependencies · arbitrary external state.

Sandbox

Isolation Model

sandbox/isolated_runner.py uses multiprocessing.Process for logical isolation. On Linux and Termux, the default start method is fork (fast, shared memory).

API

run_isolated(
    source: str,
    function_name: str,
    args: tuple = (),
    kwargs: dict | None = None,
    timeout_sec: float = 1.0,
    enforce_no_side_effects: bool = False,
) -> ExecutionResult

Differential Testing

sandbox/differential.py compares P₀ and P₁ over a corpus, observing return values (NaN-aware), exceptions, stdout, and timeouts.

differential_test(
    p0_source: str,
    p1_source: str,
    function_name: str,
    corpus: list[Input],
    timeout_sec: float = 1.0,
) -> DifferentialResult
Isolation is not a security sandbox. multiprocessing provides logical separation, not adversarial protection. Hostile code is out of scope.

Deployer

core/deployer.py manages atomic swap between P₀ and candidates, with explicit rollback and history.

API

deployer = Deployer(initial_source=P₀, function_name="f")

# Attempt atomic swap
result = deployer.try_deploy(
    candidate_source=P₁,
    accept_condition=lambda: check_behavioral(...).passed,
)
# result.activated = True (swapped) or False (rejected)

# Rollback to previous active source
deployer.rollback()

# Reset to original P₀
deployer.reset()
P₀ is immutable. The original source is always retained. history is an immutable tuple of all deployed sources.

API Reference

core/extractor.py

  • ExtractedFunction — immutable extraction result
  • extract_from_source(source, function_name)
  • extract_from_file(path, function_name)
  • replace_function(module, name, new_func)

core/transformer.py

  • ConstantFolding, AlgebraicSimplification, DeadBranchElimination, LocalVariableRenaming
  • TransformationResult, TransformationError

invariants/

  • syntactic.check_syntactic(p0_module, p1_module)
  • structural.check_structural(p0_func, p1_func)
  • behavioral.check_behavioral(p0_source, p1_source, function_name, corpus)

sandbox/

  • isolated_runner.run_isolated(...)
  • differential.differential_test(...)
  • Input, Mismatch, DifferentialResult

core/deployer.py

  • Deployer, DeploymentResult

Tests

ModuleLayerTestsStatus
core/extractor.pyCore — Extraction3PASS
core/transformer.pyCore — Transformation4PASS
core/deployer.pyCore — Deployment19PASS
invariants/syntactic.pyI_s (S1–S6)22PASS
invariants/structural.pyI_t (T1–T5)23PASS
invariants/behavioral.pyI_b (B1–B4)18PASS
sandbox/isolated_runner.pySandbox — Isolation17PASS
sandbox/differential.pySandbox — Differential12PASS
Total118PASS

Running Tests

# All tests
make test

# Specific module
python -m pytest tests/test_behavioral.py -v

# Lint (flake8 + mypy)
make lint

Limits & Threats

What Phase I Supports

  • Transformation of individual top-level Python functions.
  • Three-layer verification (syntactic, structural, behavioral).
  • Logical isolation via multiprocessing.
  • Atomic swap + rollback for stateless functions.

What Phase I Does Not Support

  • Causal effects of rewriting on system behavior (needs pilot).
  • Module-level or system-level rewriting.
  • Stateful recovery — SRF is deferred to Phase III.
  • Adversarial security — multiprocessing is not a hardened sandbox.
  • Cross-language generalization.

Threats to Validity

TypeConcernMitigation
ConstructObservation model determines what differential testing detectsExplicit corpus
InternalResults may reflect implementation detailsFixed environment
ExternalPython-only results may not generalizeScope restricted
StatisticalPilot not yet runFeasibility only
Securitymultiprocessing is not hardenedDocumented

Repository Structure

Autopoietic/
├── README.md
├── CHANGELOG.md
├── VERSION
├── LICENSE
├── CITATION.cff
├── pyproject.toml
├── requirements.txt
├── Makefile
│
├── core/
│   ├── extractor.py              # P₀ → ExtractedFunction
│   ├── transformer.py            # 4 transformations
│   └── deployer.py               # atomic swap + rollback
│
├── invariants/
│   ├── syntactic.py              # I_s: S1–S6
│   ├── structural.py             # I_t: T1–T5
│   └── behavioral.py             # I_b: B1–B4
│
├── sandbox/
│   ├── isolated_runner.py        # multiprocessing
│   └── differential.py           # P₀ vs P₁
│
├── tests/
│   ├── test_extractor.py         # 3
│   ├── test_transformer.py       # 4
│   ├── test_deployer.py          # 19
│   ├── test_syntactic.py         # 22
│   ├── test_structural.py        # 23
│   ├── test_behavioral.py        # 18
│   ├── test_isolated_runner.py   # 17
│   └── test_differential.py      # 12
│
├── DOCS/
│   ├── invariants_spec.md
│   └── experiment_protocol.md
│
└── PUBLICATION/
    └── Netlify/public/           # This site
        ├── index.html
        ├── dashboard.html
        ├── results.html
        ├── documentation.html
        └── assets/style.css

Author & Citation

Citation (BibTeX)

@misc{autopoietic2026,
  author = {Baladi, Samir},
  title  = {Autopoietic Code Rewriting inside Isolated Execution
            Environments: Stability Conditions, Structural Invariants,
            and Controlled Runtime Transformation},
  year   = {2026},
  version = {0.2.0-implementation},
  note   = {Phase I complete, no pilot executed},
  url    = {https://gitlab.com/gitdeeper15/autopoietic}
}

Status

ComponentStatus
Formal modelDefined
ArchitectureSpecified
Core (extractor + transformer + deployer)Complete
Invariants (S1–S6, T1–T5, B1–B4)Complete
Sandbox (isolation + differential)Complete
Tests118/118 passing
Pilot studyNot started
Module-level rewritingConditional
Stateful support (SRF)Deferred
Phase I complete. No pilot executed. The implementation is verified, but empirical validation of the four hypotheses (H1–H4) requires the pilot study (0.3.0-pilot), which has not been conducted. All claims about the architecture are structural, not empirical.