Skip to content

Conversation

@AshishKumar4
Copy link
Collaborator

@AshishKumar4 AshishKumar4 commented Nov 7, 2025

Summary

This PR refactors the monolithic SimpleCodeGeneratorAgent into a modular, extensible agent architecture that separates concerns between "what to build" (objectives) and "how to build it" (behaviors). This enables support for multiple project types beyond web applications, including backend workflows and presentations/slides.

Changes

Core Architecture Refactoring

Agent Infrastructure:

  • Created AgentInfrastructure interface (worker/agents/core/AgentCore.ts) - Defines the contract between the Durable Object and agent behaviors/objectives
  • Created AgentComponent base class (worker/agents/core/AgentComponent.ts) - Provides common infrastructure access patterns for all agent components
  • Refactored CodeGeneratorAgent (worker/agents/core/codingAgent.ts) - Now extends Agent (DO) and delegates to behavior + objective pattern

Behavior Pattern (How to Build):

  • Created BaseCodingBehavior (worker/agents/core/behaviors/base.ts, 1535 lines) - Abstract base class providing common functionality:
    • File management and git operations
    • Deployment and sandbox integration
    • Conversation handling and user input queuing
    • Deep debug orchestration
    • Abort controller patterns
  • Created PhasicCodingBehavior (worker/agents/core/behaviors/phasic.ts, 852 lines) - Legacy state machine-driven approach for iterative app building
  • Created AgenticCodingBehavior (worker/agents/core/behaviors/agentic.ts, 244 lines) - New agent-driven loop approach for autonomous building

Objective Pattern (What to Build):

  • Created ProjectObjective base class (worker/agents/core/objectives/base.ts) - Defines project identity, runtime requirements, and export/deployment logic
  • Created AppObjective (worker/agents/core/objectives/app.ts) - Full-stack web applications (React + Vite + Workers)
  • Created WorkflowObjective (worker/agents/core/objectives/workflow.ts) - Backend-only workflows (APIs, scheduled jobs, webhooks)
  • Created PresentationObjective (worker/agents/core/objectives/presentation.ts) - Slides/presentations (Spectacle library)

New Features

Agentic Project Builder:

  • Created AgenticProjectBuilder (worker/agents/assistants/agenticProjectBuilder.ts, 411 lines) - Autonomous LLM-driven project builder using tool-calling approach
    • Scaffold → Deploy → Verify → Fix iteration loop
    • Project-type-specific system prompts and validation
    • Integrated with debug tools for comprehensive file operations

Type System:

  • Added ProjectType - 'app' | 'workflow' | 'presentation'
  • Added RuntimeType - 'sandbox' | 'worker' | 'none'
  • Added BehaviorType - 'phasic' | 'agentic'
  • Enhanced state types with discriminated unions (PhasicState, AgenticState)
  • Updated GenerationContext to support both phasic and agentic contexts with type guards

Operations & Services:

  • Created SimpleCodeGenerationOperation (worker/agents/operations/SimpleCodeGeneration.ts) - Lightweight file generation for README and simple tasks
  • Updated ICodingAgent interface - Now behavior-agnostic with consistent method signatures
  • Updated all tool implementations to use ICodingAgent interface instead of concrete types

State Management

Enhanced State Schema:

  • Added BaseProjectState - Common fields across all behaviors
  • Added PhasicState extends BaseProjectState - State machine-specific fields (phases, counter)
  • Added AgenticState extends BaseProjectState - Agent loop-specific fields (plan)
  • Updated AgentState - Discriminated union of PhasicState | AgenticState

Schema Updates:

  • Added SimpleBlueprintSchema - Base blueprint for all project types
  • Added PhasicBlueprintSchema - Extended blueprint for phase-based generation
  • Added AgenticBlueprintSchema - Simplified blueprint for agent-driven generation

File Changes Summary

