Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 24 additions & 24 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co

## Overview

This is **codeplain**, a Python CLI tool that renders code from `***plain` specification files using the Codeplain API. The tool acts as a client that:
This is **codeplain**, a Python CLI tool that regenerates code from `***plain` specification files using the Codeplain API. The tool acts as a client that:
1. Parses `***plain` spec files (a domain-specific language for software specifications)
2. Sends specs to the Codeplain API (LLM-based code generation service)
3. Manages an iterative state-machine-driven render process with testing and refactoring cycles
3. Manages an iterative state-machine-driven regeneration process with testing and refactoring cycles
4. Outputs generated code to a build folder

The codebase serves two audiences:
- **End users**: developers who write `***plain` specs and run `plain2code.py` to generate code
- **Internal devs**: maintaining the renderer itself (this codebase)
- **Internal devs**: maintaining the regeneration engine itself (this codebase)

### Related Repository: codeplain-api

Expand Down Expand Up @@ -59,13 +59,13 @@ Hook is located at `.git/hooks/pre-push`.

### Running the Tool
```bash
# Basic usage - render a .plain file
# Basic usage - regenerate code from a .plain file
python plain2code.py path/to/file.plain

# Display account status (user info, credits, API key label)
python plain2code.py --status

# Dry run (parse and validate .plain files without rendering code)
# Dry run (parse and validate .plain files without regenerating code)
# This parses the spec files, resolves imports/requires, but doesn't generate code
python plain2code.py path/to/file.plain --dry-run

Expand All @@ -75,8 +75,8 @@ python plain2code.py path/to/file.plain --log-to-file
# Headless mode (no TUI, logs to file only)
python plain2code.py path/to/file.plain --headless

# Render specific functionality range
python plain2code.py file.plain --render-range add-task,delete-task # Render add-task through delete-task
# Regenerate specific functionality range
python plain2code.py file.plain --render-range add-task,delete-task # Regenerate add-task through delete-task
python plain2code.py file.plain --render-from delete-task # Resume from delete-task

# Run with examples
Expand Down Expand Up @@ -125,27 +125,27 @@ black . --check && isort . --check-only && flake8 . && mypy . --check-untyped-de
### High-Level Flow
1. **Entry Point** (`plain2code.py`): CLI argument parsing, logging setup, TUI initialization
2. **Module Loading** (`plain_modules.py`, `plain_file.py`): Parse `.plain` files into `PlainModule` objects with dependency trees
3. **Rendering Orchestration** (`module_renderer.py`): Coordinates render process across modules
4. **State Machine** (`render_machine/`): Hierarchical state machine drives the render lifecycle
3. **Regeneration Orchestration** (`module_renderer.py`): Coordinates regeneration process across modules
4. **State Machine** (`render_machine/`): Hierarchical state machine drives the regeneration lifecycle
5. **API Communication** (`codeplain_REST_api.py`): HTTP client for Codeplain API
6. **Code Generation** (`render_machine/code_renderer.py`): Main code renderer class that orchestrates the code generation workflow using a hierarchical state machine
7. **TUI** (`tui/`): Textual-based terminal UI showing render progress
8. **CLI Output** (`cli_output/`): Non-interactive terminal output formatting for status, dry-run, and render summaries
6. **Code Generation** (`render_machine/code_renderer.py`): Main `CodeRenderer` class that orchestrates the code generation workflow using a hierarchical state machine
7. **TUI** (`tui/`): Textual-based terminal UI showing regeneration progress
8. **CLI Output** (`cli_output/`): Non-interactive terminal output formatting for status, dry-run, and regeneration summaries

### Key Concepts

**Plain Modules**: A `.plain` file can `import` other `.plain` files, creating a module dependency tree. The renderer processes required modules first (depth-first), then the top module.
**Plain Modules**: A `.plain` file can `import` other `.plain` files, creating a module dependency tree. The regeneration engine processes required modules first (depth-first), then the top module.

**Functionalities (FRIDs)**: Each functional requirement in a `.plain` file has a unique ID (FRID), the func-id of its `# <func-id>` heading. The renderer processes them sequentially. State is checkpointed after each FRID.
**Functionalities (FRIDs)**: Each functional requirement in a `.plain` file has a unique ID (FRID), the func-id of its `# <func-id>` heading. The regeneration engine processes them sequentially. State is checkpointed after each FRID.

