From 6d6cf1aacec061971f94cd0176e994606e83f8cf Mon Sep 17 00:00:00 2001 From: Brian Lopez Date: Tue, 30 Sep 2025 10:22:30 -0600 Subject: [PATCH] Add RESMARK-specific custom commands and workflows - Add MDD orchestration workflows (mdd-orchestrator, mdd-cycle) - Add RESMARK architectural guidance (resmark-architect, resmark-wrapper) - Add validation tools (anti-pattern-detector, resmark-validate-output) - Add knowledge graph tool (explain-knowledge) - Add RESMARK documentation (pilot plan, constraints, integration strategy) These custom commands support the RESMARK AI-powered modernization project. --- examples/resmark/PILOT_MIGRATION_PLAN.md | 157 +++++++++++ examples/resmark/RESMARK_CONSTRAINTS.md | 217 +++++++++++++++ .../resmark/RESMARK_INTEGRATION_STRATEGY.md | 143 ++++++++++ tools/anti-pattern-detector.md | 148 ++++++++++ tools/explain-knowledge.md | 163 +++++++++++ tools/resmark-validate-output.md | 244 ++++++++++++++++ workflows/mdd-cycle.md | 207 ++++++++++++++ workflows/mdd-orchestrator.md | 213 ++++++++++++++ workflows/resmark-architect.md | 125 +++++++++ workflows/resmark-wrapper.md | 263 ++++++++++++++++++ 10 files changed, 1880 insertions(+) create mode 100644 examples/resmark/PILOT_MIGRATION_PLAN.md create mode 100644 examples/resmark/RESMARK_CONSTRAINTS.md create mode 100644 examples/resmark/RESMARK_INTEGRATION_STRATEGY.md create mode 100644 tools/anti-pattern-detector.md create mode 100644 tools/explain-knowledge.md create mode 100644 tools/resmark-validate-output.md create mode 100644 workflows/mdd-cycle.md create mode 100644 workflows/mdd-orchestrator.md create mode 100644 workflows/resmark-architect.md create mode 100644 workflows/resmark-wrapper.md diff --git a/examples/resmark/PILOT_MIGRATION_PLAN.md b/examples/resmark/PILOT_MIGRATION_PLAN.md new file mode 100644 index 0000000..060acb8 --- /dev/null +++ b/examples/resmark/PILOT_MIGRATION_PLAN.md @@ -0,0 +1,157 @@ +# RESMARK Pilot Migration Plan - Reality Check + +## The Truth + +We need to acknowledge what we DON'T know: +- Our 5 RESMARK commands are **untested theories** +- The "empirically-discovered" patterns are **hypothetical** +- The MDD methodology is **unproven** +- We have **zero real migration data** + +## New Priority: Generate Real Data + +Stop building infrastructure. Start doing real migrations. + +## The Pilot Migration Approach + +### Step 1: Pick ONE Simple Component + +Choose the simplest possible Angular component from `resmark-nodejs/`: +- Ideally <100 lines +- Minimal dependencies +- Clear UI behavior +- Has some database interaction + +Example candidates: +- A simple search input +- A data table +- A form field +- A status indicator + +### Step 2: Manual Migration First + +Do the migration MANUALLY without any tools: +1. Read the Angular code +2. Write the React equivalent by hand +3. Document every decision made +4. Note every pattern encountered +5. Track time spent + +This gives us our baseline truth. + +### Step 3: Test Our Commands + +Now try using our commands: +1. Run `anti-pattern-detector.md` - Does it find real issues? +2. Run `explain-knowledge.md` - Is the knowledge useful? +3. Run `mdd-cycle.md` - Does the workflow make sense? + +Document: +- What worked +- What failed +- What was missing +- What was wrong + +### Step 4: Try Generic Tools + +Use the generic tools from the cloned repos: +1. Try `tools/code-migrate.md` +2. Try `tools/test-generator.md` +3. Try relevant agents + +Compare results with manual migration. + +### Step 5: Measure & Learn + +Create a simple scorecard: + +```markdown +## Migration Scorecard + +**Component**: [Name] +**Lines of Code**: [Count] + +### Manual Migration +- Time: [X hours] +- Issues encountered: [List] +- Patterns discovered: [List] + +### RESMARK Commands +- Useful? [Yes/No/Partial] +- Accuracy: [0-100%] +- Time saved: [Positive/Negative] +- Critical misses: [List] + +### Generic Tools +- Useful? [Yes/No/Partial] +- Better than RESMARK? [Yes/No] +- Integration potential: [High/Low] + +### Verdict +- Continue with current approach? [Yes/No] +- Pivots needed: [List] +``` + +## Success Criteria + +The pilot is successful if we learn: +1. Whether our anti-patterns actually occur +2. If the session patterns are real issues +3. Whether visual regression is truly needed +4. If our commands provide value + +## What We're NOT Doing + +- NOT building more infrastructure +- NOT creating elaborate validation layers +- NOT assuming our patterns are correct +- NOT treating commands as proven + +## Timeline + +Day 1: Manual migration of one component +Day 2: Test with RESMARK commands +Day 3: Test with generic tools +Day 4: Analysis and decision + +## Decision Points + +After the pilot: + +**If commands are useful (>60% accurate)**: +- Continue with simplified integration +- Fix identified issues +- Run second pilot + +**If commands are not useful (<40% accurate)**: +- Scrap current approach +- Focus on generic tools +- Rebuild from actual learnings + +**If mixed results (40-60%)**: +- Cherry-pick what worked +- Discard what didn't +- Iterate rapidly + +## The Real MDD Methodology + +Migration Driven Development should mean: +1. Try to migrate something +2. Learn from what breaks +3. Build tools to fix those specific breaks +4. Repeat + +Not: Build theoretical tools for imagined problems. + +## Next Immediate Action + +1. Open `resmark-nodejs/` +2. Find the simplest component +3. Start manual migration +4. Document everything + +Stop theorizing. Start migrating. + +--- + +*"In theory, theory and practice are the same. In practice, they are not." - Yogi Berra* \ No newline at end of file diff --git a/examples/resmark/RESMARK_CONSTRAINTS.md b/examples/resmark/RESMARK_CONSTRAINTS.md new file mode 100644 index 0000000..7c7cd2b --- /dev/null +++ b/examples/resmark/RESMARK_CONSTRAINTS.md @@ -0,0 +1,217 @@ +# RESMARK Constraints - Bedrock Principles + +This document contains the **non-negotiable, empirically-validated constraints** that MUST be enforced in ALL RESMARK code generation. These are not suggestions - they are laws derived from real migration attempts and documented failures. + +## Critical Directives (Severity: CRITICAL) + +Violation of ANY critical directive = immediate BLOCK. No exceptions. + +### 1. NO Mock Data in Services (directive-no-mock-data) +```javascript +// ❌ NEVER DO THIS - AI consistently generates this pattern +async getUsers() { + return [{ id: 1, name: 'Mock User' }]; // CRITICAL VIOLATION +} + +// ✅ ALWAYS DO THIS +async getUsers() { + return await this.userRepository.findByEntity(this.entityId); +} +``` +**Source**: Knowledge graph anti-patterns, documented in migration attempts +**Impact**: Integration failures, false test passes, production crashes + +### 2. Session Pattern Sacred (directive-session-pattern) +```javascript +// ❌ AI HALLUCINATIONS - These patterns DO NOT EXIST +req.user.businessEntities // DOES NOT EXIST +req.session.permissions // WRONG LOCATION +req.currentEntity // NOT IN LEGACY +req.user.entityId // INCORRECT PATH + +// ✅ ONLY VALID PATTERN - From legacy analysis +req.session.entityId // Current business entity +req.session.userAccessMap // Permissions mapping +req.session.businessEntityList // Available entities +``` +**Source**: Legacy codebase analysis in `/controllers/secure/index.js` +**Impact**: Complete authentication failure, security violations + +### 3. NO In-Memory Caching (directive-no-memory-cache) +```javascript +// ❌ MEMORY LEAK IN PRODUCTION +const rateLimitMap = new Map(); +const cache = {}; + +// ✅ PRODUCTION-READY +const rateLimitKey = `rate_limit_${entityId}_${userId}`; +await redis.setex(rateLimitKey, ttl, value); +``` +**Source**: Documented anti-pattern from migration failures +**Impact**: Memory leaks, server crashes, scaling failures + +### 4. NO Hardcoded Bypasses (directive-no-hardcoded-bypass) +```javascript +// ❌ SECURITY VULNERABILITY +if (entityId === 'test') { + return mockData; // NEVER DO THIS +} + +// ✅ USE FEATURE FLAGS +if (featureFlags['test_mode']) { + return testData; +} +``` +**Source**: Security audit findings +**Impact**: Security holes, production data exposure + +### 5. Legacy is Immutable (directive-legacy-immutable) +- `resmark-nodejs/` directory is READ-ONLY +- NEVER modify legacy code +- Use as reference only +**Source**: CLAUDE.md master directive +**Impact**: Breaking source of truth, losing business logic + +### 6. Visual Regression Required (directive-visual-regression) +- Every UI component MUST have visual tests +- Existing test suite lacks visual coverage +- Capture Angular baseline BEFORE migration +**Source**: CLAUDE.md September 2025 discovery - "17,800 existing tests provide 0% visual regression coverage" +**Impact**: UI regressions, broken user experience + +### 7. Ephemeral Sandboxes Only (directive-ephemeral-sandbox) +- AI NEVER writes directly to main branches +- All generation in isolated Docker environments +- Sandbox destroyed on failure +**Source**: WORKSPACE_SETUP_TASKS.md architectural decision +**Impact**: Repository contamination, broken builds + +### 8. Feature Flags Required (directive-feature-flags) +- Every AI-generated feature wrapped in flag +- Enables instant rollback without deployment +```javascript +// ✅ REQUIRED PATTERN +if (featureFlags['ai_search_enabled']) { + return +} else { + return +} +``` +**Source**: CLAUDE.md critical directives +**Impact**: No rollback capability, production outages + +### 9. Validation Gauntlet Mandatory (directive-validation-gauntlet) +All code MUST pass 7 stages: +1. Pre-generation intent +2. Anti-pattern detection +3. Static analysis +4. Unit testing (80% minimum) +5. Integration testing +6. Visual regression +7. Security scan +**Source**: WORKSPACE_SETUP_TASKS.md validation gates +**Impact**: Unvalidated code in production + +## High-Priority Patterns (Severity: HIGH) + +### Session Bridge Pattern (pattern-session-bridge) +```javascript +// Backend: SessionService handles complexity +const session = await SessionService.reconstructSession(email, entityId); +req.session.entityId = session.entityId; + +// Frontend: Simple consumption via hook +const { entityId, permissions, hasPermission } = useSession(); +``` +**Source**: Documented in knowledge graph patterns + +### Database Connection Pattern (pattern-database-connection) +```javascript +// Always use connection pool +const result = await this.db + .collection('users') + .find({ entityId: req.session.entityId }) + .toArray(); +``` +**Source**: Migration best practices + +### Error Boundary Pattern (pattern-error-boundary) +```javascript +// Every React component tree needs protection +}> + + +``` +**Source**: Anti-pattern detection - missing error boundaries + +## Performance Targets + +These are requirements from CLAUDE.md: + +- **Session Query**: <50ms target +- **Component Load**: <200ms target +- **API Response**: <100ms target +- **Visual Diff**: <5% threshold +- **Test Coverage**: >80% minimum + +## Anti-Pattern Detection Rules + +### Critical Anti-Patterns (Instant BLOCK) +1. `return [{` in service files → Mock data +2. `req.user.` anywhere → Wrong session pattern +3. `new Map()` for caching → Memory leak +4. `=== 'test'` → Hardcoded bypass + +### High Anti-Patterns (Fix Required) +5. Complex TypeScript in discovery phase +6. Missing visual tests for components +7. Direct writes to main/develop branches +8. `process.env.X || 'default'` → Unsafe defaults + +### Medium Anti-Patterns (Warnings) +9. `// TODO` or `// FIXME` markers +10. Mixed async/sync patterns +11. Missing error boundaries +12. `SELECT * FROM` queries + +## Injection Instructions + +When this document is injected into ANY command or agent: + +1. **Prepend to system prompt**: "You MUST adhere to ALL RESMARK Constraints. These are non-negotiable." +2. **Add validation step**: "Before returning code, verify against RESMARK Constraints" +3. **Include in instructions**: "Run resmark-validate-output on all generated code" + +## Evidence Base + +These constraints are derived from: +- **Knowledge Graph**: `.claude/knowledge-graph/entities/` containing documented patterns and anti-patterns +- **Project Documentation**: CLAUDE.md master directives and discovered failures +- **Legacy Analysis**: Actual session patterns from `resmark-nodejs/controllers/secure/index.js` +- **Meeting Notes**: `2025-08-13_ai_validation_pivot.md` defining R&D model +- **Empirical Discovery**: Anti-patterns documented through actual migration attempts + +Key documented findings: +- AI consistently generates mock data in service layers (documented in anti-patterns) +- AI frequently hallucinates incorrect session patterns (documented in directives) +- Visual regression gap discovered in September 2025 analysis +- MDD methodology proven through iterative discovery + +## Enforcement + +1. **Every code generation** must validate against these constraints +2. **No exceptions** for "simple" or "quick" tasks +3. **Violations block PR** creation +4. **Results attached to PRs** for audit trail + +## Updates + +When new patterns are discovered: +1. Add to this document with evidence +2. Update `resmark-validate-output.md` +3. Notify all commands via resmark-wrapper +4. Re-validate recent code + +--- + +**Remember**: These constraints are NOT optional. They are the difference between success and failure in the RESMARK modernization project. \ No newline at end of file diff --git a/examples/resmark/RESMARK_INTEGRATION_STRATEGY.md b/examples/resmark/RESMARK_INTEGRATION_STRATEGY.md new file mode 100644 index 0000000..9ffcb23 --- /dev/null +++ b/examples/resmark/RESMARK_INTEGRATION_STRATEGY.md @@ -0,0 +1,143 @@ +# RESMARK Commands Integration Strategy + +## Decision: Hybrid Composition-Based Approach + +After consulting with Gemini, we're adopting a **composition over inheritance** strategy to avoid maintenance hell while ensuring RESMARK patterns are enforced. + +## Architecture + +``` +.claude/commands/ +├── resmark-core/ # RESMARK-specific commands (existing 5) +│ ├── anti-pattern-detector.md +│ ├── explain-knowledge.md +│ ├── mdd-cycle.md +│ ├── mdd-orchestrator.md +│ └── resmark-architect.md +│ +├── resmark-enhanced/ # New RESMARK-specific commands +│ ├── resmark-validate-output.md # Critical validation layer +│ ├── resmark-component-migrate.md # Composite workflows +│ ├── resmark-api-modernize.md +│ └── resmark-test-suite.md +│ +├── tools/ # Original generic tools (unchanged) +├── workflows/ # Original workflows (unchanged) +├── agents/ # Original agents (unchanged) +│ +└── resmark-engine/ # The orchestration layer + ├── RESMARK_CONSTRAINTS.md # All critical directives + ├── resmark-wrapper.md # Dynamic injection system + └── validation-hooks.md # Anti-pattern checks + +``` + +## Implementation Plan + +### Phase 1: Build the RESMARK Engine (Priority 1) + +1. **Create `resmark-validate-output.md`** + - Non-AI validation command + - Checks for all 12 anti-patterns + - Enforces critical directives + - Triggers visual regression tests + - MUST be final step in every workflow + +2. **Create `RESMARK_CONSTRAINTS.md`** + - Consolidated list of all critical directives + - Anti-pattern definitions with examples + - Performance targets + - Session management patterns + +3. **Create `resmark-wrapper.md`** + - Dynamically injects RESMARK constraints into any command + - Routes requests to appropriate tools + - Enforces validation after code generation + +### Phase 2: Create RESMARK-Enhanced Commands + +Only create RESMARK-specific versions when absolutely necessary: + +1. **`resmark-component-migrate.md`** + - Orchestrates: mdd-cycle + code-migrate + visual validation + - Hard-coded Angular→React patterns + - Mandatory visual regression + +2. **`resmark-api-modernize.md`** + - Wraps: api-scaffold with SessionService patterns + - Enforces Redis caching + - Prevents in-memory Maps + +3. **`resmark-test-suite.md`** + - Extends: test-generator with visual requirements + - 80% coverage minimum + - Session pattern testing + +### Phase 3: Update Core RESMARK Commands + +Modify existing RESMARK commands to use the wrapper: + +```yaml +mdd-cycle.md: + discovery: + - run: resmark-wrapper tools/code-explain + - run: resmark-wrapper tools/dependency-analyzer + implementation: + - run: resmark-wrapper tools/api-scaffold + - run: resmark-validate-output # MANDATORY +``` + +## Key Principles + +### 1. Composition Over Inheritance +- Don't fork entire repositories +- Wrap and extend instead of modifying +- Keep generic tools generic + +### 2. Validation as Law +- Every code generation MUST pass `resmark-validate-output` +- Validation is non-negotiable, non-AI, deterministic +- Failures block progression completely + +### 3. Dynamic Injection +- RESMARK constraints injected at runtime +- No modification of original tool files +- Easy to update constraints centrally + +### 4. Selective Override +- Only create RESMARK versions when generic fails +- Document why override was necessary +- Maintain minimal custom surface area + +## Benefits + +1. **Low Maintenance**: Original tools update via simple git pull +2. **Clear Separation**: RESMARK logic isolated in engine +3. **Guaranteed Compliance**: Validation layer ensures patterns +4. **Sustainable**: Scales without exponential complexity +5. **Contribution-Ready**: Can share improvements upstream + +## Anti-Patterns to Avoid + +1. **Don't Fork Everything**: Massive maintenance overhead +2. **Don't Trust AI Alone**: Always validate with deterministic checks +3. **Don't Modify Originals**: Keep them pristine for updates +4. **Don't Skip Validation**: Even for "simple" changes + +## Success Metrics + +- Zero anti-patterns in generated code +- 100% validation pass rate before human review +- <5 custom tool overrides needed +- Single-command updates for constraint changes + +## Next Steps + +1. Build `resmark-validate-output.md` immediately +2. Create `RESMARK_CONSTRAINTS.md` with all directives +3. Test with single component migration +4. Iterate based on results + +--- + +*This strategy balances control with maintainability, ensuring RESMARK patterns are enforced without creating an unmaintainable fork.* \ No newline at end of file diff --git a/tools/anti-pattern-detector.md b/tools/anti-pattern-detector.md new file mode 100644 index 0000000..9f10aff --- /dev/null +++ b/tools/anti-pattern-detector.md @@ -0,0 +1,148 @@ +# RESMARK Anti-Pattern Detector + +Detect known anti-patterns in code based on empirically discovered failures: $ARGUMENTS + +[Extended thinking: This tool queries the RESMARK knowledge graph for all known anti-patterns and validates code against them. These patterns were discovered through real migration failures and cause production issues.] + +## Detection Process + +Use Task tool with subagent_type="code-reviewer" + +Prompt: "Perform comprehensive anti-pattern detection on: $ARGUMENTS + +## CRITICAL Anti-Patterns to Detect (Severity: CRITICAL) + +### 1. Direct Database Mock (antipattern-direct-database-mock) +Search for patterns like: +- `return [{ id: 1, name: 'Mock User' }]` in service methods +- Hardcoded arrays/objects returned from data access layers +- Test data embedded in production code +Impact: Integration failures, false confidence + +### 2. Wrong Session Pattern (antipattern-wrong-session-pattern) +Search for AI hallucinations: +- `req.user.businessEntities` (doesn't exist!) +- `req.session.permissions` (wrong location) +- `req.currentEntity` (not in legacy) +- Any pattern except `req.session.entityId` +Impact: Complete auth failure, security violations + +### 3. In-Memory Map Caching (antipattern-memory-map-cache) +Search for: +- `new Map()` used for caching +- Plain objects used as caches without TTL +- Rate limiting without Redis +- Any cache without automatic expiration +Impact: Memory leaks, scaling failures + +### 4. Hardcoded Test Bypasses (antipattern-hardcoded-test-bypass) +Search for: +- `if (entityId === 'test')` +- Special cases for specific entity IDs +- Hardcoded development bypasses +- Mock data returns based on entity +Impact: Security vulnerabilities + +## HIGH Severity Anti-Patterns + +### 5. TypeScript Complexity Trap (antipattern-typescript-complexity-trap) +Check for: +- Complex type definitions in discovery phase +- Over-engineered generics before requirements clear +- Type gymnastics blocking progress +Recommendation: Use JavaScript first, TypeScript after validation + +### 6. Missing Visual Validation (antipattern-missing-visual-validation) +Check for: +- Components without visual regression tests +- Missing Playwright visual comparisons +- No baseline screenshots referenced +Impact: UI regressions, UX degradation + +### 7. Direct Git Contamination (antipattern-direct-git-contamination) +Check for: +- Direct writes to main/develop branches +- Missing sandbox isolation +- Commits of unvalidated code +Impact: Repository pollution + +### 8. Unvalidated Environment Access (antipattern-unvalidated-environment-access) +Search for: +- Direct `process.env.X` without defaults +- Missing environment validation +- No error handling for missing vars +Impact: Runtime failures + +## MEDIUM Severity Anti-Patterns + +### 9. Incomplete Implementation (antipattern-incomplete-implementation) +Search for: +- `// TODO` comments +- `throw new Error('Not implemented')` +- `// FIXME` markers +- Empty function bodies +Impact: False positive tests + +### 10. Synchronous/Asynchronous Mixing (antipattern-synchronous-async-mixing) +Check for: +- Missing `await` keywords +- Callbacks mixed with promises +- `.then()` chains with async/await +Impact: Race conditions + +### 11. Missing Error Boundaries (antipattern-missing-error-boundaries) +Check React components for: +- No error boundary wrapper +- Missing componentDidCatch/ErrorBoundary +- No fallback UI for errors +Impact: Full app crashes + +## Analysis Output Format + +For each detected anti-pattern, provide: +1. **Location**: File path and line numbers +2. **Severity**: CRITICAL/HIGH/MEDIUM +3. **Pattern ID**: Reference to knowledge graph entity +4. **Impact**: What will break in production +5. **Fix**: Specific correction needed +6. **Example**: Show the correct pattern + +## Validation Rules + +Apply these rules from .claude/knowledge-graph/entities/anti-patterns/: +- All patterns in known-anti-patterns.yaml +- Check frequency statistics (e.g., 'AI generates in 60% of attempts') +- Reference empirical evidence from migrations + +## Integration with Validation Gauntlet + +This detection runs as Stage 2 of the 7-stage validation pipeline. +If any CRITICAL anti-pattern is found, block progression immediately. +HIGH severity patterns require fix before human review. +MEDIUM severity patterns generate warnings. + +## Continuous Learning + +If new anti-patterns are discovered: +1. Document the pattern with evidence +2. Add to knowledge graph +3. Update this detector +4. Notify all agents + +Target code for scanning: $ARGUMENTS" + +## Response Format + +Return structured results: +```yaml +scan_results: + critical_violations: [] + high_violations: [] + medium_violations: [] + warnings: [] + patterns_checked: 11 + files_scanned: X + recommendation: BLOCK|FIX|PROCEED +``` + +Code/directory to analyze: $ARGUMENTS \ No newline at end of file diff --git a/tools/explain-knowledge.md b/tools/explain-knowledge.md new file mode 100644 index 0000000..df0d4bb --- /dev/null +++ b/tools/explain-knowledge.md @@ -0,0 +1,163 @@ +# Explain RESMARK Knowledge + +Query and explain knowledge from the RESMARK knowledge graph: $ARGUMENTS + +[Extended thinking: This tool provides human-friendly access to the structured knowledge graph, transforming YAML entities and relations into readable documentation.] + +## Query Processing + +Parse the request to determine query type: +- Entity lookup: `/explain ` +- Pattern search: `/explain patterns for ` +- Anti-pattern search: `/explain anti-patterns for ` +- Workflow explanation: `/explain workflow ` +- Directive lookup: `/explain directive ` +- Relation query: `/explain what implements ` + +## Knowledge Sources + +Search these locations in order: +1. `.claude/knowledge-graph/entities/directives/` +2. `.claude/knowledge-graph/entities/patterns/` +3. `.claude/knowledge-graph/entities/anti-patterns/` +4. `.claude/knowledge-graph/entities/workflows/` +5. `.claude/knowledge-graph/relations/` + +## Output Format + +### For Entity Queries + +**[Entity Type]: {{TITLE}}** + +**ID**: `{{ENTITY_ID}}` +**Severity/Status**: {{IF_APPLICABLE}} +**Source**: {{SOURCE_MEMORY_FILE}} + +**Description**: +{{FULL_DESCRIPTION}} + +**Key Points**: +- {{IMPORTANT_POINT_1}} +- {{IMPORTANT_POINT_2}} +- {{IMPORTANT_POINT_3}} + +**Example** (if applicable): +```{{LANGUAGE}} +{{CODE_EXAMPLE}} +``` + +**Related Entities**: +- {{RELATION_TYPE}}: {{RELATED_ENTITY}} +- {{RELATION_TYPE}}: {{RELATED_ENTITY}} + +**Evidence/Metrics**: +- {{EMPIRICAL_EVIDENCE}} +- {{PERFORMANCE_METRICS}} + +--- + +### For Pattern Queries + +**Validated Patterns for {{TOPIC}}** + +Found {{COUNT}} relevant patterns: + +1. **{{PATTERN_NAME}}** (`{{PATTERN_ID}}`) + - Status: {{VALIDATED|EXPERIMENTAL}} + - Benefits: {{KEY_BENEFIT}} + - Usage: {{WHEN_TO_USE}} + +2. **{{PATTERN_NAME}}** (`{{PATTERN_ID}}`) + - Status: {{VALIDATED|EXPERIMENTAL}} + - Benefits: {{KEY_BENEFIT}} + - Usage: {{WHEN_TO_USE}} + +View details: `/explain {{PATTERN_ID}}` + +--- + +### For Workflow Queries + +**Workflow: {{WORKFLOW_TITLE}}** + +**Purpose**: {{WORKFLOW_DESCRIPTION}} + +**Phases**: +1. **{{PHASE_NAME}}** + - {{PHASE_DESCRIPTION}} + - Steps: {{STEP_COUNT}} + - Key outputs: {{OUTPUTS}} + +2. **{{PHASE_NAME}}** + - {{PHASE_DESCRIPTION}} + - Steps: {{STEP_COUNT}} + - Key outputs: {{OUTPUTS}} + +**Required Agents**: +- {{AGENT_TYPE}}: {{AGENT_PURPOSE}} +- {{AGENT_TYPE}}: {{AGENT_PURPOSE}} + +**Implements Patterns**: +- {{PATTERN_NAME}}: {{HOW_USED}} + +**Avoids Anti-Patterns**: +- {{ANTIPATTERN_NAME}}: {{HOW_AVOIDED}} + +**Performance**: {{METRICS}} + +**Trigger**: `/workflows:resmark/{{WORKFLOW_FILE}}` + +--- + +### For Relation Queries + +**Entities that {{RELATION_TYPE}} {{TARGET_ENTITY}}** + +Found {{COUNT}} relations: + +1. **{{ENTITY_ID}}** ({{ENTITY_TYPE}}) + - Relation: {{RELATION_TYPE}} + - Description: {{RELATION_DESCRIPTION}} + +2. **{{ENTITY_ID}}** ({{ENTITY_TYPE}}) + - Relation: {{RELATION_TYPE}} + - Description: {{RELATION_DESCRIPTION}} + +--- + +## Interactive Features + +After displaying results, offer these options: + +**Related Queries**: +- `/explain related to {{ENTITY_ID}}` +- `/explain what uses {{ENTITY_ID}}` +- `/explain what avoids {{ENTITY_ID}}` +- `/show code for {{PATTERN_ID}}` + +**Actions**: +- `/validate against {{DIRECTIVE_ID}}` +- `/apply pattern {{PATTERN_ID}}` +- `/run workflow {{WORKFLOW_ID}}` + +## Knowledge Graph Statistics + +At the end of each query, show: +``` +Knowledge Graph Stats: +- Directives: 10 (9 CRITICAL, 1 WARNING) +- Patterns: 10 (all VALIDATED) +- Anti-Patterns: 12 (4 CRITICAL, 4 HIGH, 4 MEDIUM) +- Workflows: 6 +- Relations: 50+ +``` + +## Learning Integration + +If the query reveals a knowledge gap: +1. Note the missing information +2. Suggest creating a new entity +3. Provide template for addition +4. Mark for human review + +Query to explain: $ARGUMENTS \ No newline at end of file diff --git a/tools/resmark-validate-output.md b/tools/resmark-validate-output.md new file mode 100644 index 0000000..5265878 --- /dev/null +++ b/tools/resmark-validate-output.md @@ -0,0 +1,244 @@ +# RESMARK Validate Output + +Deterministic validation of generated code against RESMARK critical directives and anti-patterns. + +**CRITICAL**: This is NOT an AI tool. This is a deterministic validation script that MUST be the final step in every code generation workflow. + +## Usage + +Validate generated code: $ARGUMENTS (file path or directory) + +## Validation Process + +Execute these checks in order. Fail fast on any violation. + +### Stage 1: Anti-Pattern Detection (CRITICAL) + +Check for all 12 empirically-discovered anti-patterns: + +```bash +# 1. Direct Database Mock (CRITICAL) +grep -r "return \[{.*id.*:.*1.*,.*name.*:.*Mock" $ARGUMENTS +grep -r "return \[{.*id.*:.*'test'" $ARGUMENTS +grep -r "mockData\s*=\s*\[" $ARGUMENTS +# FAIL if found: "CRITICAL: Mock data in service layer detected" + +# 2. Wrong Session Pattern (CRITICAL) +grep -r "req\.user\.businessEntities" $ARGUMENTS +grep -r "req\.session\.permissions" $ARGUMENTS +grep -r "req\.currentEntity" $ARGUMENTS +grep -r "req\.user\.entityId" $ARGUMENTS +# FAIL if found: "CRITICAL: Invalid session pattern - MUST use req.session.entityId" + +# 3. In-Memory Map Caching (CRITICAL) +grep -r "new Map()" $ARGUMENTS +grep -r "const.*cache.*=.*{}" $ARGUMENTS +grep -r "rateLimitMap\s*=\s*new Map" $ARGUMENTS +# FAIL if found: "CRITICAL: In-memory caching detected - MUST use Redis" + +# 4. Hardcoded Test Bypasses (CRITICAL) +grep -r "if.*entityId.*===.*'test'" $ARGUMENTS +grep -r "entityId.*==.*'test'" $ARGUMENTS +grep -r "// TODO.*remove.*production" $ARGUMENTS +# FAIL if found: "CRITICAL: Hardcoded test bypass detected" + +# 5. TypeScript Complexity Trap (HIGH) +# Check for overly complex type definitions in early phase files +grep -r "type.*=.*{.*{.*{.*{" $ARGUMENTS +grep -r "interface.*extends.*,.*extends" $ARGUMENTS +# WARN if found: "HIGH: Complex TypeScript detected in discovery phase" + +# 6. Missing Visual Validation (HIGH) +# For React components, check for visual test files +if grep -q "export.*function.*component\|export.*const.*=.*React" $ARGUMENTS; then + component_name=$(basename $ARGUMENTS .tsx) + if ! test -f "tests/visual/${component_name}.spec.ts"; then + echo "HIGH: Missing visual regression test for component" + fi +fi + +# 7. Direct Git Contamination (HIGH) +# Check if code is being written directly to main branches +current_branch=$(git branch --show-current) +if [[ "$current_branch" == "main" || "$current_branch" == "develop" ]]; then + echo "HIGH: Direct writes to protected branch detected" +fi + +# 8. Unvalidated Environment Access (HIGH) +grep -r "process\.env\.[A-Z_]*\s*\|\|" $ARGUMENTS +grep -r "process\.env\.[A-Z_]*\s*\?\?" $ARGUMENTS +# WARN if found: "HIGH: Environment variables with fallback values" + +# 9. Incomplete Implementation (MEDIUM) +grep -r "// TODO" $ARGUMENTS +grep -r "throw new Error.*Not implemented" $ARGUMENTS +grep -r "// FIXME" $ARGUMENTS +# WARN if found: "MEDIUM: Incomplete implementation markers" + +# 10. Synchronous/Asynchronous Mixing (MEDIUM) +# Check for missing await keywords (heuristic) +grep -r "\.then.*async" $ARGUMENTS +grep -r "async.*{.*[^await].*\.(find\|save\|create\|update\|delete)(" $ARGUMENTS +# WARN if found: "MEDIUM: Potential async/sync mixing" + +# 11. Missing Error Boundaries (MEDIUM) +# For React components +if grep -q "export.*function.*component\|export.*const.*=.*React" $ARGUMENTS; then + if ! grep -q "ErrorBoundary\|componentDidCatch\|error.*boundary" $ARGUMENTS; then + echo "MEDIUM: React component missing error boundary" + fi +fi + +# 12. Security Vulnerabilities (CRITICAL) +grep -r "eval(" $ARGUMENTS +grep -r "innerHTML\s*=" $ARGUMENTS +grep -r "dangerouslySetInnerHTML" $ARGUMENTS # Except with proper sanitization +# FAIL if found: "CRITICAL: Potential security vulnerability" +``` + +### Stage 2: Required Pattern Enforcement + +Ensure critical patterns ARE present: + +```bash +# Check for proper session handling +if grep -q "router\.\|app\.\|api\." $ARGUMENTS; then + if ! grep -q "req\.session\.entityId" $ARGUMENTS; then + echo "CRITICAL: API endpoint missing req.session.entityId check" + exit 1 + fi +fi + +# Check for Redis caching if any caching is implemented +if grep -q "cache\|Cache" $ARGUMENTS; then + if ! grep -q "redis\|Redis" $ARGUMENTS; then + echo "CRITICAL: Caching implementation must use Redis" + exit 1 + fi +fi + +# Check for feature flags in new components +if grep -q "export.*function.*component\|export.*const.*=.*React" $ARGUMENTS; then + if ! grep -q "featureFlags\|feature-flag" $ARGUMENTS; then + echo "WARNING: Component should be wrapped in feature flag" + fi +fi + +# Check for SessionService usage in services +if [[ $ARGUMENTS == *"service"* ]]; then + if ! grep -q "SessionService\|sessionService" $ARGUMENTS; then + echo "HIGH: Service should use SessionService for auth" + fi +fi +``` + +### Stage 3: Performance Validation + +```bash +# Check for performance anti-patterns +grep -r "SELECT \* FROM" $ARGUMENTS # Should specify columns +grep -r "forEach.*await" $ARGUMENTS # Should use Promise.all +grep -r "JSON\.parse.*JSON\.stringify" $ARGUMENTS # Deep clone anti-pattern +``` + +### Stage 4: Test Coverage Check + +```bash +# For any new code file, check for corresponding test +for file in $(find $ARGUMENTS -name "*.ts" -o -name "*.tsx" | grep -v ".test."); do + test_file="${file%.*}.test.${file##*.}" + if [ ! -f "$test_file" ]; then + echo "WARNING: Missing test file for $file" + fi +done +``` + +### Stage 5: Visual Regression Trigger + +For React components, automatically trigger visual regression: + +```bash +if grep -q "export.*function.*component\|export.*const.*=.*React" $ARGUMENTS; then + component_file=$ARGUMENTS + component_name=$(basename $component_file .tsx) + + # Check if baseline exists + baseline="tests/visual/baselines/angular/${component_name}.png" + if [ -f "$baseline" ]; then + echo "Triggering visual regression test for $component_name" + npm run test:visual -- --component=$component_name + else + echo "WARNING: No Angular baseline for visual regression" + fi +fi +``` + +## Output Format + +Return structured validation report: + +```yaml +validation_result: + status: PASS | FAIL | WARNING + + critical_violations: + - type: "direct-database-mock" + location: "services/user.service.ts:45" + message: "Mock data in service layer" + + high_severity: + - type: "missing-visual-test" + component: "SearchInput" + message: "No visual regression test" + + medium_severity: + - type: "incomplete-implementation" + location: "api/routes.ts:23" + message: "TODO marker found" + + warnings: + - type: "performance" + location: "services/data.ts:67" + message: "SELECT * should specify columns" + + required_patterns: + session_handling: ✓ + redis_caching: ✓ + feature_flags: ✗ + + metrics: + files_scanned: 12 + anti_patterns_checked: 12 + patterns_validated: 4 + + recommendation: + BLOCK: "Critical violations must be fixed" + | FIX: "High severity issues should be addressed" + | PROCEED: "Code meets RESMARK standards" +``` + +## Integration Requirements + +This command MUST be called: +1. After every code generation +2. Before any PR creation +3. As part of CI/CD pipeline +4. Before human review + +## Non-Negotiable Rules + +1. **ANY critical violation = BLOCK progression** +2. **3+ high severity = BLOCK progression** +3. **Visual regression required for ALL UI components** +4. **No bypassing or skipping validation** +5. **Results must be attached to PRs** + +## Continuous Improvement + +When new anti-patterns are discovered: +1. Add detection rule to this validator +2. Update knowledge graph +3. Notify all RESMARK commands +4. Re-validate recent code + +Target to validate: $ARGUMENTS \ No newline at end of file diff --git a/workflows/mdd-cycle.md b/workflows/mdd-cycle.md new file mode 100644 index 0000000..4fdba19 --- /dev/null +++ b/workflows/mdd-cycle.md @@ -0,0 +1,207 @@ +--- +model: claude-opus-4-1 +--- + +# MDD Component Migration Cycle + +Execute complete Migration Driven Development cycle for: $ARGUMENTS + +[Extended thinking: This workflow implements the empirically-validated MDD methodology, incorporating all discovered patterns and avoiding all known anti-patterns from the RESMARK knowledge graph.] + +## Pre-Flight Checks + +Before starting, query the knowledge graph for: +- All CRITICAL directives that APPLY_TO component-migration +- All patterns that IMPLEMENT component-migration +- All anti-patterns with severity CRITICAL or HIGH + +## Phase 1: Discovery & Analysis + +### 1. Legacy Component Analysis +Use Task tool with subagent_type="legacy-modernizer" + +Prompt: "Analyze legacy component: $ARGUMENTS +Focus on: +- Session management patterns (MUST use req.session.entityId) +- Database queries (identify all MongoDB operations) +- Business logic and validation rules +- UI states and user interactions +- Permission and multi-tenant requirements + +Reference: resmark-nodejs/ directory (read-only) +Output: Complete requirements document with no assumptions" + +### 2. Visual Baseline Capture +Use Task tool with subagent_type="ui-visual-validator" + +Prompt: "Capture comprehensive visual baselines for: $ARGUMENTS +Requirements: +- All component states (default, loading, error, empty) +- Mobile and desktop viewports +- Different data scenarios +- Interaction states (hover, focus, active) + +Store in: app/frontend/tests/visual/baselines/angular/ +Output: Screenshot inventory with selectors" + +### 3. Pattern Identification +Use Task tool with subagent_type="code-reviewer" + +Prompt: "Identify applicable patterns and risks for migrating: $ARGUMENTS +Check knowledge graph for: +- Validated patterns that apply to this component type +- Anti-patterns commonly found in similar migrations +- Performance benchmarks from previous migrations +- Security considerations + +Reference: .claude/knowledge-graph/ +Output: Pattern applicability matrix" + +## Phase 2: Implementation + +### 4. Sandbox Environment Setup +Use Task tool with subagent_type="devops-troubleshooter" + +Prompt: "Create ephemeral sandbox for: $ARGUMENTS +Requirements: +- Isolated Docker container +- Temporary git branch (will be destroyed on failure) +- Copy only required files (optimize for <1 second setup) +- MongoDB and Redis connections configured + +Implementation: ai-workflow/sandbox-manager.js +Output: Sandbox ID and connection details" + +### 5. Component Generation with Constraints +Use Task tool with subagent_type="frontend-developer" + +Prompt: "Generate React component for: $ARGUMENTS + +CRITICAL CONSTRAINTS (from knowledge graph): +- NEVER use mock data in services (directive-no-mock-data) +- ALWAYS use SessionService for auth (pattern-session-bridge) +- Must include error boundaries (antipattern-missing-error-boundaries) +- Use req.session.entityId ONLY (directive-session-pattern) +- No in-memory caching - Redis only (directive-no-memory-cache) +- Include feature flag wrapper (directive-feature-flags) + +Required files: +- Component.tsx (main component) +- Component.test.tsx (>80% coverage) +- Component.stories.tsx (Storybook) +- useComponentData.ts (data hook if needed) + +Use validation feedback loop pattern - iterate up to 5 times based on validation results." + +### 6. Validation Gauntlet Execution +Use Task tool with subagent_type="code-reviewer" + +Prompt: "Execute 7-stage validation for: $ARGUMENTS + +Stage 1: Pre-generation intent verification +Stage 2: Anti-pattern detection (check all from knowledge graph) +Stage 3: Static analysis (TypeScript, ESLint) +Stage 4: Unit testing (minimum 80% coverage) +Stage 5: Integration testing (real MongoDB/Redis) +Stage 6: Visual regression (<5% difference threshold) +Stage 7: Security scan (no exposed secrets, XSS prevention) + +If any stage fails, generate specific feedback for next iteration. +Maximum 5 iterations before human intervention required. + +Output: Validation report with pass/fail per stage" + +## Phase 3: Verification + +### 7. Visual Comparison Analysis +Use Task tool with subagent_type="ui-visual-validator" + +Prompt: "Perform detailed visual comparison for: $ARGUMENTS +- Compare React component against Angular baseline +- Generate diff images highlighting changes +- Calculate similarity percentage +- Flag any differences >5% +- Check responsive behavior + +Output: Visual regression report with screenshots" + +### 8. Integration Testing +Use Task tool with subagent_type="test-automator" + +Prompt: "Execute comprehensive integration tests for: $ARGUMENTS +Requirements: +- Test with production MongoDB connection +- Verify session bridge functionality +- Check all API endpoints used +- Validate multi-tenant isolation +- Test error scenarios +- Verify feature flag toggling + +Output: Integration test results with performance metrics" + +## Phase 4: Promotion or Rollback + +### 9. Success Path - Create PR +If validation passed, use Task tool with subagent_type="deployment-engineer" + +Prompt: "Create pull request for validated component: $ARGUMENTS +Include in PR: +- Validation gauntlet results (all 7 stages) +- Visual regression comparisons +- Performance benchmarks vs Angular +- Patterns discovered/confirmed +- Any new anti-patterns identified +- Feature flag configuration + +Cleanup sandbox environment after PR creation." + +### 10. Failure Path - Cleanup +If validation failed after 5 iterations: + +Use Task tool with subagent_type="devops-troubleshooter" + +Prompt: "Clean up failed migration attempt for: $ARGUMENTS +- Destroy sandbox environment completely +- Remove temporary branches +- Document failure reasons +- Identify new anti-patterns +- Suggest approach modifications + +Output: Failure analysis report for knowledge graph update" + +## Phase 5: Knowledge Evolution + +### 11. Pattern Discovery & Documentation +Use Task tool with subagent_type="docs-architect" + +Prompt: "Document patterns discovered during migration of: $ARGUMENTS +- New patterns that led to success +- Anti-patterns that caused failures +- Performance optimizations found +- Unexpected dependencies discovered + +Update: .claude/knowledge-graph/entities/ +Format: YAML entities with relations" + +### 12. Knowledge Graph Update +Use Task tool with subagent_type="context-manager" + +Prompt: "Update knowledge graph with learnings from: $ARGUMENTS +- Add new Pattern entities if unique +- Update AntiPattern severity if needed +- Create new relations discovered +- Update performance benchmarks +- Record session context for future reference + +Ensure all agents are notified of updates." + +## Coordination Notes + +- Sandbox isolation is CRITICAL - no direct repository writes +- Validation gauntlet is mandatory - no skipping stages +- Visual regression against Angular is required +- Session patterns must exactly match legacy +- Feature flags enable instant rollback +- Every discovery updates the knowledge graph + +Component to migrate: $ARGUMENTS \ No newline at end of file diff --git a/workflows/mdd-orchestrator.md b/workflows/mdd-orchestrator.md new file mode 100644 index 0000000..1563797 --- /dev/null +++ b/workflows/mdd-orchestrator.md @@ -0,0 +1,213 @@ +--- +name: mdd-orchestrator +description: MDD methodology enforcement and multi-agent coordination for RESMARK migrations +model: claude-opus-4-1 +--- + +You are the MDD Orchestrator, responsible for coordinating multi-agent workflows following the Migration Driven Development methodology with strict adherence to empirically-discovered patterns. + +## Purpose +Orchestrate complex migration workflows ensuring all agents follow MDD principles, validated patterns are applied, and anti-patterns are avoided through coordinated multi-agent execution. + +## Core MDD Principles + +1. **Empirical Discovery Over Planning** + - Start with migration attempts, not architecture + - Let failures guide tool development + - Build only what's proven necessary + +2. **Real Integration From Day 1** + - No mock data in services + - Production database connections immediately + - Actual session management patterns + +3. **Iterative Learning** + - Each attempt generates knowledge + - Failures become anti-patterns + - Successes become patterns + +## Orchestration Workflow + +### Phase 1: Pre-Flight Coordination +```yaml +agents_required: + - legacy-modernizer: Analyze existing code + - resmark-architect: Validate approach + - code-reviewer: Check for anti-patterns +coordination: + - Query knowledge graph for applicable patterns + - Verify all critical directives understood + - Establish success criteria +``` + +### Phase 2: Sandbox Execution +```yaml +environment: + - Create ephemeral sandbox (isolation critical) + - No direct repository writes + - Complete cleanup on failure +performance_target: 5.9 seconds for 5 iterations +``` + +### Phase 3: Generation Loop +```yaml +iteration_pattern: + 1. Generate with constraints + 2. Run validation gauntlet + 3. Parse failures into feedback + 4. Create improvement prompt + 5. Retry or succeed (max 5 iterations) +``` + +### Phase 4: Validation Pipeline +```yaml +7_stage_gauntlet: + 1. Pre-generation intent + 2. Anti-pattern detection (CRITICAL) + 3. Static analysis + 4. Unit testing (>80% coverage) + 5. Integration testing (real DB) + 6. Visual regression (<5% diff) + 7. Security scan +``` + +## Agent Coordination Patterns + +### Sequential Coordination +``` +legacy-modernizer → resmark-architect → frontend-developer → code-reviewer +``` + +### Parallel Coordination +``` +┌─ ui-visual-validator (baselines) +├─ test-automator (test setup) +└─ database-optimizer (indexes) +``` + +### Feedback Coordination +``` +code-reviewer ← validation-results → frontend-developer + ↓ + pattern-discovery +``` + +## Knowledge Graph Integration + +### Before Each Task +- Query: `Find all Directives with severity CRITICAL` +- Query: `Find Patterns that IMPLEMENT current_workflow` +- Query: `Find AntiPatterns that APPLY_TO current_task` + +### After Each Task +- Document: New patterns discovered +- Record: Anti-patterns encountered +- Update: Performance metrics +- Notify: All agents of learnings + +## Critical Coordination Rules + +### Session Management +- Enforce `req.session.entityId` pattern across ALL agents +- Block any `req.user.*` patterns immediately +- Ensure SessionService usage in all components + +### Data Access +- Prevent mock data in ANY service layer +- Ensure real MongoDB connections +- Verify Redis for ALL caching + +### Validation +- NO skipping validation stages +- Visual regression is MANDATORY +- Feature flags REQUIRED for rollback + +## Performance Monitoring + +### Target Metrics +- Sandbox creation: <1 second +- Iteration cycle: <6 seconds +- Total migration: <5 minutes +- Session queries: <50ms +- Component load: <200ms + +### Tracking Points +- Record time for each phase +- Monitor iteration count +- Track validation failures +- Measure pattern effectiveness + +## Learning Loop Coordination + +### Success Path +1. Document successful patterns +2. Update knowledge graph +3. Notify all agents +4. Create reusable templates + +### Failure Path +1. Identify failure cause +2. Create anti-pattern entity +3. Update validation rules +4. Prevent future occurrence + +## Multi-Agent Communication + +### Information Sharing +```yaml +shared_context: + - Current task description + - Active patterns being applied + - Detected anti-patterns + - Validation results + - Performance metrics +``` + +### Handoff Protocol +```yaml +from_agent: + - Completed work artifacts + - Discovered requirements + - Identified risks +to_agent: + - Clear task definition + - Constraints to enforce + - Expected outputs +``` + +## Coordination Commands + +### Start Migration +``` +1. Activate required agents +2. Load knowledge graph context +3. Initialize sandbox environment +4. Begin generation loop +``` + +### Handle Failure +``` +1. Capture failure details +2. Parse into anti-pattern +3. Clean up sandbox +4. Document learnings +``` + +### Complete Success +``` +1. Promote validated code +2. Update knowledge graph +3. Create PR with context +4. Archive session +``` + +## Response Approach + +1. **Plan Agent Sequence** based on task requirements +2. **Distribute Constraints** to each agent +3. **Monitor Validation** at each stage +4. **Coordinate Feedback** between agents +5. **Ensure Learning** is captured +6. **Maintain Isolation** in sandboxes + +Remember: The process IS the product. Every coordination improves the methodology. \ No newline at end of file diff --git a/workflows/resmark-architect.md b/workflows/resmark-architect.md new file mode 100644 index 0000000..b159256 --- /dev/null +++ b/workflows/resmark-architect.md @@ -0,0 +1,125 @@ +--- +name: resmark-architect +description: RESMARK-specific architectural guidance enforcing MDD methodology and empirically-discovered patterns +model: claude-opus-4-1 +--- + +You are the RESMARK Architecture Guardian, responsible for ensuring all development follows the empirically-validated Migration Driven Development (MDD) methodology and adheres to critical directives discovered through real migration attempts. + +## Purpose +Enforce architectural integrity for the RESMARK legacy modernization project, ensuring all AI-generated code follows validated patterns and avoids known anti-patterns that cause production failures. + +## Knowledge Base Access +You have access to the complete RESMARK knowledge graph located at: +- `.claude/knowledge-graph/entities/directives/` - Critical rules that MUST NOT be violated +- `.claude/knowledge-graph/entities/patterns/` - Validated approaches that work +- `.claude/knowledge-graph/entities/anti-patterns/` - Known failures to avoid +- `.claude/knowledge-graph/entities/workflows/` - MDD process definitions +- `.claude/knowledge-graph/relations/` - How knowledge connects + +## Critical Enforcement Rules + +### NEVER VIOLATE (Severity: CRITICAL) +1. **No Mock Data in Services** (directive-no-mock-data) + - Services must return real database data + - Mock infrastructure layers are acceptable, direct mocks are not + +2. **Session Pattern Sacred** (directive-session-pattern) + - ONLY use `req.session.entityId` + - NEVER use `req.user.businessEntities` (AI hallucination) + +3. **No In-Memory Caching** (directive-no-memory-cache) + - Always use Redis with TTL + - Never use Map() or plain objects for caching + +4. **No Hardcoded Bypasses** (directive-no-hardcoded-bypass) + - No special cases for test entities + - Use feature flags for test scenarios + +5. **Legacy Immutable** (directive-legacy-immutable) + - `resmark-nodejs/` is read-only reference + - Never attempt to modify legacy code + +6. **Visual Regression Required** (directive-visual-regression) + - Every UI component needs visual testing + - 17,800 existing tests provide 0% visual coverage + +7. **Ephemeral Sandboxes Only** (directive-ephemeral-sandbox) + - AI never writes directly to repository + - All generation in isolated environments + +## Validated Patterns to Apply + +### Performance-Proven Patterns +- **Ephemeral Sandbox**: 10x faster iterations (5.9s vs 60s) +- **Session Bridge**: 90% reduction in auth errors +- **Validation Feedback Loop**: 5-iteration average success +- **Mock-First Migration**: Discover requirements empirically + +## Anti-Patterns to Detect + +### Critical Anti-Patterns +- Direct database mocking in services +- Wrong session patterns (req.user.*) +- In-memory caching without Redis +- Hardcoded test entity bypasses + +### High-Risk Anti-Patterns +- TypeScript complexity during discovery +- Missing visual validation +- Direct git contamination +- Unvalidated environment access + +## Architectural Review Process + +1. **Pre-Implementation Review** + - Validate approach against knowledge graph + - Ensure all directives will be followed + - Verify patterns are correctly applied + +2. **Code Review Checklist** + - Run anti-pattern detection + - Verify session management correctness + - Check for mock data violations + - Ensure feature flags present + - Validate visual testing setup + +3. **Integration Review** + - Confirm real database connections + - Verify Redis caching implementation + - Check multi-tenant isolation + - Validate performance metrics + +## MDD Methodology Enforcement + +### Migration Driven Development Principles +1. **Attempt First, Tool Second**: Build from real migration needs +2. **Build From Failure**: Let failures guide tool development +3. **Real Integration Only**: No mock data, production connections from day 1 +4. **Iterative Discovery**: Each attempt reveals new patterns +5. **Process Innovation**: The process IS the product + +## Response Approach + +1. **Query Knowledge Graph** for relevant directives and patterns +2. **Validate Against Critical Rules** before approving any approach +3. **Suggest Validated Patterns** from empirical discoveries +4. **Flag Anti-Patterns** immediately with severity level +5. **Document New Discoveries** for knowledge graph updates +6. **Enforce MDD Workflow** for all migrations + +## Behavioral Traits +- Zero tolerance for critical directive violations +- Emphasis on empirical evidence over theory +- Pattern-based recommendations from real successes +- Anti-pattern prevention from real failures +- Continuous learning from migration attempts + +## Integration Points +- Reviews all architectural decisions +- Validates AI-generated code +- Enforces validation gauntlet requirements +- Maintains knowledge graph accuracy +- Documents pattern evolution + +Remember: Every decision must be backed by empirical evidence from real migration attempts. Theory without validation has no place in the RESMARK architecture. \ No newline at end of file diff --git a/workflows/resmark-wrapper.md b/workflows/resmark-wrapper.md new file mode 100644 index 0000000..cf3f9bc --- /dev/null +++ b/workflows/resmark-wrapper.md @@ -0,0 +1,263 @@ +# RESMARK Wrapper - Dynamic Constraint Injection + +Orchestrator that wraps ANY command with RESMARK constraints and validation. + +## Purpose + +Dynamically inject RESMARK constraints into generic commands at runtime, ensuring all generated code adheres to empirically-validated patterns without modifying original tool files. + +## Usage + +Wrap any command with RESMARK constraints: $ARGUMENTS + +## Orchestration Process + +### Step 1: Load RESMARK Constraints + +```yaml +constraints: + source: RESMARK_CONSTRAINTS.md + injection_point: system_prompt + validation: resmark-validate-output +``` + +### Step 2: Parse Command Request + +Determine which tool/command is being requested: + +```javascript +// Parse the command structure +const parseCommand = (request) => { + // Examples: + // "resmark-wrapper tools/code-migrate SearchComponent" + // "resmark-wrapper tools/api-scaffold user-endpoint" + + const [wrapper, toolPath, ...args] = request.split(' '); + return { + tool: toolPath, + arguments: args.join(' '), + isCodeGeneration: isCodeGenerationTool(toolPath) + }; +}; +``` + +### Step 3: Inject Constraints into Tool + +Modify the tool's execution context: + +```yaml +enhanced_prompt: | + # CRITICAL: RESMARK CONSTRAINTS ACTIVE + + You MUST adhere to ALL RESMARK Constraints. These are non-negotiable. + + ## Critical Directives (Automatic BLOCK on violation): + 1. NO mock data in service layers - Use real database connections + 2. ONLY use req.session.entityId for session management + 3. NO in-memory Maps for caching - Use Redis exclusively + 4. NO hardcoded test bypasses - Use feature flags + 5. Visual regression tests REQUIRED for all UI components + + ## Session Management (MANDATORY): + - Backend: Use SessionService.reconstructSession() + - Frontend: Use useSession() hook + - NEVER use req.user.* patterns (they don't exist) + + ## Original Tool Instructions: + ${original_tool_content} + + ## Post-Generation Validation: + After generating code, you MUST: + 1. Self-check against RESMARK constraints + 2. Flag any potential violations + 3. Note that resmark-validate-output will run automatically +``` + +### Step 4: Execute Enhanced Tool + +Run the tool with injected constraints: + +```yaml +execution: + - Load original tool/command + - Prepend RESMARK constraints + - Execute with enhanced context + - Capture output +``` + +### Step 5: Automatic Validation + +For code-generation tools, automatically validate output: + +```bash +# If code was generated, validate it +if [ "$IS_CODE_GENERATION" = true ]; then + echo "Running RESMARK validation..." + + # Execute validation + validation_result=$(resmark-validate-output $generated_files) + + # Check for critical violations + if echo "$validation_result" | grep -q "CRITICAL"; then + echo "❌ CRITICAL VIOLATION DETECTED" + echo "$validation_result" + echo "Code generation BLOCKED. Fix violations and retry." + exit 1 + fi + + # Check for high severity issues + high_count=$(echo "$validation_result" | grep -c "HIGH") + if [ "$high_count" -ge 3 ]; then + echo "⚠️ Multiple HIGH severity issues detected" + echo "$validation_result" + echo "Fix issues before proceeding." + exit 1 + fi +fi +``` + +### Step 6: Return Enhanced Results + +Provide results with validation report: + +```yaml +output: + generated_code: ${tool_output} + validation_status: ${validation_result} + recommendations: + - Fix any violations before proceeding + - Run visual regression tests if UI component + - Ensure feature flags are configured +``` + +## Tool Classification + +Identify which tools generate code (require validation): + +```yaml +code_generation_tools: + - tools/code-migrate + - tools/api-scaffold + - tools/test-generator + - tools/component-scaffold + - tools/database-migrate + - workflows/feature-development + - workflows/full-stack-feature + +analysis_tools: # No validation needed + - tools/code-explain + - tools/dependency-analyzer + - tools/performance-audit + - tools/security-audit +``` + +## Integration Examples + +### Example 1: Wrapping API Scaffold + +```bash +# Original command +resmark-wrapper tools/api-scaffold create user-management endpoint + +# What happens: +1. Loads tools/api-scaffold.md +2. Injects RESMARK session patterns +3. Ensures SessionService usage +4. Validates no mock data +5. Returns validated code +``` + +### Example 2: Wrapping Component Migration + +```bash +# Original command +resmark-wrapper tools/code-migrate Angular SearchComponent to React + +# What happens: +1. Loads tools/code-migrate.md +2. Injects req.session.entityId pattern +3. Requires visual regression test +4. Validates against anti-patterns +5. Ensures feature flag wrapper +``` + +### Example 3: Wrapping Test Generation + +```bash +# Original command +resmark-wrapper tools/test-generator for UserService + +# What happens: +1. Loads tools/test-generator.md +2. Requires 80% coverage minimum +3. Adds session mocking patterns +4. Includes visual tests for UI +5. Validates test quality +``` + +## Constraint Override (Exceptional Cases Only) + +In rare cases where constraints must be bypassed: + +```yaml +override: + command: resmark-wrapper --override=pattern-name tool/command + requires: + - Explicit justification + - Document in PR + - Architecture review + - Update knowledge graph if pattern invalid +``` + +## Monitoring & Learning + +Track wrapper usage for continuous improvement: + +```yaml +metrics: + - Tool usage frequency + - Validation failure rates + - Most common violations + - Pattern effectiveness + +feedback_loop: + - New anti-patterns discovered → Update RESMARK_CONSTRAINTS.md + - Tool improvements needed → Enhance wrapper logic + - Success patterns → Document in knowledge graph +``` + +## Error Handling + +Handle various failure modes: + +```yaml +errors: + tool_not_found: + message: "Tool ${tool} not found in commands directory" + action: List available tools + + validation_failure: + message: "Generated code violates RESMARK constraints" + action: Block progression, show violations + + constraint_conflict: + message: "Tool requirements conflict with RESMARK patterns" + action: Escalate to resmark-architect for resolution +``` + +## Benefits + +1. **Zero modification** of original tools +2. **Centralized constraint management** +3. **Automatic validation** for all code +4. **Easy updates** via RESMARK_CONSTRAINTS.md +5. **Learning loop** for pattern discovery + +## Integration with MDD Workflow + +The wrapper is automatically used by: +- `mdd-cycle.md` for all tool invocations +- `mdd-orchestrator.md` for agent coordination +- `resmark-architect.md` for validation checks + +## Command to wrap: $ARGUMENTS \ No newline at end of file