Added (13 files):

  • worker/agents/core/AgentComponent.ts
  • worker/agents/core/AgentCore.ts
  • worker/agents/core/behaviors/agentic.ts
  • worker/agents/core/behaviors/base.ts
  • worker/agents/core/behaviors/phasic.ts
  • worker/agents/core/codingAgent.ts
  • worker/agents/core/objectives/app.ts
  • worker/agents/core/objectives/base.ts
  • worker/agents/core/objectives/presentation.ts
  • worker/agents/core/objectives/workflow.ts
  • worker/agents/assistants/agenticProjectBuilder.ts
  • worker/agents/operations/SimpleCodeGeneration.ts

Deleted (3 files):

  • worker/agents/core/simpleGeneratorAgent.ts (2707 lines) - Split into behaviors and objectives
  • worker/agents/core/smartGeneratorAgent.ts (40 lines) - Functionality merged into behaviors
  • worker/agents/operations/ScreenshotAnalysis.ts (134 lines) - Removed unused operation

Modified (38 files):

  • State management, types, and interfaces
  • All tool implementations updated to use ICodingAgent
  • Operations updated for new context types
  • WebSocket handling updated for behavior pattern
  • Blueprint generation updated for project types

Motivation

Scalability: The monolithic agent class had grown to 2700+ lines and was becoming difficult to maintain and extend.

Extensibility: Adding new project types (workflows, presentations) required duplicating logic or adding more conditionals.

Separation of Concerns: Mixing "what to build" and "how to build it" logic made the code harder to reason about and test.

Future Features: This architecture enables:

  • CLI-based coding agents (non-DO implementations)
  • In-memory workflow definitions (no R2 templates needed)
  • Static export workflows (presentations → PDF)
  • Multiple deployment targets per project type

Testing

Manual Testing Checklist

  • Existing Apps (Phasic Behavior):

    • Create new web app with existing flow
    • Verify state migration works for old sessions
    • Test phase generation and implementation
    • Verify WebSocket state restoration
    • Test deployment and preview
  • New Project Types (Agentic Behavior):

    • Test workflow creation (if implemented in frontend)
    • Test presentation creation (if implemented in frontend)
    • Verify correct objective/behavior selection
  • Tool Operations:

    • Test file regeneration
    • Test deep debug with new interface
    • Test git operations
    • Test exec commands
  • State Management:

    • Verify state migration for existing DOs
    • Test conversation state persistence
    • Test abort controller cleanup

Breaking Changes

Interface Changes:

  • CodingAgentInterface renamed to ICodingAgent (follows naming convention)
  • Operations now receive OperationOptions<GenerationContext> instead of concrete agent reference

Backward Compatibility:

  • State migration implemented for existing Durable Objects
  • Frontend must handle new behaviorType and projectType fields
  • WebSocket messages unchanged (implementation details only)

Notes

  • Incomplete: PR marked as incomplete by author - missing frontend integration for workflow/presentation types
  • Future Work: Workflow and presentation objectives need full implementation (currently stubs)
  • Testing: Comprehensive testing needed for agentic behavior and new objective types

This PR description was automatically generated by Claude Code

- Split monolithic simpleCodeGeneratorAgent into baseAgentBehavior and PhasicAgentBehavior
- CodeGeneratorAgent now inherits Agent class (DO) and uses behavior
- AgentBehavior relies on AgentInfrastructure (provided by DO) to work, allows to write non-DO coding agents (like cli based)
- Phasic for legacy state machine app builder, Agentic for agent driven loop
- Agentic would support multiple project types - 'app', 'workflow', 'slides/docs'
AshishKumar4 and others added 2 commits November 7, 2025 18:00
…ic coding agent implemented