**Render State Machine** (`render_machine/states.py`): Hierarchical FSM with states like:
**Regeneration State Machine** (`render_machine/states.py`): Hierarchical FSM with states like:
- `IMPLEMENTING_FRID` → `PROCESSING_UNIT_TESTS` → `REFACTORING_CODE` → `PROCESSING_CONFORMANCE_TESTS`
- Transitions handled by triggers in `render_machine/triggers.py`
- Config in `render_machine/state_machine_config.py`

**Memory Management** (`memory_management.py`): Tracks previously rendered code to provide context to the LLM for incremental changes. Uses git commits to persist checkpoints.
**Memory Management** (`memory_management.py`): Tracks previously regenerated code to provide context to the LLM for incremental changes. Uses git commits to persist checkpoints.

**Partial Rendering** (`partial_rendering.py`): Detects when specs or code changed and determines the optimal starting point to resume rendering (avoids full re-renders).
**Partial Regeneration** (`partial_rendering.py`): Detects when specs or code changed and determines the optimal starting point to resume regeneration (avoids full regenerations).

**Event Bus** (`event_bus.py`): Pub/sub for UI updates. Events defined in `plain2code_events.py` (e.g., `LogMessageEmitted`, `RenderCompleted`).

Expand All @@ -157,7 +157,7 @@ black . --check && isort . --check-only && flake8 . && mypy . --check-untyped-de
- `plain_modules.py` - Module dependency resolution
- `plain_file.py` - `.plain` file parser
- `plain_spec.py` - Spec extraction and FRID utilities
- `module_renderer.py` - Orchestrates render for a module
- `module_renderer.py` - Orchestrates regeneration for a module
- `render_machine/` - State machine implementation
- `code_renderer.py` - Generates code via templates
- `states.py` - State name constants
Expand All @@ -170,15 +170,15 @@ black . --check && isort . --check-only && flake8 . && mypy . --check-untyped-de
- `cli_output/` - Non-interactive CLI output formatting
- `status.py` - Status display (`--status` flag)
- `dry_run.py` - Dry run output (`--dry-run` flag)
- `render_summary.py` - Render completion summary
- `render_summary.py` - Regeneration completion summary
- `codeplain_REST_api.py` - API client
- `memory_management.py` - Context tracking
- `git_utils.py` - Git operations for checkpointing
- `file_utils.py` - File I/O utilities
- `concept_utils.py` - Concept validation (***plain language feature)
- `plain2code_logger.py` - Custom logging with elapsed time timestamps
- `plain2code_console.py` - Rich console wrapper with custom styles
- `plain2code_state.py` - Runtime state (render ID, counters, timing)
- `plain2code_state.py` - Runtime state (regeneration ID, counters, timing)
- `standard_template_library/` - Built-in `.plain` templates (git subtree from `plainlang-examples`)
- `examples/` - Sample `.plain` projects

Expand All @@ -187,7 +187,7 @@ black . --check && isort . --check-only && flake8 . && mypy . --check-untyped-de
Tests are in `tests/` and cover:
- `test_plain_modules.py` - Module loading, dependency resolution, metadata
- `test_plainfileparser.py` - `.plain` syntax parsing
- `test_partial_rendering.py` - Render resumption logic
- `test_partial_rendering.py` - Regeneration resumption logic
- `test_git_utils.py` - Git checkpoint/restore operations
- `test_imports.py`, `test_requires.py` - Module dependency resolution

