This document describes the current architecture of version 0.2.2 of the project.
It reflects the code as implemented today, including:
- managed Neo4j bootstrap;
- SQLite support;
- SCC-E (State Compression Code — Embedding) compact state representation;
- rewarded transitions;
- FastMCP-exposed tools.
The project is an MCP server for tracking codebase evolution as a numbered state machine.
A state captures:
- the prompt that motivated a change;
- branch and diff information;
- file-hash snapshots or deltas;
- compact SCC-E (State Compression Code — Embedding) context for LLM consumption.
A transition captures:
- the source state;
- the target state;
- an optional prompt;
- timestamp;
- optional reward.
At runtime, the project supports three storage modes:
- managed Neo4j (default);
- external Neo4j;
- SQLite.
MCP client
↓
FastMCP tool function (`*_tool`)
↓
Tool wrapper in `src/mcp_server/tools/mcp_tools.py`
↓
Service layer (`StateService`, `GitManager`, bootstrap services)
↓
Repository layer (SQLite or Neo4j)
↓
Persistence backend
The server entrypoint is:
- canonical:
run_mcp_server.py - alternative:
python -m src.mcp_server - compatibility alias:
init_neo4j_and_mcp.py
Canonical launcher. Imports src.mcp_server.__main__.main and runs it.
Process-level bootstrap:
- loads settings;
- configures logging, audit, and rate limiting;
- resolves managed Neo4j when applicable;
- builds repositories;
- initializes
StateService; - imports the FastMCP app and runs it.
Module that builds the FastMCP app and registers all exposed tools.
Implemented in src/mcp_server/config.py.
| Setting | Meaning |
|---|---|
db_mode |
neo4j or sqlite |
neo4j_bootstrap_mode |
auto or external |
neo4j_auth_enabled |
Whether Neo4j auth is used |
neo4j_auto_image |
Docker image for managed Neo4j |
neo4j_auto_home |
Persistent directory for managed Neo4j |
sqlite_path |
SQLite database file |
volume_path |
Workspace snapshot path |
rate_limit_enabled |
Enables/disables rate limiting |
audit_enabled |
Enables/disables audit logging |
Behavior today:
- if
DB_MODEis omitted, the server defaults toneo4jwhen Neo4j is enabled; - if explicit Neo4j connection variables are present, bootstrap mode resolves to
external; - otherwise the server defaults to managed Neo4j bootstrap mode (
auto).
Implemented in:
src/mcp_server/services/neo4j_service_manager.pysrc/mcp_server/services/neo4j_bootstrap.py
For managed Neo4j mode, the project creates or reuses a project-scoped Docker container.
Persistent files live in:
./.data/neo4j/
├── data/
├── logs/
└── runtime.json
runtime.json stores the resolved runtime state, including:
- container name;
- selected host ports;
- directories;
- image;
- auth mode.
Managed Neo4j runs without auth from the application perspective:
- repository creation uses
auth=None; - MCP client configuration does not need Neo4j credentials;
prepare_neo4j_connection()resolves the final runtime URI before repositories are created.
When neo4j_bootstrap_mode=external, startup skips container management and uses the provided connection settings directly.
Primary file:
src/mcp_server/tools/mcp_tools.py
Responsibilities:
- validate tool-level parameters;
- apply rate limiting;
- call service methods;
- serialize state payloads (
raw,compact,both); - emit audit events where appropriate.
Primary files:
src/mcp_server/services/state_service.pysrc/mcp_server/services/git_manager.pysrc/mcp_server/services/scc_codec.pysrc/mcp_server/services/branch_detection_service.pysrc/mcp_server/services/neo4j_bootstrap.pysrc/mcp_server/services/neo4j_service_manager.py
Main business orchestrator.
Key responsibilities:
- create genesis state;
- create new state transitions;
- create arbitrary transitions;
- generate and enrich SCC-E compact context;
- expose state and transition queries;
- rebuild and repair the managed volume snapshot;
- update rewards on historical transitions.
Responsibilities:
- clone/sync project snapshots into the managed volume;
- compute directory hashes;
- compute diff and hash deltas;
- initialize repositories in managed snapshots.
Responsibilities:
- manage path vocabulary metadata;
- generate compact SCC-E payloads;
- build preview payloads for current workspace context.
Primary files:
src/mcp_server/repositories/sqlite_repository.pysrc/mcp_server/repositories/neo4j_repository.pysrc/mcp_server/repositories/abstract_repositories.pysrc/mcp_server/repositories/evm/(PoC —EVMStateRepository,EVMTransitionRepository,EVMContractClient, canonical encoder, IPFS client)
Responsibilities:
- persist and load
Stateobjects; - persist and load
Transitionobjects; - maintain metadata such as current state pointer and SCC-E vocabulary metadata.
Defined in src/mcp_server/models/state_model.py.
This is a regular Python class, not a dataclass.
Fields:
state_number: intuser_prompt: strbranch_name: strgit_diff_info: strhash: strcreated_at: datetime | Nonefile_hashes: dict[str, str] | Nonefile_hash_deltas: dict[str, str | None]llm_context: str | Nonecompression_version: str | Nonecompacted_at: datetime | None
Serialization is done through:
to_dict()from_dict()
Also defined in src/mcp_server/models/state_model.py.
Fields:
transition_id: intcurrent_state: intnext_state: intuser_prompt: str | Nonetimestamp: datetime | Nonereward: float | None
Serialization is done through:
to_dict()from_dict()
Columns:
state_number INTEGER PRIMARY KEYuser_prompt TEXT NOT NULLbranch_name VARCHAR(255) NOT NULLgit_diff_info TEXT NULLhash VARCHAR(64) UNIQUE NOT NULLcreated_at DATETIMEfile_hashes TEXT NULLfile_hash_deltas TEXT NULLllm_context TEXT NULLcompression_version VARCHAR(32) NULLcompacted_at DATETIME NULL
Columns:
id INTEGER PRIMARY KEY AUTOINCREMENTcurrent_state INTEGER NOT NULLnext_state INTEGER NOT NULLuser_prompt TEXT NULLtimestamp DATETIMEreward REAL NULL
Columns:
key VARCHAR(255) PRIMARY KEYvalue VARCHAR(255) NOT NULL
SQLite schema upgrades for new optional columns are handled by:
src/mcp_server/utils/schema_upgrade.py
Properties persisted:
state_numberuser_promptbranch_namegit_diff_infohashcreated_atfile_hashesfile_hash_deltasllm_contextcompression_versioncompacted_at
Properties persisted:
transition_iduser_prompttimestampreward
Endpoints are connected as:
(:State)-[:TRANSITION]->(:State)
Used to store:
- current state pointer
- generic metadata values
- SCC-E vocabulary metadata
The current implementation keeps logical parity between SQLite and Neo4j for all persisted domain fields.
The EVM backend is a fourth persistence mode with a different parity model. Writes anchor keccak256(canonical_json(state)) + IPFS CID on-chain via CodebaseStateRegistry; reads are served from a local SQLite mirror (EVM_MIRROR_PATH), with on-chain fallback. Parity with SQLite/Neo4j is integrity parity: the Python side computes the canonical hash and the chain stores it verbatim — the on-chain payload is not re-serialized from domain objects. Verified by tests/integration/test_evm_parity.py (100 states: canonical_hash(sqlite_state) == contract.getStateHash(n)). All EVM tests run against a local Anvil instance; the historical one-time Base Sepolia run that closed AC-11-OPT on 2026-07-21 is preserved at docs/measurements/archive/sepolia_2026-07/ for reference only.
Canonical fields persisted in both backends:
state_numberuser_promptbranch_namegit_diff_infohashcreated_atfile_hashesfile_hash_deltasllm_contextcompression_versioncompacted_at
Canonical fields persisted in both backends:
transition_idcurrent_statenext_stateuser_prompttimestampreward
Implementation detail:
- SQLite uses column
id - Neo4j uses property
transition_id
Both map to the same domain field: Transition.transition_id.
StateService.genesis() performs:
- initialization guard check;
- source/volume path validation using resolved absolute paths;
- clone or copy of the project into
VOLUME_PATH/codebase; - local Git repo initialization in the managed snapshot;
- hash generation of the source project;
- SCC-E generation for state
0; - persistence of state
0; - current state pointer set to
0; - initialized flag written to the volume root.
StateService.new_state_transition() performs:
- initialization check;
- optional consistency check/repair for SQLite-backed runtime;
- reconstruction of full previous hashes;
- diff and hash-delta computation via
GitManager.compute_changes_since_last_state(); - SCC-E generation for the new state;
- atomic creation of new state + transition + pointer update;
- sync of the project snapshot back into the managed volume.
StateService.arbitrary_state_transition():
- moves the pointer to an already existing target state;
- records a transition entry;
- enriches the target state with SCC-E if legacy data is missing.
StateService.get_current_state_compact_context():
- compares the current workspace against the current state baseline;
- generates SCC-E preview;
- does not persist a new state or transition.
In the terminology of this project:
- SCC means State Compression Code — the broader idea of turning verbose state history into a smaller, model-friendly representation.
- SCC-E means State Compression Code — Embedding — the concrete LLM-facing codec that the current codebase implements.
This distinction matters because the earlier design notes discuss SCC as a general compression family and a simpler baseline, while the running project persists SCC-E specifically as compact state context for agents.
Primary file:
src/mcp_server/services/scc_codec.py
Compact state metadata is stored in the State model itself:
llm_contextcompression_versioncompacted_at
The shared path vocabulary is stored in repository metadata using:
scc_e_path_vocabscc_e_vocab_revisionscc_e_vocab_format
State-returning tools support:
rawcompactboth
This is implemented in the tool layer, not the repositories.
If an old state does not have compact fields, StateService._ensure_compact_state_context() generates SCC-E on demand using persisted diffs and hashes.
StateService.get_compact_states():
- returns persisted compact payloads for one state, an inclusive range, or all states;
- enriches legacy states with SCC-E when needed;
- attaches the reward from the earliest transition that produced each state;
- omits the
rewardfield when the generating transition hasreward = null.
The FastMCP app currently exposes 26 tools.
genesis_toolstart_genesis_toolget_genesis_status_toolget_genesis_result_toolnew_state_transition_toolarbitrary_state_transition_toolget_current_state_number_toolget_current_state_info_toolget_state_info_tooltotal_states_toolsearch_states_tool
get_state_transitions_toolget_transition_info_tooltrack_transitions_toolget_current_state_transitions_toolget_rewarded_transitions_toolset_transition_reward_tool
get_current_state_compact_context_toolget_compact_states_toolexplain_scc_e_format_tool— didactic teacher for the SCC-E compact-state format; see §10 for the format reference
fix_volume_path_toolstart_fix_volume_path_toolget_fix_volume_path_status_toolget_fix_volume_path_result_toolcheck_consistency_toolrepair_consistency_tool
The project keeps a managed workspace snapshot under:
VOLUME_PATH/codebase
When VOLUME_PATH is not explicitly configured, the runtime default is:
/opt/codebase-state-manager/volumes/<current-project-dir-name>/codebase
This snapshot is used to:
- compute diffs against the current project;
- support recovery when the live project and persisted state diverge;
- rebuild a consistent working copy.
This service method:
- validates consistency first;
- identifies the managed project path;
- verifies snapshot divergence;
- may create a recovery transition when necessary;
- rebuilds the managed volume snapshot;
- rechecks consistency.
Primary file:
src/mcp_server/utils/validation.py
Includes validation for:
- prompts
- paths
- state ranges
- transition ids
- reward values
- SCC-E payload structure
Primary file:
src/mcp_server/utils/security.py
Current algorithm:
- sliding window, in-memory
This replaces older documentation that described token bucket behavior.
Primary file:
src/mcp_server/utils/audit.py
Tracks:
- state transitions
- arbitrary transitions
- genesis
- reward updates
- validation failures
- rate-limit events
- security events
Current repository validation commands:
python -m pytest tests -q
uv run mypy src/
uv run bandit -r src/ -qValidation status on the current codebase:
- tests:
568 passed - mypy: pass
- bandit: clean
The current codebase guarantees:
- backend parity for domain persistence fields;
- canonical launcher stability via
run_mcp_server.py; - managed Neo4j persistence across sessions in the same project;
- SCC-E persistence on newly created states;
- compact preview without mutation;
- reward persistence and historical reward updates.