AI Composition
Optimal Method Patterns
Optimal Method Patterns for AI Composition
Purpose: Define what "optimal" means when AI composes methods through Stellify's structured code system. This is about making AI better at composing, reusing, and reasoning about code at the structural level.
The Composition Model
How AI Creates Code in Stellify
AI Intent: "validate input then save to database"
↓
Composes structured representation:
↓
┌─────────────────────────────────────────────────────┐
│ Method │
│ name: "store" │
│ parameters: [clause-uuid-1] │
│ returnType: "JsonResponse" │
│ data: [stmt-uuid-1, stmt-uuid-2] │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ Statement (stmt-uuid-1) │
│ data: [clause-a, clause-b, clause-c, ...] │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ Clauses (atomic tokens) │
│ variable: "$validated" │
│ T_EQUALS: "=" │
│ method: "validate" │
│ T_OPEN_PARENTHESIS: "(" │
│ ... │
└─────────────────────────────────────────────────────┘
↓
Assembler produces target output (PHP, JS, etc.)
The Vocabulary
AI composes using three types of building blocks:
1. Predefined Tokens (Fixed UUIDs)
- Keywords:
return,if,foreach,function,class - Operators:
=,==,===,->,::,=> - Delimiters:
(,),{,},[,],;,, - Types:
bool,int,string,array,void
These are universal - same UUID always produces same token.
2. Value Clauses (Created per-use)
variable:$name→ outputs$namestring:hello→ outputs'hello'number:42→ outputs42method:validate→ outputsvalidatemodel:User→ outputsUserproperty:email→ outputsemailclass:Request→ outputsRequest
3. Statements (Ordered clause sequences)
- A statement is an array of clause UUIDs
- Order determines output
- Hash-based deduplication enables reuse
Optimal Composition Principles
1. Maximize Clause Reuse
Every unique clause gets stored. Identical clauses can be referenced.
Suboptimal:
Statement 1: [$user, =, User, ::, create, (, $data, ), ;]
Statement 2: [$post, =, Post, ::, create, (, $data, ), ;]
Statement 3: [$comment, =, Comment, ::, create, (, $data, ), ;]
Creates 3 different $data clauses, 3 different create clauses.
Optimal:
Shared clauses:
- $data (one UUID)
- create (one UUID)
- :: (predefined)
- = (predefined)
- ( ) ; (predefined)
Unique per statement:
- $user, $post, $comment (variable clauses)
- User, Post, Comment (model clauses)
Composition insight: When AI needs Model::create($data) pattern, most clauses are reusable. Only the model name and variable name change.
2. Favor Linear Statements
Statements that read left-to-right assemble cleanly.
Optimal (linear):
$result = $this->service->process($input);
Clause sequence: [$result, =, $this, ->, service, ->, process, (, $input, ), ;]
Suboptimal (nested):
$result = $this->service->process($this->other->transform($input));
Requires careful parenthesis tracking. Harder to reuse inner expression.
Composition insight: Prefer extracting nested calls to separate statements when nesting exceeds 2 levels.
3. Statement Granularity
One logical operation per statement.
Optimal:
Statement 1: $validated = $request->validate([...])
Statement 2: $user = User::create($validated)
Statement 3: return response()->json($user)
Suboptimal:
Statement 1: return response()->json(User::create($request->validate([...])))
Why this matters:
- Each statement gets its own hash → reusable independently
- Easier to modify/replace individual operations
- Clearer intent for AI reasoning
- Better error localization
4. Pattern-Based Statement Templates
Common operations should map to consistent clause sequences.
Assignment Pattern:
[$variable, T_EQUALS, ...expression..., T_END_LINE]
Method Call Pattern:
[$object, T_OBJECT_OPERATOR, method, T_OPEN_PARENTHESIS, ...args..., T_CLOSE_PARENTHESIS]
Return Pattern:
[T_RETURN, ...expression..., T_END_LINE]
Conditional Pattern:
[T_IF, T_OPEN_PARENTHESIS, ...condition..., T_CLOSE_PARENTHESIS, T_OPEN_BRACE]
...body statements...
[T_CLOSE_BRACE]
Composition insight: AI should recognize these patterns and compose using them. The pattern structure is stable; only the inner expressions change.
Method Structure Patterns
Pattern A: Input → Transform → Output
The most common and optimal method structure.
Method: processItem
├── Statement 1: Input acquisition/validation
├── Statement 2: Core transformation
└── Statement 3: Output/return
Why optimal:
- Clear data flow
- Each statement has single purpose
- Easy to reason about
- Maximum reuse potential
Pattern B: Input → Guard → Transform → Output
When validation/authorization is needed.
Method: updateItem
├── Statement 1: Input validation
├── Statement 2: Authorization check (early return if fails)
├── Statement 3: Core transformation
└── Statement 4: Output/return
The guard pattern:
if (!$condition) {
return $errorResponse;
}
This is a reusable 4-statement block (if + condition + return + close-brace).
Pattern C: Input → Loop → Accumulate → Output
For collection processing.
Method: processItems
├── Statement 1: Input/initialization
├── Statement 2: foreach open
├── Statement 3: Per-item operation
├── Statement 4: foreach close
└── Statement 5: Return accumulated result
Pattern D: Transaction Wrapper
For atomic operations.
Method: transfer
├── Statement 1: Input validation
├── Statement 2: DB::transaction open
├── Statement 3-N: Operations inside transaction
├── Statement N+1: Return inside transaction
└── Statement N+2: Transaction close
Clause Type Selection
When to Use Each Clause Type
| Type | Use When | Example Value | Output |
|------|----------|---------------|--------|
| variable | Storing/passing data | user | $user |
| string | Literal text | email | 'email' |
| number | Numeric literals | 200 | 200 |
| method | Calling functions | create | create |
| model | Eloquent models | User | User |
| property | Object properties | email | email |
| class | Class references | Request | Request |
Predefined Tokens (Always Use These)
Never create clauses for these - use the predefined UUIDs:
Keywords: return, if, else, foreach, function, new, class
Operators: =, ==, ===, ->, ::, =>, ??
Delimiters: (, ), {, }, [, ], ;, ,
Types: bool, int, string, array, void
This ensures maximum deduplication across all methods.
Deduplication Strategy
Statement-Level Hashing
Each statement gets a hash computed from its clause sequence:
hash = sha256(json_encode(clause_uuids))
Identical statements across the entire system share one hash.
When Statements Match
Two statements match when they have:
- Same clause UUIDs in same order
- Same clause values (for value clauses)
Maximizing Hash Matches
Make statements generic where possible:
Instead of:
$userEmail = $user->email;
$postTitle = $post->title;
Consider if the pattern $x = $y->z; can be expressed once and referenced.
Use consistent variable naming in templates:
If AI creates reusable "validate and create" patterns, use consistent placeholder names that can be parameterized or cloned.
Method Complexity Guidelines
Simple Methods (1-3 statements)
- Accessors, getters
- Simple transformations
- Direct returns
Optimal for: Maximum reuse, clear purpose
Medium Methods (4-8 statements)
- Standard CRUD operations
- Validation + single operation
- Conditional logic with one branch
Optimal for: Common business operations
Complex Methods (9-15 statements)
- Multi-step processes
- Transaction-wrapped operations
- Multiple conditional branches
Guidance: Consider if inner logic can be extracted to reusable sub-methods
Extract Threshold (15+ statements)
If a method exceeds 15 statements:
- Extract logical groups into separate methods
- Create helper methods for repeated patterns
- Consider if it's actually multiple methods combined
Assembler Constraints
Blocked Operations
The assembler rejects certain patterns regardless of framework:
System operations: exec, shell_exec, system, eval
File operations: file_get_contents, file_put_contents, unlink
Raw database: DB::raw, whereRaw, selectRaw (SQL injection vectors)
Debug output: dd, dump, var_dump, print_r
Composition insight: AI cannot produce these. Don't try to compose around them - use safe alternatives.
Safe Alternatives
| Blocked | Safe Alternative |
|---------|------------------|
| DB::raw() | Query builder methods |
| whereRaw() | where(), whereIn(), whereBetween() |
| file_get_contents() | Storage::get() |
| exec() | Queue jobs, dedicated services |
Framework Agnosticism
The Abstraction Layer
Stellify methods are above any specific framework:
Method (Stellify)
↓
Assembler
↓
PHP (Laravel) OR JavaScript (Vue) OR Future Target
Composing for Portability
Framework-specific clauses (like Laravel's response()->json()) are stored as method/class clauses. The assembler maps them to the target.
Logic structure (if/else, loops, assignments) uses predefined tokens that map to any imperative language.
Composition insight: When AI composes a method, the logic structure is portable. Only the framework-specific calls need assembler mapping for different targets.
Summary: What Makes a Method Optimal for AI
- Linear statement flow - Easy to reason about, assemble, modify
- One operation per statement - Maximum reuse via hashing
- Predefined tokens for syntax - Never create clauses for
=,->,;, etc. - Consistent patterns - Same operations structured the same way
- Appropriate granularity - 3-8 statements is the sweet spot
- Guard clauses early - Fail fast, reduce nesting
- Avoid deep nesting - Extract to separate statements/methods
- Framework operations via clauses - Let the assembler handle mapping
The goal: Methods that AI can compose quickly, reason about clearly, reuse maximally, and assemble to any target.
Last Updated: January 20, 2026
- Previous
- MCP & AI Setup
- Next
- Configuration