Expand All @@ -196,7 +196,7 @@ No integration tests hit the actual Codeplain API (would require API key + netwo
### Logging

Two logging modes:
1. **Console (TUI)**: Logs displayed in TUI with relative timestamps `[HH:MM:SS]` (elapsed since render start, accounts for pauses)
1. **Console (TUI)**: Logs displayed in TUI with relative timestamps `[HH:MM:SS]` (elapsed since regeneration start, accounts for pauses)
2. **File**: Same format as TUI, written to `codeplain.log` in the `.plain` file's directory

`ElapsedTimeFormatter` (in `plain2code_logger.py`) uses `RunState` to calculate elapsed time. Format: `[HH:MM:SS] LEVEL logger_name: message`
Expand All @@ -212,12 +212,12 @@ Two logging modes:
### Code Generation Process
- Templates in `standard_template_library/` use Liquid2 syntax
- Template search order: (1) `.plain` file dir, (2) `--template-dir`, (3) built-in standard lib
- Each module renders into its own tree under the build folder (configurable via `--build-folder`, default `plain_modules/`):
- Each module is regenerated into its own tree under the build folder (configurable via `--build-folder`, default `plain_modules/`):
- `<build-folder>/<module>/code/` — implementation code (its own git repo)
- `<build-folder>/<module>/tests/` — conformance tests (its own git repo; only created when a conformance tests script is configured)
- `<build-folder>/<module>/.codeplain/` — module metadata (`module_metadata.json`), not tracked in git
- `<build-folder>/<module>/.memory/` — conformance test memory, not tracked in git
- Each FRID render produces a git commit in the `code/` and `tests/` repos for rollback capability
- Each FRID regeneration produces a git commit in the `code/` and `tests/` repos for rollback capability

### Configuration
- `config.yaml` can be placed in `.plain` file dir or CWD
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ This provides a real `.plain` project for verifying the change in an actual Code

Run the tests relevant to your change before opening a pull request.

For changes that affect the CLI, rendering, or test execution, also test the change by running the relevant Codeplain command from the terminal.
For changes that affect the CLI, regeneration, or test execution, also test the change by running the relevant Codeplain command from the terminal.

Check that:

Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# *codeplain renderer
# *codeplain regeneration engine

## What is \*codeplain?

\*codeplain platform makes coding agents better by having them write and maintain specifications instead of code. It extends coding agents with agentic skills for working at the specification layer, and with tools that convert specifications into tested and validated implementation code.

This repository is the renderer that powers that last step, turning \*\*\*plain specs into software using the *codeplain API.
This repository is the regeneration engine that powers that last step, turning \*\*\*plain specs into software using the *codeplain API.

The result is a software development workflow centered on specifications, which are faster and more efficient for AI to produce and easier for developers to review and maintain than raw code.

Schematic overview of the *codeplain's code rendering:
Schematic overview of the *codeplain's code regeneration:

<img src="https://raw.githubusercontent.com/Codeplain-ai/plain2code_client/main/resources/codeplain_overview.png">

Expand Down Expand Up @@ -43,7 +43,7 @@ export CODEPLAIN_API_KEY="your_actual_api_key_here"

### 2. Let your agent work in specs, not code

You describe what you want in plain English, an agent helps you write a spec in \*\*\*plain language, and \*codeplain renders the actual code. This is what [plain-forge](https://github.com/Codeplain-ai/plain-forge) sets up: a toolkit of skills, rules, and docs that plugs into your AI coding agent of choice — Claude Code, Codex, ForgeCode, OpenCode, or any other agent that reads from a standard skills directory — and turns a conversation into a complete `.plain` spec, then keeps maintaining it across the lifetime of the project.
You describe what you want in plain English, an agent helps you write a spec in \*\*\*plain language, and \*codeplain regenerates the actual code. This is what [plain-forge](https://github.com/Codeplain-ai/plain-forge) sets up: a toolkit of skills, rules, and docs that plugs into your AI coding agent of choice — Claude Code, Codex, ForgeCode, OpenCode, or any other agent that reads from a standard skills directory — and turns a conversation into a complete `.plain` spec, then keeps maintaining it across the lifetime of the project.

If you didn't install it during step 1, run it any time using your favorite Node package runner:

Expand Down Expand Up @@ -97,7 +97,7 @@ You can immediately test the system with a simple "Hello World" example:
codeplain hello_world_python.plain
```

_Note: Rendering will take a few minutes to complete._
_Note: Regeneration will take a few minutes to complete._

- The system will generate a Python application in the `dist` directory. You can run it with:
```bash
Expand Down
4 changes: 2 additions & 2 deletions cli_output/dry_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def print_dry_run_output(plain_source_tree: dict, render_range: Optional[list[st
functional_requirement_text = specifications[plain_spec.FUNCTIONAL_REQUIREMENTS][-1]
console.info(
"-------------------------------------\n"
f"Rendering functionality {with_position(frid, functionality_position(frids, frid))}:\n"
f"Regenerating functionality {with_position(frid, functionality_position(frids, frid))}:\n"
f"{functional_requirement_text}\n"
"-------------------------------------\n"
)
Expand All @@ -34,7 +34,7 @@ def print_dry_run_output(plain_source_tree: dict, render_range: Optional[list[st
else:
console.info(
"-------------------------------------\n"
f"Skipping rendering iteration: {with_position(frid, functionality_position(frids, frid))}\n"
f"Skipping regeneration round: {with_position(frid, functionality_position(frids, frid))}\n"
"-------------------------------------"
)

Expand Down
8 changes: 4 additions & 4 deletions cli_output/render_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ def print_exit_summary(
console.quiet = False

if run_state.render_succeeded:
msg = "\n[#79FC96]✓ rendering completed\n\n"
msg = "\n[#79FC96]✓ regeneration completed\n\n"
elif run_state.render_cancelled:
msg = "\n[#FFFFFF]— rendering canceled\n\n"
msg = "\n[#FFFFFF]— regeneration canceled\n\n"
else:
msg = "\n[#FF6B6B]✗ rendering failed\n\n"
msg += f" [#8E8F91]render id:\t\t\t[#FFFFFF]{run_state.render_id}\n"
msg = "\n[#FF6B6B]✗ regeneration failed\n\n"
msg += f" [#8E8F91]regeneration id:\t\t[#FFFFFF]{run_state.render_id}\n"
msg += f" [#8E8F91]input file:\t\t\t[#FFFFFF]{spec_filename}\n"
msg += f" [#8E8F91]generated code folder:\t[#FFFFFF]{run_state.render_generated_code_path or '-'}\n\n"
msg += format_usage_summary(run_state.rendered_functionalities, run_state.render_time_accumulated) + "\n"
Expand Down
6 changes: 3 additions & 3 deletions cli_output/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def _display_status_message(plan_credits: Optional[dict], purchased_credits: lis

if not has_remaining:
console.print(
f"\nNo rendering credits remaining. Upgrade to the PRO plan at {PLANS_URL} to continue rendering."
f"\nNo regeneration credits remaining. Upgrade to the PRO plan at {PLANS_URL} to continue regenerating."
)
else:
console.print(f"\nTo manage your plan navigate to {PLANS_URL}")
Expand Down Expand Up @@ -151,8 +151,8 @@ def print_status(api_key: str, api_url: str, client_version: str) -> None:
console.print(f"Organization owner: {org_owner or 'N/A'}")
console.print(f"API key label: {api_key_label}\n")

# Display rendering credits section
console.print("Rendering credits:")
# Display regeneration credits section
console.print("Regeneration credits:")

# Display plan credits (free credits or subscription)
if plan_credits:
Expand Down
4 changes: 2 additions & 2 deletions codeplain_REST_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def _handle_retry_logic(
"Connection error: Failed to connect to API server.\n\nPlease check that your internet connection is working."
)
if isinstance(error, RequestException):
raise Exception(f"Error rendering plain code: {error}\n") from error
raise Exception(f"Error regenerating code: {error}\n") from error
raise error

def _raise_for_error_code(self, response_json):
Expand Down Expand Up @@ -217,7 +217,7 @@ def post_request(
response_json = response.json()
except requests.exceptions.JSONDecodeError as e:
self.console.debug(f"Failed to decode JSON response: {e}. Response text: {response.text}")
raise Exception(f"Error rendering plain code: Failed to decode API response ({e}).\n") from e
raise Exception(f"Error regenerating code: Failed to decode API response ({e}).\n") from e

if response.status_code == requests.codes.bad_request and "error_code" in response_json:
self._raise_for_error_code(response_json)
Expand Down
Loading