- Abstracted behaviors and objectives
- Behavior and Objectives are bot h AgentComponent
- CodeGeneratorAgent (Agent DO) houses common business logic
- Implemented agentic coding agent and and assistant
- Implemented AI-powered project type prediction (app/workflow/presentation) with confidence scoring and auto-detection when projectType is 'auto'
- Enhanced template selection to filter by project type and skip AI selection for single-template scenarios in workflow/presentation types
- Added GitHub token caching in CodeGeneratorAgent for persistent OAuth sessions across exports
- Updated commitlint config to allow longer commit messages (
- Initialize template cache during agent setup to avoid redundant fetches
- Remove redundant project name prompt from template selection
- Clean up default projectType fallback logic
- Added concurrency control to prevent duplicate workflow runs on the same PR
- Replaced Claude-based comment cleanup with direct GitHub API deletion for better reliability
- Enhanced code debugger instructions to handle Vite dev server restarts and config file restrictions
@github-actions github-actions bot added the ci/cd label Nov 10, 2025
static migrateIfNeeded(state: CodeGenState, logger: StructuredLogger): CodeGenState | null {
static migrateIfNeeded(state: AgentState, logger: StructuredLogger): AgentState | null {
let needsMigration = false;
const legacyState = state as unknown as Record<string, unknown>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM: Overly Permissive Type Casting

While migration code often needs to work with unknown schemas, casting the entire state to Record<string, unknown> reduces type safety throughout the migration function.

Recommendation: Use type guards or more specific type narrowing:

const hasField = (key: string): key is keyof AgentState => key in state;
if (hasField('latestScreenshot')) {
    // TypeScript knows the field exists
}

This is acceptable for migration code, but consider adding runtime validation using Zod schemas to catch unexpected state shapes early.

throw new Error(`State behaviorType mismatch: expected ${behaviorType}, got ${this.state.behaviorType}`);
}

if (behaviorType === 'phasic') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM: Behavior Mismatch Security Risk

This check throws an error if there's a mismatch between expected and actual behavior types, which is good. However, this happens AFTER the behavior instance is created (line 125-128), which could lead to inconsistent state.

Recommendation: Move this validation BEFORE instantiating the behavior:

const isInitialized = Boolean(this.state.query);
const behaviorType = isInitialized
    ? this.state.behaviorType
    : props.behaviorType ?? this.state.behaviorType ?? 'phasic';

// Validate FIRST
if (isInitialized && this.state.behaviorType !== behaviorType) {
    throw new Error(`State behaviorType mismatch: expected ${behaviorType}, got ${this.state.behaviorType}`);
}

// Then create behavior with validated type
if (behaviorType === 'phasic') {
    this.behavior = new PhasicCodingBehavior(...);
} else {
    this.behavior = new AgenticCodingBehavior(...);
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like a hallucination because we are already doing exactly this

AshishKumar4 and others added 3 commits November 10, 2025 11:38
- Replaced unsafe type assertions with proper type guards for legacy state detection
- Added explicit type definitions for deprecated state fields and legacy file formats
- Eliminated all 'any' types while maintaining backward compatibility with legacy states

delete (migratedInferenceContext as any).userApiKeys;
// Remove the deprecated field using type assertion
const contextWithLegacyField = migratedInferenceContext as unknown as Record<string, unknown>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM: Unsafe Type Casting

This type assertion as Record<string, unknown> bypasses TypeScript's type checking. While somewhat acceptable in migration code, it could mask issues.

Recommendation: Add runtime validation to ensure the field actually exists before deletion:

if (migratedInferenceContext && 'userApiKeys' in migratedInferenceContext) {
    const { userApiKeys, ...rest } = migratedInferenceContext as unknown as { userApiKeys?: unknown } & InferenceContext;
    migratedInferenceContext = rest;
    needsMigration = true;
}

This approach is safer and more explicit about what's being removed.

const projectType = props?.projectType ?? this.state.projectType ?? 'app';

if (behaviorType === 'phasic') {
this.behavior = new PhasicCodingBehavior(this as AgentInfrastructure<PhasicState>, projectType);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LOW: Type Assertion Without Validation

Casting to AgentInfrastructure<PhasicState> without runtime validation that the state is actually a PhasicState could lead to type mismatches if the behaviorType doesn't align with the state structure.

Recommendation: Add runtime validation:

if (behaviorType === 'phasic') {
    // Validate state structure matches PhasicState
    if (!('generatedPhases' in this.state) || !('currentDevState' in this.state)) {
        throw new Error('State structure does not match phasic behavior requirements');
    }
    this.behavior = new PhasicCodingBehavior(this as AgentInfrastructure<PhasicState>, projectType);
} else {
    // Similar validation for agentic
    this.behavior = new AgenticCodingBehavior(this as AgentInfrastructure<AgenticState>, projectType);
}

This ensures type safety at runtime, not just compile time.

@github-actions
Copy link
Contributor

Code & Security Review

Recommendation: COMMENT (Minor improvements suggested, no blocking issues)

Executive Summary

This is a well-executed architectural refactoring that successfully modularizes a 2700+ line monolithic agent class into a clean behavior/objective pattern. The architecture is sound and follows good separation of concerns principles. However, there are several type safety violations and a few implementation concerns that should be addressed.

Overall Assessment: The refactoring achieves its goals and maintains backward compatibility through state migration. The code is production-ready with minor improvements needed for type safety compliance.


Code Quality Issues

Type Safety Violations

MEDIUM - Multiple any Type Usage
Location: worker/agents/core/stateMigration.ts:98

The codebase violates CLAUDE.md's strict rule: "NEVER use any type". Found in state migration logic:

const getTimestamp = (msg: any) => {

Impact: Bypasses TypeScript's type checking in migration logic
Recommendation: Replace with proper ConversationMessage typing (inline comment posted)

MEDIUM - Unsafe Type Casting in Migration
Location: worker/agents/core/stateMigration.ts:159

const contextWithLegacyField = migratedInferenceContext as unknown as Record<string, unknown>;
delete contextWithLegacyField.userApiKeys;

Impact: Type assertion circumvents compile-time safety
Recommendation: Use destructuring for safer field removal (inline comment posted)

LOW - Unvalidated Type Assertion
Location: worker/agents/core/codingAgent.ts:119

Casting to AgentInfrastructure<PhasicState> without runtime validation that state structure matches:

this.behavior = new PhasicCodingBehavior(this as AgentInfrastructure<PhasicState>, projectType);

Impact: Could lead to runtime type mismatches if behaviorType doesn't align with state structure
Recommendation: Add runtime state structure validation (inline comment posted)

Architecture & Design

POSITIVE - Excellent Separation of Concerns

  • Behavior pattern (how to build) cleanly separated from objective pattern (what to build)
  • AgentInfrastructure interface provides clear contract between DO and behaviors
  • AgentComponent base class reduces boilerplate effectively

POSITIVE - Backward Compatibility

  • State migration logic handles legacy formats
  • Conversation message deduplication (addresses exponential bloat)
  • Template details migration from embedded objects to names

MEDIUM - Complex State Type Hierarchy
The discriminated union approach for state types is correct but adds complexity:

export type AgentState = PhasicState | AgenticState;

Observation: The type guards (isPhasicState, isAgenticState) are used inconsistently across the codebase. Some areas use type assertions instead of guards.

Recommendation: Standardize on type guards throughout the codebase for consistency and safety.

DRY Principle Compliance

POSITIVE - Good Code Reuse

  • BaseCodingBehavior (1535 lines) extracts common functionality well
  • Operations are properly shared between behaviors
  • File management, git operations, and deployment logic properly abstracted

LOW - Duplicated Type Guards
Type guards like isPhasicBlueprint appear in multiple files:

  • src/routes/chat/chat.tsx:45
  • src/routes/chat/components/blueprint.tsx:5

Recommendation: Extract to shared utility in src/utils/ or shared/types/


Security Analysis

Authentication & Authorization

PASS - No Issues Found

  • Rate limiting properly enforced in CodingAgentController.startCodeGeneration
  • User authentication checked before agent creation
  • GitHub token caching in objectives is ephemeral (memory only, lost on DO eviction)

Secrets Management

PASS - Proper Handling

  • Secrets accessed via env.ANTHROPIC_API_KEY, env.GOOGLE_AI_STUDIO_API_KEY (standard pattern)
  • State migration removes deprecated userApiKeys field from inference context
  • No secrets leaked in logs or responses

SQL Injection

PASS - No Vulnerabilities

  • All database operations use Drizzle ORM (parameterized queries)
  • Git operations use isomorphic-git with SQLite adapter (no raw SQL in agent code)
  • DO storage uses standard KV operations

Input Validation

PASS - Adequate Validation

  • CodingAgentController validates required fields (query, user auth)
  • Blueprint generation validates project types
  • Tool arguments validated by Zod schemas (not directly visible in PR but referenced)

Access Control

PASS - Git Tool Safety

  • Conversation tools exclude dangerous git commands: createGitTool(agent, logger, { excludeCommands: ['reset'] })
  • Debug tools get full git access (intentional design)
  • Sandbox commands execute with proper isolation

Testing & Validation Concerns

OBSERVATION - Manual Testing Required
PR author notes testing checklist is incomplete. Critical paths that need validation:

  1. State Migration: Existing DOs must migrate cleanly

    • Legacy templateDetailstemplateName
    • Legacy agentModebehaviorType
    • Conversation message deduplication doesn't break history
  2. Behavior Selection: Project types correctly map to behaviors

    • appphasic (existing flow)
    • presentation, workflow, generalagentic
  3. Tool Operations: All LLM tools work with ICodingAgent interface

    • File regeneration
    • Deep debug
    • Git operations
    • Sandbox commands

RECOMMENDATION: Add integration tests for state migration edge cases


Performance Considerations

POSITIVE - Efficient Architecture

  • Ephemeral state (abort controllers, promises) kept in memory, not persisted
  • File manager uses callbacks for git sync (avoids polling)
  • Preview URL caching reduces redundant sandbox calls

LOW - Large Blueprint Context
AgenticProjectBuilder system prompt is very large (279 lines of prompt construction). This increases token usage per inference.

Observation: Acceptable trade-off for autonomous building, but monitor token costs in production.


Breaking Changes Assessment

ACCURATE - Well Documented
PR correctly identifies breaking changes:

  • CodingAgentInterfaceICodingAgent (follows naming convention)
  • Operations receive OperationOptions<GenerationContext> instead of concrete agent

POSITIVE - Backward Compatibility Maintained

  • State migration handles legacy formats
  • Frontend WebSocket messages unchanged
  • Existing apps continue to work (phasic behavior is default)

Recommendations Summary

Must Fix (Before Merge)

  1. Remove all any type usage in stateMigration.ts:98 (violates project rules)

Should Fix (High Priority)

  1. Replace unsafe type casting in stateMigration.ts:159 with destructuring
  2. Add runtime validation for state structure in codingAgent.ts:119

Nice to Have (Low Priority)

  1. Extract duplicated type guards to shared utilities
  2. Standardize on type guards vs type assertions throughout codebase
  3. Add integration tests for state migration edge cases

Conclusion

This is a high-quality refactoring that achieves its architectural goals. The modular design enables future extensibility (workflows, presentations, CLI agents) while maintaining backward compatibility. The type safety violations are minor and easily fixed. Security practices are sound with no exploitable vulnerabilities found.

Approval Status: Approved pending type safety fixes. The violations are isolated to migration code and don't create runtime security risks, but should be corrected to maintain project standards.

…ess design

- Sandbox layer does not rely on templates now, instead expects raw files list
- Tools to init/list templates, files
- Templates can be chosen by agentic mode after creation
- Restructured system prompt with detailed architecture explanations covering virtual filesystem, sandbox environment, and deployment flow
- Better tool descriptions
- Improved communication guidelines and workflow steps for better agent reasoning and execution
- Replaced agent mode toggle with project mode selector (App/Slides/Chat) that determines behavior type
- Implemented agentic behavior detection for static content (docs, markdown) with automatic editor view
- Conditionally render PhaseTimeline and deployment controls based on behavior type (phasic vs agentic)

delete (migratedInferenceContext as any).userApiKeys;
// Remove the deprecated field using type assertion
const contextWithLegacyField = migratedInferenceContext as unknown as Record<string, unknown>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM: Unsafe Type Casting

Type assertion to Record<string, unknown> circumvents compile-time safety. While acceptable in migration code, safer alternatives exist.

Recommendation:

if (migratedInferenceContext && 'userApiKeys' in migratedInferenceContext) {
    // Use destructuring for safer field removal
    const { userApiKeys, ...rest } = migratedInferenceContext as InferenceContext & { userApiKeys?: unknown };
    migratedInferenceContext = rest;
    needsMigration = true;
}

This approach is more explicit and type-safe.

const projectType = props?.projectType ?? this.state.projectType ?? 'app';

if (behaviorType === 'phasic') {
this.behavior = new PhasicCodingBehavior(this as AgentInfrastructure<PhasicState>, projectType);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MEDIUM: Unvalidated Type Assertion

Casting to AgentInfrastructure<PhasicState> without runtime validation that the state structure matches could lead to runtime type mismatches.

Recommendation: Add runtime state structure validation:

if (behaviorType === 'phasic') {
    // Validate state has phasic-specific fields
    if (!('generatedPhases' in this.state) || !('currentDevState' in this.state)) {
        throw new Error('State structure does not match phasic behavior requirements');
    }
    this.behavior = new PhasicCodingBehavior(this as AgentInfrastructure<PhasicState>, projectType);
} else {
    // Similar validation for agentic state
    this.behavior = new AgenticCodingBehavior(this as AgentInfrastructure<AgenticState>, projectType);
}

This ensures the discriminated union's runtime state aligns with the compile-time type.

@github-actions
Copy link
Contributor

Code & Security Review

Recommendation: APPROVE WITH MINOR SUGGESTIONS

This is a well-architected refactoring that successfully modularizes a 2700+ line monolithic agent into clean behavior/objective patterns. The code quality is high, security practices are sound, and backward compatibility is properly maintained.


Code Quality Assessment

Architecture - EXCELLENT

  • Separation of Concerns: Clean split between "what to build" (objectives) and "how to build" (behaviors)
  • Extensibility: New project types can be added without modifying core logic
  • Backward Compatibility: State migration handles legacy formats properly
  • Type System: Well-designed discriminated unions (PhasicState | AgenticState)

Type Safety - 1 Minor Violation

MEDIUM: any type usage in stateMigration.ts:98

const getTimestamp = (msg: any) => {

This violates CLAUDE.md's strict "NEVER use any type" rule.

Fix:

const getTimestamp = (msg: ConversationMessage): number => {
    if (msg.conversationId && typeof msg.conversationId === 'string' && msg.conversationId.startsWith('conv-')) {
        const parts = msg.conversationId.split('-');
        if (parts.length >= 2) {
            return parseInt(parts[1]) || 0;
        }
    }
    return 0;
};

Note: This is existing code that predates this PR. While not introduced by this refactor, it should be fixed to maintain project standards.

DRY Compliance - GOOD

  • BaseCodingBehavior (1652 lines) effectively extracts common functionality
  • Operations properly shared between behaviors
  • File management, git operations, and deployment logic well abstracted
  • Type guards could be extracted to shared utilities (minor suggestion)

Security Analysis

SQL Injection - PASS

All database operations use parameterized queries via template literals. The Cloudflare Agents SDK properly sanitizes these.

Authentication & Authorization - PASS

  • Rate limiting enforced in CodingAgentController.startCodeGeneration
  • User authentication required via context.user\!
  • User ID properly validated and passed through inference context
  • No privilege escalation paths identified

Secrets Management - PASS

  • GitHub OAuth tokens cached in memory only (ephemeral, lost on DO eviction)
  • Token TTL properly implemented (default 1 hour)
  • No secrets persisted to state or database
  • Legacy userApiKeys field properly removed during migration

Input Validation - PASS

  • Query parameter validated (required field check)
  • Project type and behavior type validated with defaults
  • Commands sanitized before execution
  • No unsafe eval/Function usage detected

Access Control - PASS

  • Git tool safety maintained (conversation tools exclude dangerous commands)
  • Sandbox execution properly isolated
  • WebSocket origin validation exists

Testing & Migration Concerns

State Migration Logic - SOUND
The PR author correctly identified that the previous review comment about line 118 validation was inaccurate. The validation logic is correct - behavior is instantiated with resolved type, and state migration ensures consistency.

Migration Features:

  • Deduplicates conversation messages (fixes exponential bloat)
  • Removes internal memos from conversation history
  • Migrates templateDetailstemplateName
  • Migrates agentModebehaviorType
  • Removes deprecated userApiKeys from inference context
  • Generates missing projectName for legacy apps

Recommendations

Should Fix (Post-Merge)

  1. Replace any type in stateMigration.ts:98 with ConversationMessage
  2. Extract duplicated type guards to shared utilities

Nice to Have

  1. Add integration tests for state migration edge cases
  2. Document the behavior/objective pattern in architecture docs

Conclusion

This is a high-quality architectural refactoring that achieves its goals:

  • Successfully modularizes monolithic agent
  • Enables extensibility for new project types
  • Maintains backward compatibility
  • Follows security best practices
  • No exploitable vulnerabilities identified

The type safety violation is minor and exists in pre-existing code, not introduced by this PR.

Approval Status: ✅ Approved - This PR is ready to merge.

- Replaced manual template_manager tool with init_suitable_template that uses the original template selector ai
- Updated system prompts to emphasize template-first workflow for interactive projects with AI selector as mandatory first step
- Simplified template selection process by removing manual list/select commands in favor of intelligent matching
```
- Added conversation history support to AgenticProjectBuilder with message preparation and context tracking
- Implemented tool call completion callbacks to sync messages and trigger periodic compactification
- Modified AgenticCodingBehavior to queue user inputs during builds and inject them between tool call chains using abort mechanism
- Fix importTemplate to actually work
- Fixed template filtering logic to respect 'general' project type
- Added behaviorType to logger context for better debugging
- fixed not saving behaviorType to state
…ructor

- Moved behaviorType and projectType initialization from hardcoded values to constructor-based setup
- Changed initial state values to 'unknown' to ensure proper initialization through behavior constructor
- Cleared template details cache when importing new templates to prevent stale data
- Moved user input idle check from PhasicCodingBehavior to CodeGeneratorAgent for consistent behavior across all modes
- Fixed message order in agenticProjectBuilder to place history after user message instead of before
- Added replaceExisting parameter to addConversationMessage for better control over message updates
- Enhanced initial state restoration to include queued user messages and behaviorType
- Added status and queuePosition fields
- Single convo id needs to be broadcasted but messages need to be saved with unique ids.
- Fix message deduplication to use composite key (conversationId + role + tool_call_id)
- Improved tool message filtering to validate against parent assistant tool_calls
- Removed unused CodingAgentInterface stub file
- Simplified addConversationMessage interface by removing replaceExisting parameter
@github-actions
Copy link
Contributor

github-actions bot commented Nov 12, 2025

Claude encountered an error —— View job


I'll analyze this and get back to you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant