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
| Dimension | Question | Evaluation |
| Isolation | Can candidate execution be separated from the parent? | multiprocessing tests |
| Verification | Does P₁ satisfy defined acceptance conditions? | I_s ∧ I_t ∧ I_b |
| Transition Integrity | Can activation occur without partial deployment? | atomic swap |
| Recoverability | Can 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)
| Code | Condition | Check |
| S1 | P₁ parses as valid Module | cst.parse_module |
| S2 | Exactly one top-level FunctionDef | node count |
| S3 | Function name unchanged | name compare |
| S4 | Signature unchanged | params compare |
| S5 | No new decorators | decorator set |
| S6 | No new imports inside function | Import scan |
Layer I_t — Structural (T1–T5)
| Code | Condition | Check |
| T1 | Every used Name has a binding | scope analysis |
| T2 | No invalid dependency cycles | DFS cycle detection |
| T3 | No orphan variables | liveness diff |
| T4 | No new global statements | AST scan |
| T5 | Local call targets resolve | symbol table |
Layer I_b — Behavioral (B1–B4)
| Code | Condition | Check |
| B1 | Return values match over corpus | differential test |
| B2 | Exceptions match over corpus | differential test |
| B3 | stdout traces match over corpus | differential test |
| B4 | No new side effects | runtime 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
| Transformation | Example | Invariant Tested |
| Constant Folding | 2 + 3 → 5 | Syntactic + Behavioral |
| Algebraic Simplification | x * 1 → x | Structural + Behavioral |
| Dead Branch Elimination | if False: ... → removed | Structural |
| Local Variable Renaming | y → 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
| Module | Layer | Tests | Status |
| core/extractor.py | Core — Extraction | 3 | PASS |
| core/transformer.py | Core — Transformation | 4 | PASS |
| core/deployer.py | Core — Deployment | 19 | PASS |
| invariants/syntactic.py | I_s (S1–S6) | 22 | PASS |
| invariants/structural.py | I_t (T1–T5) | 23 | PASS |
| invariants/behavioral.py | I_b (B1–B4) | 18 | PASS |
| sandbox/isolated_runner.py | Sandbox — Isolation | 17 | PASS |
| sandbox/differential.py | Sandbox — Differential | 12 | PASS |
| Total | | 118 | PASS |
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
| Type | Concern | Mitigation |
| Construct | Observation model determines what differential testing detects | Explicit corpus |
| Internal | Results may reflect implementation details | Fixed environment |
| External | Python-only results may not generalize | Scope restricted |
| Statistical | Pilot not yet run | Feasibility only |
| Security | multiprocessing is not hardened | Documented |
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
| Component | Status |
| Formal model | Defined |
| Architecture | Specified |
| Core (extractor + transformer + deployer) | Complete |
| Invariants (S1–S6, T1–T5, B1–B4) | Complete |
| Sandbox (isolation + differential) | Complete |
| Tests | 118/118 passing |
| Pilot study | Not started |
| Module-level rewriting | Conditional |
| 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.