From af41321c1039a4f04d548748868bb98efbda9168 Mon Sep 17 00:00:00 2001 From: catface996 Date: Mon, 15 Dec 2025 10:40:11 +0800 Subject: [PATCH 01/18] feat: add spec-kit power for Spec-Driven Development MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add spec-kit power with 10 workflows: Steering, Specify, Clarify, Plan, Tasks, Implement, Analyze, Checklist, Sync, and Discover for transforming specifications into executable code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- README.md | 7 + spec-kit/POWER.md | 168 ++++++++ spec-kit/steering/00-interaction-protocol.md | 363 ++++++++++++++++++ spec-kit/steering/01-steering-workflow.md | 218 +++++++++++ spec-kit/steering/02-specify-workflow.md | 257 +++++++++++++ spec-kit/steering/03-clarify-workflow.md | 350 +++++++++++++++++ spec-kit/steering/04-plan-workflow.md | 279 ++++++++++++++ spec-kit/steering/05-tasks-workflow.md | 230 +++++++++++ spec-kit/steering/06-implement-workflow.md | 223 +++++++++++ spec-kit/steering/07-analyze-workflow.md | 250 ++++++++++++ spec-kit/steering/08-checklist-workflow.md | 256 ++++++++++++ spec-kit/steering/09-sync-workflow.md | 263 +++++++++++++ spec-kit/steering/10-discover-workflow.md | 355 +++++++++++++++++ .../templates/clarifications-template.md | 81 ++++ .../steering/templates/design-template.md | 170 ++++++++ .../templates/product-spec-template.md | 321 ++++++++++++++++ .../steering/templates/product-template.md | 106 +++++ .../templates/requirements-template.md | 137 +++++++ .../steering/templates/structure-template.md | 153 ++++++++ .../templates/sync-report-template.md | 140 +++++++ spec-kit/steering/templates/tasks-template.md | 177 +++++++++ spec-kit/steering/templates/tech-template.md | 136 +++++++ 22 files changed, 4640 insertions(+) create mode 100644 spec-kit/POWER.md create mode 100644 spec-kit/steering/00-interaction-protocol.md create mode 100644 spec-kit/steering/01-steering-workflow.md create mode 100644 spec-kit/steering/02-specify-workflow.md create mode 100644 spec-kit/steering/03-clarify-workflow.md create mode 100644 spec-kit/steering/04-plan-workflow.md create mode 100644 spec-kit/steering/05-tasks-workflow.md create mode 100644 spec-kit/steering/06-implement-workflow.md create mode 100644 spec-kit/steering/07-analyze-workflow.md create mode 100644 spec-kit/steering/08-checklist-workflow.md create mode 100644 spec-kit/steering/09-sync-workflow.md create mode 100644 spec-kit/steering/10-discover-workflow.md create mode 100644 spec-kit/steering/templates/clarifications-template.md create mode 100644 spec-kit/steering/templates/design-template.md create mode 100644 spec-kit/steering/templates/product-spec-template.md create mode 100644 spec-kit/steering/templates/product-template.md create mode 100644 spec-kit/steering/templates/requirements-template.md create mode 100644 spec-kit/steering/templates/structure-template.md create mode 100644 spec-kit/steering/templates/sync-report-template.md create mode 100644 spec-kit/steering/templates/tasks-template.md create mode 100644 spec-kit/steering/templates/tech-template.md diff --git a/README.md b/README.md index 58b155d..41140ec 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,13 @@ Documentation is available at https://kiro.dev/docs/powers/ --- +### spec-kit +**Spec-Driven Development** - Complete SDD methodology power with 10 workflows: Steering, Specify, Clarify, Plan, Tasks, Implement, Analyze, Checklist, Sync, and Discover - transforming specifications into executable code. + +**MCP Servers:** None (Knowledge Base Power) + +--- + ### strands **Build an agent with Strands SDK** - Build AI agents with Strands SDK using Bedrock, Anthropic, OpenAI, Gemini, or Llama models. diff --git a/spec-kit/POWER.md b/spec-kit/POWER.md new file mode 100644 index 0000000..ef5f796 --- /dev/null +++ b/spec-kit/POWER.md @@ -0,0 +1,168 @@ +--- +name: "spec-kit" +displayName: "Spec-Driven Development" +description: "Complete SDD methodology power with 10 workflows: Steering, Specify, Clarify, Plan, Tasks, Implement, Analyze, Checklist, Sync, and Discover - transforming specifications into executable code" +keywords: ["specification", "SDD", "requirements", "planning", "implementation", "TDD", "code generation", "PRD", "user stories", "acceptance criteria", "steering", "specify", "clarify", "plan", "tasks", "implement", "analyze", "checklist", "sync", "discover", "reverse", "retrospective", "spec-kit", "speckit", "功能规格", "需求文档", "技术设计", "同步", "回顾", "逆向", "发现"] +author: "Kiro User" +--- + +# Spec-Driven Development Power + +A comprehensive methodology power that guides you through the complete Spec-Driven Development (SDD) lifecycle - from project steering to implementation. + +## Overview + +**Spec-Driven Development inverts the traditional development paradigm**: Specifications don't serve code - code serves specifications. + +This power embodies the SDD philosophy where: +- Specifications are the primary artifact +- Code is the generated output that serves the specification +- Natural language intent drives development +- Multi-step refinement over one-shot generation + +## Core Principles + +### The Power Inversion +Traditional development treats specifications as scaffolding - built and discarded once coding begins. SDD eliminates the gap between specification and implementation by making specifications executable. + +### Executable Specifications +Specifications must be precise, complete, and unambiguous enough to generate working systems. The specification becomes the source of truth, with code as its expression. + +### Steering Governance +Every project operates under steering files - guiding principles split into product, technology, and structure concerns, ensuring consistency, simplicity, and quality. + +### Template-Driven Quality +Templates constrain AI behavior toward higher-quality specifications through: +- Preventing premature implementation details +- Forcing explicit uncertainty markers +- Structured thinking through checklists +- Steering compliance through gates + +## Workflow Options + +### Complete Workflow (10 Commands) + +1. **Steering** - Establish project principles (product.md, tech.md, structure.md) +2. **Specify** - Transform feature descriptions into structured specifications +3. **Clarify** - Eliminate ambiguity through targeted questioning +4. **Plan** - Convert specifications to technical architecture +5. **Tasks** - Break plans into executable task lists +6. **Implement** - Execute tasks following TDD approach +7. **Analyze** - Cross-artifact consistency validation +8. **Checklist** - Generate domain-specific quality checklists +9. **Sync** - Synchronize documentation with implementation and generate retrospective +10. **Discover** - Reverse engineer existing projects to generate steering files and product spec + +### Simplified Workflow (3 Steps) +For quick iterations: +1. **Specify** - Capture requirements +2. **Plan** - Technical approach +3. **Implement** - Execute + +## Activation Response + +See `00-interaction-protocol.md` for the activation flow. The power first asks for language selection (English/中文), then presents workflow options. + +## Methodology Overview + +### Phase 1: Foundation (Steering) +Establish guiding principles split into three files: +- **product.md** - Product vision, business constraints +- **tech.md** - Technology stack, development principles +- **structure.md** - Project layout, naming conventions + +### Phase 2: Specification (Specify + Clarify) +Transform ideas into executable specifications: +- User stories with priorities +- Acceptance scenarios (Given-When-Then) +- Functional requirements +- Success criteria (measurable, technology-agnostic) + +### Phase 3: Planning (Plan + Tasks) +Convert business requirements to technical architecture: +- Technology stack selection +- Data models and API contracts +- Task breakdown with dependencies +- Parallel execution markers + +### Phase 4: Execution (Implement) +Execute tasks following the plan: +- Phase-by-phase execution +- TDD approach +- Progress tracking +- Validation checkpoints + +### Phase 5: Quality (Analyze + Checklist) +Ensure consistency and completeness: +- Cross-artifact validation +- Coverage analysis +- Domain-specific quality checklists + +### Phase 6: Retrospective (Sync) +Synchronize documentation with implementation: +- Compare planned vs actual implementation +- Update documentation to reflect reality +- Generate lessons learned and retrospective report +- Capture technical debt and recommendations + +### Phase 0: Discovery (Discover) - For Existing Projects +Bootstrap SDD for existing codebases: +- Analyze existing code to extract product context +- Reverse engineer technology stack and patterns +- Generate steering files (product.md, tech.md, structure.md) +- Create comprehensive product specification + +## Interaction Rules + +- **WAIT for user instructions** - Never automatically start workflows +- **CONFIRM scope first** - Understand project context before proceeding +- **One question at a time** - When clarifying, ask single focused questions +- **Ask before proceeding** - Never proceed to next phase without user agreement +- **Mark uncertainties** - Use [NEEDS CLARIFICATION] markers for ambiguous items + +## Steering Files + +Detailed methodologies for each workflow are available in the steering files: +- `00-interaction-protocol.md` - Interaction guidelines (always loaded) +- `01-steering-workflow.md` - Project principles establishment +- `02-specify-workflow.md` - Feature specification creation +- `03-clarify-workflow.md` - Ambiguity elimination process +- `04-plan-workflow.md` - Technical planning workflow +- `05-tasks-workflow.md` - Task generation process +- `06-implement-workflow.md` - Implementation execution +- `07-analyze-workflow.md` - Consistency analysis +- `08-checklist-workflow.md` - Quality checklist generation +- `09-sync-workflow.md` - Documentation sync and retrospective +- `10-discover-workflow.md` - Project discovery and reverse engineering + +Template files: +- `templates/requirements-template.md` - Feature requirements template +- `templates/clarifications-template.md` - Clarification log template +- `templates/design-template.md` - Technical design template +- `templates/tasks-template.md` - Task list template +- `templates/product-template.md` - Product steering template +- `templates/tech-template.md` - Technology steering template +- `templates/structure-template.md` - Structure steering template +- `templates/sync-report-template.md` - Sync report template +- `templates/product-spec-template.md` - Product specification template + +## File Structure + +All specification files are stored in `.kiro/specs/`: + +``` +.kiro/specs/ +├── 000-product-spec/ +│ └── product-spec.md # Product specification (Discover workflow) +└── [###-feature-name]/ + ├── requirements.md # Feature specification (Specify workflow) + ├── clarifications.md # Clarification Q&A log (Clarify workflow) + ├── design.md # Technical design (Plan workflow) + ├── research.md # Technology decisions + ├── data-model.md # Entity definitions + ├── contracts/ # API specifications + ├── quickstart.md # Validation scenarios + ├── tasks.md # Task list (Tasks workflow) + ├── checklists/ # Quality checklists + └── sync-report.md # Sync report (Sync workflow) +``` diff --git a/spec-kit/steering/00-interaction-protocol.md b/spec-kit/steering/00-interaction-protocol.md new file mode 100644 index 0000000..b8e9036 --- /dev/null +++ b/spec-kit/steering/00-interaction-protocol.md @@ -0,0 +1,363 @@ +--- +inclusion: always +--- + +# Interaction Protocol (CRITICAL - READ FIRST) + +This document defines how you MUST interact with users when this power is activated. **Follow these rules strictly.** + +--- + +## Language Selection (MANDATORY FIRST STEP) + +**CRITICAL**: You MUST ask user to select language BEFORE any other interaction. This is NON-NEGOTIABLE. + +Language selection affects: +- All conversations and responses +- Generated documents (requirements.md, design.md, tasks.md, etc.) +- Questions and clarifications +- Error messages and guidance + +**Do NOT proceed with ANY workflow until language is confirmed.** + +--- + +## Activation Response + +When user activates this power, you MUST first ask for language selection: + +``` +Spec-Driven Development Power activated. + +Please select your preferred language / 请选择您的首选语言: + +► **A** - English + _All conversations and generated documents will be in English_ + +► **B** - 中文 + _所有对话和生成的文档都将使用中文_ + +--- +Reply with "A" or "B" / 请回复 "A" 或 "B" +``` + +**Wait for user response before proceeding.** + +--- + +## After Language Selection + +### If English (A) selected: + +``` +Language set to: English + +I can help you with specification-driven development across 10 workflows: + +► **Discover** - Reverse engineer existing projects + _Use when: Have existing codebase, need to bootstrap SDD_ + +► **Steering** - Establish project principles (product.md, tech.md, structure.md) + _Use when: Starting a new project_ + +► **Specify** - Create structured feature specifications + _Use when: Have a feature idea to document_ + +► **Clarify** - Eliminate ambiguity through questioning + _Use when: Spec has unclear parts_ + +► **Plan** - Generate technical implementation plans + _Use when: Have clear spec, need architecture_ + +► **Tasks** - Break plans into executable task lists + _Use when: Have plan, need actionable steps_ + +► **Implement** - Execute tasks with TDD approach + _Use when: Ready to code_ + +► **Analyze** - Cross-artifact consistency validation + _Use when: Need to verify everything aligns_ + +► **Checklist** - Generate quality validation checklists + _Use when: Need quality gates_ + +► **Sync** - Synchronize documentation with implementation + _Use when: After implementation, need to update docs_ + +--- +To get started, please tell me: +- What project are you working on? +- Do you have existing steering files (product.md, tech.md, structure.md)? +- Which workflow do you need help with? +``` + +### If 中文 (B) selected: + +``` +语言已设置为: 中文 + +我可以帮助您使用规格驱动开发(SDD)的 10 个工作流: + +► **Discover (发现)** - 逆向分析现有项目 + _适用于: 已有代码库,需要引入 SDD 方法时_ + +► **Steering (治理)** - 建立项目原则 (product.md, tech.md, structure.md) + _适用于: 启动新项目时_ + +► **Specify (规格)** - 创建结构化的功能规格 + _适用于: 有功能想法需要文档化时_ + +► **Clarify (澄清)** - 通过提问消除歧义 + _适用于: 规格中有不明确的部分时_ + +► **Plan (计划)** - 生成技术实现计划 + _适用于: 规格清晰,需要架构设计时_ + +► **Tasks (任务)** - 将计划分解为可执行任务 + _适用于: 有计划,需要具体步骤时_ + +► **Implement (实现)** - 使用 TDD 方法执行任务 + _适用于: 准备开始编码时_ + +► **Analyze (分析)** - 跨文档一致性验证 + _适用于: 需要验证所有内容是否对齐时_ + +► **Checklist (检查清单)** - 生成质量验证清单 + _适用于: 需要质量门禁时_ + +► **Sync (同步)** - 同步文档与实现,生成回顾报告 + _适用于: 实现完成后,需要更新文档时_ + +--- +请告诉我: +- 您正在开发什么项目? +- 您是否已有治理文件 (product.md, tech.md, structure.md)? +- 您需要使用哪个工作流? +``` + +--- + +## Language Consistency Rules + +Once language is selected, you MUST: + +1. **Conversations**: All responses in selected language +2. **Generated Files**: All content in requirements.md, design.md, tasks.md, etc. in selected language +3. **Questions**: Ask clarifications in selected language +4. **Templates**: Fill templates using selected language +5. **Error Messages**: Report issues in selected language + +**Exception**: Technical terms (API names, code identifiers, file paths) remain in English regardless of language selection. + +--- + +## Core Rule: WAIT FOR USER INSTRUCTIONS + +**You are a guide, not an executor.** Do NOT automatically start SDD workflows. Your job is to: + +1. **First**: Confirm language selection (MANDATORY) +2. Understand what the user needs +3. Confirm the scope and workflow +4. Guide them through the appropriate methodology +5. Execute ONLY when explicitly instructed + +--- + +## Response Decision Tree + +``` +User Input + | + +-> "Just activated" / No specific request + | -> Show greeting, list workflows, ask what they need + | + +-> Vague request ("help with SDD") + | -> Ask clarifying questions: + | - What is the project? + | - What workflow are you in? + | - What specific help do you need? + | + +-> Has project context but no workflow specified + | -> Summarize understanding, suggest appropriate workflow(s) + | -> Wait for user to confirm before proceeding + | + +-> Specifies workflow + project + | -> Confirm understanding + | -> Ask if ready to start + | -> Only proceed after "yes" or explicit instruction + | + +-> Shares existing specs/documents + | -> Read and summarize what you found + | -> Suggest appropriate action (clarify, plan, analyze) + | -> Wait for user instruction + | + +-> Explicit instruction ("Create spec for X") + -> Confirm scope + -> Execute the specific workflow + -> Stop and ask before doing more +``` + +--- + +## Clarification Rules (MANDATORY) + +### STRICT ENFORCEMENT: One Question at a Time +- **MUST ask only ONE question per response** +- **FORBIDDEN to ask multiple questions in single response** +- **MUST wait for user's answer before proceeding** +- **VIOLATION: If you ask multiple questions, you have failed** + +### MANDATORY Priority Order (Top-Down) +**MUST follow this exact sequence:** +1. **Project Context** - What system/product are we working on? +2. **Existing Artifacts** - Do you have steering files/specs already? +3. **Workflow Stage** - Which SDD phase are you in? +4. **Scope Boundary** - What's included/excluded? +5. **Technical Context** - Any constraints or preferences? + +### REQUIRED Question Format +``` +[Single focused question] + +Why I'm asking: [Brief explanation of why this matters for the workflow] +``` + +### COMPLIANCE CHECK +Before sending any clarification response, verify: +- [ ] Am I asking only ONE question? +- [ ] Is this the highest priority unanswered question? +- [ ] Have I explained why I'm asking this? + +--- + +## Workflow Transition Protocol + +When completing a workflow, ALWAYS: + +1. **Summarize** what was accomplished +2. **List** the artifacts created +3. **Ask** what the user wants to do next: + - Continue to next workflow? + - Refine current outputs? + - Pause and review? + - Do something else? + +**NEVER** automatically start the next workflow. + +--- + +## Workflow Dependencies + +``` +Discover (for existing projects) + | + v +Steering (optional but recommended first) + | + v + Specify --> Clarify (optional) --> Plan --> Tasks --> Implement --> Sync + | | + v v + Analyze (retrospective) + | + v + Checklist +``` + +### Recommended Flow for New Projects +1. Start with **Steering** to establish principles +2. Use **Specify** for each feature +3. Run **Clarify** if ambiguities exist +4. Create **Plan** for technical architecture +5. Generate **Tasks** for implementation +6. Run **Analyze** to validate consistency +7. Create **Checklist** for quality gates +8. Execute **Implement** to build +9. Run **Sync** to update documentation and generate retrospective + +### Recommended Flow for Existing Projects +1. Start with **Discover** to analyze codebase and generate steering files +2. Review and refine generated product.md, tech.md, structure.md +3. Use **Specify** for new features +4. Continue with standard workflow (Clarify → Plan → Tasks → Implement → Sync) + +### Quick Flow for Small Features +1. **Specify** - Capture requirements +2. **Plan** - Technical approach +3. **Implement** - Execute + +--- + +## Prohibited Behaviors (NEVER DO) + +| Don't Do | Do Instead | +|----------|------------| +| Auto-start example analysis | Ask what project user is working on | +| Generate sample specifications | Wait for user to provide context | +| Assume user wants full 10-workflow process | Ask which workflow(s) they need | +| Proceed to next workflow automatically | Ask if user wants to continue | +| Show lengthy methodology explanations unprompted | Give concise options, expand on request | +| Make decisions for the user | Present options, let user choose | + +--- + +## Handling User Requests + +### "Just do it" / "Go ahead" + +Even with blanket permission, confirm scope: +``` +Got it. To make sure I deliver what you need: +- I'll work on [specific scope] +- Using [specific workflow] +- Producing [specific outputs] + +Starting now. I'll check in with you at key decision points. +``` + +### "I don't know which workflow" + +Help them figure it out: +``` +No problem! Let me help you figure out where to start. + +Tell me about your current situation: +1. Have existing codebase, need documentation? -> Discover +2. Starting a new project from scratch? -> Steering +3. Have a feature idea to document? -> Specify +4. Have a spec but it's unclear? -> Clarify +5. Have a clear spec, need technical plan? -> Plan +6. Have a plan, need task breakdown? -> Tasks +7. Have tasks, ready to code? -> Implement +8. Have artifacts, need consistency check? -> Analyze +9. Need quality validation checklist? -> Checklist +10. Done implementing, need to sync docs? -> Sync +``` + +### "Do everything" + +Manage expectations: +``` +The full 10-workflow process is comprehensive. Let's make sure it's right for you: + +- Full process is best for: New products, major features, formal projects +- Lighter approach is better for: Small features, quick iterations, internal tools +- For existing projects: Start with Discover to bootstrap documentation + +What's your situation? I can recommend the right level of rigor. +``` + +--- + +## Remember + +**Your value is in guiding users through the right SDD process, not in generating content automatically.** + +A good SDD practitioner: +- Listens first +- Asks clarifying questions +- Confirms understanding +- Executes precisely what's needed +- Checks in frequently + +Act accordingly. diff --git a/spec-kit/steering/01-steering-workflow.md b/spec-kit/steering/01-steering-workflow.md new file mode 100644 index 0000000..1afeb82 --- /dev/null +++ b/spec-kit/steering/01-steering-workflow.md @@ -0,0 +1,218 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Steering workflow - establishes project principles (product.md, tech.md, structure.md)" +keywords: ["steering", "constitution", "principles", "governance", "product", "tech", "structure", "治理", "原则", "项目初始化"] +--- + +# Steering Workflow + +This workflow establishes the project steering files - guiding principles that govern how specifications become code. + +## Purpose + +The steering files act as the **architectural DNA** of the system, split into three focused areas: +- **product.md** - Product vision, goals, and business constraints +- **tech.md** - Technology decisions, coding standards, and technical principles +- **structure.md** - Project structure, file organization, and architectural patterns + +## Steering Files Location + +All steering files are stored in `.kiro/steering/`: + +``` +.kiro/steering/ +├── product.md # Product vision and business rules +├── tech.md # Technology stack and coding principles +└── structure.md # Project structure and architecture +``` + +## When to Use + +- Starting a new project +- Establishing development principles for a team +- Formalizing existing but undocumented practices +- Updating project governance + +## File Responsibilities + +### product.md - Product Steering + +Defines WHAT the product is and WHY: + +- Product vision and mission +- Target users and personas +- Business constraints and requirements +- Success metrics +- Non-functional requirements (performance, security, compliance) +- Feature prioritization guidelines + +### tech.md - Technology Steering + +Defines HOW to build technically: + +- Technology stack (languages, frameworks, databases) +- Coding standards and conventions +- Testing strategy (TDD, coverage requirements) +- Development principles (Library-First, Test-First, etc.) +- Quality gates +- Dependency management rules + +### structure.md - Structure Steering + +Defines WHERE things go: + +- Project directory structure +- File naming conventions +- Module organization +- API/endpoint patterns +- Database schema conventions +- Documentation locations + +## Execution Flow + +### Step 1: Gather Context + +Ask the user about their project: +- Project name and purpose +- Team size and structure +- Technology preferences +- Quality requirements +- Existing practices to formalize + +### Step 2: Create product.md + +Use `templates/product-template.md` as reference. Guide the user through product decisions: + +```markdown +# Product Steering + +## Vision +[What is the product and why does it exist?] + +## Target Users +[Who are the primary users?] + +## Business Constraints +- [Constraint 1] +- [Constraint 2] + +## Success Metrics +- [Metric 1]: [Target] +- [Metric 2]: [Target] + +## Non-Functional Requirements +- **Performance**: [Requirements] +- **Security**: [Requirements] +- **Compliance**: [Requirements] +``` + +### Step 3: Create tech.md + +Use `templates/tech-template.md` as reference. Guide the user through technology decisions: + +```markdown +# Technology Steering + +## Stack +- **Language**: [e.g., TypeScript 5.0] +- **Framework**: [e.g., Next.js 14] +- **Database**: [e.g., PostgreSQL] +- **Testing**: [e.g., Vitest, Playwright] + +## Development Principles + +### Test-First (NON-NEGOTIABLE) +All implementation MUST follow TDD: +1. Write tests first +2. Confirm tests fail +3. Implement to pass tests +4. Refactor while green + +### Simplicity Gate +- Maximum 3 projects initially +- No future-proofing +- Start simple, add complexity only when proven necessary + +### Anti-Abstraction Gate +- Use framework directly +- No unnecessary wrappers +- Single model representation + +## Quality Gates +- [ ] All tests pass +- [ ] Code coverage >= [X]% +- [ ] No lint errors +- [ ] Type-safe (no `any`) +``` + +### Step 4: Create structure.md + +Use `templates/structure-template.md` as reference. Guide the user through structure decisions: + +```markdown +# Structure Steering + +## Project Layout + +```text +src/ +├── components/ # UI components +├── services/ # Business logic +├── models/ # Data models +├── api/ # API routes +└── lib/ # Utilities + +tests/ +├── unit/ # Unit tests +├── integration/ # Integration tests +└── e2e/ # End-to-end tests +``` + +## Naming Conventions +- **Files**: kebab-case (e.g., `user-service.ts`) +- **Components**: PascalCase (e.g., `UserProfile.tsx`) +- **Functions**: camelCase (e.g., `getUserById`) + +## Module Rules +- Each module is self-contained +- Clear public API via index exports +- No circular dependencies +``` + +### Step 5: Validate + +Check with the user: +- Are all critical decisions captured? +- Are the rules clear and testable? +- Is the structure practical? + +### Step 6: Finalize + +Write the steering files to `.kiro/steering/`: +- `.kiro/steering/product.md` +- `.kiro/steering/tech.md` +- `.kiro/steering/structure.md` + +## Output + +After completing this workflow: +- Product steering at `.kiro/steering/product.md` +- Technology steering at `.kiro/steering/tech.md` +- Structure steering at `.kiro/steering/structure.md` +- Ready for use in Plan workflow (Steering Check) + +## Next Steps + +Suggest to the user: +``` +Steering files established: +- .kiro/steering/product.md +- .kiro/steering/tech.md +- .kiro/steering/structure.md + +Next, you can: +1. Run **Specify** to create your first feature specification +2. The steering files will be automatically referenced in **Plan** workflow +3. Run **Analyze** later to check steering compliance +``` diff --git a/spec-kit/steering/02-specify-workflow.md b/spec-kit/steering/02-specify-workflow.md new file mode 100644 index 0000000..35bc318 --- /dev/null +++ b/spec-kit/steering/02-specify-workflow.md @@ -0,0 +1,257 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Specify workflow - transforms feature descriptions into structured specifications" +keywords: ["specify", "specification", "spec", "requirements", "feature", "PRD", "需求", "规格", "功能规格"] +--- + +# Specify Workflow + +This workflow transforms a feature description into a structured, executable specification. + +## Purpose + +Create specifications that are: +- **Complete**: All necessary requirements captured +- **Unambiguous**: Only one interpretation possible +- **Testable**: Every requirement has acceptance criteria +- **Technology-agnostic**: Focus on WHAT, not HOW + +## When to Use + +- Starting a new feature +- Documenting an existing feature idea +- Converting informal requirements to formal specs + +## Quick Guidelines + +- Focus on **WHAT** users need and **WHY** +- Avoid **HOW** to implement (no tech stack, APIs, code structure) +- Written for business stakeholders, not developers +- Mark unclear items with `[NEEDS CLARIFICATION: specific question]` +- Maximum 3 clarification markers + +## Execution Flow + +### Step 1: Gather Feature Description + +Ask the user for their feature description. Example prompt: +``` +Please describe the feature you want to specify. + +Include: +- What problem it solves +- Who the users are +- Key capabilities needed +``` + +### Step 2: Generate Feature Branch Name + +Create a concise short name (2-4 words) for the feature: +- Use action-noun format: "user-auth", "payment-flow" +- Preserve technical terms: OAuth2, API, JWT +- Keep concise but descriptive + +Determine the next feature number by checking existing specs directories. + +### Step 3: Create Feature Structure + +Create the feature directory and spec file: +``` +.kiro/specs/[###-feature-name]/ +└── requirements.md +``` + +### Step 4: Create Specification Content + +Generate the spec using `templates/requirements-template.md` as reference. + +Key template structure: + +```markdown +# Feature Specification: [FEATURE NAME] + +**Feature Branch**: `[###-feature-name]` +**Created**: [DATE] +**Status**: Draft + +## User Scenarios & Testing + +### User Story 1 - [Title] (Priority: P1) + +[Description in plain language] + +**Why this priority**: [Value explanation] + +**Independent Test**: [How to test this story alone] + +**Acceptance Scenarios**: +1. **Given** [state], **When** [action], **Then** [outcome] +2. **Given** [state], **When** [action], **Then** [outcome] + +--- + +### User Story 2 - [Title] (Priority: P2) +... + +### Edge Cases + +- What happens when [boundary condition]? +- How does system handle [error scenario]? + +## Requirements + +### Functional Requirements + +- **FR-001**: System MUST [capability] +- **FR-002**: System MUST [capability] +- **FR-003**: Users MUST be able to [interaction] + +### Key Entities (if data involved) + +- **[Entity 1]**: [What it represents, key attributes] +- **[Entity 2]**: [Relationships to other entities] + +## Success Criteria + +### Measurable Outcomes + +- **SC-001**: [Measurable metric] +- **SC-002**: [Measurable metric] +``` + +### Step 4: Handle Ambiguities + +When information is unclear: + +1. **Make informed guesses** based on context and industry standards +2. **Document assumptions** in an Assumptions section +3. **Limit clarifications** to maximum 3 `[NEEDS CLARIFICATION]` markers +4. **Prioritize**: scope > security/privacy > user experience > technical details + +**Examples of reasonable defaults** (don't ask about these): +- Data retention: Industry-standard practices +- Performance targets: Standard web/mobile expectations +- Error handling: User-friendly messages with fallbacks +- Authentication: Standard session-based or OAuth2 + +### Step 5: Validate Specification + +Run quality validation: + +**Content Quality**: +- [ ] No implementation details (languages, frameworks, APIs) +- [ ] Focused on user value and business needs +- [ ] Written for non-technical stakeholders +- [ ] All mandatory sections completed + +**Requirement Completeness**: +- [ ] No [NEEDS CLARIFICATION] markers remain (or max 3) +- [ ] Requirements are testable and unambiguous +- [ ] Success criteria are measurable +- [ ] Success criteria are technology-agnostic +- [ ] All acceptance scenarios are defined +- [ ] Edge cases are identified + +**Feature Readiness**: +- [ ] All functional requirements have acceptance criteria +- [ ] User scenarios cover primary flows +- [ ] Scope is clearly bounded + +### Step 6: Handle Clarification Markers + +If clarification markers remain, present questions to user: + +```markdown +## 问题 1: [主题] + +**背景**: [引用相关规格内容] + +**需要明确**: [具体问题] + +**可选答案:** + +► **A** - [第一个答案] + _影响: [选择这个意味着什么]_ + +► **B** - [第二个答案] + _影响: [选择这个意味着什么]_ + +► **C** - [第三个答案] + _影响: [选择这个意味着什么]_ + +► **其他** - 提供您自己的答案 + +--- +**您的选择**: _[等待回复]_ +``` + +**Example (示例)**: + +```markdown +## 问题 1: 用户认证方式 + +**背景**: 规格中提到"用户需要登录系统" + +**需要明确**: 应该使用哪种认证方式? + +**可选答案:** + +► **A** - 邮箱 + 密码 + _影响: 实现简单,但需要处理密码重置流程_ + +► **B** - OAuth2 (Google/GitHub) + _影响: 用户体验更好,但依赖第三方服务_ + +► **C** - 两者都支持 + _影响: 覆盖更多用户,但实现复杂度增加_ + +► **其他** - 提供您自己的答案 + +--- +**您的选择**: _[等待回复]_ +``` + +### Step 7: Finalize + +Write the specification to the feature directory: +``` +.kiro/specs/[###-feature-name]/requirements.md +``` + +## Success Criteria Guidelines + +Success criteria must be: +1. **Measurable**: Include specific metrics (time, percentage, count) +2. **Technology-agnostic**: No frameworks, languages, databases +3. **User-focused**: Describe outcomes from user perspective +4. **Verifiable**: Can be tested without knowing implementation + +**Good examples**: +- "Users can complete checkout in under 3 minutes" +- "System supports 10,000 concurrent users" +- "95% of searches return results in under 1 second" + +**Bad examples** (implementation-focused): +- "API response time under 200ms" (too technical) +- "Database handles 1000 TPS" (implementation detail) +- "React components render efficiently" (framework-specific) + +## Output + +After completing this workflow: +- Specification at `.kiro/specs/[###-feature-name]/requirements.md` +- Quality checklist at `.kiro/specs/[###-feature-name]/checklists/requirements.md` +- Feature branch created + +## Next Steps + +Suggest to the user: +``` +Specification created at .kiro/specs/[###-feature-name]/requirements.md + +Next, you can: +1. Run **Clarify** if [N] clarification markers remain +2. Run **Plan** to create technical implementation plan +3. Run **Checklist** to create additional quality checklists +``` diff --git a/spec-kit/steering/03-clarify-workflow.md b/spec-kit/steering/03-clarify-workflow.md new file mode 100644 index 0000000..2f08ac8 --- /dev/null +++ b/spec-kit/steering/03-clarify-workflow.md @@ -0,0 +1,350 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Clarify workflow - eliminates ambiguity through targeted questioning" +keywords: ["clarify", "clarification", "ambiguity", "question", "澄清", "歧义", "问题"] +--- + +# Clarify Workflow + +This workflow identifies and resolves ambiguities in feature specifications through targeted questioning. + +## Purpose + +Detect and reduce ambiguity or missing decision points in the specification before planning, reducing downstream rework risk. + +## When to Use + +- Specification has `[NEEDS CLARIFICATION]` markers +- Specification seems incomplete or vague +- Before starting the Plan workflow +- After stakeholder review reveals gaps + +## Prerequisites + +- Feature specification exists (`requirements.md`) +- Should run BEFORE the Plan workflow + +## Execution Flow + +### Step 1: Load and Analyze Specification + +Read the specification and perform a structured ambiguity scan using this taxonomy: + +**Functional Scope & Behavior**: +- Core user goals & success criteria +- Explicit out-of-scope declarations +- User roles / personas differentiation + +**Domain & Data Model**: +- Entities, attributes, relationships +- Identity & uniqueness rules +- Lifecycle/state transitions +- Data volume / scale assumptions + +**Interaction & UX Flow**: +- Critical user journeys / sequences +- Error/empty/loading states +- Accessibility or localization notes + +**Non-Functional Quality Attributes**: +- Performance (latency, throughput targets) +- Scalability (horizontal/vertical, limits) +- Reliability & availability (uptime, recovery) +- Observability (logging, metrics, tracing) +- Security & privacy (authN/Z, data protection) +- Compliance / regulatory constraints + +**Integration & External Dependencies**: +- External services/APIs and failure modes +- Data import/export formats +- Protocol/versioning assumptions + +**Edge Cases & Failure Handling**: +- Negative scenarios +- Rate limiting / throttling +- Conflict resolution (concurrent edits) + +**Terminology & Consistency**: +- Canonical glossary terms +- Avoided synonyms / deprecated terms + +### Step 2: Generate Prioritized Questions + +Create a prioritized queue of clarification questions (maximum 5): + +**Question Constraints**: +- Must be answerable with: + - Multiple-choice (2-5 distinct options), OR + - Short phrase (<=5 words) +- Must materially impact architecture, data modeling, task decomposition, test design, UX behavior, or compliance +- Category coverage balance: highest impact first +- Exclude already-answered or trivial questions + +### Step 3: Sequential Questioning + +Present EXACTLY ONE question at a time. + +**For multiple-choice questions**: + +```markdown +**推荐:** 选项 [X] - [推荐理由] + +**可选答案:** + +► **A** - [选项 A 描述] + +► **B** - [选项 B 描述] + +► **C** - [选项 C 描述] + +► **其他** - 提供您自己的答案(≤5 个词) + +--- +回复选项字母(如 "A"),或输入 "yes" 接受推荐,或直接输入您的答案。 +``` + +**Example (示例)**: + +```markdown +**问题:** 系统应如何限制团队并发执行数量? + +**推荐:** 选项 C - 动态调整更灵活,能适应不同负载场景 + +**可选答案:** + +► **A** - 不限制,允许所有团队同时执行 + +► **B** - 限制最多 5 个团队同时执行 + +► **C** - 根据系统资源动态调整并发数 + +► **其他** - 提供您自己的答案(≤5 个词) + +--- +回复选项字母,或输入 "yes" 接受推荐,或直接输入您的答案。 +``` + +**For short-answer questions**: + +```markdown +**建议答案:** [您的建议] - [简要理由] + +请输入简短答案(≤5 个词)。 +输入 "yes" 接受建议,或直接输入您的答案。 +``` + +### Step 4: Record Answers (MANDATORY - DO NOT SKIP) + +**CRITICAL**: You MUST create and maintain a clarification log file. This is NON-NEGOTIABLE. + +#### 4.1 Create Clarification Log File (REQUIRED) + +Use `templates/clarifications-template.md` as reference. + +**IMMEDIATELY after the FIRST question is answered**, create the clarification log file: + +``` +.kiro/specs/[###-feature-name]/clarifications.md +``` + +**File Format (MUST follow exactly)**: + +```markdown +# Clarification Log: [FEATURE NAME] + +**Feature**: [###-feature-name] +**Session Date**: YYYY-MM-DD +**Total Questions**: [N] + +--- + +## Q1: [Question Title] + +**Category**: [Functional Scope / Domain & Data / Interaction & UX / Non-Functional / Integration / Edge Cases / Terminology] + +**Question**: [Complete question text] + +**Options Presented**: +- **A**: [Option A description] +- **B**: [Option B description] +- **C**: [Option C description] +- **Other**: Custom answer allowed + +**Recommended**: [Option X] - [Reason for recommendation] + +**User's Choice**: [Option letter or custom answer] + +**Resolution**: [How this was applied to the spec] + +--- + +## Q2: [Question Title] + +[Same format as above] + +--- + +## Summary + +| # | Question | Category | Choice | Applied To | +|---|----------|----------|--------|------------| +| 1 | [Brief question] | [Category] | [Choice] | [Section in spec] | +| 2 | [Brief question] | [Category] | [Choice] | [Section in spec] | + +--- + +## Impact on Specification + +- **Sections Modified**: [List of modified sections] +- **New Requirements Added**: [List if any] +- **Requirements Changed**: [List if any] +``` + +#### 4.2 Update Clarification Log After EACH Answer + +**After EACH question is answered, you MUST**: + +1. **Append the Q&A record** to `clarifications.md` immediately +2. **Update the Summary table** with the new entry +3. **Save the file** before asking the next question + +#### 4.3 Apply Clarification to Specification + +After recording in `clarifications.md`: + +1. Apply clarification to appropriate section in `requirements.md`: + - Functional ambiguity -> Functional Requirements + - User interaction -> User Stories + - Data shape -> Key Entities / Data Model + - Non-functional -> Quality Attributes section + - Edge case -> Edge Cases section + +2. If clarification invalidates earlier statement, replace it (no contradictions) + +3. Add reference in `requirements.md` Clarifications section: + ```markdown + ## Clarifications + + See [clarifications.md](./clarifications.md) for full clarification log. + + ### Session YYYY-MM-DD + - Q1: [brief question] -> A: [answer] + - Q2: [brief question] -> A: [answer] + ``` + +4. Save both files after each integration + +### Step 5: Stop Conditions + +Stop asking questions when: +- All critical ambiguities resolved +- User signals completion ("done", "good", "no more") +- Reached 5 asked questions + +### Step 6: Validation + +After each write: +- Clarifications section has one bullet per answer +- Total questions <= 5 +- No lingering vague placeholders +- No contradictory statements +- Markdown structure valid +- Terminology consistent + +### Step 7: Report Completion (MUST include file paths) + +**BEFORE reporting completion**, verify: +1. `clarifications.md` has been created and saved +2. `requirements.md` has been updated +3. All questions and answers are recorded + +Output completion report: + +```markdown +## Clarification Complete + +### Files Generated/Updated + +| File | Path | Status | +|------|------|--------| +| Clarification Log | `.kiro/specs/[###-feature-name]/clarifications.md` | CREATED | +| Requirements | `.kiro/specs/[###-feature-name]/requirements.md` | UPDATED | + +### Session Summary + +**Questions asked**: [N] +**Session date**: YYYY-MM-DD + +### Questions & Answers + +| # | Question | User's Choice | +|---|----------|---------------| +| 1 | [Brief question] | [Choice] | +| 2 | [Brief question] | [Choice] | + +### Coverage Summary + +| Category | Status | +|----------|--------| +| Functional Scope | Resolved / Clear / Deferred | +| Domain & Data | Resolved / Clear / Deferred | +| Interaction & UX | Resolved / Clear / Deferred | +| Non-Functional | Resolved / Clear / Deferred | +| Integration | Resolved / Clear / Deferred | +| Edge Cases | Resolved / Clear / Deferred | +| Terminology | Resolved / Clear / Deferred | + +**Status Legend**: +- Resolved: Was ambiguous, now clarified +- Clear: Already sufficient +- Deferred: Exceeds question quota or better for planning phase + +### Recommendation + +[Recommend proceeding to Plan or running Clarify again] +``` + +**IMPORTANT**: If `clarifications.md` was not created, DO NOT report completion. Go back and create the file first. + +## Behavior Rules + +- If no meaningful ambiguities found: "No critical ambiguities detected. Suggest proceeding to Plan." +- If spec file missing: "Please run Specify first." +- Never exceed 5 total questions +- Avoid speculative tech stack questions unless blocking functional clarity +- Respect user early termination signals + +## Output (MANDATORY FILES) + +After completing this workflow, you MUST have created/updated: + +1. **`clarifications.md`** (REQUIRED - New File) + - Location: `.kiro/specs/[###-feature-name]/clarifications.md` + - Contains: Complete Q&A log with all options, recommendations, and user choices + - Format: As specified in Step 4.1 + +2. **`requirements.md`** (REQUIRED - Updated) + - Clarifications applied to relevant sections + - Reference to `clarifications.md` in Clarifications section + - No contradictory statements + +**VALIDATION CHECKLIST** (verify before reporting completion): +- [ ] `clarifications.md` file exists +- [ ] All questions recorded with complete details +- [ ] All user choices documented +- [ ] Summary table is complete +- [ ] `requirements.md` updated with applied clarifications +- [ ] `requirements.md` references `clarifications.md` + +## Next Steps + +Suggest to the user: +``` +Clarification complete. + +Next, you can: +1. Run **Plan** to create technical implementation plan +2. Run **Clarify** again if deferred items need resolution +3. Review updated spec before proceeding +``` diff --git a/spec-kit/steering/04-plan-workflow.md b/spec-kit/steering/04-plan-workflow.md new file mode 100644 index 0000000..430824b --- /dev/null +++ b/spec-kit/steering/04-plan-workflow.md @@ -0,0 +1,279 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Plan workflow - converts requirements into technical architecture and design" +keywords: ["plan", "design", "architecture", "technical", "计划", "设计", "架构", "技术方案"] +--- + +# Plan Workflow + +This workflow converts business requirements into technical architecture and implementation plans. + +## Purpose + +Transform feature specifications into detailed technical plans that: +- Map requirements to technical decisions +- Document technology choices with rationale +- Create data models and API contracts +- Ensure steering compliance + +## When to Use + +- Feature specification is complete and clarified +- Ready to start technical planning +- Need to document architecture decisions + +## Prerequisites + +- Feature specification exists (`requirements.md`) +- Clarification complete (no critical `[NEEDS CLARIFICATION]` markers) +- Project steering files exist (optional but recommended) + +## Execution Flow + +### Step 1: Load Context + +Read required documents: +- Feature specification (`requirements.md`) +- Steering files (if exist): + - `.kiro/steering/product.md` - Product vision and constraints + - `.kiro/steering/tech.md` - Technology stack and principles + - `.kiro/steering/structure.md` - Project structure patterns + +### Step 2: Create Design File + +Create `design.md` in the feature directory using `templates/design-template.md` as reference: +``` +.kiro/specs/[###-feature-name]/ +├── requirements.md +└── design.md # Create this +``` + +### Step 3: Gather Technical Context + +If `.kiro/steering/tech.md` exists, use it as reference. Otherwise, determine or ask about: +- **Language/Version**: e.g., Python 3.11, TypeScript 5.0 +- **Primary Dependencies**: e.g., FastAPI, React, Express +- **Storage**: e.g., PostgreSQL, MongoDB, files +- **Testing**: e.g., pytest, Jest, Vitest +- **Target Platform**: e.g., Linux server, iOS, Web +- **Project Type**: single/web/mobile +- **Performance Goals**: domain-specific targets +- **Constraints**: specific limitations +- **Scale/Scope**: expected usage levels + +Mark any unknowns as `NEEDS CLARIFICATION` for research phase. + +### Step 4: Steering Check + +If steering files exist, evaluate compliance: + +```markdown +## Steering Check + +*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* + +### Product Alignment (from product.md) +- [ ] Aligns with product vision? +- [ ] Respects business constraints? +- [ ] Meets non-functional requirements? + +### Tech Compliance (from tech.md) +- [ ] Uses approved technology stack? +- [ ] Follows development principles? +- [ ] Passes quality gates? + +### Structure Compliance (from structure.md) +- [ ] Follows project layout? +- [ ] Uses correct naming conventions? +- [ ] Respects module organization rules? +``` + +**ERROR if violations not justified.** + +### Step 4: Phase 0 - Research + +For each unknown in Technical Context: + +1. **Extract unknowns**: Each `NEEDS CLARIFICATION` -> research task +2. **Research dependencies**: Best practices for chosen technologies +3. **Evaluate patterns**: Integration approaches + +**Output**: `research.md` with format: +```markdown +# Research: [FEATURE] + +## Decision 1: [Topic] +- **Decision**: [What was chosen] +- **Rationale**: [Why chosen] +- **Alternatives**: [What else evaluated] + +## Decision 2: [Topic] +... +``` + +### Step 5: Phase 1 - Design + +**Prerequisites**: `research.md` complete + +#### Generate Data Model + +Extract entities from feature spec: +```markdown +# Data Model: [FEATURE] + +## Entity: [Name] +- **Purpose**: [What it represents] +- **Fields**: + - `id`: unique identifier + - `field1`: [type] - [description] + - `field2`: [type] - [description] +- **Relationships**: [Links to other entities] +- **Validation**: [Rules from requirements] +- **State Transitions**: [If applicable] + +## Entity: [Name] +... +``` + +#### Generate API Contracts + +For each user action -> endpoint: +```markdown +# API Contracts: [FEATURE] + +## POST /api/[resource] +- **Purpose**: [From user story] +- **Request**: [Schema] +- **Response**: [Schema] +- **Errors**: [Error cases] +``` + +Or use OpenAPI/GraphQL schema in `/contracts/` directory. + +#### Generate Quickstart + +Key validation scenarios: +```markdown +# Quickstart: [FEATURE] + +## Scenario 1: [Happy Path] +1. [Step] +2. [Step] +3. [Expected Result] + +## Scenario 2: [Edge Case] +... +``` + +### Step 6: Create Implementation Plan + +Generate the plan document: + +```markdown +# Implementation Plan: [FEATURE] + +**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link] + +## Summary + +[Primary requirement + technical approach] + +## Technical Context + +**Language/Version**: [e.g., Python 3.11] +**Primary Dependencies**: [e.g., FastAPI, SQLAlchemy] +**Storage**: [e.g., PostgreSQL] +**Testing**: [e.g., pytest] +**Target Platform**: [e.g., Linux server] +**Project Type**: [single/web/mobile] +**Performance Goals**: [specific targets] +**Constraints**: [limitations] +**Scale/Scope**: [expected usage] + +## Steering Check + +[Gates and compliance status] + +## Project Structure + +### Documentation (this feature) +```text +.kiro/specs/[###-feature]/ +├── design.md # This file +├── research.md # Phase 0 output +├── data-model.md # Phase 1 output +├── quickstart.md # Phase 1 output +├── contracts/ # Phase 1 output +└── tasks.md # Tasks workflow output +``` + +### Source Code +```text +src/ +├── models/ +├── services/ +├── cli/ or api/ +└── lib/ +tests/ +├── contract/ +├── integration/ +└── unit/ +``` + +## Complexity Tracking + +> Fill ONLY if Steering Check has violations to justify + +| Violation | Why Needed | Simpler Alternative Rejected Because | +|-----------|------------|-------------------------------------| +| [violation] | [reason] | [why simpler won't work] | +``` + +### Step 7: Re-evaluate Steering + +After design phase, re-check steering compliance: +- Have new decisions violated any principles? +- Document justifications if needed + +### Step 8: Report Completion + +```markdown +## Plan Complete + +**Branch**: [branch-name] +**Plan**: [path to design.md] + +### Generated Artifacts +- design.md - Implementation plan +- research.md - Technology decisions +- data-model.md - Entity definitions +- contracts/ - API specifications +- quickstart.md - Validation scenarios + +### Steering Status +[Pass / Violations justified] + +### Ready for Tasks Workflow +``` + +## Output + +After completing this workflow: +- `design.md` - Implementation plan +- `research.md` - Research decisions +- `data-model.md` - Data model +- `contracts/` - API contracts +- `quickstart.md` - Validation scenarios + +## Next Steps + +Suggest to the user: +``` +Plan created at .kiro/specs/[###-feature-name]/design.md + +Next, you can: +1. Run **Tasks** to generate executable task list +2. Review plan artifacts before proceeding +3. Run **Checklist** to create quality checklists +``` diff --git a/spec-kit/steering/05-tasks-workflow.md b/spec-kit/steering/05-tasks-workflow.md new file mode 100644 index 0000000..84f1b2d --- /dev/null +++ b/spec-kit/steering/05-tasks-workflow.md @@ -0,0 +1,230 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Tasks workflow - breaks plans into executable task lists" +keywords: ["tasks", "task", "breakdown", "todolist", "任务", "任务分解", "待办"] +--- + +# Tasks Workflow + +This workflow generates an actionable, dependency-ordered task list from the implementation plan. + +## Purpose + +Break down the implementation plan into executable tasks that: +- Are organized by user story for independent testing +- Have clear dependencies and parallel execution markers +- Include specific file paths +- Can be immediately executed by an AI agent + +## When to Use + +- Implementation plan is complete +- Ready to start implementation +- Need a clear task breakdown + +## Prerequisites + +- **Required**: `design.md` (tech stack, libraries, structure) +- **Required**: `requirements.md` (user stories with priorities) +- **Optional**: `data-model.md` (entities) +- **Optional**: `contracts/` (API endpoints) +- **Optional**: `research.md` (decisions) +- **Optional**: `quickstart.md` (test scenarios) + +## Execution Flow + +### Step 1: Load Design Documents + +Read from feature directory (`.kiro/specs/[###-feature-name]/`): +1. `design.md` - Extract tech stack, libraries, project structure +2. `requirements.md` - Extract user stories with priorities (P1, P2, P3) +3. If exists: `data-model.md` - Extract entities +4. If exists: `contracts/` - Map endpoints +5. If exists: `research.md` - Extract setup decisions + +### Step 2: Map Requirements to Tasks + +**From User Stories (PRIMARY ORGANIZATION)**: +- Each user story (P1, P2, P3) gets its own phase +- Map related components to their story: + - Models needed for that story + - Services needed for that story + - Endpoints/UI needed for that story + - Tests specific to that story + +**From Contracts**: +- Map each endpoint to the user story it serves +- Contract tests before implementation (if requested) + +**From Data Model**: +- Map each entity to user story(ies) that need it +- If entity serves multiple stories: put in earliest or Setup phase + +**From Infrastructure**: +- Shared infrastructure -> Setup phase +- Story-specific setup -> within that story's phase + +### Step 3: Generate Task List + +Use `templates/tasks-template.md` as reference for the output format. + +#### Task Format (REQUIRED) + +Every task MUST follow this format: +``` +- [ ] [TaskID] [P?] [Story?] Description with file path +``` + +**Format Components**: +1. **Checkbox**: ALWAYS start with `- [ ]` +2. **Task ID**: Sequential (T001, T002, T003...) +3. **[P] marker**: ONLY if task is parallelizable +4. **[Story] label**: REQUIRED for user story phases (US1, US2, etc.) +5. **Description**: Clear action with exact file path + +**Examples**: +```markdown +- [ ] T001 Create project structure per implementation plan +- [ ] T005 [P] Implement authentication middleware in src/middleware/auth.py +- [ ] T012 [P] [US1] Create User model in src/models/user.py +- [ ] T014 [US1] Implement UserService in src/services/user_service.py +``` + +**WRONG** (don't do this): +```markdown +- [ ] Create User model # Missing ID and Story label +T001 [US1] Create model # Missing checkbox +- [ ] [US1] Create User model # Missing Task ID +- [ ] T001 [US1] Create model # Missing file path +``` + +### Step 4: Organize by Phase + +```markdown +# Tasks: [FEATURE NAME] + +## Phase 1: Setup +[Project initialization tasks] + +- [ ] T001 Create project directory structure +- [ ] T002 [P] Initialize package.json with dependencies +- [ ] T003 [P] Create configuration files + +## Phase 2: Foundational +[Blocking prerequisites for all user stories] + +- [ ] T004 Create database schema +- [ ] T005 [P] Implement base model classes + +## Phase 3: User Story 1 - [Title] (P1) + +**Goal**: [Story goal from spec] +**Independent Test**: [How to test this story alone] + +- [ ] T006 [US1] Create Entity model in src/models/entity.py +- [ ] T007 [US1] Implement EntityService in src/services/entity_service.py +- [ ] T008 [US1] Create API endpoint in src/api/entity.py + +## Phase 4: User Story 2 - [Title] (P2) + +**Goal**: [Story goal] +**Independent Test**: [How to test] + +- [ ] T009 [US2] ... +- [ ] T010 [US2] ... + +## Phase N: Polish & Cross-Cutting + +- [ ] T0XX Add logging throughout application +- [ ] T0XX Update documentation + +## Dependencies + +```mermaid +graph TD + US1[User Story 1] --> US2[User Story 2] + US1 --> US3[User Story 3] +``` + +## Parallel Execution + +### Within Phase 3 (US1) +T006, T007 can run in parallel (different files) +T008 depends on T006, T007 + +## Implementation Strategy + +- **MVP Scope**: Complete Phase 3 (User Story 1) for minimum viable product +- **Incremental Delivery**: Each user story phase is independently testable +``` + +### Step 5: Validate Tasks + +**Checklist Format Validation**: +- [ ] ALL tasks start with `- [ ]` +- [ ] ALL tasks have Task ID (T001, T002...) +- [ ] User Story phase tasks have [USx] label +- [ ] ALL tasks have file paths where applicable +- [ ] [P] markers only on parallelizable tasks + +**Coverage Validation**: +- [ ] Each user story has all needed tasks +- [ ] Each story is independently testable +- [ ] Dependencies are clear +- [ ] No orphan tasks (tasks without requirement source) + +### Step 6: Report Completion + +```markdown +## Tasks Generated + +**Output**: [path to tasks.md] + +### Summary +- Total tasks: [N] +- Setup phase: [N] tasks +- Foundational phase: [N] tasks +- User Story phases: [N] stories, [N] tasks each +- Polish phase: [N] tasks + +### Parallel Opportunities +[N] tasks marked for parallel execution + +### MVP Scope +User Story 1 (Phase 3) provides minimum viable product + +### Format Validation +All tasks follow checklist format: PASS/FAIL +``` + +## Tests Are Optional + +Test tasks should ONLY be generated if: +- Explicitly requested in feature specification +- User requests TDD approach +- Steering (tech.md) mandates test-first + +If tests are included, order within each story phase: +1. Tests (contract -> integration -> e2e -> unit) +2. Models +3. Services +4. Endpoints +5. Integration + +## Output + +After completing this workflow: +- `tasks.md` - Complete task list organized by user story + +## Next Steps + +Suggest to the user: +``` +Tasks generated at .kiro/specs/[###-feature-name]/tasks.md + +Next, you can: +1. Run **Analyze** to validate consistency across spec/plan/tasks +2. Run **Implement** to start execution +3. Review tasks before proceeding +``` diff --git a/spec-kit/steering/06-implement-workflow.md b/spec-kit/steering/06-implement-workflow.md new file mode 100644 index 0000000..6a1f8bd --- /dev/null +++ b/spec-kit/steering/06-implement-workflow.md @@ -0,0 +1,223 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Implement workflow - executes tasks with TDD approach" +keywords: ["implement", "implementation", "execute", "coding", "TDD", "实现", "编码", "开发"] +--- + +# Implement Workflow + +This workflow executes the implementation plan by processing tasks from `tasks.md`. + +## Purpose + +Execute tasks systematically to build the feature: +- Phase-by-phase execution +- TDD approach when tests are included +- Progress tracking with checkmarks +- Validation at each checkpoint + +## When to Use + +- Tasks have been generated +- Ready to start coding +- Want AI-assisted implementation + +## Prerequisites + +- **Required**: `tasks.md` - Complete task list +- **Required**: `design.md` - Tech stack and architecture +- **Optional**: `data-model.md` - Entity definitions +- **Optional**: `contracts/` - API specifications +- **Optional**: `research.md` - Technical decisions +- **Optional**: `quickstart.md` - Validation scenarios +- **Optional**: `checklists/` - Quality checklists + +## Execution Flow + +### Step 1: Check Checklists (if exist) + +If `checklists/` directory exists, scan all checklist files: + +```markdown +| Checklist | Total | Completed | Incomplete | Status | +|-----------|-------|-----------|------------|--------| +| ux.md | 12 | 12 | 0 | PASS | +| test.md | 8 | 5 | 3 | FAIL | +| security.md | 6 | 6 | 0 | PASS | +``` + +**If any checklist incomplete**: +- Display the table +- Ask: "Some checklists are incomplete. Proceed anyway? (yes/no)" +- Wait for user response + +**If all complete**: Proceed automatically + +### Step 2: Load Implementation Context + +Read required documents: +- `tasks.md` - Task list and execution plan +- `design.md` - Tech stack, architecture, file structure + +Read if available: +- `data-model.md` - Entities and relationships +- `contracts/` - API specifications +- `research.md` - Technical decisions +- `quickstart.md` - Integration scenarios + +### Step 3: Project Setup Verification + +Create/verify ignore files based on detected technologies: + +**Detection Logic**: +- Git repo? -> `.gitignore` +- Dockerfile exists? -> `.dockerignore` +- ESLint config? -> `.eslintignore` or config ignores +- Prettier config? -> `.prettierignore` +- Terraform files? -> `.terraformignore` + +**Common Patterns by Technology**: + +| Technology | Patterns | +|------------|----------| +| Node.js | `node_modules/`, `dist/`, `build/`, `*.log`, `.env*` | +| Python | `__pycache__/`, `*.pyc`, `.venv/`, `dist/` | +| Java | `target/`, `*.class`, `*.jar`, `.gradle/`, `build/` | +| Go | `*.exe`, `*.test`, `vendor/`, `*.out` | +| Rust | `target/`, `debug/`, `release/`, `*.rs.bk` | + +**Universal**: `.DS_Store`, `Thumbs.db`, `.vscode/`, `.idea/` + +### Step 4: Parse Task Structure + +Extract from `tasks.md`: +- **Task phases**: Setup, Foundational, User Stories, Polish +- **Task dependencies**: Sequential vs parallel +- **Task details**: ID, description, file paths, [P] markers +- **Execution flow**: Order and dependencies + +### Step 5: Execute Tasks + +#### Execution Rules + +1. **Phase-by-phase**: Complete each phase before moving to next +2. **Respect dependencies**: Run sequential tasks in order +3. **Parallel execution**: Tasks with [P] can run together if different files +4. **TDD approach**: If tests exist, run test tasks before implementation +5. **File coordination**: Tasks affecting same files run sequentially +6. **Validation checkpoints**: Verify phase completion before proceeding + +#### Execution Order + +1. **Setup first**: Project structure, dependencies, configuration +2. **Tests before code** (if TDD): Write tests for contracts/entities +3. **Core development**: Models, services, CLI/endpoints +4. **Integration**: Database, middleware, external services +5. **Polish**: Unit tests, optimization, documentation + +### Step 6: Progress Tracking + +After completing each task: +1. Mark task as complete in `tasks.md`: `- [X] T001 ...` +2. Report progress to user +3. If task fails: halt and report error +4. For parallel tasks: continue with successful ones, report failures + +### Step 7: Error Handling + +**Non-parallel task fails**: +- Halt execution +- Report clear error with context +- Suggest debugging steps +- Ask how to proceed + +**Parallel task fails**: +- Continue with other parallel tasks +- Report failure +- Allow user to decide: fix and retry, skip, or stop + +### Step 8: Validation Checkpoints + +At each phase completion: +- Verify all phase tasks completed +- Run any phase-specific tests +- Check against quickstart scenarios +- Report status before proceeding + +### Step 9: Completion Validation + +After all tasks: +- [ ] All required tasks completed +- [ ] Implemented features match specification +- [ ] Tests pass (if applicable) +- [ ] Implementation follows technical plan +- [ ] All tasks marked [X] in tasks.md + +### Step 10: Report Completion + +```markdown +## Implementation Complete + +### Summary +- Total tasks: [N] +- Completed: [N] +- Failed: [N] +- Skipped: [N] + +### Phase Status +| Phase | Tasks | Status | +|-------|-------|--------| +| Setup | N/N | Complete | +| Foundational | N/N | Complete | +| US1 | N/N | Complete | +| US2 | N/N | Complete | +| Polish | N/N | Complete | + +### Validation +- Tests passing: Yes/No +- Quickstart scenarios: Verified/Not verified + +### Files Created/Modified +[List of files] + +### Next Steps +[Recommendations] +``` + +## TDD Approach Details + +When tests are included: + +1. **Red Phase**: Write failing tests + - Contract tests first + - Then integration tests + - Then unit tests + +2. **Green Phase**: Write minimal code to pass + - Implement just enough to pass tests + - No extra features + +3. **Refactor Phase**: Clean up while green + - Improve code quality + - Keep tests passing + +## Output + +After completing this workflow: +- All tasks executed and marked complete in `tasks.md` +- Source code created per implementation plan +- Tests passing (if applicable) + +## Next Steps + +Suggest to the user: +``` +Implementation complete. + +Next, you can: +1. Run **Analyze** to verify consistency +2. Run tests manually to confirm +3. Review generated code +4. Create PR for review +``` diff --git a/spec-kit/steering/07-analyze-workflow.md b/spec-kit/steering/07-analyze-workflow.md new file mode 100644 index 0000000..303f66b --- /dev/null +++ b/spec-kit/steering/07-analyze-workflow.md @@ -0,0 +1,250 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Analyze workflow - cross-artifact consistency validation" +keywords: ["analyze", "analysis", "consistency", "validation", "review", "分析", "一致性", "验证"] +--- + +# Analyze Workflow + +This workflow performs cross-artifact consistency and quality analysis across spec, plan, and tasks. + +## Purpose + +Identify inconsistencies, duplications, ambiguities, and underspecified items before implementation: +- **Non-destructive**: Read-only analysis +- **Steering-aware**: Flag principle violations +- **Coverage-focused**: Ensure all requirements have tasks + +## When to Use + +- After Tasks workflow, before Implement +- When artifacts seem inconsistent +- Before major reviews or milestones +- To validate specification quality + +## Prerequisites + +- **Required**: `requirements.md` - Feature specification +- **Required**: `design.md` - Implementation plan +- **Required**: `tasks.md` - Task list +- **Reference**: Steering files in `.kiro/steering/`: + - `product.md` - Product vision and constraints + - `tech.md` - Technology principles + - `structure.md` - Project structure rules + +## Operating Constraints + +**STRICTLY READ-ONLY**: Do NOT modify any files. Output analysis report only. + +**Steering Authority**: Steering files are authoritative. Steering conflicts are automatically CRITICAL. + +## Execution Flow + +### Step 1: Load Artifacts + +Load from feature directory (`.kiro/specs/[###-feature-name]/`): + +**From requirements.md**: +- Overview/Context +- Functional Requirements +- Non-Functional Requirements +- User Stories +- Edge Cases + +**From design.md**: +- Architecture/stack choices +- Data Model references +- Phases +- Technical constraints + +**From tasks.md**: +- Task IDs and descriptions +- Phase grouping +- Parallel markers [P] +- Referenced file paths + +**From steering files** (`.kiro/steering/`): +- `product.md`: Product vision, business constraints +- `tech.md`: Development principles, quality gates +- `structure.md`: Project layout, naming conventions + +### Step 2: Build Semantic Models + +Create internal representations: + +1. **Requirements inventory**: Each requirement with stable key + - `user-can-upload-file` from "User can upload file" + +2. **User story inventory**: Actions with acceptance criteria + +3. **Task coverage mapping**: Map tasks to requirements/stories + +4. **Steering rule set**: Extracted principles from tech.md, product.md, structure.md + +### Step 3: Run Detection Passes + +Limit to 50 findings total. Focus on high-signal issues. + +#### A. Duplication Detection +- Near-duplicate requirements +- Mark lower-quality phrasing for consolidation + +#### B. Ambiguity Detection +- Vague adjectives without metrics: fast, scalable, secure, intuitive, robust +- Unresolved placeholders: TODO, TKTK, ???, `` + +#### C. Underspecification +- Requirements with verbs but missing object or outcome +- User stories missing acceptance criteria +- Tasks referencing undefined components + +#### D. Steering Alignment +- Requirements conflicting with MUST principles +- Missing mandated sections or quality gates + +#### E. Coverage Gaps +- Requirements with zero associated tasks +- Tasks with no mapped requirement +- Non-functional requirements not in tasks + +#### F. Inconsistency +- Terminology drift (same concept, different names) +- Data entities in plan but not spec (or vice versa) +- Task ordering contradictions +- Conflicting requirements + +### Step 4: Assign Severity + +| Severity | Criteria | +|----------|----------| +| CRITICAL | Violates steering MUST, missing core artifact, requirement with zero coverage blocking baseline | +| HIGH | Duplicate/conflicting requirement, ambiguous security/performance, untestable acceptance | +| MEDIUM | Terminology drift, missing non-functional coverage, underspecified edge case | +| LOW | Style/wording improvements, minor redundancy | + +### Step 5: Generate Report + +Output Markdown report (do NOT write to file): + +```markdown +# Specification Analysis Report + +## Findings + +| ID | Category | Severity | Location(s) | Summary | Recommendation | +|----|----------|----------|-------------|---------|----------------| +| D1 | Duplication | HIGH | requirements.md:L120 | Two similar requirements | Merge, keep clearer version | +| A1 | Ambiguity | MEDIUM | requirements.md:L45 | "fast" undefined | Add specific metric | +| C1 | Steering | CRITICAL | design.md:L30 | 4 projects violates tech.md | Justify or simplify | +| G1 | Coverage | HIGH | requirements.md FR-005 | No task for requirement | Add task to tasks.md | + +## Coverage Summary + +| Requirement Key | Has Task? | Task IDs | Notes | +|-----------------|-----------|----------|-------| +| user-can-login | Yes | T003, T004 | | +| user-can-upload | No | - | CRITICAL: Missing coverage | +| admin-can-delete | Yes | T012 | | + +## Steering Alignment Issues + +| Principle | Status | Issue | +|-----------|--------|-------| +| Simplicity (Art VII) | FAIL | 4 projects without justification | +| Test-First (Art III) | PASS | Tests before implementation | + +## Unmapped Tasks + +| Task ID | Description | Issue | +|---------|-------------|-------| +| T015 | Add caching layer | No requirement source | + +## Metrics + +- Total Requirements: [N] +- Total Tasks: [N] +- Coverage %: [N]% (requirements with >=1 task) +- Ambiguity Count: [N] +- Duplication Count: [N] +- Critical Issues: [N] +``` + +### Step 6: Provide Next Actions + +```markdown +## Next Actions + +### Critical Issues (must resolve) +1. [Issue] - [Recommendation] +2. [Issue] - [Recommendation] + +### Recommended Fixes +1. [Issue] - [Recommendation] + +### Suggested Commands +- Run `/speckit.specify` with refinement to address spec gaps +- Run `/speckit.plan` to adjust architecture +- Manually edit tasks.md to add coverage for [requirement] + +### Proceed to Implement? +[Recommendation based on analysis] +``` + +### Step 7: Offer Remediation + +Ask user: +``` +Would you like me to suggest concrete remediation edits for the top [N] issues? + +Note: I will NOT apply them automatically. You must approve each change. +``` + +## Analysis Guidelines + +- **NEVER modify files** (read-only) +- **NEVER hallucinate** missing sections +- **Prioritize steering violations** (always CRITICAL) +- **Use examples** over exhaustive rules +- **Report zero issues gracefully** with coverage statistics + +## Severity Quick Reference + +**CRITICAL** (must fix): +- Steering MUST violation +- Missing core spec/plan/tasks +- Requirement with zero coverage blocking baseline + +**HIGH** (should fix): +- Duplicate or conflicting requirement +- Ambiguous security/performance +- Untestable acceptance criterion + +**MEDIUM** (nice to fix): +- Terminology drift +- Missing non-functional coverage +- Underspecified edge case + +**LOW** (optional): +- Style/wording improvements +- Minor redundancy + +## Output + +After completing this workflow: +- Analysis report displayed +- No files modified +- Remediation offered (not applied) + +## Next Steps + +Suggest to the user: +``` +Analysis complete. + +Next, you can: +1. Address CRITICAL issues before implementation +2. Run **Implement** if no blockers +3. Request remediation suggestions for top issues +4. Re-run analysis after fixes +``` diff --git a/spec-kit/steering/08-checklist-workflow.md b/spec-kit/steering/08-checklist-workflow.md new file mode 100644 index 0000000..0ac4c1d --- /dev/null +++ b/spec-kit/steering/08-checklist-workflow.md @@ -0,0 +1,256 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Checklist workflow - generates quality validation checklists" +keywords: ["checklist", "quality", "validation", "gate", "检查清单", "质量", "门禁"] +--- + +# Checklist Workflow + +This workflow generates domain-specific quality checklists for requirement validation. + +## Purpose + +Create checklists that are **"Unit Tests for Requirements"** - validating the quality of requirements themselves, NOT testing implementation. + +## Core Concept + +**CRITICAL**: Checklists validate REQUIREMENTS QUALITY, not implementation behavior. + +**NOT for verification**: +- "Verify the button clicks correctly" +- "Test error handling works" +- "Confirm the API returns 200" + +**FOR requirements quality**: +- "Are visual hierarchy requirements defined for all card types?" +- "Is 'prominent display' quantified with specific sizing?" +- "Are accessibility requirements specified for keyboard navigation?" + +## When to Use + +- After Specify, to validate spec quality +- Before Plan, to ensure spec is ready +- Before Implementation, as quality gates +- For specific domain validation (UX, security, API) + +## Prerequisites + +- Feature specification exists (`requirements.md`) +- Optional: `design.md`, `tasks.md` for additional context + +## Execution Flow + +### Step 1: Clarify Intent + +Ask up to THREE contextual questions to understand: + +**Generation Algorithm**: +1. Extract signals from user request: domain keywords (auth, UX, API), risk indicators, stakeholder hints +2. Cluster signals into candidate focus areas (max 4) +3. Identify audience & timing (author, reviewer, QA) +4. Detect missing dimensions: scope, depth, risk emphasis +5. Formulate questions from these archetypes: + - Scope refinement + - Risk prioritization + - Depth calibration + - Audience framing + - Boundary exclusion + +**Question Formatting**: +```markdown +Q1: [Question] + +| Option | Candidate | Why It Matters | +|--------|-----------|----------------| +| A | [Option A] | [Impact] | +| B | [Option B] | [Impact] | +| C | [Option C] | [Impact] | +``` + +**Defaults** (if interaction impossible): +- Depth: Standard +- Audience: Reviewer (PR) if code-related +- Focus: Top 2 relevance clusters + +### Step 2: Load Feature Context + +Read from feature directory: +- `requirements.md`: Requirements and scope +- `design.md` (if exists): Technical details +- `tasks.md` (if exists): Implementation tasks + +**Context Loading Strategy**: +- Load only portions relevant to focus areas +- Summarize long sections +- Progressive disclosure: add retrieval only if gaps detected + +### Step 3: Generate Checklist + +#### File Naming +- Create `checklists/` directory if needed +- Use descriptive names: `ux.md`, `api.md`, `security.md` +- Each run creates NEW file (never overwrites) + +#### Checklist Structure + +```markdown +# [Domain] Requirements Quality Checklist: [FEATURE NAME] + +**Purpose**: Validate [domain] requirement completeness and quality +**Created**: [DATE] +**Feature**: [Link to requirements.md] + +## Requirement Completeness +[Items checking if all necessary requirements exist] + +- [ ] CHK001 - Are [requirement type] defined for [scenario]? [Completeness] +- [ ] CHK002 - Are [edge cases] addressed in requirements? [Coverage, Gap] + +## Requirement Clarity +[Items checking if requirements are unambiguous] + +- [ ] CHK003 - Is '[vague term]' quantified with specific criteria? [Clarity, Spec §X.Y] +- [ ] CHK004 - Can '[requirement]' be objectively measured? [Measurability] + +## Requirement Consistency +[Items checking alignment across requirements] + +- [ ] CHK005 - Do [area A] requirements align with [area B]? [Consistency] +- [ ] CHK006 - Is terminology consistent for '[concept]'? [Consistency] + +## Scenario Coverage +[Items checking if all flows are addressed] + +- [ ] CHK007 - Are primary flow requirements complete? [Coverage, Spec §X.Y] +- [ ] CHK008 - Are error/exception requirements defined? [Coverage, Gap] + +## Notes + +[Any additional context or guidance] +``` + +### Step 4: Write Checklist Items + +**EVERY item MUST test REQUIREMENTS QUALITY**: + +| Quality Dimension | Pattern | Example | +|-------------------|---------|---------| +| Completeness | "Are [X] requirements defined?" | "Are error handling requirements defined for all API failures?" | +| Clarity | "Is [X] quantified/specified?" | "Is 'fast loading' quantified with timing thresholds?" | +| Consistency | "Do [X] and [Y] align?" | "Do navigation requirements align across all pages?" | +| Measurability | "Can [X] be objectively verified?" | "Can 'visual hierarchy' be objectively measured?" | +| Coverage | "Are [scenarios] addressed?" | "Are zero-state scenarios defined?" | +| Edge Cases | "Is [boundary] defined?" | "Is fallback behavior specified for image load failure?" | + +**Item Structure**: +``` +- [ ] CHK### - [Question about requirement quality] [Dimension, Reference] +``` + +**References**: +- `[Spec §X.Y]` - Checking existing requirement +- `[Gap]` - Checking for missing requirement +- `[Ambiguity]` - Flagging unclear wording +- `[Conflict]` - Flagging contradictions +- `[Assumption]` - Flagging undocumented assumptions + +### Step 5: Traceability Requirements + +**MINIMUM**: >=80% of items must include traceability reference + +Each item should reference: +- Spec section: `[Spec §FR-001]` +- Gap marker: `[Gap]` +- Quality marker: `[Ambiguity]`, `[Conflict]`, `[Assumption]` + +### Step 6: Content Consolidation + +- Soft cap: If >40 candidate items, prioritize by risk/impact +- Merge near-duplicates +- If >5 low-impact edge cases, consolidate: "Are edge cases X, Y, Z addressed?" + +## Prohibited Patterns + +**ABSOLUTELY PROHIBITED** (makes it implementation test): +- Any item starting with "Verify", "Test", "Confirm" + implementation behavior +- References to code execution, user actions, system behavior +- "Displays correctly", "works properly", "functions as expected" +- "Click", "navigate", "render", "load", "execute" +- Test cases, test plans, QA procedures +- Implementation details (frameworks, APIs) + +**REQUIRED PATTERNS**: +- "Are [requirement type] defined/specified for [scenario]?" +- "Is [vague term] quantified with specific criteria?" +- "Are requirements consistent between [A] and [B]?" +- "Can [requirement] be objectively measured?" +- "Does the spec define [missing aspect]?" + +## Example Checklists + +### UX Requirements Quality (`ux.md`) +```markdown +- [ ] CHK001 - Are visual hierarchy requirements defined with measurable criteria? [Clarity, Spec §FR-1] +- [ ] CHK002 - Is the number and positioning of UI elements explicitly specified? [Completeness, Spec §FR-1] +- [ ] CHK003 - Are interaction state requirements (hover, focus, active) consistently defined? [Consistency] +- [ ] CHK004 - Are accessibility requirements specified for all interactive elements? [Coverage, Gap] +- [ ] CHK005 - Is fallback behavior defined when images fail to load? [Edge Case, Gap] +``` + +### API Requirements Quality (`api.md`) +```markdown +- [ ] CHK001 - Are error response formats specified for all failure scenarios? [Completeness] +- [ ] CHK002 - Are rate limiting requirements quantified with specific thresholds? [Clarity] +- [ ] CHK003 - Are authentication requirements consistent across all endpoints? [Consistency] +- [ ] CHK004 - Are retry/timeout requirements defined for external dependencies? [Coverage, Gap] +``` + +### Security Requirements Quality (`security.md`) +```markdown +- [ ] CHK001 - Are authentication requirements specified for all protected resources? [Coverage] +- [ ] CHK002 - Are data protection requirements defined for sensitive information? [Completeness] +- [ ] CHK003 - Is the threat model documented and requirements aligned to it? [Traceability] +- [ ] CHK004 - Are security failure response requirements defined? [Gap, Exception Flow] +``` + +## Output + +After completing this workflow: +- Checklist file created at `checklists/[domain].md` +- Items numbered CHK001, CHK002, etc. +- Ready for review before implementation + +## Report + +```markdown +## Checklist Generated + +**Path**: [full path to checklist] +**Items**: [N] checklist items + +### Focus Areas +[Selected focus areas] + +### Depth Level +[Standard/Comprehensive/Light] + +### Audience +[Author/Reviewer/QA] + +### Traceability +[N]% of items have spec references +``` + +## Next Steps + +Suggest to the user: +``` +Checklist created at checklists/[domain].md + +Next, you can: +1. Review and complete the checklist +2. Run **Implement** (will check checklist status) +3. Create additional checklists for other domains +4. Run **Analyze** for full consistency check +``` diff --git a/spec-kit/steering/09-sync-workflow.md b/spec-kit/steering/09-sync-workflow.md new file mode 100644 index 0000000..c269a0f --- /dev/null +++ b/spec-kit/steering/09-sync-workflow.md @@ -0,0 +1,263 @@ +--- +inclusion: auto +globs: ["**/*.md"] +description: "Sync workflow - synchronize documentation with implementation and generate retrospective report" +keywords: ["sync", "synchronize", "documentation", "retrospective", "deviation", "implementation", "同步", "回顾", "文档"] +--- + +# Sync Workflow + +This workflow synchronizes project documentation with actual implementation after development completion, generating a comprehensive retrospective report. + +## Purpose + +After a feature implementation is complete, align all documentation to reflect the actual state of the codebase: +- **Non-destructive by default**: Show proposed changes before applying +- **Comprehensive detection**: Scan all relevant documentation files +- **Retrospective analysis**: Compare planned vs actual implementation +- **Knowledge preservation**: Capture lessons learned and deviations + +## When to Use + +- After completing feature implementation +- After a deployment or release +- When documentation may be out of sync with code +- To generate lessons learned for retrospectives +- Before handoff or team transitions + +## Prerequisites + +**No strict prerequisites** - this command runs at any time. Missing files will be noted but won't block execution. + +**Files scanned if present**: +- `requirements.md` - Feature specification +- `design.md` - Implementation plan +- `tasks.md` - Task list +- `.kiro/steering/product.md` - Product principles +- `.kiro/steering/tech.md` - Technology principles +- `.kiro/steering/structure.md` - Project structure +- `README.md` - Project documentation + +## Operating Constraints + +**NON-DESTRUCTIVE BY DEFAULT**: Show proposed changes before applying; require user confirmation for modifications. + +**Update Modes**: +- **Interactive** (default): Ask for confirmation before each change +- **Preview Only**: Show all proposed changes without applying +- **Report Only**: Only generate sync report, don't propose updates + +## Execution Flow + +### Step 1: Initialize Sync Context + +Identify the feature directory and gather paths: +- Feature specification directory (`.kiro/specs/[###-feature-name]/`) +- Steering files location (`.kiro/steering/`) +- README and other project docs + +**File Existence Check**: +For each missing file: +- Log it in the sync report under "Missing Artifacts" +- Skip related analysis steps +- Continue with available files + +### Step 2: Scan Implementation State + +Analyze the actual codebase to understand what was implemented: + +**Code Analysis**: +- Scan source directories for implemented features, components, and modules +- Identify public APIs, endpoints, and interfaces +- Detect technology stack actually used (frameworks, libraries, versions) +- Map file structure and architecture patterns + +**Git Analysis (if available)**: +- Review recent commits related to the feature +- Identify files changed since feature branch creation +- Note any hotfixes or post-implementation changes + +### Step 3: Compare Plan vs Reality + +Create a deviation analysis by comparing: + +| Aspect | Planned (from docs) | Actual (from code) | Status | +|--------|--------------------|--------------------|--------| +| Architecture | From design.md | Detected patterns | MATCH / DEVIATION | +| Tech Stack | From design.md | Package files, imports | MATCH / DEVIATION | +| API Endpoints | From requirements.md/contracts | Actual routes/handlers | MATCH / DEVIATION | +| Data Models | From requirements.md/data-model.md | Actual schemas/entities | MATCH / DEVIATION | +| Features | From requirements.md user stories | Implemented functionality | MATCH / DEVIATION / PARTIAL | + +**Deviation Categories**: +- **MATCH**: Implementation matches documentation +- **DEVIATION**: Implementation differs from documentation +- **PARTIAL**: Partially implemented or modified scope +- **ADDED**: Implemented but not in original spec (scope creep or enhancement) +- **REMOVED**: In spec but not implemented (descoped) + +### Step 4: Detect Documentation Requiring Updates + +Scan each documentation file and identify sections needing updates: + +#### A. requirements.md Updates +- Features that were descoped or modified +- New features added during implementation +- Updated acceptance criteria based on actual behavior +- Edge cases discovered during development + +#### B. design.md Updates +- Architecture changes from original design +- Technology substitutions or version changes +- Modified file structure +- Updated dependency list + +#### C. Steering Files Updates +- New architectural principles established +- Modified coding standards based on learnings +- Updated quality gates or review processes + +#### D. README.md Updates +- Installation/setup changes +- Updated usage examples +- New configuration options +- Changed prerequisites + +### Step 5: Generate Sync Report + +Use `templates/sync-report-template.md` as reference to create a comprehensive sync report at `[FEATURE_DIR]/sync-report.md`. + +Key sections to include: +- **Executive Summary**: Brief summary of sync findings +- **Missing Artifacts**: Files that were expected but not found +- **Deviation Analysis**: Matched items, deviations, and scope changes +- **Documentation Updates Required**: Files and sections needing updates +- **Lessons Learned**: What went well, challenges, recommendations +- **Technical Debt Identified**: Items needing future attention +- **Coverage Summary**: Planned vs implemented comparison +- **Next Actions**: Prioritized action items + +### Step 6: Display Terminal Summary + +Output a concise summary: + +```text +Sync Analysis Complete +====================== + +Feature: [FEATURE_NAME] +Status: [X] deviations found, [Y] docs need updates + +Deviations: + - HIGH: [count] + - MEDIUM: [count] + - LOW: [count] + +Documentation Updates: + - design.md: [sections needing update] + - requirements.md: [sections needing update] + - README.md: [sections needing update] + +Full report: [FEATURE_DIR]/sync-report.md +``` + +### Step 7: Propose Documentation Updates + +For each file requiring updates, show the proposed changes: + +```text +Proposed Updates for design.md: +------------------------------- +Section: ## Architecture +Change: Update to reflect actual implementation pattern + +[Show diff or before/after preview] + +Apply this change? (yes/no/skip) +``` + +### Step 8: Apply Updates (with confirmation) + +After user approval: +1. Create backup of original files (optional) +2. Apply approved modifications +3. Verify changes were applied correctly +4. Update sync-report.md with applied changes log + +### Step 9: Final Summary + +Output completion status: + +```text +Sync Complete +============= + +Documents Updated: + [x] design.md - Architecture section + [x] requirements.md - User stories + [ ] README.md - Skipped by user + +Sync Report: [FEATURE_DIR]/sync-report.md + +Suggested commit message: + docs: sync documentation with [feature-name] implementation + + - Updated architecture in design.md + - Added new user stories to requirements.md + - Generated sync report with lessons learned +``` + +## Operating Principles + +### Documentation Accuracy +- **Reflect reality**: Ensure all docs match the current implementation state +- **Preserve history**: Don't delete original intent; document what changed and why +- **Actionable updates**: Each proposed change should be specific and immediately applicable + +### Knowledge Preservation +- **Capture decisions**: Record architectural decisions made during implementation +- **Document deviations**: Explain why implementation differs from plan +- **Lessons learned**: Extract reusable insights for future projects + +### Analysis Guidelines +- **NEVER auto-apply changes** without user confirmation +- **NEVER hallucinate implementation details** (only report what's actually in the code) +- **Prioritize high-impact deviations** (architecture > API > minor details) +- **Report zero issues gracefully** (emit success report with alignment statistics) + +## Severity Reference + +**HIGH** (significant deviation): +- Architecture pattern differs from design +- Major API changes from specification +- Core features modified or removed + +**MEDIUM** (notable change): +- Technology version changes +- Additional features beyond spec +- File structure reorganization + +**LOW** (minor adjustment): +- Configuration differences +- Documentation formatting +- Non-functional improvements + +## Output + +After completing this workflow: +- `sync-report.md` generated in feature directory +- Proposed documentation updates displayed +- Changes applied only with user confirmation + +## Next Steps + +Suggest to the user: +``` +Sync complete. + +Next, you can: +1. Review the sync report for lessons learned +2. Commit documentation updates +3. Share findings in team retrospective +4. Archive the feature spec for reference +``` diff --git a/spec-kit/steering/10-discover-workflow.md b/spec-kit/steering/10-discover-workflow.md new file mode 100644 index 0000000..73f5eee --- /dev/null +++ b/spec-kit/steering/10-discover-workflow.md @@ -0,0 +1,355 @@ +--- +inclusion: auto +globs: ["**/*.md", "**/*.json", "**/*.yaml", "**/*.yml", "**/*.toml"] +description: "Discover workflow - reverse engineer existing projects to generate steering files and product specification" +keywords: ["discover", "reverse", "bootstrap", "analyze", "existing", "project", "逆向", "发现", "分析", "现有项目"] +--- + +# Discover Workflow + +This workflow analyzes existing projects to reverse-engineer steering files (product.md, tech.md, structure.md) and generate a comprehensive product specification document. + +## Purpose + +Bootstrap SDD methodology for existing projects by: +- **Analyzing codebase**: Understand technology stack, architecture, and patterns +- **Extracting product context**: Identify purpose, users, and business logic +- **Documenting structure**: Map project layout and conventions +- **Generating specification**: Create product documentation from code analysis + +## When to Use + +- Onboarding to an existing project without documentation +- Adopting SDD methodology for legacy codebases +- Creating documentation for undocumented projects +- Understanding unfamiliar codebases quickly +- Preparing for major refactoring or modernization + +## Prerequisites + +**Required**: +- An existing codebase to analyze +- Access to source files, configuration files, and package manifests + +**Helpful but optional**: +- Existing README or documentation +- Git history for context +- Running application for behavior observation + +## Operating Constraints + +**NON-DESTRUCTIVE**: This workflow only reads and analyzes; it generates new files but does NOT modify existing code. + +**USER CONFIRMATION**: All generated files require user review and approval before saving. + +**ITERATIVE REFINEMENT**: Generated files are drafts; expect multiple rounds of refinement with user input. + +**MERMAID FIRST (MANDATORY)**: When documenting flows, processes, sequences, or relationships: +- **MUST** use Mermaid syntax as the primary representation +- **NEVER** use plain text descriptions as a substitute for diagrams +- Supported diagram types: + - `sequenceDiagram` - For API calls, service interactions, user journeys + - `flowchart` - For business logic, decision trees, process flows + - `erDiagram` - For data models and entity relationships + - `classDiagram` - For component structures and dependencies +- Plain text descriptions are supplementary only, not replacements + +## Execution Flow + +### Step 1: Project Discovery + +Scan the project to gather initial context: + +**File System Analysis**: +- Identify root directory and project boundaries +- Detect monorepo vs single project structure +- Find configuration files (package.json, pyproject.toml, Cargo.toml, etc.) +- Locate source directories and entry points + +**Version Control Analysis** (if available): +- Check git history for project age and activity +- Identify main contributors +- Review recent changes for active areas + +**Output**: Project overview summary for user confirmation + +```markdown +## Project Overview + +**Root**: [path] +**Type**: [monorepo/single-project/library/application] +**Primary Language**: [detected language] +**Package Manager**: [npm/pip/cargo/etc.] +**Age**: [first commit date if available] +**Activity**: [last commit, commit frequency] +``` + +### Step 2: Technology Stack Analysis + +Analyze dependencies and configuration to determine the tech stack: + +**Dependency Analysis**: +- Parse package manifests (package.json, requirements.txt, Cargo.toml, go.mod, etc.) +- Identify frameworks (React, Django, Spring, etc.) +- Detect testing frameworks +- Find build tools and CI/CD configuration + +**Configuration Analysis**: +- Parse config files (tsconfig.json, .eslintrc, pytest.ini, etc.) +- Identify linting and formatting tools +- Detect environment configuration patterns + +**Infrastructure Detection**: +- Find Dockerfile, docker-compose.yml +- Detect cloud provider configurations (AWS, GCP, Azure) +- Identify database configurations + +**Output**: Technology inventory for tech.md generation + +### Step 3: Architecture Analysis + +Understand the project's architecture and patterns: + +**Directory Structure Analysis**: +- Map folder hierarchy +- Identify architectural patterns (MVC, Clean Architecture, Hexagonal, etc.) +- Detect module boundaries +- Find shared/common code locations + +**Code Pattern Detection**: +- Identify naming conventions (files, functions, classes) +- Detect API patterns (REST, GraphQL, gRPC) +- Find data access patterns (ORM, raw SQL, repositories) +- Identify error handling approaches + +**Dependency Graph**: +- Map internal module dependencies +- Identify circular dependencies +- Find entry points and core modules + +**Output**: Architecture summary for structure.md generation + +### Step 4: Product Context Extraction + +Understand what the product does and who it serves: + +**Documentation Analysis**: +- Parse existing README files +- Extract from code comments and docstrings +- Review API documentation if present +- Check for user guides or wikis + +**Code Semantics Analysis**: +- Analyze route handlers/controllers for features +- Identify domain models and their relationships +- Extract business logic from service layers +- Detect user-facing functionality + +**Configuration Clues**: +- Environment variables for feature flags +- Localization files for user-facing text +- Permission/role configurations + +**Output**: Product context summary for product.md generation + +### Step 5: Generate Steering Files + +Based on analysis, generate three steering files using existing templates as reference: + +#### A. Generate product.md + +Use `templates/product-template.md` as reference. Fill in with: +- **Vision**: Extracted or inferred product purpose +- **Target Users**: Identified from code analysis, auth systems, UI patterns +- **Business Constraints**: Inferred from code patterns, validations, limits +- **Success Metrics**: Suggested based on tracked analytics, logs, or metrics code +- **Non-Functional Requirements**: From caching patterns, auth implementation, data handling +- **Core Business Flows** (MERMAID REQUIRED): Extract from route handlers, service layer, and domain logic + - **MUST** create `sequenceDiagram` for each key user journey and API interaction + - **MUST** create `flowchart` for complex business logic and decision trees + - Document business flow inventory with frequency and criticality + - Plain text descriptions are supplementary only + +**Business Flow Extraction**: +- Scan route handlers for user-initiated flows → generate `sequenceDiagram` +- Trace service method call chains → generate `sequenceDiagram` +- Identify decision logic and branches → generate `flowchart` +- Map async/event-driven flows → generate `sequenceDiagram` with async notation + +#### B. Generate tech.md + +Use `templates/tech-template.md` as reference. Fill in with: +- **Stack**: Detected language, framework, database, testing tools, CI/CD +- **Development Principles**: Inferred from code patterns and existing standards +- **Coding Standards**: Detected naming, error handling, logging patterns +- **Quality Gates**: Based on existing CI/CD, linting, test setup +- **Dependency Rules**: Based on existing dependency management +- **Core Data Structures** (MERMAID REQUIRED): Extract from models, schemas, and entity definitions + - **MUST** create `erDiagram` showing all entity relationships + - Document each entity with fields, types, and relationships in tables + - Identify value objects and DTOs + - Map entity to table/collection names + +**Data Structure Extraction**: +- Parse ORM models (Sequelize, TypeORM, Prisma, Django models, etc.) → generate `erDiagram` +- Analyze database migration files for schema structure → update `erDiagram` +- Extract TypeScript/Java/Python type definitions +- Identify foreign key relationships and constraints → reflect in `erDiagram` + +#### C. Generate structure.md + +Use `templates/structure-template.md` as reference. Fill in with: +- **Project Layout**: Actual detected structure with descriptions +- **Naming Conventions**: Detected patterns for files, components, functions, constants +- **Module Organization**: Detected module patterns and rules +- **External Service Interfaces**: Complete inventory of exposed APIs and services + - Document all REST endpoints with methods, auth, rate limits + - List WebSocket/event interfaces + - Map external integrations (third-party APIs, SDKs) +- **API Patterns**: Detected from route definitions +- **Database Conventions**: Detected from models/migrations + +**Service Interface Extraction**: +- Scan route definitions for all HTTP endpoints +- Parse OpenAPI/Swagger specs if available +- Identify WebSocket handlers and event emitters +- Document authentication requirements per endpoint +- Extract rate limiting configurations + +### Step 6: Generate Product Specification + +Use `templates/product-spec-template.md` as reference to create a comprehensive product specification document. + +Key sections to fill based on analysis: +- **Executive Summary**: Overview of product purpose, users, and value proposition +- **Product Overview**: Purpose, target audience, key features +- **Feature Inventory**: Core, supporting, and planned features with status +- **Architecture Overview**: System diagram, components, data flow +- **Technical Summary**: Technology stack, dependencies, infrastructure +- **API Reference**: Endpoints, data models +- **Quality & Testing**: Test coverage, quality gates +- **Deployment & Operations**: Build, deployment, monitoring +- **Known Issues & Technical Debt**: TODO comments, deprecated code +- **Recommendations**: Documentation gaps, improvements, SDD adoption path + +### Step 7: Present Results + +Display analysis results and generated files to user: + +```text +Project Discovery Complete +========================== + +Project: [PROJECT_NAME] +Language: [PRIMARY_LANGUAGE] +Framework: [MAIN_FRAMEWORK] +Type: [APPLICATION_TYPE] + +Analysis Summary: + - Files scanned: [N] + - Modules detected: [N] + - Features identified: [N] + - API endpoints found: [N] + +Generated Files: + 1. .kiro/steering/product.md + 2. .kiro/steering/tech.md + 3. .kiro/steering/structure.md + 4. .kiro/specs/000-product-spec/product-spec.md + +Would you like to: + A) Review each file before saving + B) Save all files and review later + C) Regenerate specific sections + D) Ask questions about the analysis +``` + +### Step 8: Interactive Refinement + +Allow user to refine generated content: + +**Review Mode**: +- Display each generated file section by section +- Allow user to approve, modify, or regenerate each section +- Incorporate user corrections into final output + +**Question Mode**: +- Answer questions about detected patterns +- Explain reasoning for specific conclusions +- Provide evidence from code for each assertion + +**Regeneration Mode**: +- Re-analyze specific aspects with user guidance +- Incorporate additional context provided by user +- Update generated files with new information + +### Step 9: Save and Summarize + +After user approval, save files and provide summary: + +```text +Discovery Complete +================== + +Files Created: + [x] .kiro/steering/product.md + [x] .kiro/steering/tech.md + [x] .kiro/steering/structure.md + [x] .kiro/specs/000-product-spec/product-spec.md + +Next Steps: + 1. Review generated files and refine as needed + 2. Run **Specify** to document individual features + 3. Use **Plan** to create implementation plans for new work + 4. Consider **Analyze** to validate consistency + +Suggested commit message: + docs: add steering files and product spec from project discovery + + - Generated product.md with vision and constraints + - Generated tech.md with stack and standards + - Generated structure.md with layout and conventions + - Created initial product specification +``` + +## Analysis Guidelines + +### Evidence-Based Conclusions +- **Every assertion must have code evidence** +- Quote specific files and line numbers when possible +- Mark uncertain conclusions with [INFERRED] tag +- Distinguish between detected facts and assumptions + +### Handling Ambiguity +- When patterns are inconsistent, document all variations +- Ask user to clarify when multiple interpretations exist +- Default to most common pattern when choosing conventions +- Mark areas needing user input with [NEEDS CLARIFICATION] + +### Scope Boundaries +- Focus on primary application code, not vendored/generated code +- Skip node_modules, __pycache__, build artifacts +- Respect .gitignore patterns for exclusion +- Limit analysis depth for very large monorepos + +## Output + +After completing this workflow: +- `.kiro/steering/product.md` - Product vision and constraints +- `.kiro/steering/tech.md` - Technology stack and standards +- `.kiro/steering/structure.md` - Project layout and conventions +- `.kiro/specs/000-product-spec/product-spec.md` - Comprehensive product specification + +## Next Steps + +Suggest to the user: +``` +Discovery complete. + +Next, you can: +1. Review and refine the generated steering files +2. Run **Specify** to document specific features in detail +3. Run **Analyze** to check for consistency +4. Share product-spec.md with stakeholders for review +5. Begin new development using the established SDD methodology +``` diff --git a/spec-kit/steering/templates/clarifications-template.md b/spec-kit/steering/templates/clarifications-template.md new file mode 100644 index 0000000..b56e722 --- /dev/null +++ b/spec-kit/steering/templates/clarifications-template.md @@ -0,0 +1,81 @@ +# Clarification Log Template + +Use this template when recording clarification sessions. + +--- + +# Clarification Log: [FEATURE NAME] + +**Feature**: [###-feature-name] +**Session Date**: YYYY-MM-DD +**Total Questions**: [N] + +--- + +## Q1: [Question Title] + +**Category**: [Functional Scope / Domain & Data / Interaction & UX / Non-Functional / Integration / Edge Cases / Terminology] + +**Question**: [Complete question text that was asked] + +**Options Presented**: +- **A**: [Option A - full description] +- **B**: [Option B - full description] +- **C**: [Option C - full description] +- **Other**: Custom answer allowed + +**Recommended**: [Option X] - [Reason for this recommendation] + +**User's Choice**: [The option letter user selected, or their custom answer] + +**Resolution**: [How this clarification was applied to the specification] + +--- + +## Q2: [Question Title] + +**Category**: [Category] + +**Question**: [Question text] + +**Options Presented**: +- **A**: [Option A] +- **B**: [Option B] +- **C**: [Option C] +- **Other**: Custom answer allowed + +**Recommended**: [Option X] - [Reason] + +**User's Choice**: [Choice] + +**Resolution**: [How applied] + +--- + +## Summary + +| # | Question | Category | Choice | Applied To | +|---|----------|----------|--------|------------| +| 1 | [Brief question summary] | [Category] | [A/B/C/Custom] | [Section in requirements.md] | +| 2 | [Brief question summary] | [Category] | [A/B/C/Custom] | [Section in requirements.md] | +| 3 | [Brief question summary] | [Category] | [A/B/C/Custom] | [Section in requirements.md] | + +--- + +## Impact on Specification + +### Sections Modified +- [Section 1]: [Brief description of change] +- [Section 2]: [Brief description of change] + +### New Requirements Added +- FR-XXX: [New requirement added based on clarification] + +### Requirements Changed +- FR-XXX: [Original] → [Updated based on clarification] + +--- + +## Session Notes + +[Any additional notes about the clarification session, deferred questions, or recommendations for future clarification] diff --git a/spec-kit/steering/templates/design-template.md b/spec-kit/steering/templates/design-template.md new file mode 100644 index 0000000..e861839 --- /dev/null +++ b/spec-kit/steering/templates/design-template.md @@ -0,0 +1,170 @@ +# Implementation Plan Template + +Use this template when creating implementation plans. + +--- + +# Implementation Plan: [FEATURE] + +**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link] + +## Summary + +[Extract from feature spec: primary requirement + technical approach from research] + +## Technical Context + + + +**Language/Version**: [e.g., Python 3.11, TypeScript 5.0, or NEEDS CLARIFICATION] +**Primary Dependencies**: [e.g., FastAPI, React, Express, or NEEDS CLARIFICATION] +**Storage**: [e.g., PostgreSQL, MongoDB, files, or N/A] +**Testing**: [e.g., pytest, Jest, Vitest, or NEEDS CLARIFICATION] +**Target Platform**: [e.g., Linux server, iOS 15+, Web, or NEEDS CLARIFICATION] +**Project Type**: [single/web/mobile - determines source structure] +**Performance Goals**: [domain-specific, e.g., 1000 req/s, 60 fps, or NEEDS CLARIFICATION] +**Constraints**: [domain-specific, e.g., <200ms p95, offline-capable, or NEEDS CLARIFICATION] +**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, or NEEDS CLARIFICATION] + +## Steering Check + +*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* + + + +### Simplicity Gate +- [ ] Using <=3 projects? +- [ ] No future-proofing? +- [ ] Minimal necessary complexity? + +### Anti-Abstraction Gate +- [ ] Using framework directly? +- [ ] Single model representation? +- [ ] No unnecessary wrappers? + +### Integration-First Gate +- [ ] Contracts defined? +- [ ] Contract tests planned? +- [ ] Real environments for testing? + +### Product Alignment (from .kiro/steering/product.md) +- [ ] Aligns with product vision? +- [ ] Respects business constraints? + +### Tech Compliance (from .kiro/steering/tech.md) +- [ ] Uses approved technology stack? +- [ ] Follows development principles? + +### Structure Compliance (from .kiro/steering/structure.md) +- [ ] Follows project layout? +- [ ] Uses correct naming conventions? + +## Project Structure + +### Documentation (this feature) + +```text +.kiro/specs/[###-feature]/ +├── requirements.md # Feature specification +├── design.md # This file +├── research.md # Phase 0 output +├── data-model.md # Phase 1 output +├── quickstart.md # Phase 1 output +├── contracts/ # Phase 1 output +├── checklists/ # Checklist workflow output +└── tasks.md # Tasks workflow output +``` + +### Source Code (repository root) + + + +**Option 1: Single project (DEFAULT)** + +```text +src/ +├── models/ +├── services/ +├── cli/ +└── lib/ + +tests/ +├── contract/ +├── integration/ +└── unit/ +``` + +**Option 2: Web application** + +```text +backend/ +├── src/ +│ ├── models/ +│ ├── services/ +│ └── api/ +└── tests/ + +frontend/ +├── src/ +│ ├── components/ +│ ├── pages/ +│ └── services/ +└── tests/ +``` + +**Option 3: Mobile + API** + +```text +api/ +└── [same as backend above] + +ios/ or android/ +└── [platform-specific structure] +``` + +**Structure Decision**: [Document selected structure and rationale] + +## Complexity Tracking + +> **Fill ONLY if Steering Check has violations that must be justified** + +| Violation | Why Needed | Simpler Alternative Rejected Because | +|-----------|------------|-------------------------------------| +| [e.g., 4th project] | [current need] | [why 3 projects insufficient] | +| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] | + +## Phase 0: Research + + + +*Output: research.md* + +## Phase 1: Design + + + +### Data Model +*Extract entities from feature spec -> data-model.md* + +### API Contracts +*Generate from functional requirements -> contracts/* + +### Validation Scenarios +*Key test scenarios -> quickstart.md* + +*Output: data-model.md, contracts/, quickstart.md* diff --git a/spec-kit/steering/templates/product-spec-template.md b/spec-kit/steering/templates/product-spec-template.md new file mode 100644 index 0000000..70a51b8 --- /dev/null +++ b/spec-kit/steering/templates/product-spec-template.md @@ -0,0 +1,321 @@ +# Product Specification Template + +Use this template when generating product specifications from project discovery. + + + +--- + +# Product Specification: [PROJECT_NAME] + +**Generated**: [TIMESTAMP] +**Version**: [VERSION] +**Status**: [Draft/Review/Approved] +**Last Updated**: [DATE] + +## Executive Summary + +[2-3 paragraph overview of what the product does, who it serves, and its key value proposition. This should be understandable by non-technical stakeholders.] + +--- + +## Product Overview + +### Purpose + +[Why this product exists - the problem it solves and the value it provides] + +### Target Audience + +| Audience | Description | Primary Needs | +|----------|-------------|---------------| +| [User Type 1] | [Description] | [Key needs] | +| [User Type 2] | [Description] | [Key needs] | + +### Key Value Propositions + +1. **[Value 1]**: [Description of benefit] +2. **[Value 2]**: [Description of benefit] +3. **[Value 3]**: [Description of benefit] + +--- + +## Feature Inventory + +### Core Features + +| ID | Feature | Description | Priority | Status | +|----|---------|-------------|----------|--------| +| F001 | [Feature Name] | [Brief description] | P1 | Active | +| F002 | [Feature Name] | [Brief description] | P1 | Active | + +### Supporting Features + +| ID | Feature | Description | Priority | Status | +|----|---------|-------------|----------|--------| +| F010 | [Feature Name] | [Brief description] | P2 | Active | + +### Planned Features + +| ID | Feature | Description | Priority | Target | +|----|---------|-------------|----------|--------| +| F020 | [Feature Name] | [Brief description] | P2 | [Version/Date] | + +--- + +## User Journeys + +### Journey 1: [Journey Name] + +**Actor**: [User type] +**Goal**: [What user wants to accomplish] + +``` +1. User [action] +2. System [response] +3. User [action] +4. System [response] +5. Result: [outcome] +``` + +### Journey 2: [Journey Name] + +**Actor**: [User type] +**Goal**: [What user wants to accomplish] + +``` +1. User [action] +2. System [response] +3. ... +``` + +--- + +## Architecture Overview + +### System Context + +``` +┌─────────────────────────────────────────────────────────────┐ +│ [SYSTEM NAME] │ +│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ +│ │ [Comp1] │───▶│ [Comp2] │───▶│ [Comp3] │ │ +│ └─────────┘ └─────────┘ └─────────┘ │ +└─────────────────────────────────────────────────────────────┘ + │ │ │ + ▼ ▼ ▼ + [External 1] [External 2] [External 3] +``` + +### Component Breakdown + +| Component | Responsibility | Technology | +|-----------|----------------|------------| +| [Component 1] | [What it does] | [Tech used] | +| [Component 2] | [What it does] | [Tech used] | + +### Data Flow + +1. **Input**: [How data enters the system] +2. **Processing**: [How data is transformed] +3. **Storage**: [How data is persisted] +4. **Output**: [How data is presented/returned] + +--- + +## Technical Summary + +### Technology Stack + +| Layer | Technology | Version | Purpose | +|-------|------------|---------|---------| +| Language | [e.g., TypeScript] | [e.g., 5.0] | Primary development language | +| Framework | [e.g., Next.js] | [e.g., 14.0] | Application framework | +| Database | [e.g., PostgreSQL] | [e.g., 15] | Data persistence | +| Cache | [e.g., Redis] | [e.g., 7.0] | Performance caching | +| Search | [e.g., Elasticsearch] | [e.g., 8.0] | Full-text search | + +### External Dependencies + +| Service | Purpose | Criticality | +|---------|---------|-------------| +| [Service 1] | [What it provides] | [High/Medium/Low] | +| [Service 2] | [What it provides] | [High/Medium/Low] | + +### Infrastructure Requirements + +**Minimum Requirements**: +- CPU: [requirement] +- Memory: [requirement] +- Storage: [requirement] +- Network: [requirement] + +**Recommended Production Setup**: +- [Description of production infrastructure] + +--- + +## API Reference + +### REST Endpoints + +| Method | Endpoint | Description | Auth Required | +|--------|----------|-------------|---------------| +| GET | /api/[resource] | List resources | Yes | +| GET | /api/[resource]/:id | Get single resource | Yes | +| POST | /api/[resource] | Create resource | Yes | +| PUT | /api/[resource]/:id | Update resource | Yes | +| DELETE | /api/[resource]/:id | Delete resource | Yes | + +### Data Models + +#### [Model Name] + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| id | UUID | Yes | Unique identifier | +| [field] | [type] | [Yes/No] | [Description] | + +#### [Model Name 2] + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| id | UUID | Yes | Unique identifier | +| [field] | [type] | [Yes/No] | [Description] | + +--- + +## Security + +### Authentication + +- **Method**: [e.g., JWT, OAuth 2.0, Session-based] +- **Provider**: [e.g., Auth0, Custom, Firebase] +- **Session Duration**: [e.g., 24 hours] + +### Authorization + +| Role | Permissions | +|------|-------------| +| Admin | Full access | +| User | [Specific permissions] | +| Guest | [Limited permissions] | + +### Data Protection + +- **Encryption at Rest**: [Yes/No - details] +- **Encryption in Transit**: [Yes/No - details] +- **PII Handling**: [How personal data is handled] + +--- + +## Quality & Testing + +### Test Coverage + +| Type | Coverage | Location | +|------|----------|----------| +| Unit Tests | [X%] | [path] | +| Integration Tests | [X%] | [path] | +| E2E Tests | [X%] | [path] | + +### Quality Gates + +- [ ] All tests pass +- [ ] Code coverage >= [X]% +- [ ] No critical security vulnerabilities +- [ ] Performance benchmarks met +- [ ] Documentation updated + +--- + +## Deployment & Operations + +### Build Process + +```bash +# Build commands +[command 1] +[command 2] +``` + +### Deployment + +**Environment**: [e.g., AWS, GCP, Azure, On-premise] +**Method**: [e.g., Docker, Kubernetes, Serverless] +**Pipeline**: [e.g., GitHub Actions, Jenkins, CircleCI] + +### Monitoring + +| Aspect | Tool | Dashboard | +|--------|------|-----------| +| Application | [e.g., DataDog] | [URL] | +| Infrastructure | [e.g., CloudWatch] | [URL] | +| Logs | [e.g., ELK Stack] | [URL] | + +### Incident Response + +- **On-call**: [Team/Contact] +- **Escalation**: [Process] +- **SLA**: [Target uptime, response times] + +--- + +## Known Issues & Technical Debt + +### Active Issues + +| ID | Description | Severity | Workaround | +|----|-------------|----------|------------| +| [ID] | [Description] | [High/Medium/Low] | [Workaround if any] | + +### Technical Debt + +| Item | Description | Impact | Effort to Fix | +|------|-------------|--------|---------------| +| [Item] | [Description] | [Impact description] | [S/M/L/XL] | + +--- + +## Roadmap + +### Short-term (Next 3 months) + +- [ ] [Initiative 1] +- [ ] [Initiative 2] + +### Medium-term (3-6 months) + +- [ ] [Initiative 3] +- [ ] [Initiative 4] + +### Long-term (6-12 months) + +- [ ] [Initiative 5] +- [ ] [Initiative 6] + +--- + +## Appendix + +### Glossary + +| Term | Definition | +|------|------------| +| [Term 1] | [Definition] | +| [Term 2] | [Definition] | + +### References + +- [Reference 1]: [URL or document] +- [Reference 2]: [URL or document] + +### Change Log + +| Date | Version | Changes | Author | +|------|---------|---------|--------| +| [Date] | [Version] | [Description] | [Author] | diff --git a/spec-kit/steering/templates/product-template.md b/spec-kit/steering/templates/product-template.md new file mode 100644 index 0000000..55a8830 --- /dev/null +++ b/spec-kit/steering/templates/product-template.md @@ -0,0 +1,106 @@ +# Product Steering Template + +Use this template for `.kiro/steering/product.md`. + +--- + +# Product Steering + +## Vision + +[What is the product and why does it exist? 1-2 sentences describing the core purpose.] + +## Target Users + +[Who are the primary users? List personas or user types.] + +- **[Persona 1]**: [Description and needs] +- **[Persona 2]**: [Description and needs] + +## Business Constraints + +[What business rules or limitations must be respected?] + +- [Constraint 1] +- [Constraint 2] +- [Constraint 3] + +## Success Metrics + +[How do we measure success? Include specific, measurable targets.] + +- **[Metric 1]**: [Target value] +- **[Metric 2]**: [Target value] +- **[Metric 3]**: [Target value] + +## Non-Functional Requirements + +### Performance +- [Performance requirement 1] +- [Performance requirement 2] + +### Security +- [Security requirement 1] +- [Security requirement 2] + +### Compliance +- [Compliance requirement if applicable] + +## Core Business Flows + + + +### Flow 1: [Primary Business Flow Name] + +**Description**: [Brief description of what this flow accomplishes] + +**Actors**: [Who participates in this flow] + +```mermaid +sequenceDiagram + participant User + participant System + participant [Other] + + User->>System: [Action 1] + System->>System: [Processing] + System-->>User: [Response] +``` + +### Flow 2: [Secondary Business Flow Name] + +**Description**: [Brief description] + +```mermaid +flowchart TD + A[Start] --> B{Decision} + B -->|Yes| C[Action 1] + B -->|No| D[Action 2] + C --> E[End] + D --> E +``` + +### Business Flow Inventory + +| Flow ID | Name | Description | Frequency | Criticality | +|---------|------|-------------|-----------|-------------| +| BF-001 | [Flow Name] | [Brief description] | [Daily/Weekly/etc.] | [High/Medium/Low] | +| BF-002 | [Flow Name] | [Brief description] | [Frequency] | [Criticality] | + +## Feature Prioritization + +[Guidelines for prioritizing features] + +- **P1 (Must Have)**: [Criteria] +- **P2 (Should Have)**: [Criteria] +- **P3 (Nice to Have)**: [Criteria] diff --git a/spec-kit/steering/templates/requirements-template.md b/spec-kit/steering/templates/requirements-template.md new file mode 100644 index 0000000..1147929 --- /dev/null +++ b/spec-kit/steering/templates/requirements-template.md @@ -0,0 +1,137 @@ +# Feature Specification Template + +Use this template when creating feature specifications. + +--- + +# Feature Specification: [FEATURE NAME] + +**Feature Branch**: `[###-feature-name]` +**Created**: [DATE] +**Status**: Draft + +## User Scenarios & Testing *(mandatory)* + + + +### User Story 1 - [Brief Title] (Priority: P1) + +[Describe this user journey in plain language] + +**Why this priority**: [Explain the value and why it has this priority level] + +**Independent Test**: [Describe how this can be tested independently] + +**Acceptance Scenarios**: + +1. **Given** [initial state], **When** [action], **Then** [expected outcome] +2. **Given** [initial state], **When** [action], **Then** [expected outcome] + +--- + +### User Story 2 - [Brief Title] (Priority: P2) + +[Describe this user journey in plain language] + +**Why this priority**: [Explain the value and why it has this priority level] + +**Independent Test**: [Describe how this can be tested independently] + +**Acceptance Scenarios**: + +1. **Given** [initial state], **When** [action], **Then** [expected outcome] + +--- + +### User Story 3 - [Brief Title] (Priority: P3) + +[Describe this user journey in plain language] + +**Why this priority**: [Explain the value and why it has this priority level] + +**Independent Test**: [Describe how this can be tested independently] + +**Acceptance Scenarios**: + +1. **Given** [initial state], **When** [action], **Then** [expected outcome] + +--- + +[Add more user stories as needed, each with an assigned priority] + +### Edge Cases + + + +- What happens when [boundary condition]? +- How does system handle [error scenario]? + +## Requirements *(mandatory)* + +### Functional Requirements + + + +- **FR-001**: System MUST [specific capability] +- **FR-002**: System MUST [specific capability] +- **FR-003**: Users MUST be able to [key interaction] +- **FR-004**: System MUST [data requirement] +- **FR-005**: System MUST [behavior] + +*Marking unclear requirements:* + +- **FR-006**: System MUST [capability] via [NEEDS CLARIFICATION: specific question] + +### Key Entities *(include if feature involves data)* + +- **[Entity 1]**: [What it represents, key attributes without implementation] +- **[Entity 2]**: [What it represents, relationships to other entities] + +## Success Criteria *(mandatory)* + + + +### Measurable Outcomes + +- **SC-001**: [Measurable metric, e.g., "Users can complete task in under 2 minutes"] +- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users"] +- **SC-003**: [User satisfaction metric, e.g., "90% success rate on first attempt"] +- **SC-004**: [Business metric, e.g., "Reduce support tickets by 50%"] + +## Assumptions *(optional)* + + + +- [Assumption 1] +- [Assumption 2] + +## Clarifications *(auto-generated)* + + + +### Session YYYY-MM-DD + +- Q: [question] -> A: [answer] diff --git a/spec-kit/steering/templates/structure-template.md b/spec-kit/steering/templates/structure-template.md new file mode 100644 index 0000000..8239113 --- /dev/null +++ b/spec-kit/steering/templates/structure-template.md @@ -0,0 +1,153 @@ +# Structure Steering Template + +Use this template for `.kiro/steering/structure.md`. + +--- + +# Structure Steering + +## Project Layout + +```text +[Define your project structure here] + +# Example for web application: +src/ +├── components/ # UI components +├── services/ # Business logic +├── models/ # Data models +├── api/ # API routes +├── hooks/ # Custom hooks +├── utils/ # Utility functions +└── types/ # Type definitions + +tests/ +├── unit/ # Unit tests +├── integration/ # Integration tests +└── e2e/ # End-to-end tests + +docs/ # Documentation +``` + +## Naming Conventions + +### Files +- [Convention, e.g., kebab-case: `user-service.ts`] + +### Components +- [Convention, e.g., PascalCase: `UserProfile.tsx`] + +### Functions +- [Convention, e.g., camelCase: `getUserById`] + +### Constants +- [Convention, e.g., SCREAMING_SNAKE_CASE: `MAX_RETRY_COUNT`] + +### Database Tables +- [Convention, e.g., snake_case plural: `user_accounts`] + +## Module Organization + +### Rules +- Each module is self-contained +- Clear public API via index exports +- No circular dependencies +- Maximum module depth: [N] levels + +### Module Structure +```text +feature/ +├── index.ts # Public API exports +├── types.ts # Type definitions +├── service.ts # Business logic +├── repository.ts # Data access +└── __tests__/ # Tests +``` + +## External Service Interfaces + + + +### Service Interface Inventory + +| ID | Service/Endpoint | Method | Description | Auth Required | Rate Limit | +|----|------------------|--------|-------------|---------------|------------| +| API-001 | [/api/v1/resource] | [GET/POST/etc.] | [What it does] | [Yes/No] | [Limit] | +| API-002 | [/api/v1/resource/:id] | [Method] | [Description] | [Auth] | [Limit] | + +### REST API Endpoints + +#### [Resource Name] API + +| Endpoint | Method | Description | Request | Response | +|----------|--------|-------------|---------|----------| +| `/api/v1/[resource]` | GET | List all [resources] | Query params | Array of [Resource] | +| `/api/v1/[resource]/:id` | GET | Get single [resource] | Path param | [Resource] object | +| `/api/v1/[resource]` | POST | Create [resource] | [Resource] body | Created [Resource] | +| `/api/v1/[resource]/:id` | PUT | Update [resource] | [Resource] body | Updated [Resource] | +| `/api/v1/[resource]/:id` | DELETE | Delete [resource] | Path param | Success message | + +### WebSocket/Event Interfaces + +| Channel/Event | Direction | Description | Payload | +|---------------|-----------|-------------|---------| +| [event.name] | [In/Out/Bidirectional] | [Description] | [Payload structure] | + +### External Integrations + +| Integration | Type | Purpose | Endpoint/SDK | +|-------------|------|---------|--------------| +| [Service Name] | [REST/gRPC/SDK] | [Why integrated] | [Endpoint or SDK name] | + +## API Patterns + +### REST Conventions +- `GET /api/[resource]` - List resources +- `GET /api/[resource]/:id` - Get single resource +- `POST /api/[resource]` - Create resource +- `PUT /api/[resource]/:id` - Update resource +- `DELETE /api/[resource]/:id` - Delete resource + +### Response Format +```json +{ + "data": {}, + "error": null, + "meta": {} +} +``` + +### Error Response Format +```json +{ + "error": { + "code": "ERROR_CODE", + "message": "Human readable message", + "details": {} + } +} +``` + +## Database Conventions + +### Tables +- [Naming convention] +- [Primary key convention] + +### Migrations +- [Migration file naming] +- [Migration process] + +## Documentation + +### Locations +- API docs: [location] +- Architecture docs: [location] +- User guides: [location] + +### Requirements +- [What must be documented] +- [Documentation format] diff --git a/spec-kit/steering/templates/sync-report-template.md b/spec-kit/steering/templates/sync-report-template.md new file mode 100644 index 0000000..0af356a --- /dev/null +++ b/spec-kit/steering/templates/sync-report-template.md @@ -0,0 +1,140 @@ +# Sync Report Template + +Use this template when generating sync reports after implementation. + + + +--- + +# Sync Report: [FEATURE_NAME] + +**Generated**: [TIMESTAMP] +**Feature Directory**: [FEATURE_DIR] +**Implementation Status**: [COMPLETED/PARTIAL/IN_PROGRESS] + +## Executive Summary + +[Brief 2-3 sentence summary of sync findings. Describe overall alignment status, key deviations, and recommended priority actions.] + +--- + +## Missing Artifacts + +| Artifact | Expected Path | Status | +|----------|--------------|--------| +| requirements.md | [path] | [FOUND/MISSING] | +| design.md | [path] | [FOUND/MISSING] | +| tasks.md | [path] | [FOUND/MISSING] | +| Steering files | [path] | [FOUND/MISSING] | + +--- + +## Deviation Analysis + +### Matched Items + +| Item | Document | Section | Status | +|------|----------|---------|--------| +| [Feature/Component] | [File] | [Section] | ✅ MATCH | + +### Deviations + +| ID | Item | Planned | Actual | Impact | Recommendation | +|----|------|---------|--------|--------|----------------| +| D1 | [Item] | [What was planned] | [What was implemented] | [HIGH/MEDIUM/LOW] | [Action to take] | + +### Scope Changes + +#### Added (Beyond Original Spec) +- [Feature/component added during implementation] + +#### Removed (Descoped) +- [Feature/component not implemented] + +#### Modified (Changed Behavior) +- [Feature/component with different behavior than specified] + +--- + +## Documentation Updates Required + +| Priority | File | Section | Change Type | Description | +|----------|------|---------|-------------|-------------| +| HIGH | [file.md] | [Section] | [UPDATE/ADD/REMOVE] | [What needs to change] | +| MEDIUM | [file.md] | [Section] | [UPDATE/ADD/REMOVE] | [What needs to change] | +| LOW | [file.md] | [Section] | [UPDATE/ADD/REMOVE] | [What needs to change] | + +--- + +## Lessons Learned + +### What Went Well +- [Positive observation about the implementation process] +- [Aspects that matched the plan successfully] +- [Effective practices discovered] + +### Challenges Encountered +- [Unexpected technical challenges] +- [Deviations that required workarounds] +- [Gaps in original specification] + +### Recommendations for Future +- [Suggestion based on learnings] +- [Process improvement idea] +- [Specification enhancement] + +--- + +## Technical Debt Identified + +| ID | Item | Description | Priority | Suggested Resolution | Effort Estimate | +|----|------|-------------|----------|---------------------|-----------------| +| TD1 | [Item] | [What was compromised] | [HIGH/MEDIUM/LOW] | [How to fix] | [S/M/L] | + +--- + +## Coverage Summary + +| Category | Planned | Implemented | Coverage | +|----------|---------|-------------|----------| +| User Stories | [N] | [N] | [%] | +| API Endpoints | [N] | [N] | [%] | +| Data Models | [N] | [N] | [%] | +| Non-Functional | [N] | [N] | [%] | + +--- + +## Next Actions + +### Critical (Must Do) +- [ ] [High priority action item] + +### Recommended +- [ ] [Medium priority action item] + +### Optional +- [ ] [Low priority action item] + +--- + +## Applied Changes Log + +| Timestamp | File | Section | Change Applied | +|-----------|------|---------|----------------| +| [time] | [file] | [section] | [description] | + +--- + +## Suggested Commit Message + +``` +docs: sync documentation with [feature-name] implementation + +- [Change 1] +- [Change 2] +- Generated sync report with lessons learned +``` diff --git a/spec-kit/steering/templates/tasks-template.md b/spec-kit/steering/templates/tasks-template.md new file mode 100644 index 0000000..76228b4 --- /dev/null +++ b/spec-kit/steering/templates/tasks-template.md @@ -0,0 +1,177 @@ +# Tasks Template + +Use this template when generating task lists. + +--- + +# Tasks: [FEATURE NAME] + +**Branch**: `[###-feature-name]` +**Created**: [DATE] +**Design**: [link to design.md] +**Requirements**: [link to requirements.md] + +## Overview + +Total tasks: [N] +- Setup: [N] tasks +- Foundational: [N] tasks +- User Stories: [N] stories, [N] tasks +- Polish: [N] tasks + +Parallel opportunities: [N] tasks marked [P] +MVP Scope: Phase 3 (User Story 1) + +--- + +## Phase 1: Setup + +Project initialization tasks. + +- [ ] T001 Create project directory structure per implementation plan +- [ ] T002 [P] Initialize package manager with dependencies +- [ ] T003 [P] Create configuration files + +--- + +## Phase 2: Foundational + +Blocking prerequisites for all user stories. Must complete before story phases. + +- [ ] T004 Create database schema/models base +- [ ] T005 [P] Implement shared utilities +- [ ] T006 [P] Configure testing framework + +--- + +## Phase 3: User Story 1 - [Title] (P1) + +**Goal**: [Story goal from spec] + +**Independent Test**: [How to test this story alone] + +**Tasks**: + +- [ ] T007 [US1] Create [Entity] model in src/models/[entity].py +- [ ] T008 [US1] Implement [Entity]Service in src/services/[entity]_service.py +- [ ] T009 [US1] Create API endpoint in src/api/[entity].py +- [ ] T010 [US1] Add integration test in tests/integration/test_[entity].py + +**Checkpoint**: After T010, User Story 1 should be independently testable. + +--- + +## Phase 4: User Story 2 - [Title] (P2) + +**Goal**: [Story goal from spec] + +**Independent Test**: [How to test this story alone] + +**Tasks**: + +- [ ] T011 [US2] Create [Entity] model in src/models/[entity].py +- [ ] T012 [P] [US2] Implement [Service] in src/services/[service].py +- [ ] T013 [US2] Create API endpoint in src/api/[entity].py + +**Checkpoint**: After T013, User Story 2 should be independently testable. + +--- + +## Phase 5: User Story 3 - [Title] (P3) + +**Goal**: [Story goal from spec] + +**Independent Test**: [How to test this story alone] + +**Tasks**: + +- [ ] T014 [US3] [Task description with file path] +- [ ] T015 [US3] [Task description with file path] + +**Checkpoint**: After T015, User Story 3 should be independently testable. + +--- + +## Phase N: Polish & Cross-Cutting + +Final cleanup and cross-cutting concerns. + +- [ ] T0XX Add logging throughout application +- [ ] T0XX Update documentation +- [ ] T0XX Performance optimization +- [ ] T0XX Final integration testing + +--- + +## Dependencies + +``` +Phase 1 (Setup) + | + v +Phase 2 (Foundational) + | + +--> Phase 3 (US1) --> Phase 4 (US2) --> Phase 5 (US3) + | | + +----------------------------------------------+ + | + v + Phase N (Polish) +``` + +### Story Dependencies + +| Story | Depends On | Reason | +|-------|------------|--------| +| US2 | US1 | Shares [component] | +| US3 | None | Independent | + +--- + +## Parallel Execution Guide + +### Within Phase 3 (US1) +- T007, T008 can run in parallel (different files) +- T009 depends on T007, T008 (uses their outputs) + +### Within Phase 4 (US2) +- T011, T012 can run in parallel (different files) +- T013 depends on T011, T012 + +### Across Phases +- Phase 3 and Phase 4 are generally sequential +- Setup tasks (T001-T003) can run in parallel where marked [P] + +--- + +## Implementation Strategy + +### MVP First +Complete Phase 3 (User Story 1) for minimum viable product. + +### Incremental Delivery +Each user story phase produces independently testable increment. + +### Test Checkpoints +Verify each story works before proceeding to next. + +--- + +## Task Format Reference + +Every task MUST follow this format: +``` +- [ ] [TaskID] [P?] [Story?] Description with file path +``` + +**Components**: +1. `- [ ]` - Checkbox (required) +2. `T###` - Task ID (required) +3. `[P]` - Parallel marker (if parallelizable) +4. `[US#]` - Story label (required in story phases) +5. Description with file path (required) + +**Mark completed**: +``` +- [X] T001 Create project structure +``` diff --git a/spec-kit/steering/templates/tech-template.md b/spec-kit/steering/templates/tech-template.md new file mode 100644 index 0000000..5c9f9bc --- /dev/null +++ b/spec-kit/steering/templates/tech-template.md @@ -0,0 +1,136 @@ +# Technology Steering Template + +Use this template for `.kiro/steering/tech.md`. + +--- + +# Technology Steering + +## Stack + +- **Language**: [e.g., TypeScript 5.0, Python 3.11] +- **Framework**: [e.g., Next.js 14, FastAPI] +- **Database**: [e.g., PostgreSQL, MongoDB] +- **Cache**: [e.g., Redis, N/A] +- **Testing**: [e.g., Vitest, pytest] +- **CI/CD**: [e.g., GitHub Actions] + +## Development Principles + +### Test-First (NON-NEGOTIABLE) + +All implementation MUST follow strict TDD: +1. Tests are written first +2. Tests are validated and approved +3. Tests are confirmed to FAIL (Red phase) +4. Implementation makes tests pass (Green phase) +5. Refactor while keeping tests green + +### Simplicity Gate + +- Maximum 3 projects for initial implementation +- Additional projects require documented justification +- No future-proofing allowed +- Start simple, add complexity only when proven necessary + +### Anti-Abstraction Gate + +- Use framework features directly rather than wrapping them +- Single model representation (no DTOs unless mandated) +- No wrapper classes unless adding behavior +- Trust the framework + +### Library-First Principle + +- Every feature begins as a standalone module +- Modules MUST be self-contained +- Modules MUST be independently testable +- Clear purpose required - no organizational-only modules + +## Coding Standards + +### Naming +- [Naming convention rules] + +### Error Handling +- [Error handling approach] + +### Logging +- [Logging requirements] + +## Quality Gates + +- [ ] All tests pass +- [ ] Code coverage >= [X]% +- [ ] No lint errors +- [ ] Type-safe (no `any` or equivalent) +- [ ] No security vulnerabilities +- [ ] Documentation updated + +## Core Data Structures + + + +### Entity Relationship Overview + +```mermaid +erDiagram + [Entity1] ||--o{ [Entity2] : "relationship" + [Entity2] ||--|| [Entity3] : "relationship" +``` + +### Core Entities + +#### [Entity Name 1] + +**Purpose**: [What this entity represents in the domain] + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| id | UUID/Int | Yes | Primary identifier | +| [field_name] | [Type] | [Yes/No] | [Description] | +| created_at | Timestamp | Yes | Creation timestamp | +| updated_at | Timestamp | Yes | Last update timestamp | + +**Relationships**: +- Has many [Related Entity] +- Belongs to [Parent Entity] + +#### [Entity Name 2] + +**Purpose**: [What this entity represents] + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| id | UUID/Int | Yes | Primary identifier | +| [field_name] | [Type] | [Yes/No] | [Description] | + +### Data Model Inventory + +| Entity | Table/Collection | Description | Key Relationships | +|--------|------------------|-------------|-------------------| +| [Entity 1] | [table_name] | [Brief description] | [Key relationships] | +| [Entity 2] | [table_name] | [Brief description] | [Key relationships] | + +### Value Objects / DTOs + +| Name | Purpose | Fields | +|------|---------|--------| +| [ValueObject1] | [Purpose] | [Key fields] | +| [DTO1] | [Purpose] | [Key fields] | + +## Dependency Rules + +- [Rules for adding new dependencies] +- [Version pinning policy] +- [Security scanning requirements] From 5e4f32c366a0fda5cff88b82dd5494f094446b22 Mon Sep 17 00:00:00 2001 From: catface996 Date: Mon, 15 Dec 2025 21:43:06 +0800 Subject: [PATCH 02/18] chore: translate spec-kit workflow templates to English MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Translate Chinese text to English in specify and clarify workflow files for better international accessibility. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- spec-kit/steering/02-specify-workflow.md | 52 +++++++++++++----------- spec-kit/steering/03-clarify-workflow.md | 48 +++++++++++++--------- 2 files changed, 57 insertions(+), 43 deletions(-) diff --git a/spec-kit/steering/02-specify-workflow.md b/spec-kit/steering/02-specify-workflow.md index 35bc318..ebbaa2b 100644 --- a/spec-kit/steering/02-specify-workflow.md +++ b/spec-kit/steering/02-specify-workflow.md @@ -163,53 +163,57 @@ Run quality validation: If clarification markers remain, present questions to user: ```markdown -## 问题 1: [主题] +## Question 1: [Topic] -**背景**: [引用相关规格内容] +**Context**: [Quote relevant spec content] -**需要明确**: [具体问题] +**Why This Matters**: [Explain what aspect this affects - e.g., architecture, user experience, security, performance, cost, timeline - and why clarifying this now prevents issues later] -**可选答案:** +**Needs Clarification**: [Specific question] -► **A** - [第一个答案] - _影响: [选择这个意味着什么]_ +**Options:** -► **B** - [第二个答案] - _影响: [选择这个意味着什么]_ +► **A** - [First option] + _Impact: [What choosing this means]_ -► **C** - [第三个答案] - _影响: [选择这个意味着什么]_ +► **B** - [Second option] + _Impact: [What choosing this means]_ -► **其他** - 提供您自己的答案 +► **C** - [Third option] + _Impact: [What choosing this means]_ + +► **Other** - Provide your own answer --- -**您的选择**: _[等待回复]_ +**Your Choice**: _[Awaiting response]_ ``` -**Example (示例)**: +**Example**: ```markdown -## 问题 1: 用户认证方式 +## Question 1: User Authentication Method + +**Context**: The spec mentions "users need to log into the system" -**背景**: 规格中提到"用户需要登录系统" +**Why This Matters**: Authentication method directly impacts security architecture, user onboarding friction, and third-party dependencies. Deciding this early ensures consistent implementation across all user-facing features. -**需要明确**: 应该使用哪种认证方式? +**Needs Clarification**: Which authentication method should be used? -**可选答案:** +**Options:** -► **A** - 邮箱 + 密码 - _影响: 实现简单,但需要处理密码重置流程_ +► **A** - Email + Password + _Impact: Simple to implement, but requires password reset flow_ ► **B** - OAuth2 (Google/GitHub) - _影响: 用户体验更好,但依赖第三方服务_ + _Impact: Better user experience, but depends on third-party services_ -► **C** - 两者都支持 - _影响: 覆盖更多用户,但实现复杂度增加_ +► **C** - Support both + _Impact: Covers more users, but increases implementation complexity_ -► **其他** - 提供您自己的答案 +► **Other** - Provide your own answer --- -**您的选择**: _[等待回复]_ +**Your Choice**: _[Awaiting response]_ ``` ### Step 7: Finalize diff --git a/spec-kit/steering/03-clarify-workflow.md b/spec-kit/steering/03-clarify-workflow.md index 2f08ac8..ad93405 100644 --- a/spec-kit/steering/03-clarify-workflow.md +++ b/spec-kit/steering/03-clarify-workflow.md @@ -88,50 +88,60 @@ Present EXACTLY ONE question at a time. **For multiple-choice questions**: ```markdown -**推荐:** 选项 [X] - [推荐理由] +**Question**: [The specific question] -**可选答案:** +**Why This Matters**: [Explain what aspect this affects - e.g., architecture, data modeling, performance, security, UX - and why clarifying this now prevents issues later] -► **A** - [选项 A 描述] +**Recommendation:** Option [X] - [Reason for recommendation] -► **B** - [选项 B 描述] +**Options:** -► **C** - [选项 C 描述] +► **A** - [Option A description] -► **其他** - 提供您自己的答案(≤5 个词) +► **B** - [Option B description] + +► **C** - [Option C description] + +► **Other** - Provide your own answer (≤5 words) --- -回复选项字母(如 "A"),或输入 "yes" 接受推荐,或直接输入您的答案。 +Reply with option letter (e.g., "A"), type "yes" to accept recommendation, or enter your answer directly. ``` -**Example (示例)**: +**Example**: ```markdown -**问题:** 系统应如何限制团队并发执行数量? +**Question:** How should the system limit team concurrent execution count? + +**Why This Matters**: Concurrency limits directly impact system stability, resource utilization, and user experience during peak loads. This decision affects infrastructure sizing and cost planning. -**推荐:** 选项 C - 动态调整更灵活,能适应不同负载场景 +**Recommendation:** Option C - Dynamic adjustment is more flexible and adapts to varying load scenarios -**可选答案:** +**Options:** -► **A** - 不限制,允许所有团队同时执行 +► **A** - No limit, allow all teams to execute simultaneously -► **B** - 限制最多 5 个团队同时执行 +► **B** - Limit to maximum 5 teams executing concurrently -► **C** - 根据系统资源动态调整并发数 +► **C** - Dynamically adjust concurrency based on system resources -► **其他** - 提供您自己的答案(≤5 个词) +► **Other** - Provide your own answer (≤5 words) --- -回复选项字母,或输入 "yes" 接受推荐,或直接输入您的答案。 +Reply with option letter, type "yes" to accept recommendation, or enter your answer directly. ``` **For short-answer questions**: ```markdown -**建议答案:** [您的建议] - [简要理由] +**Question**: [The specific question] + +**Why This Matters**: [Explain the impact of this decision] + +**Suggested Answer:** [Your suggestion] - [Brief reason] -请输入简短答案(≤5 个词)。 -输入 "yes" 接受建议,或直接输入您的答案。 +Enter a short answer (≤5 words). +Type "yes" to accept suggestion, or enter your answer directly. ``` ### Step 4: Record Answers (MANDATORY - DO NOT SKIP) From ac4fdeed26aacd3c555b7f7e2530eb664f79a4f3 Mon Sep 17 00:00:00 2001 From: catface996 Date: Mon, 15 Dec 2025 22:43:16 +0800 Subject: [PATCH 03/18] feat: require userInput tool for single-choice clarification questions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add requirement for Kiro to use userInput tool when presenting multiple-choice questions during clarification workflow. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- spec-kit/steering/03-clarify-workflow.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/spec-kit/steering/03-clarify-workflow.md b/spec-kit/steering/03-clarify-workflow.md index ad93405..47e2d0c 100644 --- a/spec-kit/steering/03-clarify-workflow.md +++ b/spec-kit/steering/03-clarify-workflow.md @@ -87,6 +87,13 @@ Present EXACTLY ONE question at a time. **For multiple-choice questions**: +**IMPORTANT**: You MUST use the `userInput` tool to present single-choice questions. Configure the tool with: +- `type`: "single-select" +- `title`: The question text +- `description`: The "Why This Matters" explanation +- `options`: Array of option objects with `value` (e.g., "A", "B", "C") and `label` (option description) +- Include an "Other" option to allow custom answers + ```markdown **Question**: [The specific question] From ad030c5b350a4628f720156b4200033f99defd87 Mon Sep 17 00:00:00 2001 From: catface996 Date: Mon, 15 Dec 2025 22:45:48 +0800 Subject: [PATCH 04/18] fix: correct wording for userInput tool requirement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change "single-choice questions" to "multiple-choice questions" to match the section title. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- spec-kit/steering/03-clarify-workflow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec-kit/steering/03-clarify-workflow.md b/spec-kit/steering/03-clarify-workflow.md index 47e2d0c..ec5f876 100644 --- a/spec-kit/steering/03-clarify-workflow.md +++ b/spec-kit/steering/03-clarify-workflow.md @@ -87,7 +87,7 @@ Present EXACTLY ONE question at a time. **For multiple-choice questions**: -**IMPORTANT**: You MUST use the `userInput` tool to present single-choice questions. Configure the tool with: +**IMPORTANT**: You MUST use the `userInput` tool to present multiple-choice questions. Configure the tool with: - `type`: "single-select" - `title`: The question text - `description`: The "Why This Matters" explanation From 141d1ca7eb38b1f4daee2e1e0e0087cc2546c936 Mon Sep 17 00:00:00 2001 From: catface996 Date: Tue, 16 Dec 2025 07:51:16 +0800 Subject: [PATCH 05/18] refactor: streamline POWER.md and remove duplicates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add mandatory requirement to load 00-interaction-protocol.md first - Remove duplicate content (Workflow Options, Interaction Rules) that exists in 00-interaction-protocol.md - Remove userInput tool requirement from clarify workflow 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- spec-kit/POWER.md | 37 ++---------------------- spec-kit/steering/03-clarify-workflow.md | 7 ----- 2 files changed, 3 insertions(+), 41 deletions(-) diff --git a/spec-kit/POWER.md b/spec-kit/POWER.md index ef5f796..641a6c5 100644 --- a/spec-kit/POWER.md +++ b/spec-kit/POWER.md @@ -8,6 +8,8 @@ author: "Kiro User" # Spec-Driven Development Power +**CRITICAL - MANDATORY FIRST STEP**: You MUST read and load `steering/00-interaction-protocol.md` BEFORE proceeding with ANY other action. This is NON-NEGOTIABLE. Do NOT respond to users, do NOT start any workflow until you have loaded this file. Failure to load this file first is a violation of this power's protocol. + A comprehensive methodology power that guides you through the complete Spec-Driven Development (SDD) lifecycle - from project steering to implementation. ## Overview @@ -38,31 +40,6 @@ Templates constrain AI behavior toward higher-quality specifications through: - Structured thinking through checklists - Steering compliance through gates -## Workflow Options - -### Complete Workflow (10 Commands) - -1. **Steering** - Establish project principles (product.md, tech.md, structure.md) -2. **Specify** - Transform feature descriptions into structured specifications -3. **Clarify** - Eliminate ambiguity through targeted questioning -4. **Plan** - Convert specifications to technical architecture -5. **Tasks** - Break plans into executable task lists -6. **Implement** - Execute tasks following TDD approach -7. **Analyze** - Cross-artifact consistency validation -8. **Checklist** - Generate domain-specific quality checklists -9. **Sync** - Synchronize documentation with implementation and generate retrospective -10. **Discover** - Reverse engineer existing projects to generate steering files and product spec - -### Simplified Workflow (3 Steps) -For quick iterations: -1. **Specify** - Capture requirements -2. **Plan** - Technical approach -3. **Implement** - Execute - -## Activation Response - -See `00-interaction-protocol.md` for the activation flow. The power first asks for language selection (English/中文), then presents workflow options. - ## Methodology Overview ### Phase 1: Foundation (Steering) @@ -112,18 +89,10 @@ Bootstrap SDD for existing codebases: - Generate steering files (product.md, tech.md, structure.md) - Create comprehensive product specification -## Interaction Rules - -- **WAIT for user instructions** - Never automatically start workflows -- **CONFIRM scope first** - Understand project context before proceeding -- **One question at a time** - When clarifying, ask single focused questions -- **Ask before proceeding** - Never proceed to next phase without user agreement -- **Mark uncertainties** - Use [NEEDS CLARIFICATION] markers for ambiguous items - ## Steering Files Detailed methodologies for each workflow are available in the steering files: -- `00-interaction-protocol.md` - Interaction guidelines (always loaded) +- `00-interaction-protocol.md` - **MUST LOAD FIRST** - Interaction guidelines (mandatory before any action) - `01-steering-workflow.md` - Project principles establishment - `02-specify-workflow.md` - Feature specification creation - `03-clarify-workflow.md` - Ambiguity elimination process diff --git a/spec-kit/steering/03-clarify-workflow.md b/spec-kit/steering/03-clarify-workflow.md index ec5f876..ad93405 100644 --- a/spec-kit/steering/03-clarify-workflow.md +++ b/spec-kit/steering/03-clarify-workflow.md @@ -87,13 +87,6 @@ Present EXACTLY ONE question at a time. **For multiple-choice questions**: -**IMPORTANT**: You MUST use the `userInput` tool to present multiple-choice questions. Configure the tool with: -- `type`: "single-select" -- `title`: The question text -- `description`: The "Why This Matters" explanation -- `options`: Array of option objects with `value` (e.g., "A", "B", "C") and `label` (option description) -- Include an "Other" option to allow custom answers - ```markdown **Question**: [The specific question] From 827a791026118d7eeac40fad744b60e1e02d1fc3 Mon Sep 17 00:00:00 2001 From: catface996 Date: Tue, 16 Dec 2025 08:33:31 +0800 Subject: [PATCH 06/18] feat: add userInput tool requirement for clarification questions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add XML tool call format for rendering multiple-choice questions as clickable buttons in Kiro UI during clarification workflow. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- spec-kit/steering/03-clarify-workflow.md | 37 ++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/spec-kit/steering/03-clarify-workflow.md b/spec-kit/steering/03-clarify-workflow.md index ad93405..2b37cc0 100644 --- a/spec-kit/steering/03-clarify-workflow.md +++ b/spec-kit/steering/03-clarify-workflow.md @@ -87,6 +87,43 @@ Present EXACTLY ONE question at a time. **For multiple-choice questions**: +**IMPORTANT**: You MUST use the `userInput` tool to present multiple-choice questions. This renders clickable buttons for the user instead of plain text. + +**Tool call format**: + +```xml + +userInput + +clarification +[Question text with **Why This Matters** explanation] +[{"title": "A - [Option A]", "description": "[Impact]", "recommended": true}, {"title": "B - [Option B]", "description": "[Impact]"}, {"title": "C - [Option C]", "description": "[Impact]"}, {"title": "Other", "description": "Provide your own answer"}] + + +``` + +**Example**: + +```xml + +userInput + +clarification +**Question:** How should the system limit team concurrent execution count? + +**Why This Matters**: Concurrency limits directly impact system stability, resource utilization, and user experience during peak loads. +[{"title": "A - No limit", "description": "Allow all teams to execute simultaneously"}, {"title": "B - Limit to 5", "description": "Maximum 5 teams executing concurrently"}, {"title": "C - Dynamic adjustment", "description": "Adjust concurrency based on system resources", "recommended": true}, {"title": "Other", "description": "Provide your own answer"}] + + +``` + +**Key points**: +- Plain text options (e.g., "1. Option A 2. Option B") will NOT render as clickable buttons +- You MUST output a tool call in the format above for interactive selection +- The `recommended: true` option will be highlighted in the UI + +**Fallback format** (if userInput tool is unavailable): + ```markdown **Question**: [The specific question] From 4ea9bf2f32951bb97fb0a3e0d6aa6fd292905a0c Mon Sep 17 00:00:00 2001 From: catface996 Date: Fri, 19 Dec 2025 20:01:24 +0800 Subject: [PATCH 07/18] Add MIT License to spec-kit --- spec-kit/LICENSE.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 spec-kit/LICENSE.md diff --git a/spec-kit/LICENSE.md b/spec-kit/LICENSE.md new file mode 100644 index 0000000..9bf1b28 --- /dev/null +++ b/spec-kit/LICENSE.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) GitHub, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From ac71a2f9132aa2d8e8f2d7d54cb8031f92517c4a Mon Sep 17 00:00:00 2001 From: catface996 Date: Tue, 6 Jan 2026 13:43:38 +0800 Subject: [PATCH 08/18] Update code --- aidlc/POWER.md | 408 ++++++++++++++ aidlc/README.md | 80 +++ .../common/ascii-diagram-standards.md | 116 ++++ .../rule-details/common/content-validation.md | 78 +++ aidlc/rule-details/common/depth-levels.md | 73 +++ aidlc/rule-details/common/error-handling.md | 373 +++++++++++++ .../common/overconfidence-prevention.md | 100 ++++ aidlc/rule-details/common/process-overview.md | 141 +++++ .../common/question-format-guide.md | 332 ++++++++++++ .../rule-details/common/session-continuity.md | 47 ++ aidlc/rule-details/common/terminology.md | 189 +++++++ aidlc/rule-details/common/welcome-message.md | 109 ++++ aidlc/rule-details/common/workflow-changes.md | 285 ++++++++++ .../construction/build-and-test.md | 354 ++++++++++++ .../construction/code-generation.md | 207 +++++++ .../construction/functional-design.md | 112 ++++ .../construction/infrastructure-design.md | 94 ++++ aidlc/rule-details/construction/nfr-design.md | 90 ++++ .../construction/nfr-requirements.md | 99 ++++ .../inception/application-design.md | 145 +++++ .../inception/requirements-analysis.md | 169 ++++++ .../inception/reverse-engineering.md | 311 +++++++++++ .../inception/units-generation.md | 183 +++++++ aidlc/rule-details/inception/user-stories.md | 327 +++++++++++ .../inception/workflow-planning.md | 479 ++++++++++++++++ .../inception/workspace-detection.md | 93 ++++ aidlc/rule-details/operations/operations.md | 19 + aidlc/steering/core-workflow.md | 510 ++++++++++++++++++ 28 files changed, 5523 insertions(+) create mode 100644 aidlc/POWER.md create mode 100644 aidlc/README.md create mode 100644 aidlc/rule-details/common/ascii-diagram-standards.md create mode 100644 aidlc/rule-details/common/content-validation.md create mode 100644 aidlc/rule-details/common/depth-levels.md create mode 100644 aidlc/rule-details/common/error-handling.md create mode 100644 aidlc/rule-details/common/overconfidence-prevention.md create mode 100644 aidlc/rule-details/common/process-overview.md create mode 100644 aidlc/rule-details/common/question-format-guide.md create mode 100644 aidlc/rule-details/common/session-continuity.md create mode 100644 aidlc/rule-details/common/terminology.md create mode 100644 aidlc/rule-details/common/welcome-message.md create mode 100644 aidlc/rule-details/common/workflow-changes.md create mode 100644 aidlc/rule-details/construction/build-and-test.md create mode 100644 aidlc/rule-details/construction/code-generation.md create mode 100644 aidlc/rule-details/construction/functional-design.md create mode 100644 aidlc/rule-details/construction/infrastructure-design.md create mode 100644 aidlc/rule-details/construction/nfr-design.md create mode 100644 aidlc/rule-details/construction/nfr-requirements.md create mode 100644 aidlc/rule-details/inception/application-design.md create mode 100644 aidlc/rule-details/inception/requirements-analysis.md create mode 100644 aidlc/rule-details/inception/reverse-engineering.md create mode 100644 aidlc/rule-details/inception/units-generation.md create mode 100644 aidlc/rule-details/inception/user-stories.md create mode 100644 aidlc/rule-details/inception/workflow-planning.md create mode 100644 aidlc/rule-details/inception/workspace-detection.md create mode 100644 aidlc/rule-details/operations/operations.md create mode 100644 aidlc/steering/core-workflow.md diff --git a/aidlc/POWER.md b/aidlc/POWER.md new file mode 100644 index 0000000..4fc2247 --- /dev/null +++ b/aidlc/POWER.md @@ -0,0 +1,408 @@ +--- +name: "aidlc" +displayName: "AI-DLC (AI-Driven Development Life Cycle)" +description: "Intelligent software development workflow that adapts to your needs with three phases: Inception (requirements & design), Construction (implementation & testing), and Operations (deployment). Maintains quality standards while keeping you in control." +keywords: ["aidlc", "ai-dlc", "software development", "workflow", "sdlc", "requirements", "design", "implementation", "testing", "adaptive workflow"] +author: "AWS" +--- + +# AI-DLC (AI-Driven Development Life Cycle) + +## Overview + +AI-DLC is an intelligent software development workflow that adapts to your needs, maintains quality standards, and keeps you in control of the process. It provides a structured approach to software development with three adaptive phases that intelligently determine which stages are needed based on your project's complexity and requirements. + +**CRITICAL FIRST STEP**: Before starting any workflow, you MUST select your preferred language (English or 中文). This is a mandatory, non-negotiable step that determines the language for all subsequent interactions, documentation, and outputs. + +**Key Principles:** +- **Language Selection FIRST**: Mandatory language selection before any workflow steps +- **Adaptive Intelligence**: Only executes stages that add value to your specific request +- **Context-Aware**: Analyzes existing codebase and complexity requirements +- **Risk-Based**: Complex changes get comprehensive treatment, simple changes stay efficient +- **Question-Driven**: Structured multiple-choice questions in files, not chat +- **Always in Control**: Review execution plans and approve each phase +- **Complete Audit Trail**: All decisions and changes are tracked +- **Language Consistency**: All outputs in your selected language + +## Available Steering Files + +This power includes one main steering file that contains the complete workflow: + +- **core-workflow** - Complete AI-DLC workflow with all three phases (Inception, Construction, Operations) + +To access the workflow, use: +``` +Call action "readSteering" with powerName="aidlc", steeringFile="core-workflow.md" +``` + +## Three-Phase Adaptive Workflow + +AI-DLC follows a structured three-phase approach that adapts to your project's complexity: + +### 🔵 INCEPTION PHASE +**Purpose**: Determines **WHAT** to build and **WHY** + +**Stages:** +- **Workspace Detection** (ALWAYS) - Analyze project state and determine greenfield vs brownfield +- **Reverse Engineering** (CONDITIONAL) - Analyze existing codebase for brownfield projects +- **Requirements Analysis** (ALWAYS) - Gather and validate requirements with adaptive depth +- **User Stories** (CONDITIONAL) - Create user stories when they add value +- **Workflow Planning** (ALWAYS) - Determine execution plan for remaining phases +- **Application Design** (CONDITIONAL) - Design components and services when needed +- **Units Generation** (CONDITIONAL) - Break down complex systems into manageable units + +### 🟢 CONSTRUCTION PHASE +**Purpose**: Determines **HOW** to build it + +**Per-Unit Loop** (executes for each unit of work): +- **Functional Design** (CONDITIONAL) - Design data models and business logic +- **NFR Requirements** (CONDITIONAL) - Assess non-functional requirements +- **NFR Design** (CONDITIONAL) - Design NFR implementation patterns +- **Infrastructure Design** (CONDITIONAL) - Design cloud resources and deployment +- **Code Generation** (ALWAYS) - Generate code, tests, and artifacts + +**Final Stage:** +- **Build and Test** (ALWAYS) - Comprehensive build and test instructions + +### 🟡 OPERATIONS PHASE +**Purpose**: How to DEPLOY and RUN it (future expansion) + +**Stages:** +- **Operations** (PLACEHOLDER) - Deployment, monitoring, and maintenance workflows + +## MANDATORY: Language Selection (CRITICAL - NO NEGOTIATION) + +**⚠️ CRITICAL REQUIREMENT - MUST BE EXECUTED FIRST ⚠️** + +**BEFORE ANY OTHER WORKFLOW STEPS**, you **MUST** ask the user to select their preferred language. This step is **MANDATORY** and **CANNOT BE SKIPPED** under any circumstances. + +### Language Selection Rules + +**CRITICAL ENFORCEMENT:** +- ✋ **STOP**: Do NOT proceed with ANY workflow steps until language is selected +- 🚫 **NO NEGOTIATION**: This step MUST be completed first - no exceptions +- ⚠️ **MANDATORY**: Language selection is REQUIRED before displaying welcome message +- 🔒 **NON-SKIPPABLE**: Cannot be bypassed, deferred, or skipped + +### Language Selection Process + +**Step 1: Display Language Selection Prompt** + +Present the following options to the user immediately: + +``` +🌐 LANGUAGE SELECTION (REQUIRED) + +Please select your preferred language for this AI-DLC workflow: + +A) English - All documentation, questions, and outputs will be in English +B) 中文 - 所有文档、问题和输出将使用中文 + +[Answer]: Please respond with A or B +``` + +**Step 2: Wait for User Response** + +- **MUST** wait for explicit user selection (A or B) +- **DO NOT** proceed until valid response received +- If response is unclear, ask again + +**Step 3: Record Language Selection** + +Once language is selected: +1. **MUST** record the selection in `aidlc-docs/aidlc-state.md` immediately +2. **MUST** log the selection in `aidlc-docs/audit.md` with timestamp +3. **MUST** use the selected language for ALL subsequent interactions + +### Language Usage Rules + +**After language selection:** + +- ✅ **If English selected**: All outputs, questions, documentation, and communication in English +- ✅ **If 中文 selected**: 所有输出、问题、文档和交流使用中文 +- 🔄 **Consistency**: MUST maintain selected language throughout entire workflow +- 📝 **Documentation**: All generated files in `aidlc-docs/` MUST use selected language +- 💬 **Questions**: All structured questions MUST be in selected language +- 📊 **Plans**: All execution plans and approval messages MUST be in selected language + +**CRITICAL**: Once language is selected, it CANNOT be changed mid-workflow. User must restart workflow to change language. + +--- + +## How to Use AI-DLC + +### Getting Started + +1. **Activate the workflow** by starting your request with: + ``` + Using AI-DLC, [describe your software development need] + ``` + +2. **MANDATORY FIRST STEP**: Select your preferred language (English or 中文) + - This step MUST be completed before any other workflow steps + - Cannot be skipped or bypassed + +3. **AI-DLC automatically activates** and displays a welcome message (in selected language) + +4. **Follow the guided workflow**: + - Answer structured questions when asked + - Review execution plans before each phase + - Approve or request changes at each stage + - All artifacts are generated in `aidlc-docs/` directory + +### Example Usage + +**Step 1: Activate AI-DLC** +``` +Using AI-DLC, create a REST API for managing user accounts with authentication +``` + +**Step 2: Select Language (MANDATORY)** +``` +AI-DLC will prompt: +🌐 LANGUAGE SELECTION (REQUIRED) +Please select your preferred language: +A) English +B) 中文 + +You respond: A (for English) or B (for 中文) +``` + +**Step 3: Follow Workflow** +After language selection, AI-DLC proceeds with the workflow in your selected language. + +**Example Scenarios:** + +**Greenfield Project (English):** +``` +Using AI-DLC, create a REST API for managing user accounts with authentication +[Select: A - English] +``` + +**Greenfield Project (中文):** +``` +Using AI-DLC, 创建一个用户账户管理的 REST API,包含身份验证功能 +[选择: B - 中文] +``` + +**Brownfield Project (English):** +``` +Using AI-DLC, add payment processing functionality to the existing e-commerce application +[Select: A - English] +``` + +**Brownfield Project (中文):** +``` +Using AI-DLC, 为现有的电商应用添加支付处理功能 +[选择: B - 中文] +``` + +**Simple Change (English):** +``` +Using AI-DLC, fix the login validation bug in the authentication service +[Select: A - English] +``` + +**Simple Change (中文):** +``` +Using AI-DLC, 修复身份验证服务中的登录验证错误 +[选择: B - 中文] +``` + +## Workflow Adaptation + +AI-DLC intelligently adapts based on: + +1. **User's stated intent and clarity** - Clear requests may skip detailed requirements +2. **Existing codebase state** - Brownfield projects get reverse engineering +3. **Complexity and scope** - Complex changes get comprehensive treatment +4. **Risk and impact assessment** - High-risk changes get extra validation + +**Depth Levels:** +- **Minimal**: Simple, clear requests with low risk +- **Standard**: Normal complexity with moderate risk +- **Comprehensive**: Complex, high-risk changes requiring detailed analysis + +## Directory Structure + +AI-DLC creates a structured documentation hierarchy: + +``` +/ # Application code lives here +├── [project-specific structure] # Your actual code +│ +├── aidlc-docs/ # All AI-DLC documentation +│ ├── inception/ # 🔵 INCEPTION PHASE +│ │ ├── plans/ +│ │ ├── reverse-engineering/ # Brownfield only +│ │ ├── requirements/ +│ │ ├── user-stories/ +│ │ └── application-design/ +│ ├── construction/ # 🟢 CONSTRUCTION PHASE +│ │ ├── plans/ +│ │ ├── {unit-name}/ +│ │ │ ├── functional-design/ +│ │ │ ├── nfr-requirements/ +│ │ │ ├── nfr-design/ +│ │ │ ├── infrastructure-design/ +│ │ │ └── code/ # Markdown summaries only +│ │ └── build-and-test/ +│ ├── operations/ # 🟡 OPERATIONS PHASE +│ ├── aidlc-state.md # Workflow state tracking +│ └── audit.md # Complete audit trail +``` + +**Critical Rule**: Application code goes in workspace root, documentation goes in `aidlc-docs/` + +## Rule Details Files + +This power includes comprehensive rule detail files organized by phase: + +### Common Rules (Always Loaded) +- `rule-details/common/process-overview.md` - Workflow overview +- `rule-details/common/session-continuity.md` - Session resumption +- `rule-details/common/content-validation.md` - Content validation requirements +- `rule-details/common/question-format-guide.md` - Question formatting rules +- `rule-details/common/terminology.md` - Standard terminology +- `rule-details/common/welcome-message.md` - Initial welcome message +- `rule-details/common/ascii-diagram-standards.md` - Diagram standards +- `rule-details/common/depth-levels.md` - Depth level definitions +- `rule-details/common/error-handling.md` - Error handling guidelines +- `rule-details/common/overconfidence-prevention.md` - Quality safeguards +- `rule-details/common/workflow-changes.md` - Workflow modification rules + +### Inception Phase Rules +- `rule-details/inception/workspace-detection.md` +- `rule-details/inception/reverse-engineering.md` +- `rule-details/inception/requirements-analysis.md` +- `rule-details/inception/user-stories.md` +- `rule-details/inception/workflow-planning.md` +- `rule-details/inception/application-design.md` +- `rule-details/inception/units-generation.md` + +### Construction Phase Rules +- `rule-details/construction/functional-design.md` +- `rule-details/construction/nfr-requirements.md` +- `rule-details/construction/nfr-design.md` +- `rule-details/construction/infrastructure-design.md` +- `rule-details/construction/code-generation.md` +- `rule-details/construction/build-and-test.md` + +### Operations Phase Rules +- `rule-details/operations/operations.md` + +## Best Practices + +### For Users + +1. **Select Language First**: MUST select language (English or 中文) before proceeding - this is mandatory +2. **Be Clear About Intent**: Start with "Using AI-DLC" to activate the workflow +3. **Review Plans Carefully**: Always review execution plans before approval +4. **Provide Feedback**: Request changes when plans don't match your needs +5. **Track Progress**: Monitor `aidlc-state.md` for workflow progress +6. **Review Audit Trail**: Check `audit.md` for complete decision history +7. **Language Consistency**: All workflow outputs will be in your selected language + +### For AI Agents + +1. **CRITICAL - Language Selection FIRST**: MUST ask user to select language (English or 中文) BEFORE any other steps - NO EXCEPTIONS +2. **Enforce Language Selection**: DO NOT proceed with welcome message or any workflow steps until language is selected +3. **Use Selected Language**: ALL outputs, questions, documentation MUST be in the selected language +4. **Load Common Rules First**: Always load common rules at workflow start (after language selection) +5. **Validate Content**: Validate all content before file creation +6. **Follow Question Format**: Use structured multiple-choice questions +7. **Update Checkboxes**: Mark plan steps complete immediately after execution +8. **Log Everything**: Record all user inputs and AI responses in audit.md +9. **Never Overwrite audit.md**: Always append, never overwrite the audit log +10. **Wait for Approval**: Never proceed without explicit user approval + +## Troubleshooting + +### Language Selection Not Prompted + +**Problem**: Workflow started without asking for language selection + +**Solution**: +1. **STOP the workflow immediately** +2. Remind the AI agent: "Language selection is MANDATORY and must be completed first" +3. Request language selection prompt +4. Restart workflow if necessary + +### Wrong Language Being Used + +**Problem**: Outputs are in wrong language or mixed languages + +**Solution**: +1. Check `aidlc-state.md` for recorded language selection +2. Remind AI agent of selected language +3. If language was never selected, stop and complete language selection first +4. If wrong language was selected, restart workflow to change language + +### Workflow Not Starting + +**Problem**: AI-DLC doesn't activate when starting a request + +**Solution**: +1. Ensure you start with "Using AI-DLC, ..." in your message +2. Verify the power is properly installed +3. Check that steering files are accessible + +### Missing Documentation + +**Problem**: Expected documentation files not created + +**Solution**: +1. Check `aidlc-state.md` to see which stages were executed +2. Review `audit.md` for any errors or skipped stages +3. Verify the stage was included in the execution plan + +### Workflow Stuck at Approval + +**Problem**: Workflow waiting for approval but unclear what to do + +**Solution**: +1. Look for the approval message with options +2. Respond with your choice (e.g., "Continue to Next Stage" or "Request Changes") +3. If unclear, ask "What are my options?" to see available choices + +### Audit Log Issues + +**Problem**: Audit log has duplicate entries or missing information + +**Solution**: +1. Ensure AI agent is appending to audit.md, not overwriting +2. Check that all user inputs are being logged with timestamps +3. Verify ISO 8601 timestamp format is being used + +## Configuration + +**No additional configuration required** - AI-DLC works immediately after power installation. + +The workflow automatically: +- **Prompts for language selection** (MANDATORY first step) +- Detects your project structure +- Determines greenfield vs brownfield +- Adapts depth levels based on complexity +- Creates necessary documentation directories +- Generates all outputs in your selected language + +**Language Configuration:** +- Language selection is prompted at workflow start +- Selection is recorded in `aidlc-docs/aidlc-state.md` +- Cannot be changed mid-workflow (must restart to change) +- All documentation, questions, and outputs use selected language + +## Additional Resources + +- **Blog**: [AI-Driven Development Life Cycle](https://aws.amazon.com/blogs/devops/ai-driven-development-life-cycle/) +- **Method Definition Paper**: [AI-DLC Methodology](https://prod.d13rzhkk8cj2z0.amplifyapp.com/) +- **GitHub Repository**: [aidlc-workflows](https://github.com/aws-samples/aidlc-workflows) + +--- + +**Power Type**: Knowledge Base Power (No MCP server required) +**Installation**: Works immediately after installation +**Usage**: +1. Start any request with "Using AI-DLC, ..." +2. **MANDATORY**: Select language (English or 中文) when prompted +3. Follow the guided workflow in your selected language diff --git a/aidlc/README.md b/aidlc/README.md new file mode 100644 index 0000000..91ce1a8 --- /dev/null +++ b/aidlc/README.md @@ -0,0 +1,80 @@ +# AI-DLC Kiro Power + +This is a Kiro Power for the AI-Driven Development Life Cycle (AI-DLC) methodology. + +## Installation + +### Method 1: Local Directory (Recommended for Testing) + +1. Open Kiro Powers UI (use command palette or click Powers icon) +2. Click "Add Custom Power" button +3. Select "Local Directory" +4. Provide the full absolute path to this directory: + ``` + /path/to/your/workspace/powers/aidlc + ``` +5. Click "Add" to install + +### Method 2: Copy to Kiro Steering (Alternative) + +If you prefer to use this as steering files instead of a power: + +```bash +# From your project root +mkdir -p .kiro/steering +cp -R powers/aidlc/steering/core-workflow.md .kiro/steering/ +cp -R powers/aidlc/rule-details .kiro/ +``` + +## Usage + +Once installed as a power: + +1. **Activate the workflow** in any Kiro chat by starting with: + ``` + Using AI-DLC, [describe your software development need] + ``` + +2. **AI-DLC will automatically**: + - Display a welcome message + - Detect your project type (greenfield/brownfield) + - Guide you through the appropriate phases + - Create documentation in `aidlc-docs/` directory + +3. **Follow the guided workflow**: + - Answer structured questions + - Review and approve execution plans + - Monitor progress in `aidlc-docs/aidlc-state.md` + - Check audit trail in `aidlc-docs/audit.md` + +## Power Structure + +``` +powers/aidlc/ +├── POWER.md # Power documentation with frontmatter +├── README.md # This file +├── steering/ +│ └── core-workflow.md # Main AI-DLC workflow +└── rule-details/ # Detailed rules for each phase + ├── common/ # Common rules (always loaded) + ├── inception/ # Inception phase rules + ├── construction/ # Construction phase rules + └── operations/ # Operations phase rules +``` + +## What's Different from Original aidlc-rules? + +This power packages the AI-DLC methodology as a Kiro Power with: + +1. **POWER.md**: Comprehensive documentation with proper frontmatter metadata +2. **Updated paths**: All file references updated to work within the power structure +3. **Organized structure**: Clear separation of steering files and rule details +4. **Easy installation**: Can be installed via Kiro Powers UI + +The actual workflow content (all .md files) remains unchanged from the original. + +## Additional Resources + +- **Blog**: [AI-Driven Development Life Cycle](https://aws.amazon.com/blogs/devops/ai-driven-development-life-cycle/) +- **Method Definition Paper**: [AI-DLC Methodology](https://prod.d13rzhkk8cj2z0.amplifyapp.com/) +- **Original Repository**: [aidlc-workflows](https://github.com/aws-samples/aidlc-workflows) diff --git a/aidlc/rule-details/common/ascii-diagram-standards.md b/aidlc/rule-details/common/ascii-diagram-standards.md new file mode 100644 index 0000000..498ab22 --- /dev/null +++ b/aidlc/rule-details/common/ascii-diagram-standards.md @@ -0,0 +1,116 @@ +# ASCII Diagram Standards + +## MANDATORY: Use Basic ASCII Only + +**CRITICAL**: ALWAYS use basic ASCII characters for diagrams (maximum compatibility). + +### ✅ ALLOWED: `+` `-` `|` `^` `v` `<` `>` and alphanumeric text + +### ❌ FORBIDDEN: Unicode box-drawing characters +- NO: `┌` `─` `│` `└` `┐` `┘` `├` `┤` `┬` `┴` `┼` `▼` `▲` `►` `◄` +- Reason: Inconsistent rendering across fonts/platforms + +## Standard ASCII Diagram Patterns + +### CRITICAL: Character Width Rule +**Every line in a box MUST have EXACTLY the same character count (including spaces)** + +✅ CORRECT (all lines = 67 chars): +``` ++---------------------------------------------------------------+ +| Component Name | +| Description text here | ++---------------------------------------------------------------+ +``` + +❌ WRONG (inconsistent widths): +``` ++---------------------------------------------------------------+ +| Component Name | +| Description text here | ++---------------------------------------------------------------+ +``` + +### Box Pattern +``` ++-----------------------------------------------------+ +| | +| Calculator Application | +| | +| Provides basic arithmetic operations for users | +| through a web-based interface | +| | ++-----------------------------------------------------+ +``` + +### Nested Boxes +``` ++-------------------------------------------------------+ +| Web Server (PHP Runtime) | +| +-------------------------------------------------+ | +| | index.php (Monolithic Application) | | +| | +-------------------------------------------+ | | +| | | HTML Template (View Layer) | | | +| | | - Form rendering | | | +| | | - Result display | | | +| | +-------------------------------------------+ | | +| +-------------------------------------------------+ | ++-------------------------------------------------------+ +``` + +### Arrows and Connections +``` ++----------+ +| Source | ++----------+ + | + | HTTP POST + v ++----------+ +| Target | ++----------+ +``` + +### Horizontal Flow +``` ++-------+ +-------+ +-------+ +| Step1 | --> | Step2 | --> | Step3 | ++-------+ +-------+ +-------+ +``` + +### Vertical Flow with Labels +``` +User Action Flow: + | + v ++----------+ +| Input | ++----------+ + | + | validates + v ++----------+ +| Process | ++----------+ + | + | returns + v ++----------+ +| Output | ++----------+ +``` + +## Validation + +Before creating diagrams: +- [ ] Basic ASCII only: `+` `-` `|` `^` `v` `<` `>` +- [ ] No Unicode box-drawing +- [ ] Spaces (not tabs) for alignment +- [ ] Corners use `+` +- [ ] **ALL box lines same character width** (count characters including spaces) +- [ ] Test: Verify corners align vertically in monospace font + +## Alternative + +For complex diagrams, use Mermaid (see `content-validation.md`) + diff --git a/aidlc/rule-details/common/content-validation.md b/aidlc/rule-details/common/content-validation.md new file mode 100644 index 0000000..f80c304 --- /dev/null +++ b/aidlc/rule-details/common/content-validation.md @@ -0,0 +1,78 @@ +# Content Validation Rules + +## MANDATORY: Content Validation Before File Creation + +**CRITICAL**: All generated content MUST be validated before writing to files to prevent parsing errors. + +## ASCII Diagram Standards + +**CRITICAL**: Before creating ANY file with ASCII diagrams: + +1. **LOAD** `common/ascii-diagram-standards.md` +2. **VALIDATE** each diagram: + - Count characters per line (all lines MUST be same width) + - Use ONLY: `+` `-` `|` `^` `v` `<` `>` and spaces + - NO Unicode box-drawing characters + - Spaces only (NO tabs) +3. **TEST** alignment by verifying box corners align vertically + +**See `common/ascii-diagram-standards.md` for patterns and validation checklist.** + +## Mermaid Diagram Validation + +### Required Validation Steps +1. **Syntax Check**: Validate Mermaid syntax before file creation +2. **Character Escaping**: Ensure special characters are properly escaped +3. **Fallback Content**: Provide text alternative if Mermaid fails validation + +### Mermaid Validation Rules +```markdown +## BEFORE creating any file with Mermaid diagrams: + +1. Check for invalid characters in node IDs (use alphanumeric + underscore only) +2. Escape special characters in labels: " → \" and ' → \' +3. Validate flowchart syntax: node connections must be valid +4. Test diagram parsing with simple validation + +## FALLBACK: If Mermaid validation fails, use text-based workflow representation +``` + +### Implementation Pattern +```markdown +## Workflow Visualization + +### Mermaid Diagram (if syntax valid) +```mermaid +[validated diagram content] +``` + +### Text Alternative (always include) +``` +Phase 1: INCEPTION +- Stage 1: Workspace Detection (COMPLETED) +- Stage 2: Requirements Analysis (COMPLETED) +[continue with text representation] +``` + +## General Content Validation + +### Pre-Creation Validation Checklist +- [ ] Validate embedded code blocks (Mermaid, JSON, YAML) +- [ ] Check special character escaping +- [ ] Verify markdown syntax correctness +- [ ] Test content parsing compatibility +- [ ] Include fallback content for complex elements + +### Error Prevention Rules +1. **Always validate before using tools/commands to write files**: Never write unvalidated content +2. **Escape special characters**: Particularly in diagrams and code blocks +3. **Provide alternatives**: Include text versions of visual content +4. **Test syntax**: Validate complex content structures + +## Validation Failure Handling + +### When Validation Fails +1. **Log the error**: Record what failed validation +2. **Use fallback content**: Switch to text-based alternative +3. **Continue workflow**: Don't block on content validation failures +4. **Inform user**: Mention simplified content was used due to parsing constraints diff --git a/aidlc/rule-details/common/depth-levels.md b/aidlc/rule-details/common/depth-levels.md new file mode 100644 index 0000000..5f2ea74 --- /dev/null +++ b/aidlc/rule-details/common/depth-levels.md @@ -0,0 +1,73 @@ +# Adaptive Depth + +**Purpose**: Explain how AI-DLC adapts detail level to problem complexity + +## Core Principle + +**When a stage executes, ALL its defined artifacts are created. The "depth" refers to the level of detail and rigor within those artifacts, which adapts to the problem's complexity.** + +## Stage Selection vs Detail Level + +### Stage Selection (Binary) +- **Workflow Planning** decides: EXECUTE or SKIP for each stage +- **If EXECUTE**: Stage runs and creates ALL its defined artifacts +- **If SKIP**: Stage doesn't run at all + +### Detail Level (Adaptive) +- **Simple problems**: Concise artifacts with essential detail +- **Complex problems**: Comprehensive artifacts with extensive detail +- **Model decides**: Based on problem characteristics, not prescriptive rules + +## Factors Influencing Detail Level + +The model considers these factors when determining appropriate detail: + +1. **Request Clarity**: How clear and complete is the user's request? +2. **Problem Complexity**: How intricate is the solution space? +3. **Scope**: Single file, component, multiple components, or system-wide? +4. **Risk Level**: What's the impact of errors or omissions? +5. **Available Context**: Greenfield vs brownfield, existing documentation +6. **User Preferences**: Has user expressed preference for brevity or detail? + +## Example: Requirements Analysis Artifacts + +**All scenarios create the same artifacts**: +- `requirement-verification-questions.md` (if needed) +- `requirements.md` + +**Note**: User's initial request is captured in `audit.md` (no separate user-intent.md needed) + +**Detail level varies by complexity**: + +### Simple Scenario (Bug Fix) +- **requirement-verification-questions.md**: necessary clarifying questions +- **requirements.md**: Concise functional requirement, minimal sections + +### Complex Scenario (System Migration) +- **requirement-verification-questions.md**: Multiple rounds, 10+ questions +- **requirements.md**: Comprehensive functional + non-functional requirements, traceability, acceptance criteria + +## Example: Application Design Artifacts + +**All scenarios create the same artifacts**: +- `application-design.md` +- `component-diagram.md` + +**Detail level varies by complexity**: + +### Simple Scenario (Single Component) +- **application-design.md**: Basic component description, key methods +- **component-diagram.md**: Simple diagram with essential relationships + +### Complex Scenario (Multi-Component System) +- **application-design.md**: Detailed component responsibilities, all methods with signatures, design patterns, alternatives considered +- **component-diagram.md**: Comprehensive diagram with all relationships, data flows, integration points + +## Guiding Principle for Model + +**"Create exactly the detail needed for the problem at hand - no more, no less."** + +- Don't artificially inflate simple problems with unnecessary detail +- Don't shortchange complex problems by omitting critical detail +- Let problem characteristics drive detail level naturally +- All required artifacts are always created when stage executes diff --git a/aidlc/rule-details/common/error-handling.md b/aidlc/rule-details/common/error-handling.md new file mode 100644 index 0000000..18d1890 --- /dev/null +++ b/aidlc/rule-details/common/error-handling.md @@ -0,0 +1,373 @@ +# Error Handling and Recovery Procedures + +## General Error Handling Principles + +### When Errors Occur +1. **Identify the error**: Clearly state what went wrong +2. **Assess impact**: Determine if the error is blocking or can be worked around +3. **Communicate**: Inform the user about the error and options +4. **Offer solutions**: Provide clear steps to resolve or work around the error +5. **Document**: Log the error and resolution in `audit.md` + +### Error Severity Levels + +**Critical**: Workflow cannot continue +- Missing required files or artifacts +- Invalid user input that cannot be processed +- System errors preventing file operations + +**High**: Phase cannot complete as planned +- Incomplete answers to required questions +- Contradictory user responses +- Missing dependencies from prior phases + +**Medium**: Phase can continue with workarounds +- Optional artifacts missing +- Non-critical validation failures +- Partial completion possible + +**Low**: Minor issues that don't block progress +- Formatting inconsistencies +- Optional information missing +- Non-blocking warnings + +## Phase-Specific Error Handling + +### Context Assessment Errors + +**Error**: Cannot read workspace files +- **Cause**: Permission issues, missing directories +- **Solution**: Ask user to verify workspace path and permissions +- **Workaround**: Proceed with user-provided information only + +**Error**: Existing `aidlc-state.md` is corrupted +- **Cause**: Manual editing, incomplete previous run +- **Solution**: Ask user if they want to start fresh or attempt recovery +- **Recovery**: Create backup, start new state file + +**Error**: Cannot determine required phases +- **Cause**: Insufficient information from user +- **Solution**: Ask clarifying questions about intent and scope +- **Workaround**: Default to comprehensive execution plan + +### Requirements Assessment Errors + +**Error**: User provides contradictory requirements +- **Cause**: Unclear understanding, changing needs +- **Solution**: Create follow-up questions to resolve contradictions +- **Do Not Proceed**: Until contradictions are resolved + +**Error**: Requirements document cannot be converted +- **Cause**: Unsupported format, corrupted file +- **Solution**: Ask user to provide requirements in supported format +- **Workaround**: Work with user's verbal description + +**Error**: Incomplete answers to verification questions +- **Cause**: User skipped questions, unclear what to answer +- **Solution**: Highlight unanswered questions, provide examples +- **Do Not Proceed**: Until all required questions are answered + +### Story Development Errors + +**Error**: Cannot map requirements to stories +- **Cause**: Requirements too vague, missing functional details +- **Solution**: Return to Requirements Assessment for clarification +- **Workaround**: Create stories based on available information, mark as incomplete + +**Error**: User provides ambiguous story planning answers +- **Cause**: Unclear options, complex decision +- **Solution**: Add follow-up questions with specific examples +- **Do Not Proceed**: Until ambiguities are resolved + +**Error**: Story generation plan has uncompleted steps +- **Cause**: Execution interrupted, steps skipped +- **Solution**: Resume from first uncompleted step +- **Recovery**: Review completed steps, continue from checkpoint + +### Application Design Errors + +**Error**: Architectural decision is unclear or contradictory +- **Cause**: Ambiguous answers, conflicting requirements +- **Solution**: Add follow-up questions to clarify decision +- **Do Not Proceed**: Until decision is clear and documented + +**Error**: Cannot determine number of services/units +- **Cause**: Insufficient information about boundaries +- **Solution**: Ask specific questions about deployment, team structure, scaling +- **Workaround**: Default to monolith, allow change later + +### Design Errors + +**Error**: Unit dependencies are circular +- **Cause**: Poor boundary definition, tight coupling +- **Solution**: Identify circular dependencies, suggest refactoring +- **Recovery**: Revise unit boundaries to break cycles + +**Error**: Unit design plan has missing steps +- **Cause**: Plan generation incomplete, template error +- **Solution**: Regenerate plan with all required steps +- **Recovery**: Add missing steps to existing plan + +**Error**: Cannot generate design artifacts +- **Cause**: Missing unit information, unclear requirements +- **Solution**: Return to Units Planning to clarify unit definition +- **Workaround**: Generate partial design, mark gaps + +### NFR Implementation Errors + +**Error**: Technology stack choices are incompatible +- **Cause**: Conflicting requirements, platform limitations +- **Solution**: Highlight incompatibilities, ask user to choose +- **Do Not Proceed**: Until compatible choices are made + +**Error**: Organizational constraints cannot be met +- **Cause**: Network restrictions, security policies +- **Solution**: Document constraints, ask user for workarounds +- **Escalation**: May require human intervention for setup + +**Error**: NFR implementation step requires human action +- **Cause**: AI cannot perform certain tasks (network config, credentials) +- **Solution**: Clearly mark as **HUMAN TASK**, provide instructions +- **Wait**: For user confirmation before proceeding + +### Code Planning Errors + +**Error**: Code generation plan is incomplete +- **Cause**: Missing design artifacts, unclear requirements +- **Solution**: Return to Design phase to complete artifacts +- **Recovery**: Generate plan with available information, mark gaps + +**Error**: Unit dependencies not satisfied +- **Cause**: Dependent units not yet generated +- **Solution**: Reorder generation sequence to respect dependencies +- **Workaround**: Generate with stub dependencies, integrate later + +### Code Generation Errors + +**Error**: Cannot generate code for a step +- **Cause**: Insufficient design information, unclear requirements +- **Solution**: Skip step, document as incomplete, continue +- **Recovery**: Return to step after gathering more information + +**Error**: Generated code has syntax errors +- **Cause**: Template issues, language-specific problems +- **Solution**: Fix syntax errors, regenerate if needed +- **Validation**: Verify code compiles before proceeding + +**Error**: Test generation fails +- **Cause**: Complex logic, missing test framework setup +- **Solution**: Generate basic test structure, mark for manual completion +- **Workaround**: Proceed without tests, add in Operations phase + +### Operations Errors + +**Error**: Cannot determine build tool +- **Cause**: Unusual project structure, multiple build systems +- **Solution**: Ask user to specify build tool and commands +- **Workaround**: Provide generic instructions, user adapts + +**Error**: Deployment target is unclear +- **Cause**: Multiple environments, complex infrastructure +- **Solution**: Ask user to specify deployment targets and methods +- **Workaround**: Provide instructions for common platforms + +## Recovery Procedures + +### Partial Phase Completion + +**Scenario**: Phase was interrupted mid-execution + +**Recovery Steps**: +1. Load the phase plan file +2. Identify last completed step (last [x] checkbox) +3. Resume from next uncompleted step +4. Verify all prior steps are actually complete +5. Continue execution normally + +### Corrupted State File + +**Scenario**: `aidlc-state.md` is corrupted or inconsistent + +**Recovery Steps**: +1. Create backup: `aidlc-state.md.backup` +2. Ask user which phase they're actually on +3. Regenerate state file from scratch +4. Mark completed phases based on existing artifacts +5. Resume from current phase + +### Missing Artifacts + +**Scenario**: Required artifacts from prior phase are missing + +**Recovery Steps**: +1. Identify which artifacts are missing +2. Determine if they can be regenerated +3. If yes: Return to that phase, regenerate artifacts +4. If no: Ask user to provide information manually +5. Document the gap in `audit.md` + +### User Wants to Restart Phase + +**Scenario**: User is unhappy with phase results and wants to redo + +**Recovery Steps**: +1. Confirm user wants to restart (data will be lost) +2. Archive existing artifacts: `{artifact}.backup` +3. Reset phase status in `aidlc-state.md` +4. Clear phase checkboxes in plan files +5. Re-execute phase from beginning + +### User Wants to Skip Phase + +**Scenario**: User wants to skip a phase that was planned + +**Recovery Steps**: +1. Confirm user understands implications +2. Document skip reason in `audit.md` +3. Mark phase as "SKIPPED" in `aidlc-state.md` +4. Proceed to next phase +5. Note: May cause issues in later phases if dependencies missing + +## Escalation Guidelines + +### When to Ask for User Help + +**Immediately**: +- Contradictory or ambiguous user input +- Missing required information +- Technical constraints AI cannot resolve +- Decisions requiring business judgment + +**After Attempting Resolution**: +- Repeated errors in same step +- Complex technical issues +- Unusual project structures +- Integration with external systems + +### When to Suggest Starting Over + +**Consider Fresh Start If**: +- Multiple phases have errors +- State file is severely corrupted +- User cannot provide missing information +- Artifacts are inconsistent across phases + +## Session Resumption Errors + +### Missing Artifacts During Resumption + +**Error**: Required artifacts from previous stages are missing +- **Cause**: Files deleted, moved, or never created +- **Solution**: + 1. Identify which stage created the missing artifacts + 2. Check if stage was marked complete in aidlc-state.md + 3. If marked complete but artifacts missing: Regenerate that stage + 4. If not marked complete: Resume from that stage +- **Recovery**: Return to the stage that creates missing artifacts and re-execute + +**Error**: Artifact file exists but is empty or corrupted +- **Cause**: Interrupted write, manual editing, file system issues +- **Solution**: + 1. Create backup of corrupted file + 2. Attempt to regenerate from stage that creates it + 3. If cannot regenerate: Ask user for information to recreate +- **Recovery**: Re-execute the stage that creates the artifact + +### Inconsistent State During Resumption + +**Error**: aidlc-state.md shows stage complete but artifacts don't exist +- **Cause**: State file updated but artifact generation failed +- **Solution**: + 1. Mark stage as incomplete in aidlc-state.md + 2. Re-execute the stage to generate artifacts + 3. Verify artifacts exist before marking complete +- **Recovery**: Reset stage status and re-execute + +**Error**: Artifacts exist but aidlc-state.md shows stage incomplete +- **Cause**: Artifact generation succeeded but state update failed +- **Solution**: + 1. Verify artifacts are complete and valid + 2. Update aidlc-state.md to mark stage complete + 3. Proceed to next stage +- **Recovery**: Update state file to reflect actual completion + +**Error**: Multiple stages marked as "current" in aidlc-state.md +- **Cause**: State file corruption, manual editing +- **Solution**: + 1. Review artifacts to determine actual progress + 2. Ask user which stage they're actually on + 3. Correct aidlc-state.md to show single current stage +- **Recovery**: Rebuild state file based on existing artifacts + +### Context Loading Errors + +**Error**: Cannot load required context from previous stages +- **Cause**: Missing files, corrupted content, wrong file paths +- **Solution**: + 1. List which artifacts are needed for current stage + 2. Check which ones are missing or corrupted + 3. Regenerate missing artifacts or ask user for information +- **Recovery**: Complete prerequisite stages before resuming current stage + +**Error**: Loaded artifacts contain contradictory information +- **Cause**: Manual editing, multiple people working, incomplete updates +- **Solution**: + 1. Identify contradictions and present to user + 2. Ask user which information is correct + 3. Update artifacts to resolve contradictions +- **Recovery**: Reconcile contradictions before proceeding + +### Resumption Best Practices + +1. **Always validate state**: Check aidlc-state.md matches actual artifacts +2. **Load incrementally**: Load artifacts stage-by-stage, validate each +3. **Fail fast**: Stop immediately if critical artifacts are missing +4. **Communicate clearly**: Tell user exactly what's missing and why it's needed +5. **Offer options**: Regenerate, provide manually, or start fresh +6. **Document recovery**: Log all recovery actions in audit.md State file is severely corrupted +- User requirements have changed significantly +- Architectural decision needs to be reversed + +**Before Starting Over**: +1. Archive all existing work +2. Document lessons learned +3. Identify what to preserve +4. Get user confirmation +5. Create new execution plan + +## Logging Requirements + +### Error Logging Format + +```markdown +## Error - [Phase Name] +**Timestamp**: [ISO timestamp] +**Error Type**: [Critical/High/Medium/Low] +**Description**: [What went wrong] +**Cause**: [Why it happened] +**Resolution**: [How it was resolved] +**Impact**: [Effect on workflow] + +--- +``` + +### Recovery Logging Format + +```markdown +## Recovery - [Phase Name] +**Timestamp**: [ISO timestamp] +**Issue**: [What needed recovery] +**Recovery Steps**: [What was done] +**Outcome**: [Result of recovery] +**Artifacts Affected**: [List of files] + +--- +``` + +## Prevention Best Practices + +1. **Validate Early**: Check inputs and dependencies before starting work +2. **Checkpoint Often**: Update checkboxes immediately after completing steps +3. **Communicate Clearly**: Explain what you're doing and why +4. **Ask Questions**: Don't assume - clarify ambiguities immediately +5. **Document Everything**: Log all decisions and changes in `audit.md` diff --git a/aidlc/rule-details/common/overconfidence-prevention.md b/aidlc/rule-details/common/overconfidence-prevention.md new file mode 100644 index 0000000..d63334d --- /dev/null +++ b/aidlc/rule-details/common/overconfidence-prevention.md @@ -0,0 +1,100 @@ +# Overconfidence Prevention Guide + +## Problem Statement + +AI-DLC was exhibiting overconfidence by not asking enough clarifying questions, even for complex project intent statements. This led to assumptions being made instead of gathering proper requirements. + +## Root Cause Analysis + +The overconfidence issue was caused by directives in multiple stages that encouraged skipping questions: + +1. **Functional Design**: "Skip entire categories if not applicable" +2. **User Stories**: "Use categories as inspiration, NOT as mandatory checklist" +3. **Requirements Analysis**: Similar patterns encouraging minimal questioning +4. **NFR Requirements**: "Only if" conditions that discouraged thorough analysis + +These directives were telling the AI to avoid asking questions rather than encouraging comprehensive requirements gathering. + +## Solution Implemented + +### Updated Question Generation Philosophy + +**OLD APPROACH**: "Only ask questions if absolutely necessary" +**NEW APPROACH**: "When in doubt, ask the question - overconfidence leads to poor outcomes" + +### Key Changes Made + +#### 1. Requirements Analysis Stage +- Changed from "only if needed" to "ALWAYS create questions unless exceptionally clear" +- Added comprehensive evaluation areas (functional, non-functional, business context, technical context) +- Emphasized proactive questioning approach + +#### 2. User Stories Stage +- Removed "skip entire categories" directive +- Added comprehensive question categories to evaluate +- Enhanced answer analysis requirements +- Strengthened follow-up question mandates + +#### 3. Functional Design Stage +- Replaced "only if" conditions with comprehensive evaluation +- Added more question categories (data flow, integration points, error handling) +- Strengthened ambiguity detection and resolution requirements + +#### 4. NFR Requirements Stage +- Expanded question categories beyond basic NFRs +- Added reliability, maintainability, and usability considerations +- Enhanced answer analysis for technical ambiguities + +### New Guiding Principles + +1. **Default to Asking**: When there's any ambiguity, ask clarifying questions +2. **Comprehensive Coverage**: Evaluate ALL relevant categories, don't skip areas +3. **Thorough Analysis**: Carefully analyze ALL user responses for ambiguities +4. **Mandatory Follow-up**: Create follow-up questions for ANY unclear responses +5. **No Proceeding with Ambiguity**: Don't move forward until ALL ambiguities are resolved + +## Implementation Guidelines + +### For Question Generation +- Evaluate ALL question categories, don't skip any +- Ask questions wherever clarification would improve quality +- Include comprehensive question categories in each stage +- Default to inclusion rather than exclusion of questions + +### For Answer Analysis +- Look for vague responses: "depends", "maybe", "not sure", "mix of", "somewhere between" +- Detect undefined terms and references to external concepts +- Identify contradictory or incomplete answers +- Create follow-up questions for ANY ambiguities + +### For Follow-up Questions +- Create separate clarification files when ambiguities are detected +- Ask specific questions to resolve each ambiguity +- Don't proceed until ALL unclear responses are clarified +- Be thorough - better to over-clarify than under-clarify + +## Quality Assurance + +### Red Flags to Watch For +- Stages completing without asking any questions on complex projects +- Proceeding with vague or ambiguous user responses +- Skipping entire question categories without justification +- Making assumptions instead of asking for clarification + +### Success Indicators +- Appropriate number of clarifying questions for project complexity +- Thorough analysis of user responses with follow-up when needed +- Clear, unambiguous requirements before proceeding to implementation +- Reduced need for changes during later stages due to better upfront clarification + +## Maintenance + +This guide should be referenced when: +- Adding new stages to AI-DLC +- Updating existing stage instructions +- Reviewing AI-DLC performance for overconfidence issues +- Training team members on AI-DLC question generation principles + +## Key Takeaway + +**It's better to ask too many questions than to make incorrect assumptions.** The cost of asking clarifying questions upfront is far less than the cost of implementing the wrong solution based on assumptions. \ No newline at end of file diff --git a/aidlc/rule-details/common/process-overview.md b/aidlc/rule-details/common/process-overview.md new file mode 100644 index 0000000..a547a58 --- /dev/null +++ b/aidlc/rule-details/common/process-overview.md @@ -0,0 +1,141 @@ +# AI-DLC Adaptive Workflow Overview + +**Purpose**: Technical reference for AI model and developers to understand complete workflow structure. + +**Note**: Similar content exists in core-workflow.md (user welcome message) and README.md (documentation). This duplication is INTENTIONAL - each file serves a different purpose: +- **This file**: Detailed technical reference with Mermaid diagram for AI model context loading +- **core-workflow.md**: User-facing welcome message with ASCII diagram +- **README.md**: Human-readable documentation for repository + +## The Three-Phase Lifecycle: +• **INCEPTION PHASE**: Planning and architecture (Workspace Detection + conditional phases + Workflow Planning) +• **CONSTRUCTION PHASE**: Design, implementation, build and test (per-unit design + Code Planning/Generation + Build & Test) +• **OPERATIONS PHASE**: Placeholder for future deployment and monitoring workflows + +## The Adaptive Workflow: +• **Workspace Detection** (always) → **Reverse Engineering** (brownfield only) → **Requirements Analysis** (always, adaptive depth) → **Conditional Phases** (as needed) → **Workflow Planning** (always) → **Code Generation** (always, per-unit) → **Build and Test** (always) + +## How It Works: +• **AI analyzes** your request, workspace, and complexity to determine which stages are needed +• **These stages always execute**: Workspace Detection, Requirements Analysis (adaptive depth), Workflow Planning, Code Generation (per-unit), Build and Test +• **All other stages are conditional**: Reverse Engineering, User Stories, Application Design, Units Generation, per-unit design stages (Functional Design, NFR Requirements, NFR Design, Infrastructure Design) +• **No fixed sequences**: Stages execute in the order that makes sense for your specific task + +## Your Team's Role: +• **Answer questions** in dedicated question files using [Answer]: tags with letter choices (A, B, C, D, E) +• **Option E available**: Choose "Other" and describe your custom response if provided options don't match +• **Work as a team** to review and approve each phase before proceeding +• **Collectively decide** on architectural approach when needed +• **Important**: This is a team effort - involve relevant stakeholders for each phase + +## AI-DLC Three-Phase Workflow: + +```mermaid +flowchart TD + Start(["User Request"]) + + subgraph INCEPTION["🔵 INCEPTION PHASE"] + WD["Workspace Detection
ALWAYS"] + RE["Reverse Engineering
CONDITIONAL"] + RA["Requirements Analysis
ALWAYS"] + Stories["User Stories
CONDITIONAL"] + WP["Workflow Planning
ALWAYS"] + AppDesign["Application Design
CONDITIONAL"] + UnitsG["Units Generation
CONDITIONAL"] + end + + subgraph CONSTRUCTION["🟢 CONSTRUCTION PHASE"] + FD["Functional Design
CONDITIONAL"] + NFRA["NFR Requirements
CONDITIONAL"] + NFRD["NFR Design
CONDITIONAL"] + ID["Infrastructure Design
CONDITIONAL"] + CG["Code Generation
ALWAYS"] + BT["Build and Test
ALWAYS"] + end + + subgraph OPERATIONS["🟡 OPERATIONS PHASE"] + OPS["Operations
PLACEHOLDER"] + end + + Start --> WD + WD -.-> RE + WD --> RA + RE --> RA + + RA -.-> Stories + RA --> WP + Stories --> WP + + WP -.-> AppDesign + WP -.-> UnitsG + AppDesign -.-> UnitsG + UnitsG --> FD + FD -.-> NFRA + NFRA -.-> NFRD + NFRD -.-> ID + + WP --> CG + FD --> CG + NFRA --> CG + NFRD --> CG + ID --> CG + CG -.->|Next Unit| FD + CG --> BT + BT -.-> OPS + BT --> End(["Complete"]) + + style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style RA fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style WP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + + style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff + style OPS fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 + style RE fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style Stories fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style AppDesign fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + + style UnitsG fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style FD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style NFRA fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style NFRD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style ID fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000 + style INCEPTION fill:#BBDEFB,stroke:#1565C0,stroke-width:3px, color:#000 + style CONSTRUCTION fill:#C8E6C9,stroke:#2E7D32,stroke-width:3px, color:#000 + style OPERATIONS fill:#FFF59D,stroke:#F57F17,stroke-width:3px, color:#000 + style Start fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + style End fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + + linkStyle default stroke:#333,stroke-width:2px +``` + +**Stage Descriptions:** + +**🔵 INCEPTION PHASE** - Planning and Architecture +- Workspace Detection: Analyze workspace state and project type (ALWAYS) +- Reverse Engineering: Analyze existing codebase (CONDITIONAL - Brownfield only) +- Requirements Analysis: Gather and validate requirements (ALWAYS - Adaptive depth) +- User Stories: Create user stories and personas (CONDITIONAL) +- Workflow Planning: Create execution plan (ALWAYS) +- Application Design: High-level component identification and service layer design (CONDITIONAL) +- Units Generation: Decompose into units of work (CONDITIONAL) + +**🟢 CONSTRUCTION PHASE** - Design, Implementation, Build and Test +- Functional Design: Detailed business logic design per unit (CONDITIONAL, per-unit) +- NFR Requirements: Determine NFRs and select tech stack (CONDITIONAL, per-unit) +- NFR Design: Incorporate NFR patterns and logical components (CONDITIONAL, per-unit) +- Infrastructure Design: Map to actual infrastructure services (CONDITIONAL, per-unit) +- Code Generation: Generate code with Part 1 - Planning, Part 2 - Generation (ALWAYS, per-unit) +- Build and Test: Build all units and execute comprehensive testing (ALWAYS) + +**🟡 OPERATIONS PHASE** - Placeholder +- Operations: Placeholder for future deployment and monitoring workflows (PLACEHOLDER) + +**Key Principles:** +- Phases execute only when they add value +- Each phase independently evaluated +- INCEPTION focuses on "what" and "why" +- CONSTRUCTION focuses on "how" plus "build and test" +- OPERATIONS is placeholder for future expansion +- Simple changes may skip conditional INCEPTION stages +- Complex changes get full INCEPTION and CONSTRUCTION treatment \ No newline at end of file diff --git a/aidlc/rule-details/common/question-format-guide.md b/aidlc/rule-details/common/question-format-guide.md new file mode 100644 index 0000000..d15c4d8 --- /dev/null +++ b/aidlc/rule-details/common/question-format-guide.md @@ -0,0 +1,332 @@ +# Question Format Guide + +## MANDATORY: All Questions Must Use This Format + +### Rule: Never Ask Questions in Chat +**CRITICAL**: You must NEVER ask questions directly in the chat. ALL questions must be placed in dedicated question files. + +### Question File Format + +#### File Naming Convention +- Use descriptive names: `{phase-name}-questions.md` +- Examples: + - `classification-questions.md` + - `requirements-questions.md` + - `story-planning-questions.md` + - `design-questions.md` + +#### Question Structure +Every question must include meaningful options plus "Other" as the last option: + +```markdown +## Question [Number] +[Clear, specific question text] + +A) [First meaningful option] +B) [Second meaningful option] +[...additional options as needed...] +X) Other (please describe after [Answer]: tag below) + +[Answer]: +``` + +**CRITICAL**: +- "Other" is MANDATORY as the LAST option for every question +- Only include meaningful options - don't make up options to fill slots +- Use as many or as few options as make sense (minimum 2 + Other) + +### Complete Example + +```markdown +# Requirements Clarification Questions + +Please answer the following questions to help clarify the requirements. + +## Question 1 +What is the primary user authentication method? + +A) Username and password +B) Social media login (Google, Facebook) +C) Single Sign-On (SSO) +D) Multi-factor authentication +E) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Question 2 +Will this be a web or mobile application? + +A) Web application +B) Mobile application +C) Both web and mobile +D) Other (please describe after [Answer]: tag below) + +[Answer]: + +## Question 3 +Is this a new project or existing codebase? + +A) New project (greenfield) +B) Existing codebase (brownfield) +C) Other (please describe after [Answer]: tag below) + +[Answer]: +``` + +### User Response Format +Users will answer by filling in the letter choice after [Answer]: tag: + +```markdown +## Question 1 +What is the primary user authentication method? + +A) Username and password +B) Social media login (Google, Facebook) +C) Single Sign-On (SSO) +D) Multi-factor authentication + +[Answer]: C +``` + +### Reading User Responses +After user confirms completion: +1. Read the question file +2. Extract answers after [Answer]: tags +3. Validate all questions are answered +4. Proceed with analysis based on responses + +### Multiple Choice Guidelines + +#### Option Count +- Minimum: 2 meaningful options + "Other" (A, B, C) +- Typical: 3-4 meaningful options + "Other" (A, B, C, D, E) +- Maximum: 5 meaningful options + "Other" (A, B, C, D, E, F) +- **CRITICAL**: Don't make up options just to fill slots - only include meaningful choices + +#### Option Quality +- Make options mutually exclusive +- Cover the most common scenarios +- Only include meaningful, realistic options +- **ALWAYS include "Other" as the LAST option** (MANDATORY) +- Be specific and clear +- **Don't make up options to fill A, B, C, D slots** + +#### Good Example: +```markdown +## Question 5 +What database technology will be used? + +A) Relational (PostgreSQL, MySQL) +B) NoSQL Document (MongoDB, DynamoDB) +C) NoSQL Key-Value (Redis, Memcached) +D) Graph Database (Neo4j, Neptune) +E) Other (please describe after [Answer]: tag below) + +[Answer]: +``` + +#### Bad Example (Avoid): +```markdown +## Question 5 +What database will you use? + +A) Yes +B) No +C) Maybe + +[Answer]: +``` + +### Workflow Integration + +#### Step 1: Create Question File +```markdown +Create aidlc-docs/{phase-name}-questions.md with all questions +``` + +#### Step 2: Inform User +``` +"I've created {phase-name}-questions.md with [X] questions. +Please answer each question by filling in the letter choice after the [Answer]: tag. +If none of the options match your needs, choose the last option (Other) and describe your preference. Let me know when you're done." +``` + +#### Step 3: Wait for Confirmation +Wait for user to say "done", "completed", "finished", or similar. + +#### Step 4: Read and Analyze +``` +Read aidlc-docs/{phase-name}-questions.md +Extract all answers +Validate completeness +Proceed with analysis +``` + +### Error Handling + +#### Missing Answers +If any [Answer]: tag is empty: +``` +"I noticed Question [X] is not answered. Please provide an answer using one of the letter choices +for all questions before proceeding." +``` + +#### Invalid Answers +If answer is not a valid letter choice: +``` +"Question [X] has an invalid answer '[answer]'. +Please use only the letter choices provided in the question." +``` + +#### Ambiguous Answers +If user provides explanation instead of letter: +``` +"For Question [X], please provide the letter choice that best matches your answer. +If none match, choose 'Other' and add your description after the [Answer]: tag." +``` + +### Contradiction and Ambiguity Detection + +**MANDATORY**: After reading user responses, you MUST check for contradictions and ambiguities. + +#### Detecting Contradictions +Look for logically inconsistent answers: +- Scope mismatch: "Bug fix" but "Entire codebase affected" +- Risk mismatch: "Low risk" but "Breaking changes" +- Timeline mismatch: "Quick fix" but "Multiple subsystems" +- Impact mismatch: "Single component" but "Significant architecture changes" + +#### Detecting Ambiguities +Look for unclear or borderline responses: +- Answers that could fit multiple classifications +- Responses that lack specificity +- Conflicting indicators across multiple questions + +#### Creating Clarification Questions +If contradictions or ambiguities detected: + +1. **Create clarification file**: `{phase-name}-clarification-questions.md` +2. **Explain the issue**: Clearly state what contradiction/ambiguity was detected +3. **Ask targeted questions**: Use multiple choice format to resolve the issue +4. **Reference original questions**: Show which questions had conflicting answers + +**Example**: +```markdown +# [Phase Name] Clarification Questions + +I detected contradictions in your responses that need clarification: + +## Contradiction 1: [Brief Description] +You indicated "[Answer A]" (Q[X]:[Letter]) but also "[Answer B]" (Q[Y]:[Letter]). +These responses are contradictory because [explanation]. + +### Clarification Question 1 +[Specific question to resolve contradiction] + +A) [Option that resolves toward first answer] +B) [Option that resolves toward second answer] +C) [Option that provides middle ground] +D) [Option that reframes the question] + +[Answer]: + +## Ambiguity 1: [Brief Description] +Your response to Q[X] ("[Answer]") is ambiguous because [explanation]. + +### Clarification Question 2 +[Specific question to clarify ambiguity] + +A) [Clear option 1] +B) [Clear option 2] +C) [Clear option 3] +D) [Clear option 4] + +[Answer]: +``` + +#### Workflow for Clarifications + +1. **Detect**: Analyze all responses for contradictions/ambiguities +2. **Create**: Generate clarification question file if issues found +3. **Inform**: Tell user about the issues and clarification file +4. **Wait**: Do not proceed until user provides clarifications +5. **Re-validate**: After clarifications, check again for consistency +6. **Proceed**: Only move forward when all contradictions are resolved + +#### Example User Message +``` +"I detected 2 contradictions in your responses: + +1. Bug fix scope vs. codebase impact (Q1 vs Q2) +2. Low risk vs. breaking changes (Q7 vs Q4) + +I've created classification-clarification-questions.md with 2 questions to resolve these. +Please answer these clarifying questions before I can proceed with classification." +``` + +### Best Practices + +1. **Be Specific**: Questions should be clear and unambiguous +2. **Be Comprehensive**: Cover all necessary information +3. **Be Concise**: Keep questions focused on one topic +4. **Be Practical**: Options should be realistic and actionable +5. **Be Consistent**: Use same format throughout all question files + +### Phase-Specific Examples + +#### Example with 2 meaningful options: +```markdown +## Question 1 +Is this a new project or existing codebase? + +A) New project (greenfield) +B) Existing codebase (brownfield) +C) Other (please describe after [Answer]: tag below) + +[Answer]: +``` + +#### Example with 3 meaningful options: +```markdown +## Question 2 +What is the deployment target? + +A) Cloud (AWS, Azure, GCP) +B) On-premises servers +C) Hybrid (both cloud and on-premises) +D) Other (please describe after [Answer]: tag below) + +[Answer]: +``` + +#### Example with 4 meaningful options: +```markdown +## Question 3 +What architectural pattern should be used? + +A) Monolithic architecture +B) Microservices architecture +C) Serverless architecture +D) Event-driven architecture +E) Other (please describe after [Answer]: tag below) + +[Answer]: +``` + +## Summary + +**Remember**: +- ✅ Always create question files +- ✅ Always use multiple choice format +- ✅ **Always include "Other" as the LAST option (MANDATORY)** +- ✅ Only include meaningful options - don't make up options to fill slots +- ✅ Always use [Answer]: tags +- ✅ Always wait for user completion +- ✅ Always validate responses for contradictions +- ✅ Always create clarification files if needed +- ✅ Always resolve contradictions before proceeding +- ❌ Never ask questions in chat +- ❌ Never make up options just to have A, B, C, D +- ❌ Never proceed without answers +- ❌ Never proceed with unresolved contradictions +- ❌ Never make assumptions about ambiguous responses diff --git a/aidlc/rule-details/common/session-continuity.md b/aidlc/rule-details/common/session-continuity.md new file mode 100644 index 0000000..c2fc739 --- /dev/null +++ b/aidlc/rule-details/common/session-continuity.md @@ -0,0 +1,47 @@ +# Session Continuity Templates + +## Welcome Back Prompt Template +When a user returns to continue work on an existing AI-DLC project, present this prompt: + +```markdown +**Welcome back! I can see you have an existing AI-DLC project in progress.** + +Based on your aidlc-state.md, here's your current status: +- **Project**: [project-name] +- **Current Phase**: [INCEPTION/CONSTRUCTION/OPERATIONS] +- **Current Stage**: [Stage Name] +- **Last Completed**: [Last completed step] +- **Next Step**: [Next step to work on] + +**What would you like to work on today?** + +A) Continue where you left off ([Next step description]) +B) Review a previous stage ([Show available stages]) + +[Answer]: +``` + +## MANDATORY: Session Continuity Instructions +1. **Always read aidlc-state.md first** when detecting existing project +2. **Parse current status** from the workflow file to populate the prompt +3. **MANDATORY: Load Previous Stage Artifacts** - Before resuming any stage, automatically read all relevant artifacts from previous stages: + - **Reverse Engineering**: Read architecture.md, code-structure.md, api-documentation.md + - **Requirements Analysis**: Read requirements.md, requirement-verification-questions.md + - **User Stories**: Read stories.md, personas.md, story-generation-plan.md + - **Application Design**: Read application-design artifacts (components.md, component-methods.md, services.md) + - **Design (Units)**: Read unit-of-work.md, unit-of-work-dependency.md, unit-of-work-story-map.md + - **Per-Unit Design**: Read functional-design.md, nfr-requirements.md, nfr-design.md, infrastructure-design.md + - **Code Stages**: Read all code files, plans, AND all previous artifacts +4. **Smart Context Loading by Stage**: + - **Early Stages (Workspace Detection, Reverse Engineering)**: Load workspace analysis + - **Requirements/Stories**: Load reverse engineering + requirements artifacts + - **Design Stages**: Load requirements + stories + architecture + design artifacts + - **Code Stages**: Load ALL artifacts + existing code files +5. **Adapt options** based on architectural choice and current phase +6. **Show specific next steps** rather than generic descriptions +7. **Log the continuity prompt** in audit.md with timestamp +8. **Context Summary**: After loading artifacts, provide brief summary of what was loaded for user awareness +9. **Asking questions**: ALWAYS ask clarification or user feedback questions by placing them in .md files. DO NOT place the multiple-choice questions in-line in the chat session. + +## Error Handling +If artifacts are missing or corrupted during session resumption, see [error-handling.md](error-handling.md) for guidance on recovery procedures. \ No newline at end of file diff --git a/aidlc/rule-details/common/terminology.md b/aidlc/rule-details/common/terminology.md new file mode 100644 index 0000000..5193a75 --- /dev/null +++ b/aidlc/rule-details/common/terminology.md @@ -0,0 +1,189 @@ +# AI-DLC Terminology Glossary + +## Core Terminology + +### Phase vs Stage + +**Phase**: One of the three high-level lifecycle phases in AI-DLC +- 🔵 **INCEPTION PHASE** - Planning & Architecture (WHAT and WHY) +- 🟢 **CONSTRUCTION PHASE** - Design, Implementation & Test (HOW) +- 🟡 **OPERATIONS PHASE** - Deployment & Monitoring (future expansion) + +**Stage**: An individual workflow activity within a phase +- Examples: Context Assessment stage, Requirements Assessment stage, Code Planning stage +- Each stage has specific prerequisites, steps, and outputs +- Stages can be ALWAYS-EXECUTE or CONDITIONAL + +**Usage Examples**: +- ✅ "The CONSTRUCTION phase contains 7 stages" +- ✅ "The Code Planning stage is always executed" +- ✅ "We're in the INCEPTION phase, executing the Requirements Assessment stage" +- ❌ "The Requirements Assessment phase" (should be "stage") +- ❌ "The CONSTRUCTION stage" (should be "phase") + +## Three-Phase Lifecycle + +### INCEPTION PHASE +**Purpose**: Planning and architectural decisions +**Focus**: Determine WHAT to build and WHY +**Location**: `inception/` directory + +**Stages**: +- Workspace Detection (ALWAYS) +- Reverse Engineering (CONDITIONAL - Brownfield only) +- Requirements Analysis (ALWAYS - Adaptive depth) +- User Stories (CONDITIONAL) +- Workflow Planning (ALWAYS) +- Application Design (CONDITIONAL) +- Design - Units Planning/Generation (CONDITIONAL) + +**Outputs**: Requirements, user stories, architectural decisions, unit definitions + +### CONSTRUCTION PHASE +**Purpose**: Detailed design and implementation +**Focus**: Determine HOW to build it +**Location**: `construction/` directory + +**Stages**: +- Functional Design (CONDITIONAL, per-unit) +- NFR Requirements (CONDITIONAL, per-unit) +- NFR Design (CONDITIONAL, per-unit) +- Infrastructure Design (CONDITIONAL, per-unit) +- Code Planning (ALWAYS) +- Code Generation (ALWAYS) +- Build and Test (ALWAYS) + +**Outputs**: Design artifacts, NFR implementations, code, tests + +### OPERATIONS PHASE +**Purpose**: Deployment and operational readiness +**Focus**: How to DEPLOY and RUN it +**Location**: `operations/` directory + +**Stages**: +- Operations (PLACEHOLDER) + +**Outputs**: Build instructions, deployment guides, monitoring setup, verification procedures + +--- + +## Workflow Stages + +### Always-Execute Stages +- **Workspace Detection**: Initial analysis of workspace state and project type +- **Requirements Analysis**: Gathering requirements (depth varies based on complexity) +- **Workflow Planning**: Creating execution plan for which phases to run +- **Code Planning**: Creating detailed implementation plans for code generation +- **Code Generation**: Generating actual code based on plans and prior artifacts +- **Build and Test**: Building all units and executing comprehensive testing + +### Conditional Stages +- **Reverse Engineering**: Analyzing existing codebase (brownfield projects only) +- **User Stories**: Creating user stories and personas (includes Story Planning and Story Generation) +- **Application Design**: Designing application components, methods, business rules, and services +- **Design**: Designing system components (includes Units Planning, Units Generation, per-unit design) +- **Functional Design**: Technology-agnostic business logic design (per-unit) +- **NFR Requirements**: Determining NFRs and selecting tech stack (per-unit) +- **NFR Design**: Incorporating NFR patterns and logical components (per-unit) +- **Infrastructure Design**: Mapping to actual infrastructure services (per-unit) + +## Application Design Terms + +- **Component**: A functional unit with specific responsibilities +- **Method**: A function or operation within a component with defined business rules +- **Business Rule**: Logic that governs method behavior and validation +- **Service**: Orchestration layer that coordinates business logic across components +- **Component Dependency**: Relationship and communication pattern between components + +## Architecture Terms (Infrastructure) + +### Unit of Work +A logical grouping of user stories for development purposes. The term used during planning and decomposition. + +**Usage**: "We need to decompose the system into units of work" + +### Service +An independently deployable component in a microservices architecture. Each service is a separate unit of work. + +**Usage**: "The Payment Service handles all payment processing" + +### Module +A logical grouping of functionality within a single service or monolith. Modules are not independently deployable. + +**Usage**: "The authentication module within the User Service" + +### Component +A reusable building block within a service or module. Components are classes, functions, or packages that provide specific functionality. + +**Usage**: "The EmailValidator component validates email addresses" + +## Terminology Guidelines + +### When to Use Each Term + +**Unit of Work**: +- During Units Planning and Units Generation phases +- When discussing system decomposition +- In planning documents and discussions +- Example: "How should we decompose this into units of work?" + +**Service**: +- When referring to independently deployable components +- In microservices architecture contexts +- In deployment and infrastructure discussions +- Example: "The Order Service will be deployed to ECS" + +**Module**: +- When referring to logical groupings within a service +- In monolith architecture contexts +- When discussing internal organization +- Example: "The reporting module generates all reports" + +**Component**: +- When referring to specific classes, functions, or packages +- In design and implementation discussions +- When discussing reusable building blocks +- Example: "The DatabaseConnection component manages connections" + +## Stage Terminology + +### Planning vs Generation +- **Planning**: Creating a plan with questions and checkboxes for execution +- **Generation**: Executing the plan to create artifacts + +Examples: +- Story Planning → Story Generation +- Units Planning → Units Generation +- Unit Design Planning → Unit Design Generation +- NFR Planning → NFR Generation +- Code Planning → Code Generation + +### Depth Levels +- **Minimal**: Quick, focused execution for simple changes +- **Standard**: Normal depth with standard artifacts for typical projects +- **Comprehensive**: Full depth with all artifacts for complex/high-risk projects + +## Artifact Types + +### Plans +Documents with checkboxes and questions that guide execution. +- Located in `aidlc-docs/plans/` +- Examples: `story-generation-plan.md`, `unit-of-work-plan.md` + +### Artifacts +Generated outputs from executing plans. +- Located in various `aidlc-docs/` subdirectories +- Examples: `requirements.md`, `stories.md`, `design.md` + +### State Files +Files tracking workflow progress and status. +- `aidlc-state.md`: Overall workflow state +- `audit.md`: Complete audit trail of all interactions + +## Common Abbreviations + +- **AI-DLC**: AI-Driven Development Life Cycle +- **NFR**: Non-Functional Requirements +- **UOW**: Unit of Work +- **API**: Application Programming Interface +- **CDK**: Cloud Development Kit (AWS) diff --git a/aidlc/rule-details/common/welcome-message.md b/aidlc/rule-details/common/welcome-message.md new file mode 100644 index 0000000..8c775ef --- /dev/null +++ b/aidlc/rule-details/common/welcome-message.md @@ -0,0 +1,109 @@ +# AI-DLC Welcome Message + +**Purpose**: This file contains the user-facing welcome message that should be displayed ONCE at the start of any AI-DLC workflow. + +--- + +# 👋 Welcome to AI-DLC (AI-Driven Development Life Cycle)! 👋 + +I'll guide you through an adaptive software development workflow that intelligently tailors itself to your specific needs. + +## What is AI-DLC? + +AI-DLC is a structured yet flexible software development process that adapts to your project's needs. Think of it as having an experienced software architect who: + +- **Analyzes your requirements** and asks clarifying questions when needed +- **Plans the optimal approach** based on complexity and risk +- **Skips unnecessary steps** for simple changes while providing comprehensive coverage for complex projects +- **Documents everything** so you have a complete record of decisions and rationale +- **Guides you through each phase** with clear checkpoints and approval gates + +## The Three-Phase Lifecycle + +``` + User Request + | + v + ╔═══════════════════════════════════════╗ + ║ INCEPTION PHASE ║ + ║ Planning & Application Design ║ + ╠═══════════════════════════════════════╣ + ║ • Workspace Detection (ALWAYS) ║ + ║ • Reverse Engineering (COND) ║ + ║ • Requirements Analysis (ALWAYS) ║ + ║ • User Stories (CONDITIONAL) ║ + ║ • Workflow Planning (ALWAYS) ║ + ║ • Application Design (CONDITIONAL) ║ + ║ • Units Generation (CONDITIONAL) ║ + ╚═══════════════════════════════════════╝ + | + v + ╔═══════════════════════════════════════╗ + ║ CONSTRUCTION PHASE ║ + ║ Design, Implementation & Test ║ + ╠═══════════════════════════════════════╣ + ║ • Per-Unit Loop (for each unit): ║ + ║ - Functional Design (COND) ║ + ║ - NFR Requirements Assess (COND) ║ + ║ - NFR Design (COND) ║ + ║ - Infrastructure Design (COND) ║ + ║ - Code Generation (ALWAYS) ║ + ║ • Build and Test (ALWAYS) ║ + ╚═══════════════════════════════════════╝ + | + v + ╔═══════════════════════════════════════╗ + ║ OPERATIONS PHASE ║ + ║ Placeholder for Future ║ + ╠═══════════════════════════════════════╣ + ║ • Operations (PLACEHOLDER) ║ + ╚═══════════════════════════════════════╝ + | + v + Complete +``` + +### Phase Breakdown: + +**INCEPTION PHASE** - *Planning & Application Design* +- **Purpose**: Determines WHAT to build and WHY +- **Activities**: Understanding requirements, analyzing existing code (if any), planning the approach +- **Output**: Clear requirements, execution plan, decisions on the number of units of work for parallel development +- **Your Role**: Answer questions, review plans, approve direction + +**CONSTRUCTION PHASE** - *Detailed Design, Implementation & Test* +- **Purpose**: Determines HOW to build it +- **Activities**: Detailed design (when needed), code generation, comprehensive testing +- **Output**: Working code, tests, build instructions +- **Your Role**: Review designs, approve implementation plans, validate results + +**OPERATIONS PHASE** - *Deployment & Monitoring (Future)* +- **Purpose**: How to DEPLOY and RUN it +- **Status**: Placeholder for future deployment and monitoring workflows +- **Current State**: Build and test activities handled in CONSTRUCTION phase + +## Key Principles: + +- ⚡ **Fully Adaptive**: Each stage independently evaluated based on your needs +- 🎯 **Efficient**: Simple changes execute only essential stages +- 📋 **Comprehensive**: Complex changes get full treatment with all safeguards +- 🔍 **Transparent**: You see and approve the execution plan before work begins +- 📝 **Documented**: Complete audit trail of all decisions and changes +- 🎛️ **User Control**: You can request stages be included or excluded + +## What Happens Next: + +1. **I'll analyze your workspace** to understand if this is a new or existing project +2. **I'll gather requirements** and ask clarifying questions if needed +3. **I'll create an execution plan** showing which stages I propose to run and why +4. **You'll review and approve** the plan (or request changes) +5. **We'll execute the plan** with checkpoints at each major stage +6. **You'll get working code** with complete documentation and tests + +The AI-DLC process adapts to: +- 📋 Your intent clarity and complexity +- 🔍 Existing codebase state +- 🎯 Scope and impact of changes +- ⚡ Risk and quality requirements + +Let's begin! diff --git a/aidlc/rule-details/common/workflow-changes.md b/aidlc/rule-details/common/workflow-changes.md new file mode 100644 index 0000000..cc7d33f --- /dev/null +++ b/aidlc/rule-details/common/workflow-changes.md @@ -0,0 +1,285 @@ +# Mid-Workflow Changes and Phase Management + +## Overview + +Users may request changes to the execution plan or phase execution during the workflow. This document provides guidance on handling these requests safely and effectively. + +--- + +## Types of Mid-Workflow Changes + +### 1. Adding a Skipped Phase + +**Scenario**: User wants to add a phase that was originally skipped + +**Example**: "Actually, I want to add user stories even though we skipped that stage" + +**Handling**: +1. **Confirm Request**: "You want to add User Stories stage. This will create user stories and personas. Confirm?" +2. **Check Dependencies**: Verify all prerequisite phases are complete +3. **Update Execution Plan**: Add phase to `execution-plan.md` with rationale +4. **Update State**: Mark phase as "PENDING" in `aidlc-state.md` +5. **Execute Phase**: Follow normal phase execution process +6. **Log Change**: Document in `audit.md` with timestamp and reason + +**Considerations**: +- May need to update later phases that could benefit from new artifacts +- Existing artifacts may need revision to incorporate new information +- Timeline will be extended + +--- + +### 2. Skipping a Planned Phase + +**Scenario**: User wants to skip a phase that was planned to execute + +**Example**: "Let's skip the NFR Design stage for now" + +**Handling**: +1. **Confirm Request**: "You want to skip NFR Design. This means no NFR patterns or logical components will be incorporated. Confirm?" +2. **Warn About Impact**: Explain what will be missing and potential consequences +3. **Get Explicit Confirmation**: User must explicitly confirm understanding of impact +4. **Update Execution Plan**: Mark phase as "SKIPPED" with reason +5. **Update State**: Mark phase as "SKIPPED" in `aidlc-state.md` +6. **Adjust Later Phases**: Note that later phases may need manual setup +7. **Log Change**: Document in `audit.md` with timestamp and reason + +**Considerations**: +- Later phases may fail or require manual intervention +- User accepts responsibility for missing artifacts +- Can be added back later if needed + +--- + +### 3. Restarting Current Stage + +**Scenario**: User is unhappy with current stage results and wants to redo it + +**Example**: "I don't like these user stories. Can we start over?" + +**Handling**: +1. **Understand Concern**: "What specifically would you like to change about the stories?" +2. **Offer Options**: + - **Option A**: Modify existing artifacts (faster, preserves some work) + - **Option B**: Complete restart (clean slate, more time) +3. **If Restart Chosen**: + - Archive existing artifacts: `{artifact}.backup.{timestamp}` + - Reset stage checkboxes in plan file + - Mark stage as "IN PROGRESS" in `aidlc-state.md` + - Clear stage completion status + - Re-execute from beginning +4. **Log Change**: Document reason for restart and what will change + +**Considerations**: +- Existing work will be lost (but backed up) +- May need to redo dependent stages +- Timeline will be extended + +--- + +### 4. Restarting Previous Stage + +**Scenario**: User wants to go back and redo a completed stage + +**Example**: "I want to change the architectural decision we made earlier" + +**Handling**: +1. **Assess Impact**: Identify all stages that depend on the stage to be restarted +2. **Warn User**: "Restarting Application Design will require redoing: Units Planning, Units Generation, per-unit design (all units), Code Planning, Code Generation. Confirm?" +3. **Get Explicit Confirmation**: User must understand full impact +4. **If Confirmed**: + - Archive all affected artifacts + - Reset all affected stages in `aidlc-state.md` + - Clear checkboxes in all affected plan files + - Return to the stage to restart + - Re-execute from that point forward +5. **Log Change**: Document full impact and reason for restart + +**Considerations**: +- Significant rework required +- All dependent stages must be redone +- Timeline will be significantly extended +- Consider if modification is better than restart + +--- + +### 5. Changing Stage Depth + +**Scenario**: User wants to change the depth level of current or upcoming stage + +**Example**: "Let's do a comprehensive requirements analysis instead of standard" + +**Handling**: +1. **Confirm Request**: "You want to change Requirements Analysis from Standard to Comprehensive depth. This will be more thorough but take longer. Confirm?" +2. **Update Execution Plan**: Change depth level in `workflow-planning.md` +3. **Adjust Approach**: Follow comprehensive depth guidelines for the stage +4. **Update Estimates**: Inform user of new timeline estimate +5. **Log Change**: Document depth change and reason + +**Considerations**: +- More depth = more time but better quality +- Less depth = faster but may miss details +- Can only change before or during stage, not after completion + +--- + +### 6. Pausing Workflow + +**Scenario**: User needs to pause and resume later + +**Example**: "I need to stop for now and continue tomorrow" + +**Handling**: +1. **Complete Current Step**: Finish the current step in progress if possible +2. **Update Checkboxes**: Mark all completed steps with [x] +3. **Update State**: Ensure `aidlc-state.md` reflects current status +4. **Log Pause**: Document pause point in `audit.md` +5. **Provide Resume Instructions**: "When you return, I'll detect your existing project and offer to continue from: [current phase, current step]" + +**On Resume**: +1. **Detect Existing Project**: Check for `aidlc-state.md` +2. **Load Context**: Read all artifacts from completed stages +3. **Show Status**: Display current stage and next step +4. **Offer Options**: Continue where left off or review previous work +5. **Log Resume**: Document resume point in `audit.md` + +--- + +### 7. Changing Architectural Decision + +**Scenario**: User wants to change from monolith to microservices (or vice versa) + +**Example**: "Actually, let's do microservices instead of a monolith" + +**Handling**: +1. **Assess Current Progress**: Determine how far into workflow +2. **Explain Impact**: + - If before Units Planning: Minimal impact, just update decision + - If after Units Planning: Must redo Units Planning, Units Generation, all per-unit design + - If after Code Generation: Significant rework required +3. **Recommend Approach**: + - Early in workflow: Restart from Application Design stage + - Late in workflow: Consider if modification is feasible vs. restart +4. **Get Confirmation**: User must understand full scope of change +5. **Execute Change**: Follow restart procedures for affected stages + +**Considerations**: +- Architectural changes have cascading effects +- Earlier in workflow = easier to change +- Later in workflow = consider cost vs. benefit + +--- + +### 8. Adding/Removing Units + +**Scenario**: User wants to add or remove units after Units Generation + +**Example**: "We need to split the Payment unit into Payment and Billing" + +**Handling**: +1. **Assess Impact**: Determine which units have completed design/code +2. **Explain Consequences**: + - Adding unit: Need to do full design and code for new unit + - Removing unit: Need to redistribute functionality to other units + - Splitting unit: Need to redo design and code for both resulting units +3. **Update Unit Artifacts**: + - Modify `unit-of-work.md` + - Update `unit-of-work-dependency.md` + - Revise `unit-of-work-story-map.md` +4. **Reset Affected Units**: Mark affected units as needing redesign +5. **Execute Changes**: Follow normal unit design and code process for affected units + +**Considerations**: +- Affects all downstream stages for those units +- May affect other units if dependencies change +- Timeline impact depends on how many units affected + +--- + +## General Guidelines for Handling Changes + +### Before Making Changes + +1. **Understand the Request**: Ask clarifying questions about what user wants to change and why +2. **Assess Impact**: Identify all affected stages, artifacts, and dependencies +3. **Explain Consequences**: Clearly communicate what will need to be redone and timeline impact +4. **Offer Alternatives**: Sometimes modification is better than restart +5. **Get Explicit Confirmation**: User must understand and accept the impact + +### During Changes + +1. **Archive Existing Work**: Always backup before making destructive changes +2. **Update All Tracking**: Keep `aidlc-state.md`, plan files, and `audit.md` in sync +3. **Communicate Progress**: Keep user informed about what's happening +4. **Validate Changes**: Ensure changes are consistent across all artifacts +5. **Test Continuity**: Verify workflow can continue smoothly after changes + +### After Changes + +1. **Verify Consistency**: Check that all artifacts are aligned with changes +2. **Update Documentation**: Ensure all references are updated +3. **Log Completely**: Document full change history in `audit.md` +4. **Confirm with User**: Verify changes meet user's expectations +5. **Resume Workflow**: Continue with normal execution from new state + +--- + +## Change Request Decision Tree + +``` +User requests change + | + ├─ Is it current phase? + | ├─ Yes: Can modify or restart current phase + | └─ No: Go to next question + | + ├─ Is it a completed phase? + | ├─ Yes: Assess impact on dependent phases + | | ├─ Low impact: Modify and update dependents + | | └─ High impact: Recommend restart from that phase + | └─ No: Go to next question + | + ├─ Is it adding a skipped phase? + | ├─ Yes: Check prerequisites, add to plan, execute + | └─ No: Go to next question + | + ├─ Is it skipping a planned phase? + | ├─ Yes: Warn about impact, get confirmation, skip + | └─ No: Go to next question + | + └─ Is it changing depth level? + ├─ Yes: Update plan, adjust approach + └─ No: Clarify request with user +``` + +--- + +## Logging Requirements + +### Change Request Log Format + +```markdown +## Change Request - [Phase Name] +**Timestamp**: [ISO timestamp] +**Request**: [What user wants to change] +**Current State**: [Where we are in workflow] +**Impact Assessment**: [What will be affected] +**User Confirmation**: [User's explicit confirmation] +**Action Taken**: [What was done] +**Artifacts Affected**: [List of files changed/reset] + +--- +``` + +--- + +## Best Practices + +1. **Always Confirm**: Never make destructive changes without explicit user confirmation +2. **Explain Impact**: Users need to understand consequences before deciding +3. **Offer Options**: Sometimes there are multiple ways to handle a change +4. **Archive First**: Always backup before making destructive changes +5. **Update Everything**: Keep all tracking files in sync +6. **Log Thoroughly**: Document all changes for audit trail +7. **Validate After**: Ensure workflow can continue smoothly +8. **Be Flexible**: Workflow should adapt to user needs, not force rigid process diff --git a/aidlc/rule-details/construction/build-and-test.md b/aidlc/rule-details/construction/build-and-test.md new file mode 100644 index 0000000..85f5951 --- /dev/null +++ b/aidlc/rule-details/construction/build-and-test.md @@ -0,0 +1,354 @@ +# Build and Test + +**Purpose**: Build all units and execute comprehensive testing strategy + +## Prerequisites +- Code Generation must be complete for all units +- All code artifacts must be generated +- Project is ready for build and testing + +--- + +## Step 1: Analyze Testing Requirements + +Analyze the project to determine appropriate testing strategy: +- **Unit tests**: Already generated per unit during code generation +- **Integration tests**: Test interactions between units/services +- **Performance tests**: Load, stress, and scalability testing +- **End-to-end tests**: Complete user workflows +- **Contract tests**: API contract validation between services +- **Security tests**: Vulnerability scanning, penetration testing + +--- + +## Step 2: Generate Build Instructions + +Create `aidlc-docs/construction/build-and-test/build-instructions.md`: + +```markdown +# Build Instructions + +## Prerequisites +- **Build Tool**: [Tool name and version] +- **Dependencies**: [List all required dependencies] +- **Environment Variables**: [List required env vars] +- **System Requirements**: [OS, memory, disk space] + +## Build Steps + +### 1. Install Dependencies +\`\`\`bash +[Command to install dependencies] +# Example: npm install, mvn dependency:resolve, pip install -r requirements.txt +\`\`\` + +### 2. Configure Environment +\`\`\`bash +[Commands to set up environment] +# Example: export variables, configure credentials +\`\`\` + +### 3. Build All Units +\`\`\`bash +[Command to build all units] +# Example: mvn clean install, npm run build, brazil-build +\`\`\` + +### 4. Verify Build Success +- **Expected Output**: [Describe successful build output] +- **Build Artifacts**: [List generated artifacts and locations] +- **Common Warnings**: [Note any acceptable warnings] + +## Troubleshooting + +### Build Fails with Dependency Errors +- **Cause**: [Common causes] +- **Solution**: [Step-by-step fix] + +### Build Fails with Compilation Errors +- **Cause**: [Common causes] +- **Solution**: [Step-by-step fix] +``` + +--- + +## Step 3: Generate Unit Test Execution Instructions + +Create `aidlc-docs/construction/build-and-test/unit-test-instructions.md`: + +```markdown +# Unit Test Execution + +## Run Unit Tests + +### 1. Execute All Unit Tests +\`\`\`bash +[Command to run all unit tests] +# Example: mvn test, npm test, pytest tests/unit +\`\`\` + +### 2. Review Test Results +- **Expected**: [X] tests pass, 0 failures +- **Test Coverage**: [Expected coverage percentage] +- **Test Report Location**: [Path to test reports] + +### 3. Fix Failing Tests +If tests fail: +1. Review test output in [location] +2. Identify failing test cases +3. Fix code issues +4. Rerun tests until all pass +``` + +--- + +## Step 4: Generate Integration Test Instructions + +Create `aidlc-docs/construction/build-and-test/integration-test-instructions.md`: + +```markdown +# Integration Test Instructions + +## Purpose +Test interactions between units/services to ensure they work together correctly. + +## Test Scenarios + +### Scenario 1: [Unit A] → [Unit B] Integration +- **Description**: [What is being tested] +- **Setup**: [Required test environment setup] +- **Test Steps**: [Step-by-step test execution] +- **Expected Results**: [What should happen] +- **Cleanup**: [How to clean up after test] + +### Scenario 2: [Unit B] → [Unit C] Integration +[Similar structure] + +## Setup Integration Test Environment + +### 1. Start Required Services +\`\`\`bash +[Commands to start services] +# Example: docker-compose up, start test database +\`\`\` + +### 2. Configure Service Endpoints +\`\`\`bash +[Commands to configure endpoints] +# Example: export API_URL=http://localhost:8080 +\`\`\` + +## Run Integration Tests + +### 1. Execute Integration Test Suite +\`\`\`bash +[Command to run integration tests] +# Example: mvn integration-test, npm run test:integration +\`\`\` + +### 2. Verify Service Interactions +- **Test Scenarios**: [List key integration test scenarios] +- **Expected Results**: [Describe expected outcomes] +- **Logs Location**: [Where to check logs] + +### 3. Cleanup +\`\`\`bash +[Commands to clean up test environment] +# Example: docker-compose down, stop test services +\`\`\` +``` + +--- + +## Step 5: Generate Performance Test Instructions (If Applicable) + +Create `aidlc-docs/construction/build-and-test/performance-test-instructions.md`: + +```markdown +# Performance Test Instructions + +## Purpose +Validate system performance under load to ensure it meets requirements. + +## Performance Requirements +- **Response Time**: < [X]ms for [Y]% of requests +- **Throughput**: [X] requests/second +- **Concurrent Users**: Support [X] concurrent users +- **Error Rate**: < [X]% + +## Setup Performance Test Environment + +### 1. Prepare Test Environment +\`\`\`bash +[Commands to set up performance testing] +# Example: scale services, configure load balancers +\`\`\` + +### 2. Configure Test Parameters +- **Test Duration**: [X] minutes +- **Ramp-up Time**: [X] seconds +- **Virtual Users**: [X] users + +## Run Performance Tests + +### 1. Execute Load Tests +\`\`\`bash +[Command to run load tests] +# Example: jmeter -n -t test.jmx, k6 run script.js +\`\`\` + +### 2. Execute Stress Tests +\`\`\`bash +[Command to run stress tests] +# Example: gradually increase load until failure +\`\`\` + +### 3. Analyze Performance Results +- **Response Time**: [Actual vs Expected] +- **Throughput**: [Actual vs Expected] +- **Error Rate**: [Actual vs Expected] +- **Bottlenecks**: [Identified bottlenecks] +- **Results Location**: [Path to performance reports] + +## Performance Optimization + +If performance doesn't meet requirements: +1. Identify bottlenecks from test results +2. Optimize code/queries/configurations +3. Rerun tests to validate improvements +``` + +--- + +## Step 6: Generate Additional Test Instructions (As Needed) + +Based on project requirements, generate additional test instruction files: + +### Contract Tests (For Microservices) +Create `aidlc-docs/construction/build-and-test/contract-test-instructions.md`: +- API contract validation between services +- Consumer-driven contract testing +- Schema validation + +### Security Tests +Create `aidlc-docs/construction/build-and-test/security-test-instructions.md`: +- Vulnerability scanning +- Dependency security checks +- Authentication/authorization testing +- Input validation testing + +### End-to-End Tests +Create `aidlc-docs/construction/build-and-test/e2e-test-instructions.md`: +- Complete user workflow testing +- Cross-service scenarios +- UI testing (if applicable) + +--- + +## Step 7: Generate Test Summary + +Create `aidlc-docs/construction/build-and-test/build-and-test-summary.md`: + +```markdown +# Build and Test Summary + +## Build Status +- **Build Tool**: [Tool name] +- **Build Status**: [Success/Failed] +- **Build Artifacts**: [List artifacts] +- **Build Time**: [Duration] + +## Test Execution Summary + +### Unit Tests +- **Total Tests**: [X] +- **Passed**: [X] +- **Failed**: [X] +- **Coverage**: [X]% +- **Status**: [Pass/Fail] + +### Integration Tests +- **Test Scenarios**: [X] +- **Passed**: [X] +- **Failed**: [X] +- **Status**: [Pass/Fail] + +### Performance Tests +- **Response Time**: [Actual] (Target: [Expected]) +- **Throughput**: [Actual] (Target: [Expected]) +- **Error Rate**: [Actual] (Target: [Expected]) +- **Status**: [Pass/Fail] + +### Additional Tests +- **Contract Tests**: [Pass/Fail/N/A] +- **Security Tests**: [Pass/Fail/N/A] +- **E2E Tests**: [Pass/Fail/N/A] + +## Overall Status +- **Build**: [Success/Failed] +- **All Tests**: [Pass/Fail] +- **Ready for Operations**: [Yes/No] + +## Next Steps +[If all pass]: Ready to proceed to Operations phase for deployment planning +[If failures]: Address failing tests and rebuild +``` + +--- + +## Step 8: Update State Tracking + +Update `aidlc-docs/aidlc-state.md`: +- Mark Build and Test stage as complete +- Update current status + +--- + +## Step 9: Present Results to User + +Present comprehensive message: + +``` +"🔨 Build and Test Complete! + +**Build Status**: [Success/Failed] + +**Test Results**: +✅ Unit Tests: [X] passed +✅ Integration Tests: [X] scenarios passed +✅ Performance Tests: [Status] +✅ Additional Tests: [Status] + +**Generated Files**: +1. ✅ build-instructions.md +2. ✅ unit-test-instructions.md +3. ✅ integration-test-instructions.md +4. ✅ performance-test-instructions.md (if applicable) +5. ✅ [additional test files as needed] +6. ✅ build-and-test-summary.md + +Review the summary in aidlc-docs/construction/build-and-test/build-and-test-summary.md + +**Ready to proceed to Operations stage for deployment planning?"" +``` + +--- + +## Step 10: Log Interaction + +**MANDATORY**: Log the phase completion in `aidlc-docs/audit.md`: + +```markdown +## Build and Test Stage +**Timestamp**: [ISO timestamp] +**Build Status**: [Success/Failed] +**Test Status**: [Pass/Fail] +**Files Generated**: +- build-instructions.md +- unit-test-instructions.md +- integration-test-instructions.md +- performance-test-instructions.md +- build-and-test-summary.md + +--- +``` diff --git a/aidlc/rule-details/construction/code-generation.md b/aidlc/rule-details/construction/code-generation.md new file mode 100644 index 0000000..36bbe23 --- /dev/null +++ b/aidlc/rule-details/construction/code-generation.md @@ -0,0 +1,207 @@ +# Code Generation - Detailed Steps + +## Overview +This stage generates code for each unit of work through two integrated parts: +- **Part 1 - Planning**: Create detailed code generation plan with explicit steps +- **Part 2 - Generation**: Execute approved plan to generate code, tests, and artifacts + +**Note**: For brownfield projects, "generate" means modify existing files when appropriate, not create duplicates. + +## Prerequisites +- Unit Design Generation must be complete for the unit +- NFR Implementation (if executed) must be complete for the unit +- All unit design artifacts must be available +- Unit is ready for code generation + +--- + +# PART 1: PLANNING + +## Step 1: Analyze Unit Context +- [ ] Read unit design artifacts from Unit Design Generation +- [ ] Read unit story map to understand assigned stories +- [ ] Identify unit dependencies and interfaces +- [ ] Validate unit is ready for code generation + +## Step 2: Create Detailed Unit Code Generation Plan +- [ ] Read workspace root and project type from `aidlc-docs/aidlc-state.md` +- [ ] Determine code location (see Critical Rules for structure patterns) +- [ ] **Brownfield only**: Review reverse engineering code-structure.md for existing files to modify +- [ ] Document exact paths (never aidlc-docs/) +- [ ] Create explicit steps for unit generation: + - Project Structure Setup (greenfield only) + - Business Logic Generation + - Business Logic Unit Testing + - Business Logic Summary + - API Layer Generation + - API Layer Unit Testing + - API Layer Summary + - Repository Layer Generation + - Repository Layer Unit Testing + - Repository Layer Summary + - Database Migration Scripts (if data models exist) + - Documentation Generation (API docs, README updates) + - Deployment Artifacts Generation +- [ ] Number each step sequentially +- [ ] Include story mapping references +- [ ] Add checkboxes [ ] for each step + +## Step 3: Include Unit Generation Context +- [ ] For this unit, include: + - Stories implemented by this unit + - Dependencies on other units/services + - Expected interfaces and contracts + - Database entities owned by this unit + - Service boundaries and responsibilities + +## Step 4: Create Unit Plan Document +- [ ] Save complete plan as `aidlc-docs/construction/plans/{unit-name}-code-generation-plan.md` +- [ ] Include step numbering (Step 1, Step 2, etc.) +- [ ] Include unit context and dependencies +- [ ] Include story traceability +- [ ] Ensure plan is executable step-by-step +- [ ] Emphasize that this plan is the single source of truth for Code Generation + +## Step 5: Summarize Unit Plan +- [ ] Provide summary of the unit code generation plan to the user +- [ ] Highlight unit generation approach +- [ ] Explain step sequence and story coverage +- [ ] Note total number of steps and estimated scope + +## Step 6: Log Approval Prompt +- [ ] Before asking for approval, log the prompt with timestamp in `aidlc-docs/audit.md` +- [ ] Include reference to the complete unit code generation plan +- [ ] Use ISO 8601 timestamp format + +## Step 7: Wait for Explicit Approval +- [ ] Do not proceed until the user explicitly approves the unit code generation plan +- [ ] Approval must cover the entire plan and generation sequence +- [ ] If user requests changes, update the plan and repeat approval process + +## Step 8: Record Approval Response +- [ ] Log the user's approval response with timestamp in `aidlc-docs/audit.md` +- [ ] Include the exact user response text +- [ ] Mark the approval status clearly + +## Step 9: Update Progress +- [ ] Mark Code Planning complete in `aidlc-state.md` +- [ ] Update the "Current Status" section +- [ ] Prepare for transition to Code Generation + +--- + +# PART 2: GENERATION + +## Step 10: Load Unit Code Generation Plan +- [ ] Read the complete plan from `aidlc-docs/construction/plans/{unit-name}-code-generation-plan.md` +- [ ] Identify the next uncompleted step (first [ ] checkbox) +- [ ] Load the context for that step (unit, dependencies, stories) + +## Step 11: Execute Current Step +- [ ] Verify target directory from plan (never aidlc-docs/) +- [ ] **Brownfield only**: Check if target file exists +- [ ] Generate exactly what the current step describes: + - **If file exists**: Modify it in-place (never create `ClassName_modified.java`, `ClassName_new.java`, etc.) + - **If file doesn't exist**: Create new file +- [ ] Write to correct locations: + - **Application Code**: Workspace root per project structure + - **Documentation**: `aidlc-docs/construction/{unit-name}/code/` (markdown only) + - **Build/Config Files**: Workspace root +- [ ] Follow unit story requirements +- [ ] Respect dependencies and interfaces + +## Step 12: Update Progress +- [ ] Mark the completed step as [x] in the unit code generation plan +- [ ] Mark associated unit stories as [x] when their generation is finished +- [ ] Update `aidlc-docs/aidlc-state.md` current status +- [ ] **Brownfield only**: Verify no duplicate files created (e.g., no `ClassName_modified.java` alongside `ClassName.java`) +- [ ] Save all generated artifacts + +## Step 13: Continue or Complete Generation +- [ ] If more steps remain, return to Step 10 +- [ ] If all steps complete, proceed to present completion message + +## Step 14: Present Completion Message +- Present completion message in this structure: + 1. **Completion Announcement** (mandatory): Always start with this: + +```markdown +# 💻 Code Generation Complete - [unit-name] +``` + + 2. **AI Summary** (optional): Provide structured bullet-point summary + - **Brownfield**: Distinguish modified vs created files (e.g., "• Modified: `src/services/user-service.ts`", "• Created: `src/services/auth-service.ts`") + - **Greenfield**: List created files with paths (e.g., "• Created: `src/services/user-service.ts`") + - List tests, documentation, deployment artifacts with paths + - Keep factual, no workflow instructions + 3. **Formatted Workflow Message** (mandatory): Always end with this exact format: + +```markdown +> **📋 **REVIEW REQUIRED:**** +> Please examine the generated code at: +> - **Application Code**: `[actual-workspace-path]` +> - **Documentation**: `aidlc-docs/construction/[unit-name]/code/` + + + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the generated code based on your review +> ✅ **Continue to Next Stage** - Approve code generation and proceed to **[next-unit/Build & Test]** + +--- +``` + +## Step 15: Wait for Explicit Approval +- Do not proceed until the user explicitly approves the generated code +- Approval must be clear and unambiguous +- If user requests changes, update the code and repeat the approval process + +## Step 16: Record Approval and Update Progress +- Log approval in audit.md with timestamp +- Record the user's approval response with timestamp +- Mark Code Generation stage as complete for this unit in aidlc-state.md + +--- + +## Critical Rules + +### Code Location Rules +- **Application code**: Workspace root only (NEVER aidlc-docs/) +- **Documentation**: aidlc-docs/ only (markdown summaries) +- **Read workspace root** from aidlc-state.md before generating code + +**Structure patterns by project type**: +- **Brownfield**: Use existing structure (e.g., `src/main/java/`, `lib/`, `pkg/`) +- **Greenfield single unit**: `src/`, `tests/`, `config/` in workspace root +- **Greenfield multi-unit (microservices)**: `{unit-name}/src/`, `{unit-name}/tests/` +- **Greenfield multi-unit (monolith)**: `src/{unit-name}/`, `tests/{unit-name}/` + +### Brownfield File Modification Rules +- Check if file exists before generating +- If exists: Modify in-place (never create copies like `ClassName_modified.java`) +- If doesn't exist: Create new file +- Verify no duplicate files after generation (Step 12) + +### Planning Phase Rules +- Create explicit, numbered steps for all generation activities +- Include story traceability in the plan +- Document unit context and dependencies +- Get explicit user approval before generation + +### Generation Phase Rules +- **NO HARDCODED LOGIC**: Only execute what's written in the unit plan +- **FOLLOW PLAN EXACTLY**: Do not deviate from the step sequence +- **UPDATE CHECKBOXES**: Mark [x] immediately after completing each step +- **STORY TRACEABILITY**: Mark unit stories [x] when functionality is implemented +- **RESPECT DEPENDENCIES**: Only implement when unit dependencies are satisfied + +## Completion Criteria +- Complete unit code generation plan created and approved +- All steps in unit code generation plan marked [x] +- All unit stories implemented according to plan +- All code and tests generated (tests will be executed in Build & Test phase) +- Deployment artifacts generated +- Complete unit ready for build and verification diff --git a/aidlc/rule-details/construction/functional-design.md b/aidlc/rule-details/construction/functional-design.md new file mode 100644 index 0000000..18b997c --- /dev/null +++ b/aidlc/rule-details/construction/functional-design.md @@ -0,0 +1,112 @@ +# Functional Design + +## Purpose +**Detailed business logic design per unit** + +Functional Design focuses on: +- Detailed business logic and algorithms for the unit +- Domain models with entities and relationships +- Detailed business rules, validation logic, and constraints +- Technology-agnostic design (no infrastructure concerns) + +**Note**: This builds upon high-level component design from Application Design (INCEPTION phase) + +## Prerequisites +- Units Generation must be complete +- Unit of work artifacts must be available +- Application Design recommended (provides high-level component structure) +- Execution plan must indicate Functional Design stage should execute + +## Overview +Design detailed business logic for the unit, technology-agnostic and focused purely on business functions. + +## Steps to Execute + +### Step 1: Analyze Unit Context +- Read unit definition from `aidlc-docs/inception/application-design/unit-of-work.md` +- Read assigned stories from `aidlc-docs/inception/application-design/unit-of-work-story-map.md` +- Understand unit responsibilities and boundaries + +### Step 2: Create Functional Design Plan +- Generate plan with checkboxes [] for functional design +- Focus on business logic, domain models, business rules +- Each step should have a checkbox [] + +### Step 3: Generate Context-Appropriate Questions +**DIRECTIVE**: Thoroughly analyze the unit definition and functional design artifacts to identify ALL areas where clarification would improve the functional design. Be proactive in asking questions to ensure comprehensive understanding. + +**CRITICAL**: Default to asking questions when there is ANY ambiguity or missing detail that could affect functional design quality. It's better to ask too many questions than to make incorrect assumptions. + +- EMBED questions using [Answer]: tag format +- Focus on ANY ambiguities, missing information, or areas needing clarification +- Generate questions wherever user input would improve functional design decisions +- **When in doubt, ask the question** - overconfidence leads to poor designs + +**Question categories to consider** (evaluate ALL categories): +- **Business Logic Modeling** - Ask about core entities, workflows, data transformations, and business processes +- **Domain Model** - Ask about domain concepts, entity relationships, data structures, and business objects +- **Business Rules** - Ask about decision rules, validation logic, constraints, and business policies +- **Data Flow** - Ask about data inputs, outputs, transformations, and persistence requirements +- **Integration Points** - Ask about external system interactions, APIs, and data exchange +- **Error Handling** - Ask about error scenarios, validation failures, and exception handling +- **Business Scenarios** - Ask about edge cases, alternative flows, and complex business situations + +### Step 4: Store Plan +- Save as `aidlc-docs/construction/plans/{unit-name}-functional-design-plan.md` +- Include all [Answer]: tags for user input + +### Step 5: Collect and Analyze Answers +- Wait for user to complete all [Answer]: tags +- **MANDATORY**: Carefully review ALL responses for vague or ambiguous answers +- **CRITICAL**: Add follow-up questions for ANY unclear responses - do not proceed with ambiguity +- Look for responses like "depends", "maybe", "not sure", "mix of", "somewhere between" +- Create clarification questions file if ANY ambiguities are detected +- **Do not proceed until ALL ambiguities are resolved** + +### Step 6: Generate Functional Design Artifacts +- Create `aidlc-docs/construction/{unit-name}/functional-design/business-logic-model.md` +- Create `aidlc-docs/construction/{unit-name}/functional-design/business-rules.md` +- Create `aidlc-docs/construction/{unit-name}/functional-design/domain-entities.md` + +### Step 7: Present Completion Message +- Present completion message in this structure: + 1. **Completion Announcement** (mandatory): Always start with this: + +```markdown +# 🔧 Functional Design Complete - [unit-name] +``` + + 2. **AI Summary** (optional): Provide structured bullet-point summary of functional design + - Format: "Functional design has created [description]:" + - List key business logic models and entities (bullet points) + - List business rules and validation logic defined + - Mention domain model structure and relationships + - DO NOT include workflow instructions ("please review", "let me know", "proceed to next phase", "before we proceed") + - Keep factual and content-focused + 3. **Formatted Workflow Message** (mandatory): Always end with this exact format: + +```markdown +> **📋 **REVIEW REQUIRED:**** +> Please examine the functional design artifacts at: `aidlc-docs/construction/[unit-name]/functional-design/` + + + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the functional design based on your review +> ✅ **Continue to Next Stage** - Approve functional design and proceed to **[next-stage-name]** + +--- +``` + +### Step 8: Wait for Explicit Approval +- Do not proceed until the user explicitly approves the functional design +- Approval must be clear and unambiguous +- If user requests changes, update the design and repeat the approval process + +### Step 9: Record Approval and Update Progress +- Log approval in audit.md with timestamp +- Record the user's approval response with timestamp +- Mark Functional Design stage complete in aidlc-state.md diff --git a/aidlc/rule-details/construction/infrastructure-design.md b/aidlc/rule-details/construction/infrastructure-design.md new file mode 100644 index 0000000..8ff9b27 --- /dev/null +++ b/aidlc/rule-details/construction/infrastructure-design.md @@ -0,0 +1,94 @@ +# Infrastructure Design + +## Prerequisites +- Functional Design must be complete for the unit +- NFR Design recommended (provides logical components to map) +- Execution plan must indicate Infrastructure Design stage should execute + +## Overview +Map logical software components to actual infrastructure choices for deployment environments. + +## Steps to Execute + +### Step 1: Analyze Design Artifacts +- Read functional design from `aidlc-docs/construction/{unit-name}/functional-design/` +- Read NFR design from `aidlc-docs/construction/{unit-name}/nfr-design/` (if exists) +- Identify logical components needing infrastructure + +### Step 2: Create Infrastructure Design Plan +- Generate plan with checkboxes [] for infrastructure design +- Focus on mapping to actual services (AWS, Azure, GCP, on-premise) +- Each step should have a checkbox [] + +### Step 3: Generate Context-Appropriate Questions +**DIRECTIVE**: Analyze the functional and NFR design to generate ONLY questions relevant to THIS specific unit's infrastructure needs. Use the categories below as inspiration, NOT as a mandatory checklist. Skip entire categories if not applicable. + +- EMBED questions using [Answer]: tag format +- Focus on ambiguities and missing information specific to this unit +- Generate questions only where user input is needed for infrastructure decisions + +**Example question categories** (adapt as needed): +- **Deployment Environment** - Only if cloud provider or environment setup is unclear +- **Compute Infrastructure** - Only if compute service choice needs clarification +- **Storage Infrastructure** - Only if database or storage selection is ambiguous +- **Messaging Infrastructure** - Only if messaging/queuing services need specification +- **Networking Infrastructure** - Only if load balancing or API gateway approach is unclear +- **Monitoring Infrastructure** - Only if observability tooling needs clarification +- **Shared Infrastructure** - Only if infrastructure sharing strategy is ambiguous + +### Step 4: Store Plan +- Save as `aidlc-docs/construction/plans/{unit-name}-infrastructure-design-plan.md` +- Include all [Answer]: tags for user input + +### Step 5: Collect and Analyze Answers +- Wait for user to complete all [Answer]: tags +- Review for vague or ambiguous responses +- Add follow-up questions if needed + +### Step 6: Generate Infrastructure Design Artifacts +- Create `aidlc-docs/construction/{unit-name}/infrastructure-design/infrastructure-design.md` +- Create `aidlc-docs/construction/{unit-name}/infrastructure-design/deployment-architecture.md` +- If shared infrastructure: Create `aidlc-docs/construction/shared-infrastructure.md` + +### Step 7: Present Completion Message +- Present completion message in this structure: + 1. **Completion Announcement** (mandatory): Always start with this: + +```markdown +# 🏢 Infrastructure Design Complete - [unit-name] +``` + + 2. **AI Summary** (optional): Provide structured bullet-point summary of infrastructure design + - Format: "Infrastructure design has mapped [description]:" + - List key infrastructure services and components (bullet points) + - List deployment architecture decisions and rationale + - Mention cloud provider choices and service mappings + - DO NOT include workflow instructions ("please review", "let me know", "proceed to next phase", "before we proceed") + - Keep factual and content-focused + 3. **Formatted Workflow Message** (mandatory): Always end with this exact format: + +```markdown +> **📋 **REVIEW REQUIRED:**** +> Please examine the infrastructure design at: `aidlc-docs/construction/[unit-name]/infrastructure-design/` + + + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the infrastructure design based on your review +> ✅ **Continue to Next Stage** - Approve infrastructure design and proceed to **Code Generation** + +--- +``` + +### Step 8: Wait for Explicit Approval +- Do not proceed until the user explicitly approves the infrastructure design +- Approval must be clear and unambiguous +- If user requests changes, update the design and repeat the approval process + +### Step 9: Record Approval and Update Progress +- Log approval in audit.md with timestamp +- Record the user's approval response with timestamp +- Mark Infrastructure Design stage complete in aidlc-state.md diff --git a/aidlc/rule-details/construction/nfr-design.md b/aidlc/rule-details/construction/nfr-design.md new file mode 100644 index 0000000..92b950b --- /dev/null +++ b/aidlc/rule-details/construction/nfr-design.md @@ -0,0 +1,90 @@ +# NFR Design + +## Prerequisites +- NFR Requirements must be complete for the unit +- NFR requirements artifacts must be available +- Execution plan must indicate NFR Design stage should execute + +## Overview +Incorporate NFR requirements into unit design using patterns and logical components. + +## Steps to Execute + +### Step 1: Analyze NFR Requirements +- Read NFR requirements from `aidlc-docs/construction/{unit-name}/nfr-requirements/` +- Understand scalability, performance, availability, security needs + +### Step 2: Create NFR Design Plan +- Generate plan with checkboxes [] for NFR design +- Focus on design patterns and logical components +- Each step should have a checkbox [] + +### Step 3: Generate Context-Appropriate Questions +**DIRECTIVE**: Analyze the NFR requirements to generate ONLY questions relevant to THIS specific unit's NFR design. Use the categories below as inspiration, NOT as a mandatory checklist. Skip entire categories if not applicable. + +- EMBED questions using [Answer]: tag format +- Focus on ambiguities and missing information specific to this unit +- Generate questions only where user input is needed for pattern and component decisions + +**Example question categories** (adapt as needed): +- **Resilience Patterns** - Only if fault tolerance approach needs clarification +- **Scalability Patterns** - Only if scaling mechanisms are unclear +- **Performance Patterns** - Only if performance optimization strategy is ambiguous +- **Security Patterns** - Only if security implementation approach needs input +- **Logical Components** - Only if infrastructure components (queues, caches, etc.) need clarification + +### Step 4: Store Plan +- Save as `aidlc-docs/construction/plans/{unit-name}-nfr-design-plan.md` +- Include all [Answer]: tags for user input + +### Step 5: Collect and Analyze Answers +- Wait for user to complete all [Answer]: tags +- Review for vague or ambiguous responses +- Add follow-up questions if needed + +### Step 6: Generate NFR Design Artifacts +- Create `aidlc-docs/construction/{unit-name}/nfr-design/nfr-design-patterns.md` +- Create `aidlc-docs/construction/{unit-name}/nfr-design/logical-components.md` + +### Step 7: Present Completion Message +- Present completion message in this structure: + 1. **Completion Announcement** (mandatory): Always start with this: + +```markdown +# 🎨 NFR Design Complete - [unit-name] +``` + + 2. **AI Summary** (optional): Provide structured bullet-point summary of NFR design + - Format: "NFR design has incorporated [description]:" + - List key design patterns implemented (bullet points) + - List logical components and infrastructure elements + - Mention resilience, scalability, and performance patterns applied + - DO NOT include workflow instructions ("please review", "let me know", "proceed to next phase", "before we proceed") + - Keep factual and content-focused + 3. **Formatted Workflow Message** (mandatory): Always end with this exact format: + +```markdown +> **📋 **REVIEW REQUIRED:**** +> Please examine the NFR design at: `aidlc-docs/construction/[unit-name]/nfr-design/` + + + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the NFR design based on your review +> ✅ **Continue to Next Stage** - Approve NFR design and proceed to **[next-stage-name]** + +--- +``` + +### Step 8: Wait for Explicit Approval +- Do not proceed until the user explicitly approves the NFR design +- Approval must be clear and unambiguous +- If user requests changes, update the design and repeat the approval process + +### Step 9: Record Approval and Update Progress +- Log approval in audit.md with timestamp +- Record the user's approval response with timestamp +- Mark NFR Design stage complete in aidlc-state.md diff --git a/aidlc/rule-details/construction/nfr-requirements.md b/aidlc/rule-details/construction/nfr-requirements.md new file mode 100644 index 0000000..3bd3310 --- /dev/null +++ b/aidlc/rule-details/construction/nfr-requirements.md @@ -0,0 +1,99 @@ +# NFR Requirements + +## Prerequisites +- Functional Design must be complete for the unit +- Unit functional design artifacts must be available +- Execution plan must indicate NFR Requirements stage should execute + +## Overview +Determine non-functional requirements for the unit and make tech stack choices. + +## Steps to Execute + +### Step 1: Analyze Functional Design +- Read functional design artifacts from `aidlc-docs/construction/{unit-name}/functional-design/` +- Understand business logic complexity and requirements + +### Step 2: Create NFR Requirements Plan +- Generate plan with checkboxes [] for NFR assessment +- Focus on scalability, performance, availability, security +- Each step should have a checkbox [] + +### Step 3: Generate Context-Appropriate Questions +**DIRECTIVE**: Thoroughly analyze the functional design to identify ALL areas where NFR clarification would improve system quality and architecture decisions. Be proactive in asking questions to ensure comprehensive NFR coverage. + +**CRITICAL**: Default to asking questions when there is ANY ambiguity or missing detail that could affect system quality. It's better to ask too many questions than to make incorrect NFR assumptions. + +- EMBED questions using [Answer]: tag format +- Focus on ANY ambiguities, missing information, or areas needing clarification +- Generate questions wherever user input would improve NFR and tech stack decisions +- **When in doubt, ask the question** - overconfidence leads to poor system quality + +**Question categories to evaluate** (consider ALL categories): +- **Scalability Requirements** - Ask about expected load, growth patterns, scaling triggers, and capacity planning +- **Performance Requirements** - Ask about response times, throughput, latency, and performance benchmarks +- **Availability Requirements** - Ask about uptime expectations, disaster recovery, failover, and business continuity +- **Security Requirements** - Ask about data protection, compliance, authentication, authorization, and threat models +- **Tech Stack Selection** - Ask about technology preferences, constraints, existing systems, and integration requirements +- **Reliability Requirements** - Ask about error handling, fault tolerance, monitoring, and alerting needs +- **Maintainability Requirements** - Ask about code quality, documentation, testing, and operational requirements +- **Usability Requirements** - Ask about user experience, accessibility, and interface requirements + +### Step 4: Store Plan +- Save as `aidlc-docs/construction/plans/{unit-name}-nfr-requirements-plan.md` +- Include all [Answer]: tags for user input + +### Step 5: Collect and Analyze Answers +- Wait for user to complete all [Answer]: tags +- **MANDATORY**: Carefully review ALL responses for vague or ambiguous answers +- **CRITICAL**: Add follow-up questions for ANY unclear responses - do not proceed with ambiguity +- Look for responses like "depends", "maybe", "not sure", "mix of", "somewhere between", "standard", "typical" +- Create clarification questions file if ANY ambiguities are detected +- **Do not proceed until ALL ambiguities are resolved** + +### Step 6: Generate NFR Requirements Artifacts +- Create `aidlc-docs/construction/{unit-name}/nfr-requirements/nfr-requirements.md` +- Create `aidlc-docs/construction/{unit-name}/nfr-requirements/tech-stack-decisions.md` + +### Step 7: Present Completion Message +- Present completion message in this structure: + 1. **Completion Announcement** (mandatory): Always start with this: + +```markdown +# 📊 NFR Requirements Complete - [unit-name] +``` + + 2. **AI Summary** (optional): Provide structured bullet-point summary of NFR requirements + - Format: "NFR requirements assessment has identified [description]:" + - List key scalability, performance, availability requirements (bullet points) + - List security and compliance requirements identified + - Mention tech stack decisions and rationale + - DO NOT include workflow instructions ("please review", "let me know", "proceed to next phase", "before we proceed") + - Keep factual and content-focused + 3. **Formatted Workflow Message** (mandatory): Always end with this exact format: + +```markdown +> **📋 **REVIEW REQUIRED:**** +> Please examine the NFR requirements at: `aidlc-docs/construction/[unit-name]/nfr-requirements/` + + + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the NFR requirements based on your review +> ✅ **Continue to Next Stage** - Approve NFR requirements and proceed to **[next-stage-name]** + +--- +``` + +### Step 8: Wait for Explicit Approval +- Do not proceed until the user explicitly approves the NFR requirements +- Approval must be clear and unambiguous +- If user requests changes, update the requirements and repeat the approval process + +### Step 9: Record Approval and Update Progress +- Log approval in audit.md with timestamp +- Record the user's approval response with timestamp +- Mark NFR Requirements stage complete in aidlc-state.md diff --git a/aidlc/rule-details/inception/application-design.md b/aidlc/rule-details/inception/application-design.md new file mode 100644 index 0000000..9ad90f6 --- /dev/null +++ b/aidlc/rule-details/inception/application-design.md @@ -0,0 +1,145 @@ +# Application Design - Detailed Steps + +## Purpose +**High-level component identification and service layer design** + +Application Design focuses on: +- Identifying main functional components and their responsibilities +- Defining component interfaces (not detailed business logic) +- Designing service layer for orchestration +- Establishing component dependencies and communication patterns + +**Note**: Detailed business logic design happens later in Functional Design (per-unit, CONSTRUCTION phase) + +## Prerequisites +- Context Assessment must be complete +- Requirements Assessment recommended (provides functional context) +- Story Development recommended (user stories guide design decisions) +- Execution plan must indicate Application Design stage should execute + +## Step-by-Step Execution + +### 1. Analyze Context +- Read `aidlc-docs/inception/requirements/requirements.md` and `aidlc-docs/inception/user-stories/stories.md` +- Identify key business capabilities and functional areas +- Determine design scope and complexity + +### 2. Create Application Design Plan +- Generate plan with checkboxes [] for application design +- Focus on components, responsibilities, methods, business rules, and services +- Each step and sub-step should have a checkbox [] + +### 3. Include Mandatory Design Artifacts in Plan +- **ALWAYS** include these mandatory artifacts in the design plan: + - [ ] Generate components.md with component definitions and high-level responsibilities + - [ ] Generate component-methods.md with method signatures (business rules detailed later in Functional Design) + - [ ] Generate services.md with service definitions and orchestration patterns + - [ ] Generate component-dependency.md with dependency relationships and communication patterns + - [ ] Validate design completeness and consistency + +### 4. Generate Context-Appropriate Questions +**DIRECTIVE**: Analyze the requirements and stories to generate ONLY questions relevant to THIS specific application design. Use the categories below as inspiration, NOT as a mandatory checklist. Skip entire categories if not applicable. + +- EMBED questions using [Answer]: tag format +- Focus on ambiguities and missing information specific to this context +- Generate questions only where user input is needed for design decisions + +**Example question categories** (adapt as needed): +- **Component Identification** - Only if component boundaries or organization is unclear +- **Component Methods** - Only if method signatures need clarification (detailed business rules come later) +- **Service Layer Design** - Only if service orchestration or boundaries are ambiguous +- **Component Dependencies** - Only if communication patterns or dependency management is unclear +- **Design Patterns** - Only if architectural style or pattern choice needs user input + +### 5. Store Application Design Plan +- Save as `aidlc-docs/inception/plans/application-design-plan.md` +- Include all [Answer]: tags for user input +- Ensure plan covers all design aspects + +### 6. Request User Input +- Ask user to fill [Answer]: tags directly in the plan document +- Emphasize importance of design decisions +- Provide clear instructions on completing the [Answer]: tags + +### 7. Collect Answers +- Wait for user to provide answers to all questions using [Answer]: tags in the document +- Do not proceed until ALL [Answer]: tags are completed +- Review the document to ensure no [Answer]: tags are left blank + +### 8. ANALYZE ANSWERS (MANDATORY) +Before proceeding, you MUST carefully review all user answers for: +- **Vague or ambiguous responses**: "mix of", "somewhere between", "not sure", "depends" +- **Undefined criteria or terms**: References to concepts without clear definitions +- **Contradictory answers**: Responses that conflict with each other +- **Missing design details**: Answers that lack specific guidance +- **Answers that combine options**: Responses that merge different approaches without clear decision rules + +### 9. MANDATORY Follow-up Questions +If the analysis in step 8 reveals ANY ambiguous answers, you MUST: +- Add specific follow-up questions to the plan document using [Answer]: tags +- DO NOT proceed to approval until all ambiguities are resolved +- Examples of required follow-ups: + - "You mentioned 'mix of A and B' - what specific criteria should determine when to use A vs B?" + - "You said 'somewhere between A and B' - can you define the exact middle ground approach?" + - "You indicated 'not sure' - what additional information would help you decide?" + - "You mentioned 'depends on complexity' - how do you define complexity levels?" + +### 10. Generate Application Design Artifacts +- Execute the approved plan to generate design artifacts +- Create `aidlc-docs/inception/application-design/components.md` with: + - Component name and purpose + - Component responsibilities + - Component interfaces +- Create `aidlc-docs/inception/application-design/component-methods.md` with: + - Method signatures for each component + - High-level purpose of each method + - Input/output types + - Note: Detailed business rules will be defined in Functional Design (per-unit, CONSTRUCTION phase) +- Create `aidlc-docs/inception/application-design/services.md` with: + - Service definitions + - Service responsibilities + - Service interactions and orchestration +- Create `aidlc-docs/inception/application-design/component-dependency.md` with: + - Dependency matrix showing relationships + - Communication patterns between components + - Data flow diagrams + +### 11. Log Approval +- Log approval prompt with timestamp in `aidlc-docs/audit.md` +- Include complete approval prompt text +- Use ISO 8601 timestamp format + +### 12. Present Completion Message + +```markdown +# 🏗️ Application Design Complete + +[AI-generated summary of application design artifacts created in bullet points] + +> **📋 **REVIEW REQUIRED:**** +> Please examine the application design artifacts at: `aidlc-docs/inception/application-design/` + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the application design if required +> [IF Units Generation is skipped:] +> 📝 **Add Units Generation** - Choose to include **Units Generation** stage (currently skipped) +> ✅ **Approve & Continue** - Approve design and proceed to **[Units Generation/CONSTRUCTION PHASE]** +``` + +### 13. Wait for Explicit Approval +- Do not proceed until the user explicitly approves the application design +- Approval must be clear and unambiguous +- If user requests changes, update the design and repeat the approval process + +### 14. Record Approval Response +- Log the user's approval response with timestamp in `aidlc-docs/audit.md` +- Include the exact user response text +- Mark the approval status clearly + +### 15. Update Progress +- Mark Application Design stage complete in `aidlc-docs/aidlc-state.md` +- Update the "Current Status" section +- Prepare for transition to next stage diff --git a/aidlc/rule-details/inception/requirements-analysis.md b/aidlc/rule-details/inception/requirements-analysis.md new file mode 100644 index 0000000..cc47828 --- /dev/null +++ b/aidlc/rule-details/inception/requirements-analysis.md @@ -0,0 +1,169 @@ +# Requirements Analysis (Adaptive) + +**Assume the role** of a product owner + +**Adaptive Phase**: Always executes. Detail level adapts to problem complexity. + +**See [depth-levels.md](../common/depth-levels.md) for adaptive depth explanation** + +## Prerequisites +- Workspace Detection must be complete +- Reverse Engineering must be complete (if brownfield) + +## Execution Steps + +### Step 1: Load Reverse Engineering Context (if available) + +**IF brownfield project**: +- Load `aidlc-docs/inception/reverse-engineering/architecture.md` +- Load `aidlc-docs/inception/reverse-engineering/component-inventory.md` +- Load `aidlc-docs/inception/reverse-engineering/technology-stack.md` +- Use these to understand existing system when analyzing request + +### Step 2: Analyze User Request (Intent Analysis) + +#### 2.1 Request Clarity +- **Clear**: Specific, well-defined, actionable +- **Vague**: General, ambiguous, needs clarification +- **Incomplete**: Missing key information + +#### 2.2 Request Type +- **New Feature**: Adding new functionality +- **Bug Fix**: Fixing existing issue +- **Refactoring**: Improving code structure +- **Upgrade**: Updating dependencies or frameworks +- **Migration**: Moving to different technology +- **Enhancement**: Improving existing feature +- **New Project**: Starting from scratch + +#### 2.3 Initial Scope Estimate +- **Single File**: Changes to one file +- **Single Component**: Changes to one component/package +- **Multiple Components**: Changes across multiple components +- **System-wide**: Changes affecting entire system +- **Cross-system**: Changes affecting multiple systems + +#### 2.4 Initial Complexity Estimate +- **Trivial**: Simple, straightforward change +- **Simple**: Clear implementation path +- **Moderate**: Some complexity, multiple considerations +- **Complex**: Significant complexity, many considerations + +### Step 3: Determine Requirements Depth + +**Based on request analysis, determine depth:** + +**Minimal Depth** - Use when: +- Request is clear and simple +- No detailed requirements needed +- Just document the basic understanding + +**Standard Depth** - Use when: +- Request needs clarification +- Functional and non-functional requirements needed +- Normal complexity + +**Comprehensive Depth** - Use when: +- Complex project with multiple stakeholders +- High risk or critical system +- Detailed requirements with traceability needed + +### Step 4: Assess Current Requirements + +Analyze whatever the user has provided: + - Intent statements or descriptions (already logged in audit.md) + - Existing requirements documents (search workspace if mentioned) + - Pasted content or file references + - Convert any non-markdown documents to markdown format + +### Step 5: Thorough Completeness Analysis + +**CRITICAL**: Use comprehensive analysis to evaluate requirements completeness. Default to asking questions when there is ANY ambiguity or missing detail. + +**MANDATORY**: Evaluate ALL of these areas and ask questions for ANY that are unclear: +- **Functional Requirements**: Core features, user interactions, system behaviors +- **Non-Functional Requirements**: Performance, security, scalability, usability +- **User Scenarios**: Use cases, user journeys, edge cases, error scenarios +- **Business Context**: Goals, constraints, success criteria, stakeholder needs +- **Technical Context**: Integration points, data requirements, system boundaries +- **Quality Attributes**: Reliability, maintainability, testability, accessibility + +**When in doubt, ask questions** - incomplete requirements lead to poor implementations. + +### Step 6: Generate Clarifying Questions (PROACTIVE APPROACH) + - **ALWAYS** create `aidlc-docs/inception/requirements/requirement-verification-questions.md` unless requirements are exceptionally clear and complete + - Ask questions about ANY missing, unclear, or ambiguous areas + - Focus on functional requirements, non-functional requirements, user scenarios, and business context + - Request user to fill in all [Answer]: tags directly in the questions document + - If presenting multiple-choice options for answers: + - Label the options as A, B, C, D etc. + - Ensure options are mutually exclusive and don't overlap + - ALWAYS include option for custom response: "X) Other (please describe after [Answer]: tag below)" + - Wait for user answers in the document + - **MANDATORY**: Analyze ALL answers for ambiguities and create follow-up questions if needed + - **MANDATORY**: Keep asking questions until ALL ambiguities are resolved OR user explicitly asks to proceed + +### Step 7: Generate Requirements Document + - Create `aidlc-docs/inception/requirements/requirements.md` + - Include intent analysis summary at the top: + - User request + - Request type + - Scope estimate + - Complexity estimate + - Include both functional and non-functional requirements + - Incorporate user's answers to clarifying questions + - Provide brief summary of key requirements + +### Step 8: Update State Tracking + +Update `aidlc-docs/aidlc-state.md`: + +```markdown +## Stage Progress +### 🔵 INCEPTION PHASE +- [x] Workspace Detection +- [x] Reverse Engineering (if applicable) +- [x] Requirements Analysis +``` + +### Step 9: Log and Proceed + - Log approval prompt with timestamp in `aidlc-docs/audit.md` + - Present completion message in this structure: + 1. **Completion Announcement** (mandatory): Always start with this: + +```markdown +# 🔍 Requirements Analysis Complete +``` + + 2. **AI Summary** (optional): Provide structured bullet-point summary of requirements + - Format: "Requirements analysis has identified [project type/complexity]:" + - List key functional requirements (bullet points) + - List key non-functional requirements (bullet points) + - Mention architectural considerations or technical decisions if relevant + - DO NOT include workflow instructions ("please review", "let me know", "proceed to next phase", "before we proceed") + - Keep factual and content-focused + 3. **Formatted Workflow Message** (mandatory): Always end with this exact format: + +```markdown +> **📋 **REVIEW REQUIRED:**** +> Please examine the requirements document at: `aidlc-docs/inception/requirements/requirements.md` + + + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the requirements if required based on your review +> [IF User Stories will be skipped, add this option:] +> 📝 **Add User Stories** - Choose to Include **User Stories** stage (currently skipped based on project simplicity) +> ✅ **Approve & Continue** - Approve requirements and proceed to **[User Stories/Workflow Planning]** + +--- +``` + +**Note**: Include the "Add User Stories" option only when User Stories stage will be skipped. Replace [User Stories/Workflow Planning] with the actual next stage name. + + - Wait for explicit user approval before proceeding + - Record approval response with timestamp + - Update Requirements Analysis stage complete in aidlc-state.md \ No newline at end of file diff --git a/aidlc/rule-details/inception/reverse-engineering.md b/aidlc/rule-details/inception/reverse-engineering.md new file mode 100644 index 0000000..f7b08f5 --- /dev/null +++ b/aidlc/rule-details/inception/reverse-engineering.md @@ -0,0 +1,311 @@ +# Reverse Engineering + +**Purpose**: Analyze existing codebase and generate comprehensive design artifacts + +**Execute when**: Brownfield project detected (existing code found in workspace) + +**Skip when**: Greenfield project (no existing code) + +**Rerun behavior**: Always rerun when brownfield project detected, even if artifacts exist. This ensures artifacts reflect current code state + +## Step 1: Multi-Package Discovery + +### 1.1 Scan Workspace +- All packages (not just mentioned ones) +- Package relationships via config files +- Package types: Application, CDK/Infrastructure, Models, Clients, Tests + +### 1.2 Understand the Business Context +- The core business that the system is implementing overall +- The business overview of every package +- List of Business Transactions that are implemented in the system + +### 1.3 Infrastructure Discovery +- CDK packages (package.json with CDK dependencies) +- Terraform (.tf files) +- CloudFormation (.yaml/.json templates) +- Deployment scripts + +### 1.4 Build System Discovery +- Build systems: Brazil, Maven, Gradle, npm +- Config files for build-system declarations +- Build dependencies between packages + +### 1.5 Service Architecture Discovery +- Lambda functions (handlers, triggers) +- Container services (Docker/ECS configs) +- API definitions (Smithy models, OpenAPI specs) +- Data stores (DynamoDB, S3, etc.) + +### 1.6 Code Quality Analysis +- Programming languages and frameworks +- Test coverage indicators +- Linting configurations +- CI/CD pipelines + +## Step 1: Generate Business Overview Documentation + +Create `aidlc-docs/inception/reverse-engineering/business-overview.md`: + +```markdown +# Business Overview + +## Business Context Diagram +[Mermaid diagram showing the Business Context] + +## Business Description +- **Business Description**: [Overall Business description of what the system does] +- **Business Transactions**: [List of Business Transactions that the system implements and their descriptions] +- **Business Dictionary**: [Business dictionary terms that the system follows and their meaning] + +## Component Level Business Descriptions +### [Package/Component Name] +- **Purpose**: [What it does from the business perspective] +- **Responsibilities**: [Key responsibilities] +``` + +## Step 2: Generate Architecture Documentation + +Create `aidlc-docs/inception/reverse-engineering/architecture.md`: + +```markdown +# System Architecture + +## System Overview +[High-level description of the system] + +## Architecture Diagram +[Mermaid diagram showing all packages, services, data stores, relationships] + +## Component Descriptions +### [Package/Component Name] +- **Purpose**: [What it does] +- **Responsibilities**: [Key responsibilities] +- **Dependencies**: [What it depends on] +- **Type**: [Application/Infrastructure/Model/Client/Test] + +## Data Flow +[Mermaid sequence diagram of key workflows] + +## Integration Points +- **External APIs**: [List with purposes] +- **Databases**: [List with purposes] +- **Third-party Services**: [List with purposes] + +## Infrastructure Components +- **CDK Stacks**: [List with purposes] +- **Deployment Model**: [Description] +- **Networking**: [VPC, subnets, security groups] +``` + +## Step 3: Generate Code Structure Documentation + +Create `aidlc-docs/inception/reverse-engineering/code-structure.md`: + +```markdown +# Code Structure + +## Build System +- **Type**: [Maven/Gradle/npm/Brazil] +- **Configuration**: [Key build files and settings] + +## Key Classes/Modules +[Mermaid class diagram or module hierarchy] + +### Existing Files Inventory +[List all source files with their purposes - these are candidates for modification in brownfield projects] + +**Example format**: +- `[path/to/file]` - [Purpose/responsibility] + +## Design Patterns +### [Pattern Name] +- **Location**: [Where used] +- **Purpose**: [Why used] +- **Implementation**: [How implemented] + +## Critical Dependencies +### [Dependency Name] +- **Version**: [Version number] +- **Usage**: [How and where used] +- **Purpose**: [Why needed] +``` + +## Step 4: Generate API Documentation + +Create `aidlc-docs/inception/reverse-engineering/api-documentation.md`: + +```markdown +# API Documentation + +## REST APIs +### [Endpoint Name] +- **Method**: [GET/POST/PUT/DELETE] +- **Path**: [/api/path] +- **Purpose**: [What it does] +- **Request**: [Request format] +- **Response**: [Response format] + +## Internal APIs +### [Interface/Class Name] +- **Methods**: [List with signatures] +- **Parameters**: [Parameter descriptions] +- **Return Types**: [Return type descriptions] + +## Data Models +### [Model Name] +- **Fields**: [Field descriptions] +- **Relationships**: [Related models] +- **Validation**: [Validation rules] +``` + +## Step 5: Generate Component Inventory + +Create `aidlc-docs/inception/reverse-engineering/component-inventory.md`: + +```markdown +# Component Inventory + +## Application Packages +- [Package name] - [Purpose] + +## Infrastructure Packages +- [Package name] - [CDK/Terraform] - [Purpose] + +## Shared Packages +- [Package name] - [Models/Utilities/Clients] - [Purpose] + +## Test Packages +- [Package name] - [Integration/Load/Unit] - [Purpose] + +## Total Count +- **Total Packages**: [Number] +- **Application**: [Number] +- **Infrastructure**: [Number] +- **Shared**: [Number] +- **Test**: [Number] +``` + +## Step 6: Generate Technology Stack Documentation + +Create `aidlc-docs/inception/reverse-engineering/technology-stack.md`: + +```markdown +# Technology Stack + +## Programming Languages +- [Language] - [Version] - [Usage] + +## Frameworks +- [Framework] - [Version] - [Purpose] + +## Infrastructure +- [Service] - [Purpose] + +## Build Tools +- [Tool] - [Version] - [Purpose] + +## Testing Tools +- [Tool] - [Version] - [Purpose] +``` + +## Step 7: Generate Dependencies Documentation + +Create `aidlc-docs/inception/reverse-engineering/dependencies.md`: + +```markdown +# Dependencies + +## Internal Dependencies +[Mermaid diagram showing package dependencies] + +### [Package A] depends on [Package B] +- **Type**: [Compile/Runtime/Test] +- **Reason**: [Why dependency exists] + +## External Dependencies +### [Dependency Name] +- **Version**: [Version] +- **Purpose**: [Why used] +- **License**: [License type] +``` + +## Step 8: Generate Code Quality Assessment + +Create `aidlc-docs/inception/reverse-engineering/code-quality-assessment.md`: + +```markdown +# Code Quality Assessment + +## Test Coverage +- **Overall**: [Percentage or Good/Fair/Poor/None] +- **Unit Tests**: [Status] +- **Integration Tests**: [Status] + +## Code Quality Indicators +- **Linting**: [Configured/Not configured] +- **Code Style**: [Consistent/Inconsistent] +- **Documentation**: [Good/Fair/Poor] + +## Technical Debt +- [Issue description and location] + +## Patterns and Anti-patterns +- **Good Patterns**: [List] +- **Anti-patterns**: [List with locations] +``` + +## Step 9: Create Timestamp File + +Create `aidlc-docs/inception/reverse-engineering/reverse-engineering-timestamp.md`: + +```markdown +# Reverse Engineering Metadata + +**Analysis Date**: [ISO timestamp] +**Analyzer**: AI-DLC +**Workspace**: [Workspace path] +**Total Files Analyzed**: [Number] + +## Artifacts Generated +- [x] architecture.md +- [x] code-structure.md +- [x] api-documentation.md +- [x] component-inventory.md +- [x] technology-stack.md +- [x] dependencies.md +- [x] code-quality-assessment.md +``` + +## Step 10: Update State Tracking + +Update `aidlc-docs/aidlc-state.md`: + +```markdown +## Reverse Engineering Status +- [x] Reverse Engineering - Completed on [timestamp] +- **Artifacts Location**: aidlc-docs/inception/reverse-engineering/ +``` + +## Step 11: Present Completion Message to User + +```markdown +# 🔍 Reverse Engineering Complete + +[AI-generated summary of key findings from analysis in the form of bullet points] + +> **📋 **REVIEW REQUIRED:**** +> Please examine the reverse engineering artifacts at: `aidlc-docs/inception/reverse-engineering/` + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the reverse engineering analysis if required +> ✅ **Approve & Continue** - Approve analysis and proceed to **Requirements Analysis** +``` + +## Step 12: Wait for User Approval + +- **MANDATORY**: Do not proceed until user explicitly approves +- **MANDATORY**: Log user's response in audit.md with complete raw input diff --git a/aidlc/rule-details/inception/units-generation.md b/aidlc/rule-details/inception/units-generation.md new file mode 100644 index 0000000..db228c8 --- /dev/null +++ b/aidlc/rule-details/inception/units-generation.md @@ -0,0 +1,183 @@ +# Units Generation - Detailed Steps + +## Overview +This stage decomposes the system into manageable units of work through two integrated parts: +- **Part 1 - Planning**: Create decomposition plan with questions, collect answers, analyze for ambiguities, get approval +- **Part 2 - Generation**: Execute approved plan to generate unit artifacts + +**DEFINITION**: A unit of work is a logical grouping of stories for development purposes. For microservices, each unit becomes an independently deployable service. For monoliths, the single unit represents the entire application with logical modules. + +**Terminology**: Use "Service" for independently deployable components, "Module" for logical groupings within a service, "Unit of Work" for planning context. + +## Prerequisites +- Context Assessment must be complete +- Requirements Assessment recommended (provides functional scope) +- Story Development recommended (stories map to units) +- Application Design phase REQUIRED (determines components, methods, and services) +- Execution plan must indicate Design phase should execute + +--- + +# PART 1: PLANNING + +## Step 1: Create Unit of Work Plan +- Generate plan with checkboxes [] for decomposing system into units of work +- Focus on breaking down the system into manageable development units +- Each step and sub-step should have a checkbox [] + +## Step 2: Include Mandatory Unit Artifacts in Plan +**ALWAYS** include these mandatory artifacts in the unit plan: +- [ ] Generate `aidlc-docs/inception/application-design/unit-of-work.md` with unit definitions and responsibilities +- [ ] Generate `aidlc-docs/inception/application-design/unit-of-work-dependency.md` with dependency matrix +- [ ] Generate `aidlc-docs/inception/application-design/unit-of-work-story-map.md` mapping stories to units +- [ ] **Greenfield only**: Document code organization strategy in `unit-of-work.md` (see code-generation.md for structure patterns) +- [ ] Validate unit boundaries and dependencies +- [ ] Ensure all stories are assigned to units + +## Step 3: Generate Context-Appropriate Questions +**DIRECTIVE**: Analyze the requirements, stories, and application design to generate ONLY questions relevant to THIS specific decomposition problem. Use the categories below as inspiration, NOT as a mandatory checklist. Skip entire categories if not applicable. + +- EMBED questions using [Answer]: tag format +- Focus on ambiguities and missing information specific to this context +- Generate questions only where user input is needed for decision-making + +**Example question categories** (adapt as needed): +- **Story Grouping** - Only if multiple stories exist and grouping strategy is unclear +- **Dependencies** - Only if multiple units likely and integration approach is ambiguous +- **Team Alignment** - Only if team structure or ownership is unclear +- **Technical Considerations** - Only if scalability/deployment requirements differ across units +- **Business Domain** - Only if domain boundaries or bounded contexts are unclear +- **Code Organization (Greenfield multi-unit only)** - Ask deployment model and directory structure preferences + +## Step 4: Store UOW Plan +- Save as `aidlc-docs/inception/plans/unit-of-work-plan.md` +- Include all [Answer]: tags for user input +- Ensure plan covers all aspects of system decomposition + +## Step 5: Request User Input +- Ask user to fill [Answer]: tags directly in the plan document +- Emphasize importance of decomposition decisions +- Provide clear instructions on completing the [Answer]: tags + +## Step 6: Collect Answers +- Wait for user to provide answers to all questions using [Answer]: tags in the document +- Do not proceed until ALL [Answer]: tags are completed +- Review the document to ensure no [Answer]: tags are left blank + +## Step 7: ANALYZE ANSWERS (MANDATORY) +Before proceeding, you MUST carefully review all user answers for: +- **Vague or ambiguous responses**: "mix of", "somewhere between", "not sure", "depends" +- **Undefined criteria or terms**: References to concepts without clear definitions +- **Contradictory answers**: Responses that conflict with each other +- **Missing generation details**: Answers that lack specific guidance +- **Answers that combine options**: Responses that merge different approaches without clear decision rules + +## Step 8: MANDATORY Follow-up Questions +If the analysis in step 7 reveals ANY ambiguous answers, you MUST: +- Add specific follow-up questions to the plan document using [Answer]: tags +- DO NOT proceed to approval until all ambiguities are resolved +- Examples of required follow-ups: + - "You mentioned 'mix of A and B' - what specific criteria should determine when to use A vs B?" + - "You said 'somewhere between A and B' - can you define the exact middle ground approach?" + - "You indicated 'not sure' - what additional information would help you decide?" + - "You mentioned 'depends on complexity' - how do you define complexity levels?" + +## Step 9: Request Approval +- Ask: "**Unit of work plan complete. Review the plan in aidlc-docs/inception/plans/unit-of-work-plan.md. Ready to proceed to generation?**" +- DO NOT PROCEED until user confirms + +## Step 10: Log Approval +- Log prompt and response in audit.md with timestamp +- Use ISO 8601 timestamp format +- Include complete approval prompt text + +## Step 11: Update Progress +- Mark Units Planning complete in aidlc-state.md +- Update the "Current Status" section +- Prepare for transition to Units Generation + +--- + +# PART 2: GENERATION + +## Step 12: Load Unit of Work Plan +- [ ] Read the complete plan from `aidlc-docs/inception/plans/unit-of-work-plan.md` +- [ ] Identify the next uncompleted step (first [ ] checkbox) +- [ ] Load the context and requirements for that step + +## Step 13: Execute Current Step +- [ ] Perform exactly what the current step describes +- [ ] Generate unit artifacts as specified in the plan +- [ ] Follow the approved decomposition approach from Planning +- [ ] Use the criteria and boundaries specified in the plan + +## Step 14: Update Progress +- [ ] Mark the completed step as [x] in the unit of work plan +- [ ] Update `aidlc-docs/aidlc-state.md` current status +- [ ] Save all generated artifacts + +## Step 15: Continue or Complete +- [ ] If more steps remain, return to Step 12 +- [ ] If all steps complete, verify units are ready for design stages +- [ ] Mark Units Generation stage as complete + +## Step 16: Present Completion Message + +```markdown +# 🔧 Units Generation Complete + +[AI-generated summary of units and decomposition created in bullet points] + +> **📋 **REVIEW REQUIRED:**** +> Please examine the units generation artifacts at: `aidlc-docs/inception/application-design/` + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the units generation if required +> ✅ **Approve & Continue** - Approve units and proceed to **CONSTRUCTION PHASE** +``` + +## Step 17: Wait for Explicit Approval +- Do not proceed until the user explicitly approves the units generation +- Approval must be clear and unambiguous +- If user requests changes, update the units and repeat the approval process + +## Step 18: Record Approval Response +- Log the user's approval response with timestamp in `aidlc-docs/audit.md` +- Include the exact user response text +- Mark the approval status clearly + +## Step 19: Update Progress +- Mark Units Generation stage complete in `aidlc-docs/aidlc-state.md` +- Update the "Current Status" section +- Prepare for transition to CONSTRUCTION PHASE + +--- + +## Critical Rules + +### Planning Phase Rules +- Generate ONLY context-relevant questions +- Use [Answer]: tag format for all questions +- Analyze all answers for ambiguities before proceeding +- Resolve ALL ambiguities with follow-up questions +- Get explicit user approval before generation + +### Generation Phase Rules +- **NO HARDCODED LOGIC**: Only execute what's written in the unit of work plan +- **FOLLOW PLAN EXACTLY**: Do not deviate from the step sequence +- **UPDATE CHECKBOXES**: Mark [x] immediately after completing each step +- **USE APPROVED APPROACH**: Follow the decomposition methodology from Planning +- **VERIFY COMPLETION**: Ensure all unit artifacts are complete before proceeding + +## Completion Criteria +- All planning questions answered and ambiguities resolved +- User approval obtained for the plan +- All steps in unit of work plan marked [x] +- All unit artifacts generated according to plan: + - `unit-of-work.md` with unit definitions + - `unit-of-work-dependency.md` with dependency matrix + - `unit-of-work-story-map.md` with story mappings +- Units verified and ready for per-unit design stages diff --git a/aidlc/rule-details/inception/user-stories.md b/aidlc/rule-details/inception/user-stories.md new file mode 100644 index 0000000..e12a7fa --- /dev/null +++ b/aidlc/rule-details/inception/user-stories.md @@ -0,0 +1,327 @@ +# User Stories - Detailed Steps + +## Purpose +**Convert requirements into user-centered stories with acceptance criteria** + +User Stories focus on: +- Translating business requirements into user-centered narratives +- Defining clear acceptance criteria for each story +- Creating user personas that represent different stakeholder types +- Establishing shared understanding across teams +- Providing testable specifications for implementation + +## Prerequisites +- Workspace Detection must be complete +- Requirements Analysis recommended (can reference requirements if available) +- Workflow Planning must indicate User Stories stage should execute + +## Intelligent Assessment Guidelines + +**WHEN TO EXECUTE USER STORIES**: Use this enhanced assessment before proceeding: + +### High Priority Execution (ALWAYS Execute) +- **New User Features**: Any new functionality users will directly interact with +- **User Experience Changes**: Modifications to existing user workflows or interfaces +- **Multi-Persona Systems**: Applications serving different types of users +- **Customer-Facing APIs**: Services that external users or systems will consume +- **Complex Business Logic**: Requirements with multiple scenarios or business rules +- **Cross-Team Projects**: Work requiring shared understanding across multiple teams + +### Medium Priority Execution (Assess Complexity) +- **Backend User Impact**: Internal changes that indirectly affect user experience +- **Performance Improvements**: Enhancements with user-visible benefits +- **Integration Work**: Connecting systems that affect user workflows +- **Data Changes**: Modifications affecting user data, reports, or analytics +- **Security Enhancements**: Changes affecting user authentication or permissions + +### Complexity Assessment Factors +For medium priority cases, execute user stories if ANY of these apply: +- **Scope**: Changes span multiple components or user touchpoints +- **Ambiguity**: Requirements have unclear aspects that stories could clarify +- **Risk**: High business impact or potential for misunderstanding +- **Stakeholders**: Multiple business stakeholders involved in requirements +- **Testing**: User acceptance testing will be required +- **Options**: Multiple valid implementation approaches exist + +### Skip Only For Simple Cases +- **Pure Refactoring**: Internal code improvements with zero user impact +- **Isolated Bug Fixes**: Simple, well-defined fixes with clear scope +- **Infrastructure Only**: Changes with no user-facing effects +- **Developer Tooling**: Build processes, CI/CD, or development environment changes +- **Documentation**: Updates that don't affect functionality + +### Default Decision Rule +**When in doubt, include user stories AND ask clarifying questions.** The overhead of creating comprehensive stories with proper clarification is typically outweighed by the benefits of: +- Clearer requirements understanding +- Better team alignment +- Improved testing criteria +- Enhanced stakeholder communication +- Reduced implementation risks +- Fewer costly changes during development +- Better user experience outcomes + +--- + +# PART 1: PLANNING + +## Step 1: Validate User Stories Need (MANDATORY) + +**CRITICAL**: Before proceeding with user stories, perform this assessment: + +### Assessment Process +1. **Analyze Request Context**: + - Review the original user request and requirements + - Identify user-facing vs internal-only changes + - Assess complexity and scope of the work + - Evaluate business stakeholder involvement + +2. **Apply Assessment Criteria**: + - Check against High Priority indicators (always execute) + - Evaluate Medium Priority factors (complexity-based decision) + - Confirm this isn't a simple case that should be skipped + +3. **Document Assessment Decision**: + - Create `aidlc-docs/inception/plans/user-stories-assessment.md` + - Include reasoning for why user stories are valuable for this request + - Reference specific assessment criteria that apply + - Explain expected benefits (clarity, testing, stakeholder alignment) + +4. **Proceed Only If Justified**: + - User stories must add clear value to the project + - Assessment must show concrete benefits outweigh overhead + - Decision should be defensible to project stakeholders + +### Assessment Documentation Template +```markdown +# User Stories Assessment + +## Request Analysis +- **Original Request**: [Brief summary] +- **User Impact**: [Direct/Indirect/None] +- **Complexity Level**: [Simple/Medium/Complex] +- **Stakeholders**: [List involved parties] + +## Assessment Criteria Met +- [ ] High Priority: [List applicable criteria] +- [ ] Medium Priority: [List applicable criteria with complexity justification] +- [ ] Benefits: [Expected value from user stories] + +## Decision +**Execute User Stories**: [Yes/No] +**Reasoning**: [Detailed justification] + +## Expected Outcomes +- [List specific benefits user stories will provide] +- [How stories will improve project success] +``` + +## Step 2: Create Story Plan +- Assume the role of a product owner +- Generate a comprehensive plan with step-by-step execution checklist for story development +- Each step and sub-step should have a checkbox [] +- Focus on methodology and approach for converting requirements into user stories + +## Step 3: Generate Context-Appropriate Questions +**DIRECTIVE**: Thoroughly analyze the requirements and context to identify ALL areas where clarification would improve story quality and team understanding. Be proactive in asking questions to ensure comprehensive user story development. + +**CRITICAL**: Default to asking questions when there is ANY ambiguity or missing detail that could affect story quality. It's better to ask too many questions than to create incomplete or unclear stories. + +**See `common/question-format-guide.md` for question formatting rules** + +- EMBED questions using [Answer]: tag format +- Focus on ANY ambiguities, missing information, or areas needing clarification +- Generate questions wherever user input would improve story creation decisions +- **When in doubt, ask the question** - overconfidence leads to poor stories + +**Question categories to evaluate** (consider ALL categories): +- **User Personas** - Ask about user types, roles, characteristics, and motivations +- **Story Granularity** - Ask about appropriate level of detail, story size, and breakdown approach +- **Story Format** - Ask about format preferences, template usage, and documentation standards +- **Breakdown Approach** - Ask about organization method, prioritization, and grouping strategies +- **Acceptance Criteria** - Ask about detail level, format, testing approach, and validation methods +- **User Journeys** - Ask about user workflows, interaction patterns, and experience flows +- **Business Context** - Ask about business goals, success metrics, and stakeholder needs +- **Technical Constraints** - Ask about technical limitations, integration requirements, and system boundaries + +## Step 4: Include Mandatory Story Artifacts in Plan +- **ALWAYS** include these mandatory artifacts in the story plan: + - [ ] Generate stories.md with user stories following INVEST criteria + - [ ] Generate personas.md with user archetypes and characteristics + - [ ] Ensure stories are Independent, Negotiable, Valuable, Estimable, Small, Testable + - [ ] Include acceptance criteria for each story + - [ ] Map personas to relevant user stories + +## Step 5: Present Story Options +- Include different approaches for story breakdown in the plan document: + - **User Journey-Based**: Stories follow user workflows and interactions + - **Feature-Based**: Stories organized around system features and capabilities + - **Persona-Based**: Stories grouped by different user types and their needs + - **Domain-Based**: Stories organized around business domains or contexts + - **Epic-Based**: Stories structured as hierarchical epics with sub-stories +- Explain trade-offs and benefits of each approach +- Allow for hybrid approaches with clear decision criteria + +## Step 6: Store Story Plan +- Save the complete story plan with embedded questions in `aidlc-docs/inception/plans/` directory +- Filename: `story-generation-plan.md` +- Include all [Answer]: tags for user input +- Ensure plan is comprehensive and covers all story development aspects + +## Step 7: Request User Input +- Ask user to fill in all [Answer]: tags directly in the story plan document +- Emphasize importance of audit trail and decision documentation +- Provide clear instructions on how to fill in the [Answer]: tags +- Explain that all questions must be answered before proceeding + +## Step 8: Collect Answers +- Wait for user to provide answers to all questions using [Answer]: tags in the document +- Do not proceed until ALL [Answer]: tags are completed +- Review the document to ensure no [Answer]: tags are left blank + +## Step 9: ANALYZE ANSWERS (MANDATORY) +Before proceeding, you MUST carefully review all user answers for: +- **Vague or ambiguous responses**: "mix of", "somewhere between", "not sure", "depends", "maybe", "probably" +- **Undefined criteria or terms**: References to concepts without clear definitions +- **Contradictory answers**: Responses that conflict with each other +- **Missing generation details**: Answers that lack specific guidance for implementation +- **Answers that combine options**: Responses that merge different approaches without clear decision rules +- **Incomplete explanations**: Answers that reference external factors without defining them +- **Assumption-based responses**: Answers that assume knowledge not explicitly stated + +## Step 10: MANDATORY Follow-up Questions +If the analysis in step 9 reveals ANY ambiguous answers, you MUST: +- Create a separate clarification questions file using [Answer]: tags +- DO NOT proceed to approval until ALL ambiguities are completely resolved +- **CRITICAL**: Be thorough - ask follow-up questions for every unclear response +- Examples of required follow-ups: + - "You mentioned 'mix of A and B' - what specific criteria should determine when to use A vs B?" + - "You said 'somewhere between A and B' - can you define the exact middle ground approach?" + - "You indicated 'not sure' - what additional information would help you decide?" + - "You mentioned 'depends on complexity' - how do you define complexity levels and thresholds?" + - "You chose 'hybrid approach' - what are the specific rules for when to use each method?" + - "You said 'probably X' - what factors would make it definitely X vs definitely not X?" + - "You referenced 'standard practice' - can you define what that standard practice is?" + +## Step 11: Avoid Implementation Details +- Focus on story creation methodology, not prioritization or development tasks +- Do not discuss technical generation at this stage +- Avoid creating development timelines or sprint planning +- Keep focus on story structure and format decisions + +## Step 12: Log Approval Prompt +- Before asking for approval, log the prompt with timestamp in `aidlc-docs/audit.md` +- Include the complete approval prompt text +- Use ISO 8601 timestamp format + +## Step 13: Wait for Explicit Approval of Plan +- Do not proceed until the user explicitly approves the story approach +- Approval must be clear and unambiguous +- If user requests changes, update the plan and repeat the approval process + +## Step 14: Record Approval Response +- Log the user's approval response with timestamp in `aidlc-docs/audit.md` +- Include the exact user response text +- Mark the approval status clearly + +--- + +# PART 2: GENERATION + +## Step 15: Load Story Generation Plan +- [ ] Read the complete story plan from `aidlc-docs/inception/plans/story-generation-plan.md` +- [ ] Identify the next uncompleted step (first [ ] checkbox) +- [ ] Load the context and requirements for that step + +## Step 16: Execute Current Step +- [ ] Perform exactly what the current step describes +- [ ] Generate story artifacts as specified in the plan +- [ ] Follow the approved methodology and format from Planning +- [ ] Use the story breakdown approach specified in the plan + +## Step 17: Update Progress +- [ ] Mark the completed step as [x] in the story generation plan +- [ ] Update `aidlc-docs/aidlc-state.md` current status +- [ ] Save all generated artifacts + +## Step 18: Continue or Complete Generation +- [ ] If more steps remain, return to Step 14 +- [ ] If all steps complete, verify stories are ready for next stage +- [ ] Ensure all mandatory artifacts are generated + +## Step 19: Log Approval Prompt +- Before asking for approval, log the prompt with timestamp in `aidlc-docs/audit.md` +- Include the complete approval prompt text +- Use ISO 8601 timestamp format + +## Step 20: Present Completion Message +- Present completion message in this structure: + 1. **Completion Announcement** (mandatory): Always start with this: + +```markdown +# 📚 User Stories Complete +``` + + 2. **AI Summary** (optional): Provide structured bullet-point summary of generated stories + - Format: "User stories generation has created [description]:" + - List key personas generated (bullet points) + - List user stories created with counts and organization + - Mention story structure and compliance (INVEST criteria, acceptance criteria) + - DO NOT include workflow instructions ("please review", "let me know", "proceed to next phase", "before we proceed") + - Keep factual and content-focused + 3. **Formatted Workflow Message** (mandatory): Always end with this exact format: + +```markdown +> **📋 **REVIEW REQUIRED:**** +> Please examine the user stories and personas at: `aidlc-docs/inception/user-stories/stories.md` and `aidlc-docs/inception/user-stories/personas.md` + + + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the stories or personas based on your review +> ✅ **Approve & Continue** - Approve user stories and proceed to **Workflow Planning** + +--- +``` + +## Step 21: Wait for Explicit Approval of Generated Stories +- Do not proceed until the user explicitly approves the generated stories +- Approval must be clear and unambiguous +- If user requests changes, update stories and repeat the approval process + +## Step 22: Record Approval Response +- Log the user's approval response with timestamp in `aidlc-docs/audit.md` +- Include the exact user response text +- Mark the approval status clearly + +## Step 23: Update Progress +- Mark User Stories stage complete in `aidlc-state.md` +- Update the "Current Status" section +- Prepare for transition to next stage + +--- + +# CRITICAL RULES + +## Planning Phase Rules +- **CONTEXT-APPROPRIATE QUESTIONS**: Only ask questions relevant to this specific context +- **MANDATORY ANSWER ANALYSIS**: Always analyze answers for ambiguities before proceeding +- **NO PROCEEDING WITH AMBIGUITY**: Must resolve all vague answers before generation +- **EXPLICIT APPROVAL REQUIRED**: User must approve plan before generation starts + +## Generation Phase Rules +- **NO HARDCODED LOGIC**: Only execute what's written in the story generation plan +- **FOLLOW PLAN EXACTLY**: Do not deviate from the step sequence +- **UPDATE CHECKBOXES**: Mark [x] immediately after completing each step +- **USE APPROVED METHODOLOGY**: Follow the story approach from Planning +- **VERIFY COMPLETION**: Ensure all story artifacts are complete before proceeding + +## Completion Criteria +- All planning questions answered and ambiguities resolved +- Story plan explicitly approved by user +- All steps in story generation plan marked [x] +- All story artifacts generated according to plan (stories.md, personas.md) +- Generated stories explicitly approved by user +- Stories verified and ready for next stage diff --git a/aidlc/rule-details/inception/workflow-planning.md b/aidlc/rule-details/inception/workflow-planning.md new file mode 100644 index 0000000..6f4b700 --- /dev/null +++ b/aidlc/rule-details/inception/workflow-planning.md @@ -0,0 +1,479 @@ +# Workflow Planning + +**Purpose**: Determine which phases to execute and create comprehensive execution plan + +**Always Execute**: This phase always runs after understanding requirements and scope + +## Step 1: Load All Prior Context + +### 1.1 Load Reverse Engineering Artifacts (if brownfield) +- architecture.md +- component-inventory.md +- technology-stack.md +- dependencies.md + +### 1.2 Load Requirements Analysis +- requirements.md (includes intent analysis) +- requirement-verification-questions.md (with answers) + +### 1.3 Load User Stories (if executed) +- stories.md +- personas.md + +## Step 2: Detailed Scope and Impact Analysis + +**Now that we have complete context (requirements + stories), perform detailed analysis:** + +### 2.1 Transformation Scope Detection (Brownfield Only) + +**IF brownfield project**, analyze transformation scope: + +#### Architectural Transformation +- **Single component change** vs **architectural transformation** +- **Infrastructure changes** vs **application changes** +- **Deployment model changes** (Lambda→Container, EC2→Serverless, etc.) + +#### Related Component Identification +For transformations, identify: +- **Infrastructure code** that needs updates +- **CDK stacks** requiring changes +- **API Gateway** configurations +- **Load balancer** requirements +- **Networking** changes needed +- **Monitoring/logging** adaptations + +#### Cross-Package Impact +- **CDK infrastructure** packages requiring updates +- **Shared models** needing version updates +- **Client libraries** requiring endpoint changes +- **Test packages** needing new test scenarios + +### 2.2 Change Impact Assessment + +#### Impact Areas +1. **User-facing changes**: Does this affect user experience? +2. **Structural changes**: Does this change system architecture? +3. **Data model changes**: Does this affect database schemas or data structures? +4. **API changes**: Does this affect interfaces or contracts? +5. **NFR impact**: Does this affect performance, security, or scalability? + +#### Application Layer Impact (if applicable) +- **Code changes**: New entry points, adapters, configurations +- **Dependencies**: New libraries, framework changes +- **Configuration**: Environment variables, config files +- **Testing**: Unit tests, integration tests + +#### Infrastructure Layer Impact (if applicable) +- **Deployment model**: Lambda→ECS, EC2→Fargate, etc. +- **Networking**: VPC, security groups, load balancers +- **Storage**: Persistent volumes, shared storage +- **Scaling**: Auto-scaling policies, capacity planning + +#### Operations Layer Impact (if applicable) +- **Monitoring**: CloudWatch, custom metrics, dashboards +- **Logging**: Log aggregation, structured logging +- **Alerting**: Alarm configurations, notification channels +- **Deployment**: CI/CD pipeline changes, rollback strategies + +### 2.3 Component Relationship Mapping (Brownfield Only) + +**IF brownfield project**, create component dependency graph: + +```markdown +## Component Relationships +- **Primary Component**: [Package being changed] +- **Infrastructure Components**: [CDK/Terraform packages] +- **Shared Components**: [Models, utilities, clients] +- **Dependent Components**: [Services that call this component] +- **Supporting Components**: [Monitoring, logging, deployment] +``` + +For each related component: +- **Change Type**: Major, Minor, Configuration-only +- **Change Reason**: Direct dependency, deployment model, networking +- **Change Priority**: Critical, Important, Optional + +### 2.4 Risk Assessment + +Evaluate risk level: +1. **Low**: Isolated change, easy rollback, well-understood +2. **Medium**: Multiple components, moderate rollback, some unknowns +3. **High**: System-wide impact, complex rollback, significant unknowns +4. **Critical**: Production-critical, difficult rollback, high uncertainty + +## Step 3: Phase Determination + +### 3.1 User Stories - Already Executed or Skip? +**Already executed**: Move to next determination +**Not executed - Execute IF**: +- Multiple user personas +- User experience impact +- Acceptance criteria needed +- Team collaboration required + +**Skip IF**: +- Internal refactoring +- Bug fix with clear reproduction +- Technical debt reduction +- Infrastructure changes + +### 3.2 Application Design - Execute IF: +- New components or services needed +- Component methods and business rules need definition +- Service layer design required +- Component dependencies need clarification + +**Skip IF**: +- Changes within existing component boundaries +- No new components or methods +- Pure implementation changes + +### 3.3 Design (Units Planning/Generation) - Execute IF: +- New data models or schemas +- API changes or new endpoints +- Complex algorithms or business logic +- State management changes +- Multiple packages require changes +- Infrastructure-as-code updates needed + +**Skip IF**: +- Simple logic changes +- UI-only changes +- Configuration updates +- Straightforward implementations + +### 3.4 NFR Implementation - Execute IF: +- Performance requirements +- Security considerations +- Scalability concerns +- Monitoring/observability needed + +**Skip IF**: +- Existing NFR setup sufficient +- No new NFR requirements +- Simple changes with no NFR impact + +## Step 4: Note Adaptive Detail + +**See [depth-levels.md](../common/depth-levels.md) for adaptive depth explanation** + +For each stage that will execute: +- All defined artifacts will be created +- Detail level within artifacts adapts to problem complexity +- Model determines appropriate detail based on problem characteristics + +## Step 5: Multi-Module Coordination Analysis (Brownfield Only) + +**IF brownfield with multiple modules/packages**, analyze dependencies and determine optimal update strategy: + +### 5.1 Analyze Module Dependencies +- Examine build system dependencies and dependency manifests +- Identify build-time vs runtime dependencies +- Map API contracts and shared interfaces between modules + +### 5.2 Determine Update Strategy +Based on dependency analysis, decide: +- **Update sequence**: Which modules must be updated first due to dependencies +- **Parallelization opportunities**: Which modules can be updated simultaneously +- **Coordination requirements**: Version compatibility, API contracts, deployment order +- **Testing strategy**: Per-module vs integrated testing approach +- **Rollback strategy**: Recovery plan if mid-sequence failures occur + +### 5.3 Document Coordination Plan +```markdown +## Module Update Strategy +- **Update Approach**: [Sequential/Parallel/Hybrid] +- **Critical Path**: [Modules that block other updates] +- **Coordination Points**: [Shared APIs, infrastructure, data contracts] +- **Testing Checkpoints**: [When to validate integration] +``` + +Identify for each affected module: +- **Update priority**: Must-update-first vs can-update-later +- **Dependency constraints**: What it depends on, what depends on it +- **Change scope**: Major (breaking), Minor (compatible), Patch (fixes) + +## Step 6: Generate Workflow Visualization + +Create Mermaid flowchart showing: +- All phases in sequence +- EXECUTE or SKIP decision for each conditional phase +- Proper styling for each phase state + +**Styling rules** (add after flowchart): +``` +style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff +style CP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff +style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff +style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff +style US fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 +style Start fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 +style End fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000 + +linkStyle default stroke:#333,stroke-width:2px +``` + +**Style Guidelines**: +- Completed/Always execute: `fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff` (Material Green with white text) +- Conditional EXECUTE: `fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000` (Material Orange with black text) +- Conditional SKIP: `fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000` (Material Gray with black text) +- Start/End: `fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000` (Material Purple with black text) +- Phase containers: Use lighter Material colors (INCEPTION: #BBDEFB, CONSTRUCTION: #C8E6C9, OPERATIONS: #FFF59D) + +## Step 7: Create Execution Plan Document + +Create `aidlc-docs/inception/plans/execution-plan.md`: + +```markdown +# Execution Plan + +## Detailed Analysis Summary + +### Transformation Scope (Brownfield Only) +- **Transformation Type**: [Single component/Architectural/Infrastructure] +- **Primary Changes**: [Description] +- **Related Components**: [List] + +### Change Impact Assessment +- **User-facing changes**: [Yes/No - Description] +- **Structural changes**: [Yes/No - Description] +- **Data model changes**: [Yes/No - Description] +- **API changes**: [Yes/No - Description] +- **NFR impact**: [Yes/No - Description] + +### Component Relationships (Brownfield Only) +[Component dependency graph] + +### Risk Assessment +- **Risk Level**: [Low/Medium/High/Critical] +- **Rollback Complexity**: [Easy/Moderate/Difficult] +- **Testing Complexity**: [Simple/Moderate/Complex] + +## Workflow Visualization + +```mermaid +flowchart TD + Start(["User Request"]) + + subgraph INCEPTION["🔵 INCEPTION PHASE"] + WD["Workspace Detection
STATUS"] + RE["Reverse Engineering
STATUS"] + RA["Requirements Analysis
STATUS"] + US["User Stories
STATUS"] + WP["Workflow Planning
STATUS"] + AD["Application Design
STATUS"] + UP["Units Planning
STATUS"] + UG["Units Generation
STATUS"] + end + + subgraph CONSTRUCTION["🟢 CONSTRUCTION PHASE"] + FD["Functional Design
STATUS"] + NFRA["NFR Requirements
STATUS"] + NFRD["NFR Design
STATUS"] + ID["Infrastructure Design
STATUS"] + CP["Code Planning
EXECUTE"] + CG["Code Generation
EXECUTE"] + BT["Build and Test
EXECUTE"] + end + + subgraph OPERATIONS["🟡 OPERATIONS PHASE"] + OPS["Operations
PLACEHOLDER"] + end + + Start --> WD + WD --> RA + RA --> WP + WP --> CP + CP --> CG + CG --> BT + BT --> End(["Complete"]) + + %% Replace STATUS with COMPLETED, SKIP, EXECUTE as appropriate + %% Apply styling based on status +``` + +**Note**: Replace STATUS placeholders with actual phase status (COMPLETED/SKIP/EXECUTE) and apply appropriate styling + +## Phases to Execute + +### 🔵 INCEPTION PHASE +- [x] Workspace Detection (COMPLETED) +- [x] Reverse Engineering (COMPLETED/SKIPPED) +- [x] Requirements Elaboration (COMPLETED) +- [x] User Stories (COMPLETED/SKIPPED) +- [x] Execution Plan (IN PROGRESS) +- [ ] Application Design - [EXECUTE/SKIP] + - **Rationale**: [Why executing or skipping] +- [ ] Units Planning - [EXECUTE/SKIP] + - **Rationale**: [Why executing or skipping] +- [ ] Units Generation - [EXECUTE/SKIP] + - **Rationale**: [Why executing or skipping] + +### 🟢 CONSTRUCTION PHASE +- [ ] Functional Design - [EXECUTE/SKIP] + - **Rationale**: [Why executing or skipping] +- [ ] NFR Requirements - [EXECUTE/SKIP] + - **Rationale**: [Why executing or skipping] +- [ ] NFR Design - [EXECUTE/SKIP] + - **Rationale**: [Why executing or skipping] +- [ ] Infrastructure Design - [EXECUTE/SKIP] + - **Rationale**: [Why executing or skipping] +- [ ] Code Planning - EXECUTE (ALWAYS) + - **Rationale**: Implementation approach needed +- [ ] Code Generation - EXECUTE (ALWAYS) + - **Rationale**: Code implementation needed +- [ ] Build and Test - EXECUTE (ALWAYS) + - **Rationale**: Build, test, and verification needed + +### 🟡 OPERATIONS PHASE +- [ ] Operations - PLACEHOLDER + - **Rationale**: Future deployment and monitoring workflows + +## Package Change Sequence (Brownfield Only) +[If applicable, list package update sequence with dependencies] + +## Estimated Timeline +- **Total Phases**: [Number] +- **Estimated Duration**: [Time estimate] + +## Success Criteria +- **Primary Goal**: [Main objective] +- **Key Deliverables**: [List] +- **Quality Gates**: [List] + +[IF brownfield] +- **Integration Testing**: All components working together +- **Operational Readiness**: Monitoring, logging, alerting working +``` + +## Step 8: Initialize State Tracking + +Update `aidlc-docs/aidlc-state.md`: + +```markdown +# AI-DLC State Tracking + +## Project Information +- **Project Type**: [Greenfield/Brownfield] +- **Start Date**: [ISO timestamp] +- **Current Stage**: INCEPTION - Workflow Planning + +## Execution Plan Summary +- **Total Stages**: [Number] +- **Stages to Execute**: [List] +- **Stages to Skip**: [List with reasons] + +## Stage Progress + +### 🔵 INCEPTION PHASE +- [x] Workspace Detection +- [x] Reverse Engineering (if applicable) +- [x] Requirements Analysis +- [x] User Stories (if applicable) +- [x] Workflow Planning +- [ ] Application Design - [EXECUTE/SKIP] +- [ ] Units Planning - [EXECUTE/SKIP] +- [ ] Units Generation - [EXECUTE/SKIP] + +### 🟢 CONSTRUCTION PHASE +- [ ] Functional Design - [EXECUTE/SKIP] +- [ ] NFR Requirements - [EXECUTE/SKIP] +- [ ] NFR Design - [EXECUTE/SKIP] +- [ ] Infrastructure Design - [EXECUTE/SKIP] +- [ ] Code Planning - EXECUTE +- [ ] Code Generation - EXECUTE +- [ ] Build and Test - EXECUTE + +### 🟡 OPERATIONS PHASE +- [ ] Operations - PLACEHOLDER + +## Current Status +- **Lifecycle Phase**: INCEPTION +- **Current Stage**: Workflow Planning Complete +- **Next Stage**: [Next stage to execute] +- **Status**: Ready to proceed +``` + +## Step 9: Present Plan to User + +```markdown +# 📋 Workflow Planning Complete + +I've created a comprehensive execution plan based on: +- Your request: [Summary] +- Existing system: [Summary if brownfield] +- Requirements: [Summary if executed] +- User stories: [Summary if executed] + +**Detailed Analysis**: +- Risk level: [Level] +- Impact: [Summary of key impacts] +- Components affected: [List] + +**Recommended Execution Plan**: + +I recommend executing [X] stages: + +🔵 **INCEPTION PHASE:** +1. [Stage name] - *Rationale:* [Why executing] +2. [Stage name] - *Rationale:* [Why executing] +... + +🟢 **CONSTRUCTION PHASE:** +3. [Stage name] - *Rationale:* [Why executing] +4. [Stage name] - *Rationale:* [Why executing] +... + +I recommend skipping [Y] stages: + +🔵 **INCEPTION PHASE:** +1. [Stage name] - *Rationale:* [Why skipping] +2. [Stage name] - *Rationale:* [Why skipping] +... + +🟢 **CONSTRUCTION PHASE:** +3. [Stage name] - *Rationale:* [Why skipping] +4. [Stage name] - *Rationale:* [Why skipping] +... + +[IF brownfield with multiple packages] +**Recommended Package Update Sequence**: +1. [Package] - [Reason] +2. [Package] - [Reason] +... + +**Estimated Timeline**: [Duration] + +> **📋 **REVIEW REQUIRED:**** +> Please examine the execution plan at: `aidlc-docs/inception/plans/execution-plan.md` + +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the execution plan if required +> [IF any stages are skipped:] +> 📝 **Add Skipped Stages** - Choose to include stages currently marked as SKIP +> ✅ **Approve & Continue** - Approve plan and proceed to **[Next Stage Name]** +``` + +## Step 10: Handle User Response + +- **If approved**: Proceed to next stage in execution plan +- **If changes requested**: Update execution plan and re-confirm +- **If user wants to force include/exclude stages**: Update plan accordingly + +## Step 11: Log Interaction + +Log in `aidlc-docs/audit.md`: + +```markdown +## Workflow Planning - Approval +**Timestamp**: [ISO timestamp] +**AI Prompt**: "Ready to proceed with this plan?" +**User Response**: "[User's COMPLETE RAW response]" +**Status**: [Approved/Changes Requested] +**Context**: Workflow plan created with [X] stages to execute + +--- +``` diff --git a/aidlc/rule-details/inception/workspace-detection.md b/aidlc/rule-details/inception/workspace-detection.md new file mode 100644 index 0000000..b21b413 --- /dev/null +++ b/aidlc/rule-details/inception/workspace-detection.md @@ -0,0 +1,93 @@ +# Workspace Detection + +**Purpose**: Determine workspace state and check for existing AI-DLC projects + +## Step 1: Check for Existing AI-DLC Project + +Check if `aidlc-docs/aidlc-state.md` exists: +- **If exists**: Resume from last phase (load context from previous phases) +- **If not exists**: Continue with new project assessment + +## Step 2: Scan Workspace for Existing Code + +**Determine if workspace has existing code:** +- Scan workspace for source code files (.java, .py, .js, .ts, .jsx, .tsx, .kt, .kts, .scala, .groovy, .go, .rs, .rb, .php, .c, .h, .cpp, .hpp, .cc, .cs, .fs, etc.) +- Check for build files (pom.xml, package.json, build.gradle, etc.) +- Look for project structure indicators +- Identify workspace root directory (NOT aidlc-docs/) + +**Record findings:** +```markdown +## Workspace State +- **Existing Code**: [Yes/No] +- **Programming Languages**: [List if found] +- **Build System**: [Maven/Gradle/npm/etc. if found] +- **Project Structure**: [Monolith/Microservices/Library/Empty] +- **Workspace Root**: [Absolute path] +``` + +## Step 3: Determine Next Phase + +**IF workspace is empty (no existing code)**: +- Set flag: `brownfield = false` +- Next phase: Requirements Analysis + +**IF workspace has existing code**: +- Set flag: `brownfield = true` +- Check for existing reverse engineering artifacts in `aidlc-docs/inception/reverse-engineering/` +- **IF reverse engineering artifacts exist**: Load them, skip to Requirements Analysis +- **IF no reverse engineering artifacts**: Next phase is Reverse Engineering + +## Step 4: Create Initial State File + +Create `aidlc-docs/aidlc-state.md`: + +```markdown +# AI-DLC State Tracking + +## Project Information +- **Project Type**: [Greenfield/Brownfield] +- **Start Date**: [ISO timestamp] +- **Current Stage**: INCEPTION - Workspace Detection + +## Workspace State +- **Existing Code**: [Yes/No] +- **Reverse Engineering Needed**: [Yes/No] +- **Workspace Root**: [Absolute path] + +## Code Location Rules +- **Application Code**: Workspace root (NEVER in aidlc-docs/) +- **Documentation**: aidlc-docs/ only +- **Structure patterns**: See code-generation.md Critical Rules + +## Stage Progress +[Will be populated as workflow progresses] +``` + +## Step 5: Present Completion Message + +**For Brownfield Projects:** +```markdown +# 🔍 Workspace Detection Complete + +Workspace analysis findings: +• **Project Type**: Brownfield project +• [AI-generated summary of workspace findings in bullet points] +• **Next Step**: Proceeding to **Reverse Engineering** to analyze existing codebase... +``` + +**For Greenfield Projects:** +```markdown +# 🔍 Workspace Detection Complete + +Workspace analysis findings: +• **Project Type**: Greenfield project +• **Next Step**: Proceeding to **Requirements Analysis**... +``` + +## Step 6: Automatically Proceed + +- **No user approval required** - this is informational only +- Automatically proceed to next phase: + - **Brownfield**: Reverse Engineering (if no existing artifacts) or Requirements Analysis (if artifacts exist) + - **Greenfield**: Requirements Analysis diff --git a/aidlc/rule-details/operations/operations.md b/aidlc/rule-details/operations/operations.md new file mode 100644 index 0000000..5f565dc --- /dev/null +++ b/aidlc/rule-details/operations/operations.md @@ -0,0 +1,19 @@ +# Operations + +**Purpose**: Placeholder for future operational phases (deployment, monitoring, maintenance) + +**Status**: This phase is currently a placeholder and will be expanded in future versions. + +## Future Scope + +The Operations phase will eventually include: +- Deployment planning and execution +- Monitoring and observability setup +- Incident response procedures +- Maintenance and support workflows +- Production readiness checklists + +## Current State + +All build and test activities have been moved to the CONSTRUCTION phase. +The AI-DLC workflow currently ends after the Build and Test phase in CONSTRUCTION. diff --git a/aidlc/steering/core-workflow.md b/aidlc/steering/core-workflow.md new file mode 100644 index 0000000..4bf8320 --- /dev/null +++ b/aidlc/steering/core-workflow.md @@ -0,0 +1,510 @@ +# PRIORITY: This workflow OVERRIDES all other built-in workflows +# When user requests software development, ALWAYS follow this workflow FIRST + +## Adaptive Workflow Principle +**The workflow adapts to the work, not the other way around.** + +The AI model intelligently assesses what stages are needed based on: +1. User's stated intent and clarity +2. Existing codebase state (if any) +3. Complexity and scope of change +4. Risk and impact assessment + +## MANDATORY: Rule Details Loading +**CRITICAL**: When performing any phase, you MUST read and use relevant content from rule detail files in `rule-details/` directory within this power. + +**Common Rules**: ALWAYS load common rules at workflow start: +- Load `common/process-overview.md` for workflow overview +- Load `common/session-continuity.md` for session resumption guidance +- Load `common/content-validation.md` for content validation requirements +- Load `common/question-format-guide.md` for question formatting rules +- Reference these throughout the workflow execution + +## MANDATORY: Content Validation +**CRITICAL**: Before creating ANY file, you MUST validate content according to `common/content-validation.md` rules: +- Validate Mermaid diagram syntax +- Validate ASCII art diagrams (see `common/ascii-diagram-standards.md`) +- Escape special characters properly +- Provide text alternatives for complex visual content +- Test content parsing compatibility + +## MANDATORY: Question File Format +**CRITICAL**: When asking questions at any phase, you MUST follow question format guidelines. + +**See `common/question-format-guide.md` for complete question formatting rules including**: +- Multiple choice format (A, B, C, D, E options) +- [Answer]: tag usage +- Answer validation and ambiguity resolution + +## MANDATORY: Custom Welcome Message +**CRITICAL**: When starting ANY software development request, you MUST display the welcome message. + +**How to Display Welcome Message**: +1. Load the welcome message from `rule-details/common/welcome-message.md` within this power +2. Display the complete message to the user +3. This should only be done ONCE at the start of a new workflow +4. Do NOT load this file in subsequent interactions to save context space + +# Adaptive Software Development Workflow + +--- + +# INCEPTION PHASE + +**Purpose**: Planning, requirements gathering, and architectural decisions + +**Focus**: Determine WHAT to build and WHY + +**Stages in INCEPTION PHASE**: +- Workspace Detection (ALWAYS) +- Reverse Engineering (CONDITIONAL - Brownfield only) +- Requirements Analysis (ALWAYS - Adaptive depth) +- User Stories (CONDITIONAL) +- Workflow Planning (ALWAYS) +- Application Design (CONDITIONAL) +- Units Generation (CONDITIONAL) + +--- + +## Workspace Detection (ALWAYS EXECUTE) + +1. **MANDATORY**: Log initial user request in audit.md with complete raw input +2. Load all steps from `inception/workspace-detection.md` +3. Execute workspace detection: + - Check for existing aidlc-state.md (resume if found) + - Scan workspace for existing code + - Determine if brownfield or greenfield + - Check for existing reverse engineering artifacts +4. Determine next phase: Reverse Engineering (if brownfield and no artifacts) OR Requirements Analysis +5. **MANDATORY**: Log findings in audit.md +6. Present completion message to user (see workspace-detection.md for message formats) +7. Automatically proceed to next phase + +## Reverse Engineering (CONDITIONAL - Brownfield Only) + +**Execute IF**: +- Existing codebase detected +- No previous reverse engineering artifacts found + +**Skip IF**: +- Greenfield project +- Previous reverse engineering artifacts exist + +**Execution**: +1. **MANDATORY**: Log start of reverse engineering in audit.md +2. Load all steps from `inception/reverse-engineering.md` +3. Execute reverse engineering: + - Analyze all packages and components + - Generate a busienss overview of the whole system covering the business transactions + - Generate architecture documentation + - Generate code structure documentation + - Generate API documentation + - Generate component inventory + - Generate Interaction Diagrams depicting how business transactions are implemented across components + - Generate technology stack documentation + - Generate dependencies documentation + +4. **Wait for Explicit Approval**: Present detailed completion message (see reverse-engineering.md for message format) - DO NOT PROCEED until user confirms +5. **MANDATORY**: Log user's response in audit.md with complete raw input + +## Requirements Analysis (ALWAYS EXECUTE - Adaptive Depth) + +**Always executes** but depth varies based on request clarity and complexity: +- **Minimal**: Simple, clear request - just document intent analysis +- **Standard**: Normal complexity - gather functional and non-functional requirements +- **Comprehensive**: Complex, high-risk - detailed requirements with traceability + +**Execution**: +1. **MANDATORY**: Log any user input during this phase in audit.md +2. Load all steps from `inception/requirements-analysis.md` +3. Execute requirements analysis: + - Load reverse engineering artifacts (if brownfield) + - Analyze user request (intent analysis) + - Determine requirements depth needed + - Assess current requirements + - Ask clarifying questions (if needed) + - Generate requirements document +4. Execute at appropriate depth (minimal/standard/comprehensive) +5. **Wait for Explicit Approval**: Follow approval format from requirements-analysis.md detailed steps - DO NOT PROCEED until user confirms +6. **MANDATORY**: Log user's response in audit.md with complete raw input + +## User Stories (CONDITIONAL) + +**INTELLIGENT ASSESSMENT**: Use multi-factor analysis to determine if user stories add value: + +**ALWAYS Execute IF** (High Priority Indicators): +- New user-facing features or functionality +- Changes affecting user workflows or interactions +- Multiple user types or personas involved +- Complex business requirements with acceptance criteria needs +- Cross-functional team collaboration required +- Customer-facing API or service changes +- New product capabilities or enhancements + +**LIKELY Execute IF** (Medium Priority - Assess Complexity): +- Modifications to existing user-facing features +- Backend changes that indirectly affect user experience +- Integration work that impacts user workflows +- Performance improvements with user-visible benefits +- Security enhancements affecting user interactions +- Data model changes affecting user data or reports + +**COMPLEXITY-BASED ASSESSMENT**: For medium priority cases, execute user stories if: +- Request involves multiple components or services +- Changes span multiple user touchpoints +- Business logic is complex or has multiple scenarios +- Requirements have ambiguity that stories could clarify +- Implementation affects multiple user journeys +- Change has significant business impact or risk + +**SKIP ONLY IF** (Low Priority - Simple Cases): +- Pure internal refactoring with zero user impact +- Simple bug fixes with clear, isolated scope +- Infrastructure changes with no user-facing effects +- Technical debt cleanup with no functional changes +- Developer tooling or build process improvements +- Documentation-only updates + +**ASSESSMENT CRITERIA**: When in doubt, favor inclusion of user stories for: +- Requests with business stakeholder involvement +- Changes requiring user acceptance testing +- Features with multiple implementation approaches +- Work that benefits from shared team understanding +- Projects where requirements clarity is valuable + +**ASSESSMENT PROCESS**: +1. Analyze request complexity and scope +2. Identify user impact (direct or indirect) +3. Evaluate business context and stakeholder needs +4. Consider team collaboration benefits +5. Default to inclusion for borderline cases + +**Note**: If Requirements Analysis executed, Stories can reference and build upon those requirements. + +**User Stories has two parts within one stage**: +1. **Part 1 - Planning**: Create story plan with questions, collect answers, analyze for ambiguities, get approval +2. **Part 2 - Generation**: Execute approved plan to generate stories and personas + +**Execution**: +1. **MANDATORY**: Log any user input during this phase in audit.md +2. Load all steps from `inception/user-stories.md` +3. **MANDATORY**: Perform intelligent assessment (Step 1 in user-stories.md) to validate user stories are needed +4. Load reverse engineering artifacts (if brownfield) +5. If Requirements exist, reference them when creating stories +6. Execute at appropriate depth (minimal/standard/comprehensive) +7. **PART 1 - Planning**: Create story plan with questions, wait for user answers, analyze for ambiguities, get approval +8. **PART 2 - Generation**: Execute approved plan to generate stories and personas +9. **Wait for Explicit Approval**: Follow approval format from user-stories.md detailed steps - DO NOT PROCEED until user confirms +10. **MANDATORY**: Log user's response in audit.md with complete raw input + +## Workflow Planning (ALWAYS EXECUTE) + +1. **MANDATORY**: Log any user input during this phase in audit.md +2. Load all steps from `inception/workflow-planning.md` +3. **MANDATORY**: Load content validation rules from `common/content-validation.md` +4. Load all prior context: + - Reverse engineering artifacts (if brownfield) + - Intent analysis + - Requirements (if executed) + - User stories (if executed) +5. Execute workflow planning: + - Determine which phases to execute + - Determine depth level for each phase + - Create multi-package change sequence (if brownfield) + - Generate workflow visualization (VALIDATE Mermaid syntax before writing) +6. **MANDATORY**: Validate all content before file creation per content-validation.md rules +7. **Wait for Explicit Approval**: Present recommendations using language from workflow-planning.md Step 9, emphasizing user control to override recommendations - DO NOT PROCEED until user confirms +8. **MANDATORY**: Log user's response in audit.md with complete raw input + +## Application Design (CONDITIONAL) + +**Execute IF**: +- New components or services needed +- Component methods and business rules need definition +- Service layer design required +- Component dependencies need clarification + +**Skip IF**: +- Changes within existing component boundaries +- No new components or methods +- Pure implementation changes + +**Execution**: +1. **MANDATORY**: Log any user input during this phase in audit.md +2. Load all steps from `inception/application-design.md` +3. Load reverse engineering artifacts (if brownfield) +4. Execute at appropriate depth (minimal/standard/comprehensive) +5. **Wait for Explicit Approval**: Present detailed completion message (see application-design.md for message format) - DO NOT PROCEED until user confirms +6. **MANDATORY**: Log user's response in audit.md with complete raw input + +## Units Generation (CONDITIONAL) + +**Execute IF**: +- System needs decomposition into multiple units of work +- Multiple services or modules required +- Complex system requiring structured breakdown + +**Skip IF**: +- Single simple unit +- No decomposition needed +- Straightforward single-component implementation + +**Execution**: +1. **MANDATORY**: Log any user input during this phase in audit.md +2. Load all steps from `inception/units-generation.md` +3. Load reverse engineering artifacts (if brownfield) +4. Execute at appropriate depth (minimal/standard/comprehensive) +5. **Wait for Explicit Approval**: Present detailed completion message (see units-generation.md for message format) - DO NOT PROCEED until user confirms +6. **MANDATORY**: Log user's response in audit.md with complete raw input + +--- + +# 🟢 CONSTRUCTION PHASE + +**Purpose**: Detailed design, NFR implementation, and code generation + +**Focus**: Determine HOW to build it + +**Stages in CONSTRUCTION PHASE**: +- Per-Unit Loop (executes for each unit): + - Functional Design (CONDITIONAL, per-unit) + - NFR Requirements (CONDITIONAL, per-unit) + - NFR Design (CONDITIONAL, per-unit) + - Infrastructure Design (CONDITIONAL, per-unit) + - Code Generation (ALWAYS, per-unit) +- Build and Test (ALWAYS - after all units complete) + +**Note**: Each unit is completed fully (design + code) before moving to the next unit. + +--- + +## Per-Unit Loop (Executes for Each Unit) + +**For each unit of work, execute the following stages in sequence:** + +### Functional Design (CONDITIONAL, per-unit) + +**Execute IF**: +- New data models or schemas +- Complex business logic +- Business rules need detailed design + +**Skip IF**: +- Simple logic changes +- No new business logic + +**Execution**: +1. **MANDATORY**: Log any user input during this stage in audit.md +2. Load all steps from `construction/functional-design.md` +3. Execute functional design for this unit +4. **MANDATORY**: Present standardized 2-option completion message as defined in functional-design.md - DO NOT use emergent 3-option behavior +5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms +6. **MANDATORY**: Log user's response in audit.md with complete raw input + +### NFR Requirements (CONDITIONAL, per-unit) + +**Execute IF**: +- Performance requirements exist +- Security considerations needed +- Scalability concerns present +- Tech stack selection required + +**Skip IF**: +- No NFR requirements +- Tech stack already determined + +**Execution**: +1. **MANDATORY**: Log any user input during this stage in audit.md +2. Load all steps from `construction/nfr-requirements.md` +3. Execute NFR assessment for this unit +4. **MANDATORY**: Present standardized 2-option completion message as defined in nfr-requirements.md - DO NOT use emergent behavior +5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms +6. **MANDATORY**: Log user's response in audit.md with complete raw input + +### NFR Design (CONDITIONAL, per-unit) + +**Execute IF**: +- NFR Requirements was executed +- NFR patterns need to be incorporated + +**Skip IF**: +- No NFR requirements +- NFR Requirements Assessment was skipped + +**Execution**: +1. **MANDATORY**: Log any user input during this stage in audit.md +2. Load all steps from `construction/nfr-design.md` +3. Execute NFR design for this unit +4. **MANDATORY**: Present standardized 2-option completion message as defined in nfr-design.md - DO NOT use emergent behavior +5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms +6. **MANDATORY**: Log user's response in audit.md with complete raw input + +### Infrastructure Design (CONDITIONAL, per-unit) + +**Execute IF**: +- Infrastructure services need mapping +- Deployment architecture required +- Cloud resources need specification + +**Skip IF**: +- No infrastructure changes +- Infrastructure already defined + +**Execution**: +1. **MANDATORY**: Log any user input during this stage in audit.md +2. Load all steps from `construction/infrastructure-design.md` +3. Execute infrastructure design for this unit +4. **MANDATORY**: Present standardized 2-option completion message as defined in infrastructure-design.md - DO NOT use emergent behavior +5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms +6. **MANDATORY**: Log user's response in audit.md with complete raw input + +### Code Generation (ALWAYS EXECUTE, per-unit) + +**Always executes for each unit** + +**Code Generation has two parts within one stage**: +1. **Part 1 - Planning**: Create detailed code generation plan with explicit steps +2. **Part 2 - Generation**: Execute approved plan to generate code, tests, and artifacts + +**Execution**: +1. **MANDATORY**: Log any user input during this stage in audit.md +2. Load all steps from `construction/code-generation.md` +3. **PART 1 - Planning**: Create code generation plan with checkboxes, get user approval +4. **PART 2 - Generation**: Execute approved plan to generate code for this unit +5. **MANDATORY**: Present standardized 2-option completion message as defined in code-generation.md - DO NOT use emergent behavior +6. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms +7. **MANDATORY**: Log user's response in audit.md with complete raw input + +--- + +## Build and Test (ALWAYS EXECUTE) + +1. **MANDATORY**: Log any user input during this phase in audit.md +2. Load all steps from `construction/build-and-test.md` +3. Generate comprehensive build and test instructions: + - Build instructions for all units + - Unit test execution instructions + - Integration test instructions (test interactions between units) + - Performance test instructions (if applicable) + - Additional test instructions as needed (contract tests, security tests, e2e tests) +4. Create instruction files in build-and-test/ subdirectory: build-instructions.md, unit-test-instructions.md, integration-test-instructions.md, performance-test-instructions.md, build-and-test-summary.md +5. **Wait for Explicit Approval**: Ask: "**Build and test instructions complete. Ready to proceed to Operations stage?**" - DO NOT PROCEED until user confirms +6. **MANDATORY**: Log user's response in audit.md with complete raw input + +--- + +# 🟡 OPERATIONS PHASE + +**Purpose**: Placeholder for future deployment and monitoring workflows + +**Focus**: How to DEPLOY and RUN it (future expansion) + +**Stages in OPERATIONS PHASE**: +- Operations (PLACEHOLDER) + +--- + +## Operations (PLACEHOLDER) + +**Status**: This stage is currently a placeholder for future expansion. + +The Operations stage will eventually include: +- Deployment planning and execution +- Monitoring and observability setup +- Incident response procedures +- Maintenance and support workflows +- Production readiness checklists + +**Current State**: All build and test activities are handled in the CONSTRUCTION phase. + +## Key Principles + +- **Adaptive Execution**: Only execute stages that add value +- **Transparent Planning**: Always show execution plan before starting +- **User Control**: User can request stage inclusion/exclusion +- **Progress Tracking**: Update aidlc-state.md with executed and skipped stages +- **Complete Audit Trail**: Log ALL user inputs and AI responses in audit.md with timestamps + - **CRITICAL**: Capture user's COMPLETE RAW INPUT exactly as provided + - **CRITICAL**: Never summarize or paraphrase user input in audit log + - **CRITICAL**: Log every interaction, not just approvals +- **Quality Focus**: Complex changes get full treatment, simple changes stay efficient +- **Content Validation**: Always validate content before file creation per content-validation.md rules +- **NO EMERGENT BEHAVIOR**: Construction phases MUST use standardized 2-option completion messages as defined in their respective rule files. DO NOT create 3-option menus or other emergent navigation patterns. + +## MANDATORY: Plan-Level Checkbox Enforcement + +### MANDATORY RULES FOR PLAN EXECUTION +1. **NEVER complete any work without updating plan checkboxes** +2. **IMMEDIATELY after completing ANY step described in a plan file, mark that step [x]** +3. **This must happen in the SAME interaction where the work is completed** +4. **NO EXCEPTIONS**: Every plan step completion MUST be tracked with checkbox updates + +### Two-Level Checkbox Tracking System +- **Plan-Level**: Track detailed execution progress within each stage +- **Stage-Level**: Track overall workflow progress in aidlc-state.md +- **Update immediately**: All progress updates in SAME interaction where work is completed + +## Prompts Logging Requirements +- **MANDATORY**: Log EVERY user input (prompts, questions, responses) with timestamp in audit.md +- **MANDATORY**: Capture user's COMPLETE RAW INPUT exactly as provided (never summarize) +- **MANDATORY**: Log every approval prompt with timestamp before asking the user +- **MANDATORY**: Record every user response with timestamp after receiving it +- **CRITICAL**: ALWAYS append changes to EDIT audit.md file, NEVER use tools and commands that completely overwrite its contents +- **CRITICAL**: Using file writing tools and commands that overwrite contents of the entire audit.md and cause duplication +- Use ISO 8601 format for timestamps (YYYY-MM-DDTHH:MM:SSZ) +- Include stage context for each entry + +### Audit Log Format: +```markdown +## [Stage Name or Interaction Type] +**Timestamp**: [ISO timestamp] +**User Input**: "[Complete raw user input - never summarized]" +**AI Response**: "[AI's response or action taken]" +**Context**: [Stage, action, or decision made] + +--- +``` + +### Correct Tool Usage for audit.md + +✅ CORRECT: + +1. Read the audit.md file +2. Append/Edit the file to make changes + +❌ WRONG: + +1. Read the audit.md file +2. Completely overwrite the audit.md with the contents of what you read, plus the new changes you want to add to it + +## Directory Structure + +```text +/ # ⚠️ APPLICATION CODE HERE +├── [project-specific structure] # Varies by project (see code-generation.md) +│ +├── aidlc-docs/ # 📄 DOCUMENTATION ONLY +│ ├── inception/ # 🔵 INCEPTION PHASE +│ │ ├── plans/ +│ │ ├── reverse-engineering/ # Brownfield only +│ │ ├── requirements/ +│ │ ├── user-stories/ +│ │ └── application-design/ +│ ├── construction/ # 🟢 CONSTRUCTION PHASE +│ │ ├── plans/ +│ │ ├── {unit-name}/ +│ │ │ ├── functional-design/ +│ │ │ ├── nfr-requirements/ +│ │ │ ├── nfr-design/ +│ │ │ ├── infrastructure-design/ +│ │ │ └── code/ # Markdown summaries only +│ │ └── build-and-test/ +│ ├── operations/ # 🟡 OPERATIONS PHASE (placeholder) +│ ├── aidlc-state.md +│ └── audit.md +``` + +**CRITICAL RULE**: +- Application code: Workspace root (NEVER in aidlc-docs/) +- Documentation: aidlc-docs/ only +- Project structure: See code-generation.md for patterns by project type From 891ba34e66d3d6cf6cd57d9ccd61afad6cf4bb96 Mon Sep 17 00:00:00 2001 From: catface Date: Thu, 8 Jan 2026 00:11:28 +0800 Subject: [PATCH 09/18] refactor(aidlc): Flatten rule-details into steering directory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Move all rule-details files to steering/ with prefix naming - Add language selection as mandatory first step in core-workflow.md - Add inclusion: always frontmatter to core-workflow.md - Simplify POWER.md to essential metadata and activation instructions - Update all internal file references to use new naming convention - Remove redundant README.md File naming convention: {phase}-{filename}.md - common-*.md: Shared rules - inception-*.md: Inception phase rules - construction-*.md: Construction phase rules - operations-*.md: Operations phase rules 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- aidlc/POWER.md | 398 +----------------- aidlc/README.md | 80 ---- .../common-ascii-diagram-standards.md} | 0 .../common-content-validation.md} | 4 +- .../common-depth-levels.md} | 0 .../common-error-handling.md} | 0 .../common-overconfidence-prevention.md} | 0 .../common-process-overview.md} | 0 .../common-question-format-guide.md} | 0 .../common-session-continuity.md} | 0 .../common-terminology.md} | 0 .../common-welcome-message.md} | 0 .../common-workflow-changes.md} | 0 .../construction-build-and-test.md} | 0 .../construction-code-generation.md} | 0 .../construction-functional-design.md} | 0 .../construction-infrastructure-design.md} | 0 .../construction-nfr-design.md} | 0 .../construction-nfr-requirements.md} | 0 aidlc/steering/core-workflow.md | 85 +++- .../inception-application-design.md} | 0 .../inception-requirements-analysis.md} | 2 +- .../inception-reverse-engineering.md} | 0 .../inception-units-generation.md} | 0 .../inception-user-stories.md} | 2 +- .../inception-workflow-planning.md} | 2 +- .../inception-workspace-detection.md} | 0 .../operations-operations.md} | 0 28 files changed, 84 insertions(+), 489 deletions(-) delete mode 100644 aidlc/README.md rename aidlc/{rule-details/common/ascii-diagram-standards.md => steering/common-ascii-diagram-standards.md} (100%) rename aidlc/{rule-details/common/content-validation.md => steering/common-content-validation.md} (95%) rename aidlc/{rule-details/common/depth-levels.md => steering/common-depth-levels.md} (100%) rename aidlc/{rule-details/common/error-handling.md => steering/common-error-handling.md} (100%) rename aidlc/{rule-details/common/overconfidence-prevention.md => steering/common-overconfidence-prevention.md} (100%) rename aidlc/{rule-details/common/process-overview.md => steering/common-process-overview.md} (100%) rename aidlc/{rule-details/common/question-format-guide.md => steering/common-question-format-guide.md} (100%) rename aidlc/{rule-details/common/session-continuity.md => steering/common-session-continuity.md} (100%) rename aidlc/{rule-details/common/terminology.md => steering/common-terminology.md} (100%) rename aidlc/{rule-details/common/welcome-message.md => steering/common-welcome-message.md} (100%) rename aidlc/{rule-details/common/workflow-changes.md => steering/common-workflow-changes.md} (100%) rename aidlc/{rule-details/construction/build-and-test.md => steering/construction-build-and-test.md} (100%) rename aidlc/{rule-details/construction/code-generation.md => steering/construction-code-generation.md} (100%) rename aidlc/{rule-details/construction/functional-design.md => steering/construction-functional-design.md} (100%) rename aidlc/{rule-details/construction/infrastructure-design.md => steering/construction-infrastructure-design.md} (100%) rename aidlc/{rule-details/construction/nfr-design.md => steering/construction-nfr-design.md} (100%) rename aidlc/{rule-details/construction/nfr-requirements.md => steering/construction-nfr-requirements.md} (100%) rename aidlc/{rule-details/inception/application-design.md => steering/inception-application-design.md} (100%) rename aidlc/{rule-details/inception/requirements-analysis.md => steering/inception-requirements-analysis.md} (98%) rename aidlc/{rule-details/inception/reverse-engineering.md => steering/inception-reverse-engineering.md} (100%) rename aidlc/{rule-details/inception/units-generation.md => steering/inception-units-generation.md} (100%) rename aidlc/{rule-details/inception/user-stories.md => steering/inception-user-stories.md} (99%) rename aidlc/{rule-details/inception/workflow-planning.md => steering/inception-workflow-planning.md} (99%) rename aidlc/{rule-details/inception/workspace-detection.md => steering/inception-workspace-detection.md} (100%) rename aidlc/{rule-details/operations/operations.md => steering/operations-operations.md} (100%) diff --git a/aidlc/POWER.md b/aidlc/POWER.md index 4fc2247..d41b913 100644 --- a/aidlc/POWER.md +++ b/aidlc/POWER.md @@ -8,401 +8,37 @@ author: "AWS" # AI-DLC (AI-Driven Development Life Cycle) -## Overview - -AI-DLC is an intelligent software development workflow that adapts to your needs, maintains quality standards, and keeps you in control of the process. It provides a structured approach to software development with three adaptive phases that intelligently determine which stages are needed based on your project's complexity and requirements. - -**CRITICAL FIRST STEP**: Before starting any workflow, you MUST select your preferred language (English or 中文). This is a mandatory, non-negotiable step that determines the language for all subsequent interactions, documentation, and outputs. - -**Key Principles:** -- **Language Selection FIRST**: Mandatory language selection before any workflow steps -- **Adaptive Intelligence**: Only executes stages that add value to your specific request -- **Context-Aware**: Analyzes existing codebase and complexity requirements -- **Risk-Based**: Complex changes get comprehensive treatment, simple changes stay efficient -- **Question-Driven**: Structured multiple-choice questions in files, not chat -- **Always in Control**: Review execution plans and approve each phase -- **Complete Audit Trail**: All decisions and changes are tracked -- **Language Consistency**: All outputs in your selected language - -## Available Steering Files - -This power includes one main steering file that contains the complete workflow: - -- **core-workflow** - Complete AI-DLC workflow with all three phases (Inception, Construction, Operations) - -To access the workflow, use: -``` -Call action "readSteering" with powerName="aidlc", steeringFile="core-workflow.md" -``` - -## Three-Phase Adaptive Workflow - -AI-DLC follows a structured three-phase approach that adapts to your project's complexity: - -### 🔵 INCEPTION PHASE -**Purpose**: Determines **WHAT** to build and **WHY** - -**Stages:** -- **Workspace Detection** (ALWAYS) - Analyze project state and determine greenfield vs brownfield -- **Reverse Engineering** (CONDITIONAL) - Analyze existing codebase for brownfield projects -- **Requirements Analysis** (ALWAYS) - Gather and validate requirements with adaptive depth -- **User Stories** (CONDITIONAL) - Create user stories when they add value -- **Workflow Planning** (ALWAYS) - Determine execution plan for remaining phases -- **Application Design** (CONDITIONAL) - Design components and services when needed -- **Units Generation** (CONDITIONAL) - Break down complex systems into manageable units - -### 🟢 CONSTRUCTION PHASE -**Purpose**: Determines **HOW** to build it - -**Per-Unit Loop** (executes for each unit of work): -- **Functional Design** (CONDITIONAL) - Design data models and business logic -- **NFR Requirements** (CONDITIONAL) - Assess non-functional requirements -- **NFR Design** (CONDITIONAL) - Design NFR implementation patterns -- **Infrastructure Design** (CONDITIONAL) - Design cloud resources and deployment -- **Code Generation** (ALWAYS) - Generate code, tests, and artifacts - -**Final Stage:** -- **Build and Test** (ALWAYS) - Comprehensive build and test instructions - -### 🟡 OPERATIONS PHASE -**Purpose**: How to DEPLOY and RUN it (future expansion) - -**Stages:** -- **Operations** (PLACEHOLDER) - Deployment, monitoring, and maintenance workflows - -## MANDATORY: Language Selection (CRITICAL - NO NEGOTIATION) - -**⚠️ CRITICAL REQUIREMENT - MUST BE EXECUTED FIRST ⚠️** - -**BEFORE ANY OTHER WORKFLOW STEPS**, you **MUST** ask the user to select their preferred language. This step is **MANDATORY** and **CANNOT BE SKIPPED** under any circumstances. - -### Language Selection Rules - -**CRITICAL ENFORCEMENT:** -- ✋ **STOP**: Do NOT proceed with ANY workflow steps until language is selected -- 🚫 **NO NEGOTIATION**: This step MUST be completed first - no exceptions -- ⚠️ **MANDATORY**: Language selection is REQUIRED before displaying welcome message -- 🔒 **NON-SKIPPABLE**: Cannot be bypassed, deferred, or skipped - -### Language Selection Process - -**Step 1: Display Language Selection Prompt** - -Present the following options to the user immediately: - -``` -🌐 LANGUAGE SELECTION (REQUIRED) - -Please select your preferred language for this AI-DLC workflow: - -A) English - All documentation, questions, and outputs will be in English -B) 中文 - 所有文档、问题和输出将使用中文 - -[Answer]: Please respond with A or B -``` - -**Step 2: Wait for User Response** - -- **MUST** wait for explicit user selection (A or B) -- **DO NOT** proceed until valid response received -- If response is unclear, ask again - -**Step 3: Record Language Selection** - -Once language is selected: -1. **MUST** record the selection in `aidlc-docs/aidlc-state.md` immediately -2. **MUST** log the selection in `aidlc-docs/audit.md` with timestamp -3. **MUST** use the selected language for ALL subsequent interactions - -### Language Usage Rules - -**After language selection:** - -- ✅ **If English selected**: All outputs, questions, documentation, and communication in English -- ✅ **If 中文 selected**: 所有输出、问题、文档和交流使用中文 -- 🔄 **Consistency**: MUST maintain selected language throughout entire workflow -- 📝 **Documentation**: All generated files in `aidlc-docs/` MUST use selected language -- 💬 **Questions**: All structured questions MUST be in selected language -- 📊 **Plans**: All execution plans and approval messages MUST be in selected language - -**CRITICAL**: Once language is selected, it CANNOT be changed mid-workflow. User must restart workflow to change language. - ---- - -## How to Use AI-DLC - -### Getting Started - -1. **Activate the workflow** by starting your request with: - ``` - Using AI-DLC, [describe your software development need] - ``` - -2. **MANDATORY FIRST STEP**: Select your preferred language (English or 中文) - - This step MUST be completed before any other workflow steps - - Cannot be skipped or bypassed - -3. **AI-DLC automatically activates** and displays a welcome message (in selected language) - -4. **Follow the guided workflow**: - - Answer structured questions when asked - - Review execution plans before each phase - - Approve or request changes at each stage - - All artifacts are generated in `aidlc-docs/` directory - -### Example Usage - -**Step 1: Activate AI-DLC** -``` -Using AI-DLC, create a REST API for managing user accounts with authentication -``` - -**Step 2: Select Language (MANDATORY)** -``` -AI-DLC will prompt: -🌐 LANGUAGE SELECTION (REQUIRED) -Please select your preferred language: -A) English -B) 中文 - -You respond: A (for English) or B (for 中文) -``` +**CRITICAL - MANDATORY FIRST STEP**: You MUST read and load `steering/core-workflow.md` BEFORE proceeding with ANY other action. This is NON-NEGOTIABLE. Do NOT respond to users, do NOT start any workflow until you have loaded this file. Failure to load this file first is a violation of this power's protocol. -**Step 3: Follow Workflow** -After language selection, AI-DLC proceeds with the workflow in your selected language. +AI-DLC is an intelligent software development workflow that adapts to your needs, maintains quality standards, and keeps you in control of the process. -**Example Scenarios:** - -**Greenfield Project (English):** -``` -Using AI-DLC, create a REST API for managing user accounts with authentication -[Select: A - English] -``` - -**Greenfield Project (中文):** -``` -Using AI-DLC, 创建一个用户账户管理的 REST API,包含身份验证功能 -[选择: B - 中文] -``` - -**Brownfield Project (English):** -``` -Using AI-DLC, add payment processing functionality to the existing e-commerce application -[Select: A - English] -``` - -**Brownfield Project (中文):** -``` -Using AI-DLC, 为现有的电商应用添加支付处理功能 -[选择: B - 中文] -``` - -**Simple Change (English):** -``` -Using AI-DLC, fix the login validation bug in the authentication service -[Select: A - English] -``` - -**Simple Change (中文):** -``` -Using AI-DLC, 修复身份验证服务中的登录验证错误 -[选择: B - 中文] -``` - -## Workflow Adaptation - -AI-DLC intelligently adapts based on: - -1. **User's stated intent and clarity** - Clear requests may skip detailed requirements -2. **Existing codebase state** - Brownfield projects get reverse engineering -3. **Complexity and scope** - Complex changes get comprehensive treatment -4. **Risk and impact assessment** - High-risk changes get extra validation +## Overview -**Depth Levels:** -- **Minimal**: Simple, clear requests with low risk -- **Standard**: Normal complexity with moderate risk -- **Comprehensive**: Complex, high-risk changes requiring detailed analysis +AI-DLC provides a structured approach to software development with three adaptive phases: -## Directory Structure +- **Inception** - Requirements gathering and design (WHAT to build and WHY) +- **Construction** - Implementation and testing (HOW to build it) +- **Operations** - Deployment and monitoring (future expansion) -AI-DLC creates a structured documentation hierarchy: +## Activation Trigger +When user starts any request with: ``` -/ # Application code lives here -├── [project-specific structure] # Your actual code -│ -├── aidlc-docs/ # All AI-DLC documentation -│ ├── inception/ # 🔵 INCEPTION PHASE -│ │ ├── plans/ -│ │ ├── reverse-engineering/ # Brownfield only -│ │ ├── requirements/ -│ │ ├── user-stories/ -│ │ └── application-design/ -│ ├── construction/ # 🟢 CONSTRUCTION PHASE -│ │ ├── plans/ -│ │ ├── {unit-name}/ -│ │ │ ├── functional-design/ -│ │ │ ├── nfr-requirements/ -│ │ │ ├── nfr-design/ -│ │ │ ├── infrastructure-design/ -│ │ │ └── code/ # Markdown summaries only -│ │ └── build-and-test/ -│ ├── operations/ # 🟡 OPERATIONS PHASE -│ ├── aidlc-state.md # Workflow state tracking -│ └── audit.md # Complete audit trail +Using AI-DLC, [describe your software development need] ``` -**Critical Rule**: Application code goes in workspace root, documentation goes in `aidlc-docs/` - -## Rule Details Files - -This power includes comprehensive rule detail files organized by phase: - -### Common Rules (Always Loaded) -- `rule-details/common/process-overview.md` - Workflow overview -- `rule-details/common/session-continuity.md` - Session resumption -- `rule-details/common/content-validation.md` - Content validation requirements -- `rule-details/common/question-format-guide.md` - Question formatting rules -- `rule-details/common/terminology.md` - Standard terminology -- `rule-details/common/welcome-message.md` - Initial welcome message -- `rule-details/common/ascii-diagram-standards.md` - Diagram standards -- `rule-details/common/depth-levels.md` - Depth level definitions -- `rule-details/common/error-handling.md` - Error handling guidelines -- `rule-details/common/overconfidence-prevention.md` - Quality safeguards -- `rule-details/common/workflow-changes.md` - Workflow modification rules - -### Inception Phase Rules -- `rule-details/inception/workspace-detection.md` -- `rule-details/inception/reverse-engineering.md` -- `rule-details/inception/requirements-analysis.md` -- `rule-details/inception/user-stories.md` -- `rule-details/inception/workflow-planning.md` -- `rule-details/inception/application-design.md` -- `rule-details/inception/units-generation.md` - -### Construction Phase Rules -- `rule-details/construction/functional-design.md` -- `rule-details/construction/nfr-requirements.md` -- `rule-details/construction/nfr-design.md` -- `rule-details/construction/infrastructure-design.md` -- `rule-details/construction/code-generation.md` -- `rule-details/construction/build-and-test.md` - -### Operations Phase Rules -- `rule-details/operations/operations.md` - -## Best Practices +## Steering Files -### For Users +All steering files are in the `steering/` directory: -1. **Select Language First**: MUST select language (English or 中文) before proceeding - this is mandatory -2. **Be Clear About Intent**: Start with "Using AI-DLC" to activate the workflow -3. **Review Plans Carefully**: Always review execution plans before approval -4. **Provide Feedback**: Request changes when plans don't match your needs -5. **Track Progress**: Monitor `aidlc-state.md` for workflow progress -6. **Review Audit Trail**: Check `audit.md` for complete decision history -7. **Language Consistency**: All workflow outputs will be in your selected language - -### For AI Agents - -1. **CRITICAL - Language Selection FIRST**: MUST ask user to select language (English or 中文) BEFORE any other steps - NO EXCEPTIONS -2. **Enforce Language Selection**: DO NOT proceed with welcome message or any workflow steps until language is selected -3. **Use Selected Language**: ALL outputs, questions, documentation MUST be in the selected language -4. **Load Common Rules First**: Always load common rules at workflow start (after language selection) -5. **Validate Content**: Validate all content before file creation -6. **Follow Question Format**: Use structured multiple-choice questions -7. **Update Checkboxes**: Mark plan steps complete immediately after execution -8. **Log Everything**: Record all user inputs and AI responses in audit.md -9. **Never Overwrite audit.md**: Always append, never overwrite the audit log -10. **Wait for Approval**: Never proceed without explicit user approval - -## Troubleshooting - -### Language Selection Not Prompted - -**Problem**: Workflow started without asking for language selection - -**Solution**: -1. **STOP the workflow immediately** -2. Remind the AI agent: "Language selection is MANDATORY and must be completed first" -3. Request language selection prompt -4. Restart workflow if necessary - -### Wrong Language Being Used - -**Problem**: Outputs are in wrong language or mixed languages - -**Solution**: -1. Check `aidlc-state.md` for recorded language selection -2. Remind AI agent of selected language -3. If language was never selected, stop and complete language selection first -4. If wrong language was selected, restart workflow to change language - -### Workflow Not Starting - -**Problem**: AI-DLC doesn't activate when starting a request - -**Solution**: -1. Ensure you start with "Using AI-DLC, ..." in your message -2. Verify the power is properly installed -3. Check that steering files are accessible - -### Missing Documentation - -**Problem**: Expected documentation files not created - -**Solution**: -1. Check `aidlc-state.md` to see which stages were executed -2. Review `audit.md` for any errors or skipped stages -3. Verify the stage was included in the execution plan - -### Workflow Stuck at Approval - -**Problem**: Workflow waiting for approval but unclear what to do - -**Solution**: -1. Look for the approval message with options -2. Respond with your choice (e.g., "Continue to Next Stage" or "Request Changes") -3. If unclear, ask "What are my options?" to see available choices - -### Audit Log Issues - -**Problem**: Audit log has duplicate entries or missing information - -**Solution**: -1. Ensure AI agent is appending to audit.md, not overwriting -2. Check that all user inputs are being logged with timestamps -3. Verify ISO 8601 timestamp format is being used - -## Configuration - -**No additional configuration required** - AI-DLC works immediately after power installation. - -The workflow automatically: -- **Prompts for language selection** (MANDATORY first step) -- Detects your project structure -- Determines greenfield vs brownfield -- Adapts depth levels based on complexity -- Creates necessary documentation directories -- Generates all outputs in your selected language - -**Language Configuration:** -- Language selection is prompted at workflow start -- Selection is recorded in `aidlc-docs/aidlc-state.md` -- Cannot be changed mid-workflow (must restart to change) -- All documentation, questions, and outputs use selected language +- `core-workflow.md` - Main workflow (includes language selection as MANDATORY FIRST STEP) +- `common-*.md` - Shared rules (process overview, content validation, question format, etc.) +- `inception-*.md` - Inception phase rules +- `construction-*.md` - Construction phase rules +- `operations-*.md` - Operations phase rules ## Additional Resources - **Blog**: [AI-Driven Development Life Cycle](https://aws.amazon.com/blogs/devops/ai-driven-development-life-cycle/) - **Method Definition Paper**: [AI-DLC Methodology](https://prod.d13rzhkk8cj2z0.amplifyapp.com/) - **GitHub Repository**: [aidlc-workflows](https://github.com/aws-samples/aidlc-workflows) - ---- - -**Power Type**: Knowledge Base Power (No MCP server required) -**Installation**: Works immediately after installation -**Usage**: -1. Start any request with "Using AI-DLC, ..." -2. **MANDATORY**: Select language (English or 中文) when prompted -3. Follow the guided workflow in your selected language diff --git a/aidlc/README.md b/aidlc/README.md deleted file mode 100644 index 91ce1a8..0000000 --- a/aidlc/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# AI-DLC Kiro Power - -This is a Kiro Power for the AI-Driven Development Life Cycle (AI-DLC) methodology. - -## Installation - -### Method 1: Local Directory (Recommended for Testing) - -1. Open Kiro Powers UI (use command palette or click Powers icon) -2. Click "Add Custom Power" button -3. Select "Local Directory" -4. Provide the full absolute path to this directory: - ``` - /path/to/your/workspace/powers/aidlc - ``` -5. Click "Add" to install - -### Method 2: Copy to Kiro Steering (Alternative) - -If you prefer to use this as steering files instead of a power: - -```bash -# From your project root -mkdir -p .kiro/steering -cp -R powers/aidlc/steering/core-workflow.md .kiro/steering/ -cp -R powers/aidlc/rule-details .kiro/ -``` - -## Usage - -Once installed as a power: - -1. **Activate the workflow** in any Kiro chat by starting with: - ``` - Using AI-DLC, [describe your software development need] - ``` - -2. **AI-DLC will automatically**: - - Display a welcome message - - Detect your project type (greenfield/brownfield) - - Guide you through the appropriate phases - - Create documentation in `aidlc-docs/` directory - -3. **Follow the guided workflow**: - - Answer structured questions - - Review and approve execution plans - - Monitor progress in `aidlc-docs/aidlc-state.md` - - Check audit trail in `aidlc-docs/audit.md` - -## Power Structure - -``` -powers/aidlc/ -├── POWER.md # Power documentation with frontmatter -├── README.md # This file -├── steering/ -│ └── core-workflow.md # Main AI-DLC workflow -└── rule-details/ # Detailed rules for each phase - ├── common/ # Common rules (always loaded) - ├── inception/ # Inception phase rules - ├── construction/ # Construction phase rules - └── operations/ # Operations phase rules -``` - -## What's Different from Original aidlc-rules? - -This power packages the AI-DLC methodology as a Kiro Power with: - -1. **POWER.md**: Comprehensive documentation with proper frontmatter metadata -2. **Updated paths**: All file references updated to work within the power structure -3. **Organized structure**: Clear separation of steering files and rule details -4. **Easy installation**: Can be installed via Kiro Powers UI - -The actual workflow content (all .md files) remains unchanged from the original. - -## Additional Resources - -- **Blog**: [AI-Driven Development Life Cycle](https://aws.amazon.com/blogs/devops/ai-driven-development-life-cycle/) -- **Method Definition Paper**: [AI-DLC Methodology](https://prod.d13rzhkk8cj2z0.amplifyapp.com/) -- **Original Repository**: [aidlc-workflows](https://github.com/aws-samples/aidlc-workflows) diff --git a/aidlc/rule-details/common/ascii-diagram-standards.md b/aidlc/steering/common-ascii-diagram-standards.md similarity index 100% rename from aidlc/rule-details/common/ascii-diagram-standards.md rename to aidlc/steering/common-ascii-diagram-standards.md diff --git a/aidlc/rule-details/common/content-validation.md b/aidlc/steering/common-content-validation.md similarity index 95% rename from aidlc/rule-details/common/content-validation.md rename to aidlc/steering/common-content-validation.md index f80c304..2c4595d 100644 --- a/aidlc/rule-details/common/content-validation.md +++ b/aidlc/steering/common-content-validation.md @@ -8,7 +8,7 @@ **CRITICAL**: Before creating ANY file with ASCII diagrams: -1. **LOAD** `common/ascii-diagram-standards.md` +1. **LOAD** `common-ascii-diagram-standards.md` 2. **VALIDATE** each diagram: - Count characters per line (all lines MUST be same width) - Use ONLY: `+` `-` `|` `^` `v` `<` `>` and spaces @@ -16,7 +16,7 @@ - Spaces only (NO tabs) 3. **TEST** alignment by verifying box corners align vertically -**See `common/ascii-diagram-standards.md` for patterns and validation checklist.** +**See `common-ascii-diagram-standards.md` for patterns and validation checklist.** ## Mermaid Diagram Validation diff --git a/aidlc/rule-details/common/depth-levels.md b/aidlc/steering/common-depth-levels.md similarity index 100% rename from aidlc/rule-details/common/depth-levels.md rename to aidlc/steering/common-depth-levels.md diff --git a/aidlc/rule-details/common/error-handling.md b/aidlc/steering/common-error-handling.md similarity index 100% rename from aidlc/rule-details/common/error-handling.md rename to aidlc/steering/common-error-handling.md diff --git a/aidlc/rule-details/common/overconfidence-prevention.md b/aidlc/steering/common-overconfidence-prevention.md similarity index 100% rename from aidlc/rule-details/common/overconfidence-prevention.md rename to aidlc/steering/common-overconfidence-prevention.md diff --git a/aidlc/rule-details/common/process-overview.md b/aidlc/steering/common-process-overview.md similarity index 100% rename from aidlc/rule-details/common/process-overview.md rename to aidlc/steering/common-process-overview.md diff --git a/aidlc/rule-details/common/question-format-guide.md b/aidlc/steering/common-question-format-guide.md similarity index 100% rename from aidlc/rule-details/common/question-format-guide.md rename to aidlc/steering/common-question-format-guide.md diff --git a/aidlc/rule-details/common/session-continuity.md b/aidlc/steering/common-session-continuity.md similarity index 100% rename from aidlc/rule-details/common/session-continuity.md rename to aidlc/steering/common-session-continuity.md diff --git a/aidlc/rule-details/common/terminology.md b/aidlc/steering/common-terminology.md similarity index 100% rename from aidlc/rule-details/common/terminology.md rename to aidlc/steering/common-terminology.md diff --git a/aidlc/rule-details/common/welcome-message.md b/aidlc/steering/common-welcome-message.md similarity index 100% rename from aidlc/rule-details/common/welcome-message.md rename to aidlc/steering/common-welcome-message.md diff --git a/aidlc/rule-details/common/workflow-changes.md b/aidlc/steering/common-workflow-changes.md similarity index 100% rename from aidlc/rule-details/common/workflow-changes.md rename to aidlc/steering/common-workflow-changes.md diff --git a/aidlc/rule-details/construction/build-and-test.md b/aidlc/steering/construction-build-and-test.md similarity index 100% rename from aidlc/rule-details/construction/build-and-test.md rename to aidlc/steering/construction-build-and-test.md diff --git a/aidlc/rule-details/construction/code-generation.md b/aidlc/steering/construction-code-generation.md similarity index 100% rename from aidlc/rule-details/construction/code-generation.md rename to aidlc/steering/construction-code-generation.md diff --git a/aidlc/rule-details/construction/functional-design.md b/aidlc/steering/construction-functional-design.md similarity index 100% rename from aidlc/rule-details/construction/functional-design.md rename to aidlc/steering/construction-functional-design.md diff --git a/aidlc/rule-details/construction/infrastructure-design.md b/aidlc/steering/construction-infrastructure-design.md similarity index 100% rename from aidlc/rule-details/construction/infrastructure-design.md rename to aidlc/steering/construction-infrastructure-design.md diff --git a/aidlc/rule-details/construction/nfr-design.md b/aidlc/steering/construction-nfr-design.md similarity index 100% rename from aidlc/rule-details/construction/nfr-design.md rename to aidlc/steering/construction-nfr-design.md diff --git a/aidlc/rule-details/construction/nfr-requirements.md b/aidlc/steering/construction-nfr-requirements.md similarity index 100% rename from aidlc/rule-details/construction/nfr-requirements.md rename to aidlc/steering/construction-nfr-requirements.md diff --git a/aidlc/steering/core-workflow.md b/aidlc/steering/core-workflow.md index 4bf8320..f77218c 100644 --- a/aidlc/steering/core-workflow.md +++ b/aidlc/steering/core-workflow.md @@ -1,6 +1,45 @@ +--- +inclusion: always +--- + # PRIORITY: This workflow OVERRIDES all other built-in workflows # When user requests software development, ALWAYS follow this workflow FIRST +--- + +## MANDATORY FIRST STEP: Language Selection + +**CRITICAL**: You MUST ask user to select language BEFORE any other interaction. This is NON-NEGOTIABLE. + +When user activates AI-DLC, you MUST first display this prompt: + +``` +AI-DLC Power activated. + +Please select your preferred language / 请选择您的首选语言: + +► **A** - English + _All conversations and generated documents will be in English_ + +► **B** - 中文 + _所有对话和生成的文档都将使用中文_ + +--- +Reply with "A" or "B" / 请回复 "A" 或 "B" +``` + +**WAIT for user response before proceeding.** + +**Do NOT display welcome message until language is selected.** +**Do NOT proceed with ANY workflow steps until language is confirmed.** + +Once language is selected: +1. Record the selection in `aidlc-docs/aidlc-state.md` +2. Use the selected language for ALL subsequent outputs +3. Then proceed with the welcome message and workflow + +--- + ## Adaptive Workflow Principle **The workflow adapts to the work, not the other way around.** @@ -11,19 +50,19 @@ The AI model intelligently assesses what stages are needed based on: 4. Risk and impact assessment ## MANDATORY: Rule Details Loading -**CRITICAL**: When performing any phase, you MUST read and use relevant content from rule detail files in `rule-details/` directory within this power. +**CRITICAL**: When performing any phase, you MUST read and use relevant content from steering files within this power. **Common Rules**: ALWAYS load common rules at workflow start: -- Load `common/process-overview.md` for workflow overview -- Load `common/session-continuity.md` for session resumption guidance -- Load `common/content-validation.md` for content validation requirements -- Load `common/question-format-guide.md` for question formatting rules +- Load `common-process-overview.md` for workflow overview +- Load `common-session-continuity.md` for session resumption guidance +- Load `common-content-validation.md` for content validation requirements +- Load `common-question-format-guide.md` for question formatting rules - Reference these throughout the workflow execution ## MANDATORY: Content Validation -**CRITICAL**: Before creating ANY file, you MUST validate content according to `common/content-validation.md` rules: +**CRITICAL**: Before creating ANY file, you MUST validate content according to `common-content-validation.md` rules: - Validate Mermaid diagram syntax -- Validate ASCII art diagrams (see `common/ascii-diagram-standards.md`) +- Validate ASCII art diagrams (see `common-ascii-diagram-standards.md`) - Escape special characters properly - Provide text alternatives for complex visual content - Test content parsing compatibility @@ -31,7 +70,7 @@ The AI model intelligently assesses what stages are needed based on: ## MANDATORY: Question File Format **CRITICAL**: When asking questions at any phase, you MUST follow question format guidelines. -**See `common/question-format-guide.md` for complete question formatting rules including**: +**See `common-question-format-guide.md` for complete question formatting rules including**: - Multiple choice format (A, B, C, D, E options) - [Answer]: tag usage - Answer validation and ambiguity resolution @@ -40,7 +79,7 @@ The AI model intelligently assesses what stages are needed based on: **CRITICAL**: When starting ANY software development request, you MUST display the welcome message. **How to Display Welcome Message**: -1. Load the welcome message from `rule-details/common/welcome-message.md` within this power +1. Load the welcome message from `common-welcome-message.md` within this power 2. Display the complete message to the user 3. This should only be done ONCE at the start of a new workflow 4. Do NOT load this file in subsequent interactions to save context space @@ -69,7 +108,7 @@ The AI model intelligently assesses what stages are needed based on: ## Workspace Detection (ALWAYS EXECUTE) 1. **MANDATORY**: Log initial user request in audit.md with complete raw input -2. Load all steps from `inception/workspace-detection.md` +2. Load all steps from `inception-workspace-detection.md` 3. Execute workspace detection: - Check for existing aidlc-state.md (resume if found) - Scan workspace for existing code @@ -92,7 +131,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log start of reverse engineering in audit.md -2. Load all steps from `inception/reverse-engineering.md` +2. Load all steps from `inception-reverse-engineering.md` 3. Execute reverse engineering: - Analyze all packages and components - Generate a busienss overview of the whole system covering the business transactions @@ -116,7 +155,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this phase in audit.md -2. Load all steps from `inception/requirements-analysis.md` +2. Load all steps from `inception-requirements-analysis.md` 3. Execute requirements analysis: - Load reverse engineering artifacts (if brownfield) - Analyze user request (intent analysis) @@ -187,7 +226,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this phase in audit.md -2. Load all steps from `inception/user-stories.md` +2. Load all steps from `inception-user-stories.md` 3. **MANDATORY**: Perform intelligent assessment (Step 1 in user-stories.md) to validate user stories are needed 4. Load reverse engineering artifacts (if brownfield) 5. If Requirements exist, reference them when creating stories @@ -200,8 +239,8 @@ The AI model intelligently assesses what stages are needed based on: ## Workflow Planning (ALWAYS EXECUTE) 1. **MANDATORY**: Log any user input during this phase in audit.md -2. Load all steps from `inception/workflow-planning.md` -3. **MANDATORY**: Load content validation rules from `common/content-validation.md` +2. Load all steps from `inception-workflow-planning.md` +3. **MANDATORY**: Load content validation rules from `common-content-validation.md` 4. Load all prior context: - Reverse engineering artifacts (if brownfield) - Intent analysis @@ -231,7 +270,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this phase in audit.md -2. Load all steps from `inception/application-design.md` +2. Load all steps from `inception-application-design.md` 3. Load reverse engineering artifacts (if brownfield) 4. Execute at appropriate depth (minimal/standard/comprehensive) 5. **Wait for Explicit Approval**: Present detailed completion message (see application-design.md for message format) - DO NOT PROCEED until user confirms @@ -251,7 +290,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this phase in audit.md -2. Load all steps from `inception/units-generation.md` +2. Load all steps from `inception-units-generation.md` 3. Load reverse engineering artifacts (if brownfield) 4. Execute at appropriate depth (minimal/standard/comprehensive) 5. **Wait for Explicit Approval**: Present detailed completion message (see units-generation.md for message format) - DO NOT PROCEED until user confirms @@ -295,7 +334,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this stage in audit.md -2. Load all steps from `construction/functional-design.md` +2. Load all steps from `construction-functional-design.md` 3. Execute functional design for this unit 4. **MANDATORY**: Present standardized 2-option completion message as defined in functional-design.md - DO NOT use emergent 3-option behavior 5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms @@ -315,7 +354,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this stage in audit.md -2. Load all steps from `construction/nfr-requirements.md` +2. Load all steps from `construction-nfr-requirements.md` 3. Execute NFR assessment for this unit 4. **MANDATORY**: Present standardized 2-option completion message as defined in nfr-requirements.md - DO NOT use emergent behavior 5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms @@ -333,7 +372,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this stage in audit.md -2. Load all steps from `construction/nfr-design.md` +2. Load all steps from `construction-nfr-design.md` 3. Execute NFR design for this unit 4. **MANDATORY**: Present standardized 2-option completion message as defined in nfr-design.md - DO NOT use emergent behavior 5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms @@ -352,7 +391,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this stage in audit.md -2. Load all steps from `construction/infrastructure-design.md` +2. Load all steps from `construction-infrastructure-design.md` 3. Execute infrastructure design for this unit 4. **MANDATORY**: Present standardized 2-option completion message as defined in infrastructure-design.md - DO NOT use emergent behavior 5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms @@ -368,7 +407,7 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this stage in audit.md -2. Load all steps from `construction/code-generation.md` +2. Load all steps from `construction-code-generation.md` 3. **PART 1 - Planning**: Create code generation plan with checkboxes, get user approval 4. **PART 2 - Generation**: Execute approved plan to generate code for this unit 5. **MANDATORY**: Present standardized 2-option completion message as defined in code-generation.md - DO NOT use emergent behavior @@ -380,7 +419,7 @@ The AI model intelligently assesses what stages are needed based on: ## Build and Test (ALWAYS EXECUTE) 1. **MANDATORY**: Log any user input during this phase in audit.md -2. Load all steps from `construction/build-and-test.md` +2. Load all steps from `construction-build-and-test.md` 3. Generate comprehensive build and test instructions: - Build instructions for all units - Unit test execution instructions diff --git a/aidlc/rule-details/inception/application-design.md b/aidlc/steering/inception-application-design.md similarity index 100% rename from aidlc/rule-details/inception/application-design.md rename to aidlc/steering/inception-application-design.md diff --git a/aidlc/rule-details/inception/requirements-analysis.md b/aidlc/steering/inception-requirements-analysis.md similarity index 98% rename from aidlc/rule-details/inception/requirements-analysis.md rename to aidlc/steering/inception-requirements-analysis.md index cc47828..2913159 100644 --- a/aidlc/rule-details/inception/requirements-analysis.md +++ b/aidlc/steering/inception-requirements-analysis.md @@ -4,7 +4,7 @@ **Adaptive Phase**: Always executes. Detail level adapts to problem complexity. -**See [depth-levels.md](../common/depth-levels.md) for adaptive depth explanation** +**See [depth-levels.md](common-depth-levels.md) for adaptive depth explanation** ## Prerequisites - Workspace Detection must be complete diff --git a/aidlc/rule-details/inception/reverse-engineering.md b/aidlc/steering/inception-reverse-engineering.md similarity index 100% rename from aidlc/rule-details/inception/reverse-engineering.md rename to aidlc/steering/inception-reverse-engineering.md diff --git a/aidlc/rule-details/inception/units-generation.md b/aidlc/steering/inception-units-generation.md similarity index 100% rename from aidlc/rule-details/inception/units-generation.md rename to aidlc/steering/inception-units-generation.md diff --git a/aidlc/rule-details/inception/user-stories.md b/aidlc/steering/inception-user-stories.md similarity index 99% rename from aidlc/rule-details/inception/user-stories.md rename to aidlc/steering/inception-user-stories.md index e12a7fa..0e1ab0d 100644 --- a/aidlc/rule-details/inception/user-stories.md +++ b/aidlc/steering/inception-user-stories.md @@ -126,7 +126,7 @@ For medium priority cases, execute user stories if ANY of these apply: **CRITICAL**: Default to asking questions when there is ANY ambiguity or missing detail that could affect story quality. It's better to ask too many questions than to create incomplete or unclear stories. -**See `common/question-format-guide.md` for question formatting rules** +**See `common-question-format-guide.md` for question formatting rules** - EMBED questions using [Answer]: tag format - Focus on ANY ambiguities, missing information, or areas needing clarification diff --git a/aidlc/rule-details/inception/workflow-planning.md b/aidlc/steering/inception-workflow-planning.md similarity index 99% rename from aidlc/rule-details/inception/workflow-planning.md rename to aidlc/steering/inception-workflow-planning.md index 6f4b700..aa05c28 100644 --- a/aidlc/rule-details/inception/workflow-planning.md +++ b/aidlc/steering/inception-workflow-planning.md @@ -155,7 +155,7 @@ Evaluate risk level: ## Step 4: Note Adaptive Detail -**See [depth-levels.md](../common/depth-levels.md) for adaptive depth explanation** +**See [depth-levels.md](common-depth-levels.md) for adaptive depth explanation** For each stage that will execute: - All defined artifacts will be created diff --git a/aidlc/rule-details/inception/workspace-detection.md b/aidlc/steering/inception-workspace-detection.md similarity index 100% rename from aidlc/rule-details/inception/workspace-detection.md rename to aidlc/steering/inception-workspace-detection.md diff --git a/aidlc/rule-details/operations/operations.md b/aidlc/steering/operations-operations.md similarity index 100% rename from aidlc/rule-details/operations/operations.md rename to aidlc/steering/operations-operations.md From 885c37155431f5c331ca4d6d2510117ad5aa00b9 Mon Sep 17 00:00:00 2001 From: Junxiang Ji Date: Thu, 8 Jan 2026 12:53:42 +0000 Subject: [PATCH 10/18] Add PPTX Power with MCP server support This PR adds comprehensive PowerPoint presentation creation and editing capabilities through: - pptx-power-clean: Power definition with steering files and examples - pptx-mcp-server: MCP server implementation with OOXML schemas and conversion tools Key features: - Create, edit, and analyze PowerPoint presentations - HTML-to-PPTX conversion with preview workflow - Direct OOXML manipulation for advanced use cases - Template-based presentation workflows Co-Authored-By: Claude --- pptx-mcp-server/README.md | 203 + pptx-mcp-server/install-pptx-mcp-server.sh | 128 + .../schemas/ISO-IEC29500-4_2016/dml-chart.xsd | 1499 ++++++ .../ISO-IEC29500-4_2016/dml-chartDrawing.xsd | 146 + .../ISO-IEC29500-4_2016/dml-diagram.xsd | 1085 ++++ .../ISO-IEC29500-4_2016/dml-lockedCanvas.xsd | 11 + .../schemas/ISO-IEC29500-4_2016/dml-main.xsd | 3081 ++++++++++++ .../ISO-IEC29500-4_2016/dml-picture.xsd | 23 + .../dml-spreadsheetDrawing.xsd | 185 + .../dml-wordprocessingDrawing.xsd | 287 ++ .../ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd | 1676 +++++++ .../shared-additionalCharacteristics.xsd | 28 + .../shared-bibliography.xsd | 144 + .../shared-commonSimpleTypes.xsd | 174 + .../shared-customXmlDataProperties.xsd | 25 + .../shared-customXmlSchemaProperties.xsd | 18 + .../shared-documentPropertiesCustom.xsd | 59 + .../shared-documentPropertiesExtended.xsd | 56 + .../shared-documentPropertiesVariantTypes.xsd | 195 + .../ISO-IEC29500-4_2016/shared-math.xsd | 582 +++ .../shared-relationshipReference.xsd | 25 + .../ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd | 4439 +++++++++++++++++ .../schemas/ISO-IEC29500-4_2016/vml-main.xsd | 570 +++ .../ISO-IEC29500-4_2016/vml-officeDrawing.xsd | 509 ++ .../vml-presentationDrawing.xsd | 12 + .../vml-spreadsheetDrawing.xsd | 108 + .../vml-wordprocessingDrawing.xsd | 96 + .../ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd | 3646 ++++++++++++++ .../ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd | 116 + .../ecma/fouth-edition/opc-contentTypes.xsd | 42 + .../ecma/fouth-edition/opc-coreProperties.xsd | 50 + .../schemas/ecma/fouth-edition/opc-digSig.xsd | 49 + .../ecma/fouth-edition/opc-relationships.xsd | 33 + pptx-mcp-server/ooxml/schemas/mce/mc.xsd | 75 + .../ooxml/schemas/microsoft/wml-2010.xsd | 560 +++ .../ooxml/schemas/microsoft/wml-2012.xsd | 67 + .../ooxml/schemas/microsoft/wml-2018.xsd | 14 + .../ooxml/schemas/microsoft/wml-cex-2018.xsd | 20 + .../ooxml/schemas/microsoft/wml-cid-2016.xsd | 13 + .../microsoft/wml-sdtdatahash-2020.xsd | 4 + .../schemas/microsoft/wml-symex-2015.xsd | 8 + pptx-mcp-server/ooxml/scripts/pack.py | 159 + pptx-mcp-server/ooxml/scripts/unpack.py | 29 + pptx-mcp-server/ooxml/scripts/validate.py | 69 + .../ooxml/scripts/validation/__init__.py | 15 + .../ooxml/scripts/validation/base.py | 951 ++++ .../ooxml/scripts/validation/docx.py | 274 + .../ooxml/scripts/validation/pptx.py | 315 ++ .../ooxml/scripts/validation/redlining.py | 279 ++ pptx-mcp-server/package.json | 25 + pptx-mcp-server/requirements.txt | 16 + pptx-mcp-server/script_executor_mcp.py | 278 ++ pptx-mcp-server/scripts/html2pptx-cli.js | 92 + pptx-mcp-server/scripts/html2pptx.js | 995 ++++ pptx-mcp-server/scripts/inventory.py | 1020 ++++ pptx-mcp-server/scripts/rearrange.py | 231 + pptx-mcp-server/scripts/replace.py | 385 ++ pptx-mcp-server/scripts/thumbnail.py | 450 ++ pptx-mcp-server/test_mcp_server.py | 212 + pptx-power-clean/POWER.md | 397 ++ pptx-power-clean/README.md | 157 + pptx-power-clean/examples/README.md | 100 + .../example-presentation-thumbnails.jpg | Bin 0 -> 123540 bytes pptx-power-clean/mcp.json | 9 + pptx-power-clean/steering/html2pptx-guide.md | 314 ++ pptx-power-clean/steering/ooxml-guide.md | 74 + .../steering/template-workflow.md | 220 + .../steering/user-request-to-html.md | 473 ++ 68 files changed, 27600 insertions(+) create mode 100644 pptx-mcp-server/README.md create mode 100755 pptx-mcp-server/install-pptx-mcp-server.sh create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/mce/mc.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/microsoft/wml-2010.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/microsoft/wml-2012.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/microsoft/wml-2018.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/microsoft/wml-cex-2018.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/microsoft/wml-cid-2016.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd create mode 100644 pptx-mcp-server/ooxml/schemas/microsoft/wml-symex-2015.xsd create mode 100644 pptx-mcp-server/ooxml/scripts/pack.py create mode 100644 pptx-mcp-server/ooxml/scripts/unpack.py create mode 100644 pptx-mcp-server/ooxml/scripts/validate.py create mode 100644 pptx-mcp-server/ooxml/scripts/validation/__init__.py create mode 100644 pptx-mcp-server/ooxml/scripts/validation/base.py create mode 100644 pptx-mcp-server/ooxml/scripts/validation/docx.py create mode 100644 pptx-mcp-server/ooxml/scripts/validation/pptx.py create mode 100644 pptx-mcp-server/ooxml/scripts/validation/redlining.py create mode 100644 pptx-mcp-server/package.json create mode 100644 pptx-mcp-server/requirements.txt create mode 100644 pptx-mcp-server/script_executor_mcp.py create mode 100755 pptx-mcp-server/scripts/html2pptx-cli.js create mode 100644 pptx-mcp-server/scripts/html2pptx.js create mode 100644 pptx-mcp-server/scripts/inventory.py create mode 100644 pptx-mcp-server/scripts/rearrange.py create mode 100644 pptx-mcp-server/scripts/replace.py create mode 100644 pptx-mcp-server/scripts/thumbnail.py create mode 100644 pptx-mcp-server/test_mcp_server.py create mode 100644 pptx-power-clean/POWER.md create mode 100644 pptx-power-clean/README.md create mode 100644 pptx-power-clean/examples/README.md create mode 100644 pptx-power-clean/examples/example-presentation-thumbnails.jpg create mode 100644 pptx-power-clean/mcp.json create mode 100644 pptx-power-clean/steering/html2pptx-guide.md create mode 100644 pptx-power-clean/steering/ooxml-guide.md create mode 100644 pptx-power-clean/steering/template-workflow.md create mode 100644 pptx-power-clean/steering/user-request-to-html.md diff --git a/pptx-mcp-server/README.md b/pptx-mcp-server/README.md new file mode 100644 index 0000000..4e8b54d --- /dev/null +++ b/pptx-mcp-server/README.md @@ -0,0 +1,203 @@ +# PPTX MCP Server + +MCP Server for PowerPoint presentation manipulation. Provides tools for creating, editing, and analyzing .pptx files. + +## Features + +- **html2pptx** - Convert HTML slides to PowerPoint presentation +- **inventory** - Extract all text shapes and properties from a presentation +- **rearrange** - Duplicate, reorder, and delete slides +- **replace** - Replace text content while preserving formatting +- **thumbnail** - Generate visual thumbnail grids of slides + +## Installation + +### Prerequisites + +- Python 3.8+ +- Node.js 16+ (for html2pptx) + +### Quick Installation + +Use the provided installation script: + +```bash +cd powers/pptx-mcp-server +./install-pptx-mcp-server.sh +``` + +This script will: +1. Copy files to `~/.kiro/mcp-servers/pptx-mcp-server/` +2. Install Python dependencies +3. Install Node.js dependencies locally +4. Install system tools (LibreOffice, Poppler) +5. Run tests to verify installation + +### Manual Installation + +If you prefer to install manually: + +```bash +# Python dependencies +pip install -r requirements.txt + +# Node.js dependencies (installed locally) +npm install + +# System tools +# macOS +brew install libreoffice poppler + +# Ubuntu/Debian +sudo apt-get install libreoffice poppler-utils +``` + +### Install to Standard Location + +```bash +# Clone or copy to standard location +mkdir -p ~/.kiro/mcp-servers +cp -r pptx-mcp-server ~/.kiro/mcp-servers/ + +# Or clone from GitHub +git clone https://github.com/your-username/pptx-mcp-server.git ~/.kiro/mcp-servers/pptx-mcp-server +``` + +## Testing + +```bash +# Run test suite +python test_mcp_server.py +``` + +Expected output: +``` +============================================================ +MCP SERVER TEST SUITE +============================================================ +... +✅ ALL TESTS COMPLETED +🎉 The MCP server is working properly! +``` + +## Usage with Kiro + +This MCP server is designed to be used with the **PPTX Power** in Kiro. + +1. Install this MCP server to `~/.kiro/mcp-servers/pptx-mcp-server/` +2. Install the PPTX Power through Kiro Powers panel +3. The Power's mcp.json will automatically connect to this server + +## Directory Structure + +``` +pptx-mcp-server/ +├── script_executor_mcp.py # Main MCP server +├── test_mcp_server.py # Test suite +├── requirements.txt # Python dependencies +├── scripts/ # PowerPoint manipulation scripts +│ ├── html2pptx.js # HTML to PPTX converter +│ ├── inventory.py # Text extraction +│ ├── rearrange.py # Slide manipulation +│ ├── replace.py # Text replacement +│ └── thumbnail.py # Thumbnail generation +└── ooxml/ # OOXML utilities + └── scripts/ + ├── pack.py + ├── unpack.py + └── validate.py +``` + +## Available Tools + +### html2pptx +Convert HTML slides to PowerPoint presentation. + +**Parameters:** +- `html_files` (array): Array of HTML file paths for each slide +- `output_file` (string): Output .pptx file path +- `config` (object, optional): Configuration for charts, tables, etc. + +### inventory +Extract all text shapes and properties from a presentation. + +**Parameters:** +- `input_file` (string): Input .pptx file path +- `output_file` (string): Output JSON file path for inventory + +### rearrange +Duplicate, reorder, and delete slides in a presentation. + +**Parameters:** +- `input_file` (string): Input .pptx file path +- `output_file` (string): Output .pptx file path +- `slide_indices` (string): Comma-separated slide indices (0-based, can repeat) + +### replace +Replace text content in presentation while preserving formatting. + +**Parameters:** +- `input_file` (string): Input .pptx file path +- `replacement_json` (string): JSON file with replacement text and formatting +- `output_file` (string): Output .pptx file path + +### thumbnail +Generate visual thumbnail grids of presentation slides. + +**Parameters:** +- `input_file` (string): Input .pptx file path +- `output_prefix` (string, optional): Output file prefix (default: 'thumbnails') +- `columns` (integer, optional): Number of columns 3-6 (default: 5) + +## Troubleshooting + +### Error: ModuleNotFoundError + +**Solution:** Install missing dependencies +```bash +pip install -r requirements.txt +``` + +### Error: Script not found + +**Solution:** Verify all scripts are present +```bash +ls -la scripts/ +ls -la ooxml/scripts/ +``` + +### Error: Permission denied + +**Solution:** Make scripts executable +```bash +chmod +x scripts/*.py scripts/*.js +chmod +x ooxml/scripts/*.py +``` + +## Development + +### Running Tests + +```bash +python test_mcp_server.py +``` + +### Adding New Tools + +1. Add script to `scripts/` directory +2. Update `SCRIPTS` dictionary in `script_executor_mcp.py` +3. Add tests to `test_mcp_server.py` +4. Update this README + +## License + +[Your License Here] + +## Contributing + +Contributions welcome! Please open an issue or PR. + +## Related + +- **PPTX Power** - Kiro Power that uses this MCP server +- **Original Skill** - Converted from Claude Agent Skill diff --git a/pptx-mcp-server/install-pptx-mcp-server.sh b/pptx-mcp-server/install-pptx-mcp-server.sh new file mode 100755 index 0000000..536abfe --- /dev/null +++ b/pptx-mcp-server/install-pptx-mcp-server.sh @@ -0,0 +1,128 @@ +#!/bin/bash +# PPTX MCP Server Installation Script + +set -e # Exit on error + +echo "==========================================" +echo "PPTX MCP Server Installation" +echo "==========================================" +echo "" + +# Check if running on macOS or Linux +if [[ "$OSTYPE" == "darwin"* ]]; then + OS="macos" +elif [[ "$OSTYPE" == "linux-gnu"* ]]; then + OS="linux" +else + echo "❌ Unsupported operating system: $OSTYPE" + exit 1 +fi + +echo "✓ Detected OS: $OS" +echo "" + +# Step 1: Create directory +echo "Step 1: Creating MCP server directory..." +mkdir -p ~/.kiro/mcp-servers +echo "✓ Directory created: ~/.kiro/mcp-servers" +echo "" + +# Step 2: Copy files +echo "Step 2: Copying MCP server files..." +if [ -d "pptx-mcp-server" ]; then + cp -r pptx-mcp-server ~/.kiro/mcp-servers/ + echo "✓ Files copied to ~/.kiro/mcp-servers/pptx-mcp-server" +else + echo "❌ Error: pptx-mcp-server directory not found" + echo " Please run this script from the project root directory" + exit 1 +fi +echo "" + +# Step 3: Install Python dependencies +echo "Step 3: Installing Python dependencies..." +cd ~/.kiro/mcp-servers/pptx-mcp-server + +if command -v pip &> /dev/null; then + pip install -r requirements.txt + echo "✓ Python dependencies installed" +elif command -v pip3 &> /dev/null; then + pip3 install -r requirements.txt + echo "✓ Python dependencies installed" +else + echo "❌ Error: pip not found" + echo " Please install Python and pip first" + exit 1 +fi +echo "" + +# Step 4: Install Node.js dependencies +echo "Step 4: Installing Node.js dependencies..." +if command -v npm &> /dev/null; then + # Install locally using package.json + cd ~/.kiro/mcp-servers/pptx-mcp-server + npm install + echo "✓ Node.js dependencies installed locally" +else + echo "⚠️ Warning: npm not found" + echo " Node.js dependencies are required for html2pptx functionality" + echo " Please install Node.js and run:" + echo " cd ~/.kiro/mcp-servers/pptx-mcp-server" + echo " npm install" +fi +echo "" + +# Step 5: Install system tools +echo "Step 5: Installing system tools..." +if [ "$OS" == "macos" ]; then + if command -v brew &> /dev/null; then + echo "Installing LibreOffice and Poppler..." + brew install libreoffice poppler + echo "✓ System tools installed" + else + echo "⚠️ Warning: Homebrew not found" + echo " Please install Homebrew and run:" + echo " brew install libreoffice poppler" + fi +elif [ "$OS" == "linux" ]; then + if command -v apt-get &> /dev/null; then + echo "Installing LibreOffice and Poppler..." + sudo apt-get update + sudo apt-get install -y libreoffice poppler-utils + echo "✓ System tools installed" + else + echo "⚠️ Warning: apt-get not found" + echo " Please install LibreOffice and Poppler manually" + fi +fi +echo "" + +# Step 6: Test installation +echo "Step 6: Testing MCP server..." +cd ~/.kiro/mcp-servers/pptx-mcp-server +python test_mcp_server.py + +if [ $? -eq 0 ]; then + echo "" + echo "==========================================" + echo "✅ Installation Complete!" + echo "==========================================" + echo "" + echo "MCP Server installed at:" + echo " ~/.kiro/mcp-servers/pptx-mcp-server/" + echo "" + echo "Next steps:" + echo " 1. Open Kiro Powers panel" + echo " 2. Add Power from: powers/pptx-power-clean" + echo " 3. Start using PPTX tools in Kiro!" + echo "" +else + echo "" + echo "==========================================" + echo "⚠️ Installation completed with warnings" + echo "==========================================" + echo "" + echo "Some tests failed. Please check the output above." + echo "You may need to install missing dependencies." + echo "" +fi diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd new file mode 100644 index 0000000..6454ef9 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd @@ -0,0 +1,1499 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd new file mode 100644 index 0000000..afa4f46 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd new file mode 100644 index 0000000..64e66b8 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd @@ -0,0 +1,1085 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd new file mode 100644 index 0000000..687eea8 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd @@ -0,0 +1,11 @@ + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd new file mode 100644 index 0000000..6ac81b0 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd @@ -0,0 +1,3081 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd new file mode 100644 index 0000000..1dbf051 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd new file mode 100644 index 0000000..f1af17d --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd @@ -0,0 +1,185 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd new file mode 100644 index 0000000..0a185ab --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd @@ -0,0 +1,287 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd new file mode 100644 index 0000000..14ef488 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd @@ -0,0 +1,1676 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd new file mode 100644 index 0000000..c20f3bf --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd new file mode 100644 index 0000000..ac60252 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd new file mode 100644 index 0000000..424b8ba --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd new file mode 100644 index 0000000..2bddce2 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd new file mode 100644 index 0000000..8a8c18b --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd new file mode 100644 index 0000000..5c42706 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd new file mode 100644 index 0000000..853c341 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd new file mode 100644 index 0000000..da835ee --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd new file mode 100644 index 0000000..87ad265 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd @@ -0,0 +1,582 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd new file mode 100644 index 0000000..9e86f1b --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd new file mode 100644 index 0000000..d0be42e --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd @@ -0,0 +1,4439 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd new file mode 100644 index 0000000..8821dd1 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd @@ -0,0 +1,570 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd new file mode 100644 index 0000000..ca2575c --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd @@ -0,0 +1,509 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd new file mode 100644 index 0000000..dd079e6 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd new file mode 100644 index 0000000..3dd6cf6 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd new file mode 100644 index 0000000..f1041e3 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd new file mode 100644 index 0000000..9c5b7a6 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd @@ -0,0 +1,3646 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd new file mode 100644 index 0000000..0f13678 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd @@ -0,0 +1,116 @@ + + + + + + See http://www.w3.org/XML/1998/namespace.html and + http://www.w3.org/TR/REC-xml for information about this namespace. + + This schema document describes the XML namespace, in a form + suitable for import by other schema documents. + + Note that local names in this namespace are intended to be defined + only by the World Wide Web Consortium or its subgroups. The + following names are currently defined in this namespace and should + not be used with conflicting semantics by any Working Group, + specification, or document instance: + + base (as an attribute name): denotes an attribute whose value + provides a URI to be used as the base for interpreting any + relative URIs in the scope of the element on which it + appears; its value is inherited. This name is reserved + by virtue of its definition in the XML Base specification. + + lang (as an attribute name): denotes an attribute whose value + is a language code for the natural language of the content of + any element; its value is inherited. This name is reserved + by virtue of its definition in the XML specification. + + space (as an attribute name): denotes an attribute whose + value is a keyword indicating what whitespace processing + discipline is intended for the content of the element; its + value is inherited. This name is reserved by virtue of its + definition in the XML specification. + + Father (in any context at all): denotes Jon Bosak, the chair of + the original XML Working Group. This name is reserved by + the following decision of the W3C XML Plenary and + XML Coordination groups: + + In appreciation for his vision, leadership and dedication + the W3C XML Plenary on this 10th day of February, 2000 + reserves for Jon Bosak in perpetuity the XML name + xml:Father + + + + + This schema defines attributes and an attribute group + suitable for use by + schemas wishing to allow xml:base, xml:lang or xml:space attributes + on elements they define. + + To enable this, such a schema must import this schema + for the XML namespace, e.g. as follows: + <schema . . .> + . . . + <import namespace="http://www.w3.org/XML/1998/namespace" + schemaLocation="http://www.w3.org/2001/03/xml.xsd"/> + + Subsequently, qualified reference to any of the attributes + or the group defined below will have the desired effect, e.g. + + <type . . .> + . . . + <attributeGroup ref="xml:specialAttrs"/> + + will define a type which will schema-validate an instance + element with any of those attributes + + + + In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + http://www.w3.org/2001/03/xml.xsd. + At the date of issue it can also be found at + http://www.w3.org/2001/xml.xsd. + The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML Schema + itself. In other words, if the XML Schema namespace changes, the version + of this document at + http://www.w3.org/2001/xml.xsd will change + accordingly; the version at + http://www.w3.org/2001/03/xml.xsd will not change. + + + + + + In due course, we should install the relevant ISO 2- and 3-letter + codes as the enumerated possible values . . . + + + + + + + + + + + + + + + See http://www.w3.org/TR/xmlbase/ for + information about this attribute. + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd b/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd new file mode 100644 index 0000000..a6de9d2 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd b/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd new file mode 100644 index 0000000..10e978b --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd b/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd new file mode 100644 index 0000000..4248bf7 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd b/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd new file mode 100644 index 0000000..5649746 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/mce/mc.xsd b/pptx-mcp-server/ooxml/schemas/mce/mc.xsd new file mode 100644 index 0000000..ef72545 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/mce/mc.xsd @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/microsoft/wml-2010.xsd b/pptx-mcp-server/ooxml/schemas/microsoft/wml-2010.xsd new file mode 100644 index 0000000..f65f777 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/microsoft/wml-2010.xsd @@ -0,0 +1,560 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/microsoft/wml-2012.xsd b/pptx-mcp-server/ooxml/schemas/microsoft/wml-2012.xsd new file mode 100644 index 0000000..6b00755 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/microsoft/wml-2012.xsd @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/microsoft/wml-2018.xsd b/pptx-mcp-server/ooxml/schemas/microsoft/wml-2018.xsd new file mode 100644 index 0000000..f321d33 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/microsoft/wml-2018.xsd @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/microsoft/wml-cex-2018.xsd b/pptx-mcp-server/ooxml/schemas/microsoft/wml-cex-2018.xsd new file mode 100644 index 0000000..364c6a9 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/microsoft/wml-cex-2018.xsd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/microsoft/wml-cid-2016.xsd b/pptx-mcp-server/ooxml/schemas/microsoft/wml-cid-2016.xsd new file mode 100644 index 0000000..fed9d15 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/microsoft/wml-cid-2016.xsd @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/pptx-mcp-server/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd b/pptx-mcp-server/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd new file mode 100644 index 0000000..680cf15 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd @@ -0,0 +1,4 @@ + + + + diff --git a/pptx-mcp-server/ooxml/schemas/microsoft/wml-symex-2015.xsd b/pptx-mcp-server/ooxml/schemas/microsoft/wml-symex-2015.xsd new file mode 100644 index 0000000..89ada90 --- /dev/null +++ b/pptx-mcp-server/ooxml/schemas/microsoft/wml-symex-2015.xsd @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/pptx-mcp-server/ooxml/scripts/pack.py b/pptx-mcp-server/ooxml/scripts/pack.py new file mode 100644 index 0000000..68bc088 --- /dev/null +++ b/pptx-mcp-server/ooxml/scripts/pack.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +""" +Tool to pack a directory into a .docx, .pptx, or .xlsx file with XML formatting undone. + +Example usage: + python pack.py [--force] +""" + +import argparse +import shutil +import subprocess +import sys +import tempfile +import defusedxml.minidom +import zipfile +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description="Pack a directory into an Office file") + parser.add_argument("input_directory", help="Unpacked Office document directory") + parser.add_argument("output_file", help="Output Office file (.docx/.pptx/.xlsx)") + parser.add_argument("--force", action="store_true", help="Skip validation") + args = parser.parse_args() + + try: + success = pack_document( + args.input_directory, args.output_file, validate=not args.force + ) + + # Show warning if validation was skipped + if args.force: + print("Warning: Skipped validation, file may be corrupt", file=sys.stderr) + # Exit with error if validation failed + elif not success: + print("Contents would produce a corrupt file.", file=sys.stderr) + print("Please validate XML before repacking.", file=sys.stderr) + print("Use --force to skip validation and pack anyway.", file=sys.stderr) + sys.exit(1) + + except ValueError as e: + sys.exit(f"Error: {e}") + + +def pack_document(input_dir, output_file, validate=False): + """Pack a directory into an Office file (.docx/.pptx/.xlsx). + + Args: + input_dir: Path to unpacked Office document directory + output_file: Path to output Office file + validate: If True, validates with soffice (default: False) + + Returns: + bool: True if successful, False if validation failed + """ + input_dir = Path(input_dir) + output_file = Path(output_file) + + if not input_dir.is_dir(): + raise ValueError(f"{input_dir} is not a directory") + if output_file.suffix.lower() not in {".docx", ".pptx", ".xlsx"}: + raise ValueError(f"{output_file} must be a .docx, .pptx, or .xlsx file") + + # Work in temporary directory to avoid modifying original + with tempfile.TemporaryDirectory() as temp_dir: + temp_content_dir = Path(temp_dir) / "content" + shutil.copytree(input_dir, temp_content_dir) + + # Process XML files to remove pretty-printing whitespace + for pattern in ["*.xml", "*.rels"]: + for xml_file in temp_content_dir.rglob(pattern): + condense_xml(xml_file) + + # Create final Office file as zip archive + output_file.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(output_file, "w", zipfile.ZIP_DEFLATED) as zf: + for f in temp_content_dir.rglob("*"): + if f.is_file(): + zf.write(f, f.relative_to(temp_content_dir)) + + # Validate if requested + if validate: + if not validate_document(output_file): + output_file.unlink() # Delete the corrupt file + return False + + return True + + +def validate_document(doc_path): + """Validate document by converting to HTML with soffice.""" + # Determine the correct filter based on file extension + match doc_path.suffix.lower(): + case ".docx": + filter_name = "html:HTML" + case ".pptx": + filter_name = "html:impress_html_Export" + case ".xlsx": + filter_name = "html:HTML (StarCalc)" + + with tempfile.TemporaryDirectory() as temp_dir: + try: + result = subprocess.run( + [ + "soffice", + "--headless", + "--convert-to", + filter_name, + "--outdir", + temp_dir, + str(doc_path), + ], + capture_output=True, + timeout=10, + text=True, + ) + if not (Path(temp_dir) / f"{doc_path.stem}.html").exists(): + error_msg = result.stderr.strip() or "Document validation failed" + print(f"Validation error: {error_msg}", file=sys.stderr) + return False + return True + except FileNotFoundError: + print("Warning: soffice not found. Skipping validation.", file=sys.stderr) + return True + except subprocess.TimeoutExpired: + print("Validation error: Timeout during conversion", file=sys.stderr) + return False + except Exception as e: + print(f"Validation error: {e}", file=sys.stderr) + return False + + +def condense_xml(xml_file): + """Strip unnecessary whitespace and remove comments.""" + with open(xml_file, "r", encoding="utf-8") as f: + dom = defusedxml.minidom.parse(f) + + # Process each element to remove whitespace and comments + for element in dom.getElementsByTagName("*"): + # Skip w:t elements and their processing + if element.tagName.endswith(":t"): + continue + + # Remove whitespace-only text nodes and comment nodes + for child in list(element.childNodes): + if ( + child.nodeType == child.TEXT_NODE + and child.nodeValue + and child.nodeValue.strip() == "" + ) or child.nodeType == child.COMMENT_NODE: + element.removeChild(child) + + # Write back the condensed XML + with open(xml_file, "wb") as f: + f.write(dom.toxml(encoding="UTF-8")) + + +if __name__ == "__main__": + main() diff --git a/pptx-mcp-server/ooxml/scripts/unpack.py b/pptx-mcp-server/ooxml/scripts/unpack.py new file mode 100644 index 0000000..4938798 --- /dev/null +++ b/pptx-mcp-server/ooxml/scripts/unpack.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Unpack and format XML contents of Office files (.docx, .pptx, .xlsx)""" + +import random +import sys +import defusedxml.minidom +import zipfile +from pathlib import Path + +# Get command line arguments +assert len(sys.argv) == 3, "Usage: python unpack.py " +input_file, output_dir = sys.argv[1], sys.argv[2] + +# Extract and format +output_path = Path(output_dir) +output_path.mkdir(parents=True, exist_ok=True) +zipfile.ZipFile(input_file).extractall(output_path) + +# Pretty print all XML files +xml_files = list(output_path.rglob("*.xml")) + list(output_path.rglob("*.rels")) +for xml_file in xml_files: + content = xml_file.read_text(encoding="utf-8") + dom = defusedxml.minidom.parseString(content) + xml_file.write_bytes(dom.toprettyxml(indent=" ", encoding="ascii")) + +# For .docx files, suggest an RSID for tracked changes +if input_file.endswith(".docx"): + suggested_rsid = "".join(random.choices("0123456789ABCDEF", k=8)) + print(f"Suggested RSID for edit session: {suggested_rsid}") diff --git a/pptx-mcp-server/ooxml/scripts/validate.py b/pptx-mcp-server/ooxml/scripts/validate.py new file mode 100644 index 0000000..508c589 --- /dev/null +++ b/pptx-mcp-server/ooxml/scripts/validate.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +""" +Command line tool to validate Office document XML files against XSD schemas and tracked changes. + +Usage: + python validate.py --original +""" + +import argparse +import sys +from pathlib import Path + +from validation import DOCXSchemaValidator, PPTXSchemaValidator, RedliningValidator + + +def main(): + parser = argparse.ArgumentParser(description="Validate Office document XML files") + parser.add_argument( + "unpacked_dir", + help="Path to unpacked Office document directory", + ) + parser.add_argument( + "--original", + required=True, + help="Path to original file (.docx/.pptx/.xlsx)", + ) + parser.add_argument( + "-v", + "--verbose", + action="store_true", + help="Enable verbose output", + ) + args = parser.parse_args() + + # Validate paths + unpacked_dir = Path(args.unpacked_dir) + original_file = Path(args.original) + file_extension = original_file.suffix.lower() + assert unpacked_dir.is_dir(), f"Error: {unpacked_dir} is not a directory" + assert original_file.is_file(), f"Error: {original_file} is not a file" + assert file_extension in [".docx", ".pptx", ".xlsx"], ( + f"Error: {original_file} must be a .docx, .pptx, or .xlsx file" + ) + + # Run validations + match file_extension: + case ".docx": + validators = [DOCXSchemaValidator, RedliningValidator] + case ".pptx": + validators = [PPTXSchemaValidator] + case _: + print(f"Error: Validation not supported for file type {file_extension}") + sys.exit(1) + + # Run validators + success = True + for V in validators: + validator = V(unpacked_dir, original_file, verbose=args.verbose) + if not validator.validate(): + success = False + + if success: + print("All validations PASSED!") + + sys.exit(0 if success else 1) + + +if __name__ == "__main__": + main() diff --git a/pptx-mcp-server/ooxml/scripts/validation/__init__.py b/pptx-mcp-server/ooxml/scripts/validation/__init__.py new file mode 100644 index 0000000..db092ec --- /dev/null +++ b/pptx-mcp-server/ooxml/scripts/validation/__init__.py @@ -0,0 +1,15 @@ +""" +Validation modules for Word document processing. +""" + +from .base import BaseSchemaValidator +from .docx import DOCXSchemaValidator +from .pptx import PPTXSchemaValidator +from .redlining import RedliningValidator + +__all__ = [ + "BaseSchemaValidator", + "DOCXSchemaValidator", + "PPTXSchemaValidator", + "RedliningValidator", +] diff --git a/pptx-mcp-server/ooxml/scripts/validation/base.py b/pptx-mcp-server/ooxml/scripts/validation/base.py new file mode 100644 index 0000000..0681b19 --- /dev/null +++ b/pptx-mcp-server/ooxml/scripts/validation/base.py @@ -0,0 +1,951 @@ +""" +Base validator with common validation logic for document files. +""" + +import re +from pathlib import Path + +import lxml.etree + + +class BaseSchemaValidator: + """Base validator with common validation logic for document files.""" + + # Elements whose 'id' attributes must be unique within their file + # Format: element_name -> (attribute_name, scope) + # scope can be 'file' (unique within file) or 'global' (unique across all files) + UNIQUE_ID_REQUIREMENTS = { + # Word elements + "comment": ("id", "file"), # Comment IDs in comments.xml + "commentrangestart": ("id", "file"), # Must match comment IDs + "commentrangeend": ("id", "file"), # Must match comment IDs + "bookmarkstart": ("id", "file"), # Bookmark start IDs + "bookmarkend": ("id", "file"), # Bookmark end IDs + # Note: ins and del (track changes) can share IDs when part of same revision + # PowerPoint elements + "sldid": ("id", "file"), # Slide IDs in presentation.xml + "sldmasterid": ("id", "global"), # Slide master IDs must be globally unique + "sldlayoutid": ("id", "global"), # Slide layout IDs must be globally unique + "cm": ("authorid", "file"), # Comment author IDs + # Excel elements + "sheet": ("sheetid", "file"), # Sheet IDs in workbook.xml + "definedname": ("id", "file"), # Named range IDs + # Drawing/Shape elements (all formats) + "cxnsp": ("id", "file"), # Connection shape IDs + "sp": ("id", "file"), # Shape IDs + "pic": ("id", "file"), # Picture IDs + "grpsp": ("id", "file"), # Group shape IDs + } + + # Mapping of element names to expected relationship types + # Subclasses should override this with format-specific mappings + ELEMENT_RELATIONSHIP_TYPES = {} + + # Unified schema mappings for all Office document types + SCHEMA_MAPPINGS = { + # Document type specific schemas + "word": "ISO-IEC29500-4_2016/wml.xsd", # Word documents + "ppt": "ISO-IEC29500-4_2016/pml.xsd", # PowerPoint presentations + "xl": "ISO-IEC29500-4_2016/sml.xsd", # Excel spreadsheets + # Common file types + "[Content_Types].xml": "ecma/fouth-edition/opc-contentTypes.xsd", + "app.xml": "ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd", + "core.xml": "ecma/fouth-edition/opc-coreProperties.xsd", + "custom.xml": "ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd", + ".rels": "ecma/fouth-edition/opc-relationships.xsd", + # Word-specific files + "people.xml": "microsoft/wml-2012.xsd", + "commentsIds.xml": "microsoft/wml-cid-2016.xsd", + "commentsExtensible.xml": "microsoft/wml-cex-2018.xsd", + "commentsExtended.xml": "microsoft/wml-2012.xsd", + # Chart files (common across document types) + "chart": "ISO-IEC29500-4_2016/dml-chart.xsd", + # Theme files (common across document types) + "theme": "ISO-IEC29500-4_2016/dml-main.xsd", + # Drawing and media files + "drawing": "ISO-IEC29500-4_2016/dml-main.xsd", + } + + # Unified namespace constants + MC_NAMESPACE = "http://schemas.openxmlformats.org/markup-compatibility/2006" + XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" + + # Common OOXML namespaces used across validators + PACKAGE_RELATIONSHIPS_NAMESPACE = ( + "http://schemas.openxmlformats.org/package/2006/relationships" + ) + OFFICE_RELATIONSHIPS_NAMESPACE = ( + "http://schemas.openxmlformats.org/officeDocument/2006/relationships" + ) + CONTENT_TYPES_NAMESPACE = ( + "http://schemas.openxmlformats.org/package/2006/content-types" + ) + + # Folders where we should clean ignorable namespaces + MAIN_CONTENT_FOLDERS = {"word", "ppt", "xl"} + + # All allowed OOXML namespaces (superset of all document types) + OOXML_NAMESPACES = { + "http://schemas.openxmlformats.org/officeDocument/2006/math", + "http://schemas.openxmlformats.org/officeDocument/2006/relationships", + "http://schemas.openxmlformats.org/schemaLibrary/2006/main", + "http://schemas.openxmlformats.org/drawingml/2006/main", + "http://schemas.openxmlformats.org/drawingml/2006/chart", + "http://schemas.openxmlformats.org/drawingml/2006/chartDrawing", + "http://schemas.openxmlformats.org/drawingml/2006/diagram", + "http://schemas.openxmlformats.org/drawingml/2006/picture", + "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing", + "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", + "http://schemas.openxmlformats.org/wordprocessingml/2006/main", + "http://schemas.openxmlformats.org/presentationml/2006/main", + "http://schemas.openxmlformats.org/spreadsheetml/2006/main", + "http://schemas.openxmlformats.org/officeDocument/2006/sharedTypes", + "http://www.w3.org/XML/1998/namespace", + } + + def __init__(self, unpacked_dir, original_file, verbose=False): + self.unpacked_dir = Path(unpacked_dir).resolve() + self.original_file = Path(original_file) + self.verbose = verbose + + # Set schemas directory + self.schemas_dir = Path(__file__).parent.parent.parent / "schemas" + + # Get all XML and .rels files + patterns = ["*.xml", "*.rels"] + self.xml_files = [ + f for pattern in patterns for f in self.unpacked_dir.rglob(pattern) + ] + + if not self.xml_files: + print(f"Warning: No XML files found in {self.unpacked_dir}") + + def validate(self): + """Run all validation checks and return True if all pass.""" + raise NotImplementedError("Subclasses must implement the validate method") + + def validate_xml(self): + """Validate that all XML files are well-formed.""" + errors = [] + + for xml_file in self.xml_files: + try: + # Try to parse the XML file + lxml.etree.parse(str(xml_file)) + except lxml.etree.XMLSyntaxError as e: + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Line {e.lineno}: {e.msg}" + ) + except Exception as e: + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Unexpected error: {str(e)}" + ) + + if errors: + print(f"FAILED - Found {len(errors)} XML violations:") + for error in errors: + print(error) + return False + else: + if self.verbose: + print("PASSED - All XML files are well-formed") + return True + + def validate_namespaces(self): + """Validate that namespace prefixes in Ignorable attributes are declared.""" + errors = [] + + for xml_file in self.xml_files: + try: + root = lxml.etree.parse(str(xml_file)).getroot() + declared = set(root.nsmap.keys()) - {None} # Exclude default namespace + + for attr_val in [ + v for k, v in root.attrib.items() if k.endswith("Ignorable") + ]: + undeclared = set(attr_val.split()) - declared + errors.extend( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Namespace '{ns}' in Ignorable but not declared" + for ns in undeclared + ) + except lxml.etree.XMLSyntaxError: + continue + + if errors: + print(f"FAILED - {len(errors)} namespace issues:") + for error in errors: + print(error) + return False + if self.verbose: + print("PASSED - All namespace prefixes properly declared") + return True + + def validate_unique_ids(self): + """Validate that specific IDs are unique according to OOXML requirements.""" + errors = [] + global_ids = {} # Track globally unique IDs across all files + + for xml_file in self.xml_files: + try: + root = lxml.etree.parse(str(xml_file)).getroot() + file_ids = {} # Track IDs that must be unique within this file + + # Remove all mc:AlternateContent elements from the tree + mc_elements = root.xpath( + ".//mc:AlternateContent", namespaces={"mc": self.MC_NAMESPACE} + ) + for elem in mc_elements: + elem.getparent().remove(elem) + + # Now check IDs in the cleaned tree + for elem in root.iter(): + # Get the element name without namespace + tag = ( + elem.tag.split("}")[-1].lower() + if "}" in elem.tag + else elem.tag.lower() + ) + + # Check if this element type has ID uniqueness requirements + if tag in self.UNIQUE_ID_REQUIREMENTS: + attr_name, scope = self.UNIQUE_ID_REQUIREMENTS[tag] + + # Look for the specified attribute + id_value = None + for attr, value in elem.attrib.items(): + attr_local = ( + attr.split("}")[-1].lower() + if "}" in attr + else attr.lower() + ) + if attr_local == attr_name: + id_value = value + break + + if id_value is not None: + if scope == "global": + # Check global uniqueness + if id_value in global_ids: + prev_file, prev_line, prev_tag = global_ids[ + id_value + ] + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Line {elem.sourceline}: Global ID '{id_value}' in <{tag}> " + f"already used in {prev_file} at line {prev_line} in <{prev_tag}>" + ) + else: + global_ids[id_value] = ( + xml_file.relative_to(self.unpacked_dir), + elem.sourceline, + tag, + ) + elif scope == "file": + # Check file-level uniqueness + key = (tag, attr_name) + if key not in file_ids: + file_ids[key] = {} + + if id_value in file_ids[key]: + prev_line = file_ids[key][id_value] + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Line {elem.sourceline}: Duplicate {attr_name}='{id_value}' in <{tag}> " + f"(first occurrence at line {prev_line})" + ) + else: + file_ids[key][id_value] = elem.sourceline + + except (lxml.etree.XMLSyntaxError, Exception) as e: + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" + ) + + if errors: + print(f"FAILED - Found {len(errors)} ID uniqueness violations:") + for error in errors: + print(error) + return False + else: + if self.verbose: + print("PASSED - All required IDs are unique") + return True + + def validate_file_references(self): + """ + Validate that all .rels files properly reference files and that all files are referenced. + """ + errors = [] + + # Find all .rels files + rels_files = list(self.unpacked_dir.rglob("*.rels")) + + if not rels_files: + if self.verbose: + print("PASSED - No .rels files found") + return True + + # Get all files in the unpacked directory (excluding reference files) + all_files = [] + for file_path in self.unpacked_dir.rglob("*"): + if ( + file_path.is_file() + and file_path.name != "[Content_Types].xml" + and not file_path.name.endswith(".rels") + ): # This file is not referenced by .rels + all_files.append(file_path.resolve()) + + # Track all files that are referenced by any .rels file + all_referenced_files = set() + + if self.verbose: + print( + f"Found {len(rels_files)} .rels files and {len(all_files)} target files" + ) + + # Check each .rels file + for rels_file in rels_files: + try: + # Parse relationships file + rels_root = lxml.etree.parse(str(rels_file)).getroot() + + # Get the directory where this .rels file is located + rels_dir = rels_file.parent + + # Find all relationships and their targets + referenced_files = set() + broken_refs = [] + + for rel in rels_root.findall( + ".//ns:Relationship", + namespaces={"ns": self.PACKAGE_RELATIONSHIPS_NAMESPACE}, + ): + target = rel.get("Target") + if target and not target.startswith( + ("http", "mailto:") + ): # Skip external URLs + # Resolve the target path relative to the .rels file location + if rels_file.name == ".rels": + # Root .rels file - targets are relative to unpacked_dir + target_path = self.unpacked_dir / target + else: + # Other .rels files - targets are relative to their parent's parent + # e.g., word/_rels/document.xml.rels -> targets relative to word/ + base_dir = rels_dir.parent + target_path = base_dir / target + + # Normalize the path and check if it exists + try: + target_path = target_path.resolve() + if target_path.exists() and target_path.is_file(): + referenced_files.add(target_path) + all_referenced_files.add(target_path) + else: + broken_refs.append((target, rel.sourceline)) + except (OSError, ValueError): + broken_refs.append((target, rel.sourceline)) + + # Report broken references + if broken_refs: + rel_path = rels_file.relative_to(self.unpacked_dir) + for broken_ref, line_num in broken_refs: + errors.append( + f" {rel_path}: Line {line_num}: Broken reference to {broken_ref}" + ) + + except Exception as e: + rel_path = rels_file.relative_to(self.unpacked_dir) + errors.append(f" Error parsing {rel_path}: {e}") + + # Check for unreferenced files (files that exist but are not referenced anywhere) + unreferenced_files = set(all_files) - all_referenced_files + + if unreferenced_files: + for unref_file in sorted(unreferenced_files): + unref_rel_path = unref_file.relative_to(self.unpacked_dir) + errors.append(f" Unreferenced file: {unref_rel_path}") + + if errors: + print(f"FAILED - Found {len(errors)} relationship validation errors:") + for error in errors: + print(error) + print( + "CRITICAL: These errors will cause the document to appear corrupt. " + + "Broken references MUST be fixed, " + + "and unreferenced files MUST be referenced or removed." + ) + return False + else: + if self.verbose: + print( + "PASSED - All references are valid and all files are properly referenced" + ) + return True + + def validate_all_relationship_ids(self): + """ + Validate that all r:id attributes in XML files reference existing IDs + in their corresponding .rels files, and optionally validate relationship types. + """ + import lxml.etree + + errors = [] + + # Process each XML file that might contain r:id references + for xml_file in self.xml_files: + # Skip .rels files themselves + if xml_file.suffix == ".rels": + continue + + # Determine the corresponding .rels file + # For dir/file.xml, it's dir/_rels/file.xml.rels + rels_dir = xml_file.parent / "_rels" + rels_file = rels_dir / f"{xml_file.name}.rels" + + # Skip if there's no corresponding .rels file (that's okay) + if not rels_file.exists(): + continue + + try: + # Parse the .rels file to get valid relationship IDs and their types + rels_root = lxml.etree.parse(str(rels_file)).getroot() + rid_to_type = {} + + for rel in rels_root.findall( + f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" + ): + rid = rel.get("Id") + rel_type = rel.get("Type", "") + if rid: + # Check for duplicate rIds + if rid in rid_to_type: + rels_rel_path = rels_file.relative_to(self.unpacked_dir) + errors.append( + f" {rels_rel_path}: Line {rel.sourceline}: " + f"Duplicate relationship ID '{rid}' (IDs must be unique)" + ) + # Extract just the type name from the full URL + type_name = ( + rel_type.split("/")[-1] if "/" in rel_type else rel_type + ) + rid_to_type[rid] = type_name + + # Parse the XML file to find all r:id references + xml_root = lxml.etree.parse(str(xml_file)).getroot() + + # Find all elements with r:id attributes + for elem in xml_root.iter(): + # Check for r:id attribute (relationship ID) + rid_attr = elem.get(f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id") + if rid_attr: + xml_rel_path = xml_file.relative_to(self.unpacked_dir) + elem_name = ( + elem.tag.split("}")[-1] if "}" in elem.tag else elem.tag + ) + + # Check if the ID exists + if rid_attr not in rid_to_type: + errors.append( + f" {xml_rel_path}: Line {elem.sourceline}: " + f"<{elem_name}> references non-existent relationship '{rid_attr}' " + f"(valid IDs: {', '.join(sorted(rid_to_type.keys())[:5])}{'...' if len(rid_to_type) > 5 else ''})" + ) + # Check if we have type expectations for this element + elif self.ELEMENT_RELATIONSHIP_TYPES: + expected_type = self._get_expected_relationship_type( + elem_name + ) + if expected_type: + actual_type = rid_to_type[rid_attr] + # Check if the actual type matches or contains the expected type + if expected_type not in actual_type.lower(): + errors.append( + f" {xml_rel_path}: Line {elem.sourceline}: " + f"<{elem_name}> references '{rid_attr}' which points to '{actual_type}' " + f"but should point to a '{expected_type}' relationship" + ) + + except Exception as e: + xml_rel_path = xml_file.relative_to(self.unpacked_dir) + errors.append(f" Error processing {xml_rel_path}: {e}") + + if errors: + print(f"FAILED - Found {len(errors)} relationship ID reference errors:") + for error in errors: + print(error) + print("\nThese ID mismatches will cause the document to appear corrupt!") + return False + else: + if self.verbose: + print("PASSED - All relationship ID references are valid") + return True + + def _get_expected_relationship_type(self, element_name): + """ + Get the expected relationship type for an element. + First checks the explicit mapping, then tries pattern detection. + """ + # Normalize element name to lowercase + elem_lower = element_name.lower() + + # Check explicit mapping first + if elem_lower in self.ELEMENT_RELATIONSHIP_TYPES: + return self.ELEMENT_RELATIONSHIP_TYPES[elem_lower] + + # Try pattern detection for common patterns + # Pattern 1: Elements ending in "Id" often expect a relationship of the prefix type + if elem_lower.endswith("id") and len(elem_lower) > 2: + # e.g., "sldId" -> "sld", "sldMasterId" -> "sldMaster" + prefix = elem_lower[:-2] # Remove "id" + # Check if this might be a compound like "sldMasterId" + if prefix.endswith("master"): + return prefix.lower() + elif prefix.endswith("layout"): + return prefix.lower() + else: + # Simple case like "sldId" -> "slide" + # Common transformations + if prefix == "sld": + return "slide" + return prefix.lower() + + # Pattern 2: Elements ending in "Reference" expect a relationship of the prefix type + if elem_lower.endswith("reference") and len(elem_lower) > 9: + prefix = elem_lower[:-9] # Remove "reference" + return prefix.lower() + + return None + + def validate_content_types(self): + """Validate that all content files are properly declared in [Content_Types].xml.""" + errors = [] + + # Find [Content_Types].xml file + content_types_file = self.unpacked_dir / "[Content_Types].xml" + if not content_types_file.exists(): + print("FAILED - [Content_Types].xml file not found") + return False + + try: + # Parse and get all declared parts and extensions + root = lxml.etree.parse(str(content_types_file)).getroot() + declared_parts = set() + declared_extensions = set() + + # Get Override declarations (specific files) + for override in root.findall( + f".//{{{self.CONTENT_TYPES_NAMESPACE}}}Override" + ): + part_name = override.get("PartName") + if part_name is not None: + declared_parts.add(part_name.lstrip("/")) + + # Get Default declarations (by extension) + for default in root.findall( + f".//{{{self.CONTENT_TYPES_NAMESPACE}}}Default" + ): + extension = default.get("Extension") + if extension is not None: + declared_extensions.add(extension.lower()) + + # Root elements that require content type declaration + declarable_roots = { + "sld", + "sldLayout", + "sldMaster", + "presentation", # PowerPoint + "document", # Word + "workbook", + "worksheet", # Excel + "theme", # Common + } + + # Common media file extensions that should be declared + media_extensions = { + "png": "image/png", + "jpg": "image/jpeg", + "jpeg": "image/jpeg", + "gif": "image/gif", + "bmp": "image/bmp", + "tiff": "image/tiff", + "wmf": "image/x-wmf", + "emf": "image/x-emf", + } + + # Get all files in the unpacked directory + all_files = list(self.unpacked_dir.rglob("*")) + all_files = [f for f in all_files if f.is_file()] + + # Check all XML files for Override declarations + for xml_file in self.xml_files: + path_str = str(xml_file.relative_to(self.unpacked_dir)).replace( + "\\", "/" + ) + + # Skip non-content files + if any( + skip in path_str + for skip in [".rels", "[Content_Types]", "docProps/", "_rels/"] + ): + continue + + try: + root_tag = lxml.etree.parse(str(xml_file)).getroot().tag + root_name = root_tag.split("}")[-1] if "}" in root_tag else root_tag + + if root_name in declarable_roots and path_str not in declared_parts: + errors.append( + f" {path_str}: File with <{root_name}> root not declared in [Content_Types].xml" + ) + + except Exception: + continue # Skip unparseable files + + # Check all non-XML files for Default extension declarations + for file_path in all_files: + # Skip XML files and metadata files (already checked above) + if file_path.suffix.lower() in {".xml", ".rels"}: + continue + if file_path.name == "[Content_Types].xml": + continue + if "_rels" in file_path.parts or "docProps" in file_path.parts: + continue + + extension = file_path.suffix.lstrip(".").lower() + if extension and extension not in declared_extensions: + # Check if it's a known media extension that should be declared + if extension in media_extensions: + relative_path = file_path.relative_to(self.unpacked_dir) + errors.append( + f' {relative_path}: File with extension \'{extension}\' not declared in [Content_Types].xml - should add: ' + ) + + except Exception as e: + errors.append(f" Error parsing [Content_Types].xml: {e}") + + if errors: + print(f"FAILED - Found {len(errors)} content type declaration errors:") + for error in errors: + print(error) + return False + else: + if self.verbose: + print( + "PASSED - All content files are properly declared in [Content_Types].xml" + ) + return True + + def validate_file_against_xsd(self, xml_file, verbose=False): + """Validate a single XML file against XSD schema, comparing with original. + + Args: + xml_file: Path to XML file to validate + verbose: Enable verbose output + + Returns: + tuple: (is_valid, new_errors_set) where is_valid is True/False/None (skipped) + """ + # Resolve both paths to handle symlinks + xml_file = Path(xml_file).resolve() + unpacked_dir = self.unpacked_dir.resolve() + + # Validate current file + is_valid, current_errors = self._validate_single_file_xsd( + xml_file, unpacked_dir + ) + + if is_valid is None: + return None, set() # Skipped + elif is_valid: + return True, set() # Valid, no errors + + # Get errors from original file for this specific file + original_errors = self._get_original_file_errors(xml_file) + + # Compare with original (both are guaranteed to be sets here) + assert current_errors is not None + new_errors = current_errors - original_errors + + if new_errors: + if verbose: + relative_path = xml_file.relative_to(unpacked_dir) + print(f"FAILED - {relative_path}: {len(new_errors)} new error(s)") + for error in list(new_errors)[:3]: + truncated = error[:250] + "..." if len(error) > 250 else error + print(f" - {truncated}") + return False, new_errors + else: + # All errors existed in original + if verbose: + print( + f"PASSED - No new errors (original had {len(current_errors)} errors)" + ) + return True, set() + + def validate_against_xsd(self): + """Validate XML files against XSD schemas, showing only new errors compared to original.""" + new_errors = [] + original_error_count = 0 + valid_count = 0 + skipped_count = 0 + + for xml_file in self.xml_files: + relative_path = str(xml_file.relative_to(self.unpacked_dir)) + is_valid, new_file_errors = self.validate_file_against_xsd( + xml_file, verbose=False + ) + + if is_valid is None: + skipped_count += 1 + continue + elif is_valid and not new_file_errors: + valid_count += 1 + continue + elif is_valid: + # Had errors but all existed in original + original_error_count += 1 + valid_count += 1 + continue + + # Has new errors + new_errors.append(f" {relative_path}: {len(new_file_errors)} new error(s)") + for error in list(new_file_errors)[:3]: # Show first 3 errors + new_errors.append( + f" - {error[:250]}..." if len(error) > 250 else f" - {error}" + ) + + # Print summary + if self.verbose: + print(f"Validated {len(self.xml_files)} files:") + print(f" - Valid: {valid_count}") + print(f" - Skipped (no schema): {skipped_count}") + if original_error_count: + print(f" - With original errors (ignored): {original_error_count}") + print( + f" - With NEW errors: {len(new_errors) > 0 and len([e for e in new_errors if not e.startswith(' ')]) or 0}" + ) + + if new_errors: + print("\nFAILED - Found NEW validation errors:") + for error in new_errors: + print(error) + return False + else: + if self.verbose: + print("\nPASSED - No new XSD validation errors introduced") + return True + + def _get_schema_path(self, xml_file): + """Determine the appropriate schema path for an XML file.""" + # Check exact filename match + if xml_file.name in self.SCHEMA_MAPPINGS: + return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.name] + + # Check .rels files + if xml_file.suffix == ".rels": + return self.schemas_dir / self.SCHEMA_MAPPINGS[".rels"] + + # Check chart files + if "charts/" in str(xml_file) and xml_file.name.startswith("chart"): + return self.schemas_dir / self.SCHEMA_MAPPINGS["chart"] + + # Check theme files + if "theme/" in str(xml_file) and xml_file.name.startswith("theme"): + return self.schemas_dir / self.SCHEMA_MAPPINGS["theme"] + + # Check if file is in a main content folder and use appropriate schema + if xml_file.parent.name in self.MAIN_CONTENT_FOLDERS: + return self.schemas_dir / self.SCHEMA_MAPPINGS[xml_file.parent.name] + + return None + + def _clean_ignorable_namespaces(self, xml_doc): + """Remove attributes and elements not in allowed namespaces.""" + # Create a clean copy + xml_string = lxml.etree.tostring(xml_doc, encoding="unicode") + xml_copy = lxml.etree.fromstring(xml_string) + + # Remove attributes not in allowed namespaces + for elem in xml_copy.iter(): + attrs_to_remove = [] + + for attr in elem.attrib: + # Check if attribute is from a namespace other than allowed ones + if "{" in attr: + ns = attr.split("}")[0][1:] + if ns not in self.OOXML_NAMESPACES: + attrs_to_remove.append(attr) + + # Remove collected attributes + for attr in attrs_to_remove: + del elem.attrib[attr] + + # Remove elements not in allowed namespaces + self._remove_ignorable_elements(xml_copy) + + return lxml.etree.ElementTree(xml_copy) + + def _remove_ignorable_elements(self, root): + """Recursively remove all elements not in allowed namespaces.""" + elements_to_remove = [] + + # Find elements to remove + for elem in list(root): + # Skip non-element nodes (comments, processing instructions, etc.) + if not hasattr(elem, "tag") or callable(elem.tag): + continue + + tag_str = str(elem.tag) + if tag_str.startswith("{"): + ns = tag_str.split("}")[0][1:] + if ns not in self.OOXML_NAMESPACES: + elements_to_remove.append(elem) + continue + + # Recursively clean child elements + self._remove_ignorable_elements(elem) + + # Remove collected elements + for elem in elements_to_remove: + root.remove(elem) + + def _preprocess_for_mc_ignorable(self, xml_doc): + """Preprocess XML to handle mc:Ignorable attribute properly.""" + # Remove mc:Ignorable attributes before validation + root = xml_doc.getroot() + + # Remove mc:Ignorable attribute from root + if f"{{{self.MC_NAMESPACE}}}Ignorable" in root.attrib: + del root.attrib[f"{{{self.MC_NAMESPACE}}}Ignorable"] + + return xml_doc + + def _validate_single_file_xsd(self, xml_file, base_path): + """Validate a single XML file against XSD schema. Returns (is_valid, errors_set).""" + schema_path = self._get_schema_path(xml_file) + if not schema_path: + return None, None # Skip file + + try: + # Load schema + with open(schema_path, "rb") as xsd_file: + parser = lxml.etree.XMLParser() + xsd_doc = lxml.etree.parse( + xsd_file, parser=parser, base_url=str(schema_path) + ) + schema = lxml.etree.XMLSchema(xsd_doc) + + # Load and preprocess XML + with open(xml_file, "r") as f: + xml_doc = lxml.etree.parse(f) + + xml_doc, _ = self._remove_template_tags_from_text_nodes(xml_doc) + xml_doc = self._preprocess_for_mc_ignorable(xml_doc) + + # Clean ignorable namespaces if needed + relative_path = xml_file.relative_to(base_path) + if ( + relative_path.parts + and relative_path.parts[0] in self.MAIN_CONTENT_FOLDERS + ): + xml_doc = self._clean_ignorable_namespaces(xml_doc) + + # Validate + if schema.validate(xml_doc): + return True, set() + else: + errors = set() + for error in schema.error_log: + # Store normalized error message (without line numbers for comparison) + errors.add(error.message) + return False, errors + + except Exception as e: + return False, {str(e)} + + def _get_original_file_errors(self, xml_file): + """Get XSD validation errors from a single file in the original document. + + Args: + xml_file: Path to the XML file in unpacked_dir to check + + Returns: + set: Set of error messages from the original file + """ + import tempfile + import zipfile + + # Resolve both paths to handle symlinks (e.g., /var vs /private/var on macOS) + xml_file = Path(xml_file).resolve() + unpacked_dir = self.unpacked_dir.resolve() + relative_path = xml_file.relative_to(unpacked_dir) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + + # Extract original file + with zipfile.ZipFile(self.original_file, "r") as zip_ref: + zip_ref.extractall(temp_path) + + # Find corresponding file in original + original_xml_file = temp_path / relative_path + + if not original_xml_file.exists(): + # File didn't exist in original, so no original errors + return set() + + # Validate the specific file in original + is_valid, errors = self._validate_single_file_xsd( + original_xml_file, temp_path + ) + return errors if errors else set() + + def _remove_template_tags_from_text_nodes(self, xml_doc): + """Remove template tags from XML text nodes and collect warnings. + + Template tags follow the pattern {{ ... }} and are used as placeholders + for content replacement. They should be removed from text content before + XSD validation while preserving XML structure. + + Returns: + tuple: (cleaned_xml_doc, warnings_list) + """ + warnings = [] + template_pattern = re.compile(r"\{\{[^}]*\}\}") + + # Create a copy of the document to avoid modifying the original + xml_string = lxml.etree.tostring(xml_doc, encoding="unicode") + xml_copy = lxml.etree.fromstring(xml_string) + + def process_text_content(text, content_type): + if not text: + return text + matches = list(template_pattern.finditer(text)) + if matches: + for match in matches: + warnings.append( + f"Found template tag in {content_type}: {match.group()}" + ) + return template_pattern.sub("", text) + return text + + # Process all text nodes in the document + for elem in xml_copy.iter(): + # Skip processing if this is a w:t element + if not hasattr(elem, "tag") or callable(elem.tag): + continue + tag_str = str(elem.tag) + if tag_str.endswith("}t") or tag_str == "t": + continue + + elem.text = process_text_content(elem.text, "text content") + elem.tail = process_text_content(elem.tail, "tail content") + + return lxml.etree.ElementTree(xml_copy), warnings + + +if __name__ == "__main__": + raise RuntimeError("This module should not be run directly.") diff --git a/pptx-mcp-server/ooxml/scripts/validation/docx.py b/pptx-mcp-server/ooxml/scripts/validation/docx.py new file mode 100644 index 0000000..602c470 --- /dev/null +++ b/pptx-mcp-server/ooxml/scripts/validation/docx.py @@ -0,0 +1,274 @@ +""" +Validator for Word document XML files against XSD schemas. +""" + +import re +import tempfile +import zipfile + +import lxml.etree + +from .base import BaseSchemaValidator + + +class DOCXSchemaValidator(BaseSchemaValidator): + """Validator for Word document XML files against XSD schemas.""" + + # Word-specific namespace + WORD_2006_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" + + # Word-specific element to relationship type mappings + # Start with empty mapping - add specific cases as we discover them + ELEMENT_RELATIONSHIP_TYPES = {} + + def validate(self): + """Run all validation checks and return True if all pass.""" + # Test 0: XML well-formedness + if not self.validate_xml(): + return False + + # Test 1: Namespace declarations + all_valid = True + if not self.validate_namespaces(): + all_valid = False + + # Test 2: Unique IDs + if not self.validate_unique_ids(): + all_valid = False + + # Test 3: Relationship and file reference validation + if not self.validate_file_references(): + all_valid = False + + # Test 4: Content type declarations + if not self.validate_content_types(): + all_valid = False + + # Test 5: XSD schema validation + if not self.validate_against_xsd(): + all_valid = False + + # Test 6: Whitespace preservation + if not self.validate_whitespace_preservation(): + all_valid = False + + # Test 7: Deletion validation + if not self.validate_deletions(): + all_valid = False + + # Test 8: Insertion validation + if not self.validate_insertions(): + all_valid = False + + # Test 9: Relationship ID reference validation + if not self.validate_all_relationship_ids(): + all_valid = False + + # Count and compare paragraphs + self.compare_paragraph_counts() + + return all_valid + + def validate_whitespace_preservation(self): + """ + Validate that w:t elements with whitespace have xml:space='preserve'. + """ + errors = [] + + for xml_file in self.xml_files: + # Only check document.xml files + if xml_file.name != "document.xml": + continue + + try: + root = lxml.etree.parse(str(xml_file)).getroot() + + # Find all w:t elements + for elem in root.iter(f"{{{self.WORD_2006_NAMESPACE}}}t"): + if elem.text: + text = elem.text + # Check if text starts or ends with whitespace + if re.match(r"^\s.*", text) or re.match(r".*\s$", text): + # Check if xml:space="preserve" attribute exists + xml_space_attr = f"{{{self.XML_NAMESPACE}}}space" + if ( + xml_space_attr not in elem.attrib + or elem.attrib[xml_space_attr] != "preserve" + ): + # Show a preview of the text + text_preview = ( + repr(text)[:50] + "..." + if len(repr(text)) > 50 + else repr(text) + ) + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Line {elem.sourceline}: w:t element with whitespace missing xml:space='preserve': {text_preview}" + ) + + except (lxml.etree.XMLSyntaxError, Exception) as e: + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" + ) + + if errors: + print(f"FAILED - Found {len(errors)} whitespace preservation violations:") + for error in errors: + print(error) + return False + else: + if self.verbose: + print("PASSED - All whitespace is properly preserved") + return True + + def validate_deletions(self): + """ + Validate that w:t elements are not within w:del elements. + For some reason, XSD validation does not catch this, so we do it manually. + """ + errors = [] + + for xml_file in self.xml_files: + # Only check document.xml files + if xml_file.name != "document.xml": + continue + + try: + root = lxml.etree.parse(str(xml_file)).getroot() + + # Find all w:t elements that are descendants of w:del elements + namespaces = {"w": self.WORD_2006_NAMESPACE} + xpath_expression = ".//w:del//w:t" + problematic_t_elements = root.xpath( + xpath_expression, namespaces=namespaces + ) + for t_elem in problematic_t_elements: + if t_elem.text: + # Show a preview of the text + text_preview = ( + repr(t_elem.text)[:50] + "..." + if len(repr(t_elem.text)) > 50 + else repr(t_elem.text) + ) + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Line {t_elem.sourceline}: found within : {text_preview}" + ) + + except (lxml.etree.XMLSyntaxError, Exception) as e: + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" + ) + + if errors: + print(f"FAILED - Found {len(errors)} deletion validation violations:") + for error in errors: + print(error) + return False + else: + if self.verbose: + print("PASSED - No w:t elements found within w:del elements") + return True + + def count_paragraphs_in_unpacked(self): + """Count the number of paragraphs in the unpacked document.""" + count = 0 + + for xml_file in self.xml_files: + # Only check document.xml files + if xml_file.name != "document.xml": + continue + + try: + root = lxml.etree.parse(str(xml_file)).getroot() + # Count all w:p elements + paragraphs = root.findall(f".//{{{self.WORD_2006_NAMESPACE}}}p") + count = len(paragraphs) + except Exception as e: + print(f"Error counting paragraphs in unpacked document: {e}") + + return count + + def count_paragraphs_in_original(self): + """Count the number of paragraphs in the original docx file.""" + count = 0 + + try: + # Create temporary directory to unpack original + with tempfile.TemporaryDirectory() as temp_dir: + # Unpack original docx + with zipfile.ZipFile(self.original_file, "r") as zip_ref: + zip_ref.extractall(temp_dir) + + # Parse document.xml + doc_xml_path = temp_dir + "/word/document.xml" + root = lxml.etree.parse(doc_xml_path).getroot() + + # Count all w:p elements + paragraphs = root.findall(f".//{{{self.WORD_2006_NAMESPACE}}}p") + count = len(paragraphs) + + except Exception as e: + print(f"Error counting paragraphs in original document: {e}") + + return count + + def validate_insertions(self): + """ + Validate that w:delText elements are not within w:ins elements. + w:delText is only allowed in w:ins if nested within a w:del. + """ + errors = [] + + for xml_file in self.xml_files: + if xml_file.name != "document.xml": + continue + + try: + root = lxml.etree.parse(str(xml_file)).getroot() + namespaces = {"w": self.WORD_2006_NAMESPACE} + + # Find w:delText in w:ins that are NOT within w:del + invalid_elements = root.xpath( + ".//w:ins//w:delText[not(ancestor::w:del)]", + namespaces=namespaces + ) + + for elem in invalid_elements: + text_preview = ( + repr(elem.text or "")[:50] + "..." + if len(repr(elem.text or "")) > 50 + else repr(elem.text or "") + ) + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Line {elem.sourceline}: within : {text_preview}" + ) + + except (lxml.etree.XMLSyntaxError, Exception) as e: + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" + ) + + if errors: + print(f"FAILED - Found {len(errors)} insertion validation violations:") + for error in errors: + print(error) + return False + else: + if self.verbose: + print("PASSED - No w:delText elements within w:ins elements") + return True + + def compare_paragraph_counts(self): + """Compare paragraph counts between original and new document.""" + original_count = self.count_paragraphs_in_original() + new_count = self.count_paragraphs_in_unpacked() + + diff = new_count - original_count + diff_str = f"+{diff}" if diff > 0 else str(diff) + print(f"\nParagraphs: {original_count} → {new_count} ({diff_str})") + + +if __name__ == "__main__": + raise RuntimeError("This module should not be run directly.") diff --git a/pptx-mcp-server/ooxml/scripts/validation/pptx.py b/pptx-mcp-server/ooxml/scripts/validation/pptx.py new file mode 100644 index 0000000..66d5b1e --- /dev/null +++ b/pptx-mcp-server/ooxml/scripts/validation/pptx.py @@ -0,0 +1,315 @@ +""" +Validator for PowerPoint presentation XML files against XSD schemas. +""" + +import re + +from .base import BaseSchemaValidator + + +class PPTXSchemaValidator(BaseSchemaValidator): + """Validator for PowerPoint presentation XML files against XSD schemas.""" + + # PowerPoint presentation namespace + PRESENTATIONML_NAMESPACE = ( + "http://schemas.openxmlformats.org/presentationml/2006/main" + ) + + # PowerPoint-specific element to relationship type mappings + ELEMENT_RELATIONSHIP_TYPES = { + "sldid": "slide", + "sldmasterid": "slidemaster", + "notesmasterid": "notesmaster", + "sldlayoutid": "slidelayout", + "themeid": "theme", + "tablestyleid": "tablestyles", + } + + def validate(self): + """Run all validation checks and return True if all pass.""" + # Test 0: XML well-formedness + if not self.validate_xml(): + return False + + # Test 1: Namespace declarations + all_valid = True + if not self.validate_namespaces(): + all_valid = False + + # Test 2: Unique IDs + if not self.validate_unique_ids(): + all_valid = False + + # Test 3: UUID ID validation + if not self.validate_uuid_ids(): + all_valid = False + + # Test 4: Relationship and file reference validation + if not self.validate_file_references(): + all_valid = False + + # Test 5: Slide layout ID validation + if not self.validate_slide_layout_ids(): + all_valid = False + + # Test 6: Content type declarations + if not self.validate_content_types(): + all_valid = False + + # Test 7: XSD schema validation + if not self.validate_against_xsd(): + all_valid = False + + # Test 8: Notes slide reference validation + if not self.validate_notes_slide_references(): + all_valid = False + + # Test 9: Relationship ID reference validation + if not self.validate_all_relationship_ids(): + all_valid = False + + # Test 10: Duplicate slide layout references validation + if not self.validate_no_duplicate_slide_layouts(): + all_valid = False + + return all_valid + + def validate_uuid_ids(self): + """Validate that ID attributes that look like UUIDs contain only hex values.""" + import lxml.etree + + errors = [] + # UUID pattern: 8-4-4-4-12 hex digits with optional braces/hyphens + uuid_pattern = re.compile( + r"^[\{\(]?[0-9A-Fa-f]{8}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{12}[\}\)]?$" + ) + + for xml_file in self.xml_files: + try: + root = lxml.etree.parse(str(xml_file)).getroot() + + # Check all elements for ID attributes + for elem in root.iter(): + for attr, value in elem.attrib.items(): + # Check if this is an ID attribute + attr_name = attr.split("}")[-1].lower() + if attr_name == "id" or attr_name.endswith("id"): + # Check if value looks like a UUID (has the right length and pattern structure) + if self._looks_like_uuid(value): + # Validate that it contains only hex characters in the right positions + if not uuid_pattern.match(value): + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: " + f"Line {elem.sourceline}: ID '{value}' appears to be a UUID but contains invalid hex characters" + ) + + except (lxml.etree.XMLSyntaxError, Exception) as e: + errors.append( + f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}" + ) + + if errors: + print(f"FAILED - Found {len(errors)} UUID ID validation errors:") + for error in errors: + print(error) + return False + else: + if self.verbose: + print("PASSED - All UUID-like IDs contain valid hex values") + return True + + def _looks_like_uuid(self, value): + """Check if a value has the general structure of a UUID.""" + # Remove common UUID delimiters + clean_value = value.strip("{}()").replace("-", "") + # Check if it's 32 hex-like characters (could include invalid hex chars) + return len(clean_value) == 32 and all(c.isalnum() for c in clean_value) + + def validate_slide_layout_ids(self): + """Validate that sldLayoutId elements in slide masters reference valid slide layouts.""" + import lxml.etree + + errors = [] + + # Find all slide master files + slide_masters = list(self.unpacked_dir.glob("ppt/slideMasters/*.xml")) + + if not slide_masters: + if self.verbose: + print("PASSED - No slide masters found") + return True + + for slide_master in slide_masters: + try: + # Parse the slide master file + root = lxml.etree.parse(str(slide_master)).getroot() + + # Find the corresponding _rels file for this slide master + rels_file = slide_master.parent / "_rels" / f"{slide_master.name}.rels" + + if not rels_file.exists(): + errors.append( + f" {slide_master.relative_to(self.unpacked_dir)}: " + f"Missing relationships file: {rels_file.relative_to(self.unpacked_dir)}" + ) + continue + + # Parse the relationships file + rels_root = lxml.etree.parse(str(rels_file)).getroot() + + # Build a set of valid relationship IDs that point to slide layouts + valid_layout_rids = set() + for rel in rels_root.findall( + f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" + ): + rel_type = rel.get("Type", "") + if "slideLayout" in rel_type: + valid_layout_rids.add(rel.get("Id")) + + # Find all sldLayoutId elements in the slide master + for sld_layout_id in root.findall( + f".//{{{self.PRESENTATIONML_NAMESPACE}}}sldLayoutId" + ): + r_id = sld_layout_id.get( + f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id" + ) + layout_id = sld_layout_id.get("id") + + if r_id and r_id not in valid_layout_rids: + errors.append( + f" {slide_master.relative_to(self.unpacked_dir)}: " + f"Line {sld_layout_id.sourceline}: sldLayoutId with id='{layout_id}' " + f"references r:id='{r_id}' which is not found in slide layout relationships" + ) + + except (lxml.etree.XMLSyntaxError, Exception) as e: + errors.append( + f" {slide_master.relative_to(self.unpacked_dir)}: Error: {e}" + ) + + if errors: + print(f"FAILED - Found {len(errors)} slide layout ID validation errors:") + for error in errors: + print(error) + print( + "Remove invalid references or add missing slide layouts to the relationships file." + ) + return False + else: + if self.verbose: + print("PASSED - All slide layout IDs reference valid slide layouts") + return True + + def validate_no_duplicate_slide_layouts(self): + """Validate that each slide has exactly one slideLayout reference.""" + import lxml.etree + + errors = [] + slide_rels_files = list(self.unpacked_dir.glob("ppt/slides/_rels/*.xml.rels")) + + for rels_file in slide_rels_files: + try: + root = lxml.etree.parse(str(rels_file)).getroot() + + # Find all slideLayout relationships + layout_rels = [ + rel + for rel in root.findall( + f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" + ) + if "slideLayout" in rel.get("Type", "") + ] + + if len(layout_rels) > 1: + errors.append( + f" {rels_file.relative_to(self.unpacked_dir)}: has {len(layout_rels)} slideLayout references" + ) + + except Exception as e: + errors.append( + f" {rels_file.relative_to(self.unpacked_dir)}: Error: {e}" + ) + + if errors: + print("FAILED - Found slides with duplicate slideLayout references:") + for error in errors: + print(error) + return False + else: + if self.verbose: + print("PASSED - All slides have exactly one slideLayout reference") + return True + + def validate_notes_slide_references(self): + """Validate that each notesSlide file is referenced by only one slide.""" + import lxml.etree + + errors = [] + notes_slide_references = {} # Track which slides reference each notesSlide + + # Find all slide relationship files + slide_rels_files = list(self.unpacked_dir.glob("ppt/slides/_rels/*.xml.rels")) + + if not slide_rels_files: + if self.verbose: + print("PASSED - No slide relationship files found") + return True + + for rels_file in slide_rels_files: + try: + # Parse the relationships file + root = lxml.etree.parse(str(rels_file)).getroot() + + # Find all notesSlide relationships + for rel in root.findall( + f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship" + ): + rel_type = rel.get("Type", "") + if "notesSlide" in rel_type: + target = rel.get("Target", "") + if target: + # Normalize the target path to handle relative paths + normalized_target = target.replace("../", "") + + # Track which slide references this notesSlide + slide_name = rels_file.stem.replace( + ".xml", "" + ) # e.g., "slide1" + + if normalized_target not in notes_slide_references: + notes_slide_references[normalized_target] = [] + notes_slide_references[normalized_target].append( + (slide_name, rels_file) + ) + + except (lxml.etree.XMLSyntaxError, Exception) as e: + errors.append( + f" {rels_file.relative_to(self.unpacked_dir)}: Error: {e}" + ) + + # Check for duplicate references + for target, references in notes_slide_references.items(): + if len(references) > 1: + slide_names = [ref[0] for ref in references] + errors.append( + f" Notes slide '{target}' is referenced by multiple slides: {', '.join(slide_names)}" + ) + for slide_name, rels_file in references: + errors.append(f" - {rels_file.relative_to(self.unpacked_dir)}") + + if errors: + print( + f"FAILED - Found {len([e for e in errors if not e.startswith(' ')])} notes slide reference validation errors:" + ) + for error in errors: + print(error) + print("Each slide may optionally have its own slide file.") + return False + else: + if self.verbose: + print("PASSED - All notes slide references are unique") + return True + + +if __name__ == "__main__": + raise RuntimeError("This module should not be run directly.") diff --git a/pptx-mcp-server/ooxml/scripts/validation/redlining.py b/pptx-mcp-server/ooxml/scripts/validation/redlining.py new file mode 100644 index 0000000..7ed425e --- /dev/null +++ b/pptx-mcp-server/ooxml/scripts/validation/redlining.py @@ -0,0 +1,279 @@ +""" +Validator for tracked changes in Word documents. +""" + +import subprocess +import tempfile +import zipfile +from pathlib import Path + + +class RedliningValidator: + """Validator for tracked changes in Word documents.""" + + def __init__(self, unpacked_dir, original_docx, verbose=False): + self.unpacked_dir = Path(unpacked_dir) + self.original_docx = Path(original_docx) + self.verbose = verbose + self.namespaces = { + "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main" + } + + def validate(self): + """Main validation method that returns True if valid, False otherwise.""" + # Verify unpacked directory exists and has correct structure + modified_file = self.unpacked_dir / "word" / "document.xml" + if not modified_file.exists(): + print(f"FAILED - Modified document.xml not found at {modified_file}") + return False + + # First, check if there are any tracked changes by Claude to validate + try: + import xml.etree.ElementTree as ET + + tree = ET.parse(modified_file) + root = tree.getroot() + + # Check for w:del or w:ins tags authored by Claude + del_elements = root.findall(".//w:del", self.namespaces) + ins_elements = root.findall(".//w:ins", self.namespaces) + + # Filter to only include changes by Claude + claude_del_elements = [ + elem + for elem in del_elements + if elem.get(f"{{{self.namespaces['w']}}}author") == "Claude" + ] + claude_ins_elements = [ + elem + for elem in ins_elements + if elem.get(f"{{{self.namespaces['w']}}}author") == "Claude" + ] + + # Redlining validation is only needed if tracked changes by Claude have been used. + if not claude_del_elements and not claude_ins_elements: + if self.verbose: + print("PASSED - No tracked changes by Claude found.") + return True + + except Exception: + # If we can't parse the XML, continue with full validation + pass + + # Create temporary directory for unpacking original docx + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + + # Unpack original docx + try: + with zipfile.ZipFile(self.original_docx, "r") as zip_ref: + zip_ref.extractall(temp_path) + except Exception as e: + print(f"FAILED - Error unpacking original docx: {e}") + return False + + original_file = temp_path / "word" / "document.xml" + if not original_file.exists(): + print( + f"FAILED - Original document.xml not found in {self.original_docx}" + ) + return False + + # Parse both XML files using xml.etree.ElementTree for redlining validation + try: + import xml.etree.ElementTree as ET + + modified_tree = ET.parse(modified_file) + modified_root = modified_tree.getroot() + original_tree = ET.parse(original_file) + original_root = original_tree.getroot() + except ET.ParseError as e: + print(f"FAILED - Error parsing XML files: {e}") + return False + + # Remove Claude's tracked changes from both documents + self._remove_claude_tracked_changes(original_root) + self._remove_claude_tracked_changes(modified_root) + + # Extract and compare text content + modified_text = self._extract_text_content(modified_root) + original_text = self._extract_text_content(original_root) + + if modified_text != original_text: + # Show detailed character-level differences for each paragraph + error_message = self._generate_detailed_diff( + original_text, modified_text + ) + print(error_message) + return False + + if self.verbose: + print("PASSED - All changes by Claude are properly tracked") + return True + + def _generate_detailed_diff(self, original_text, modified_text): + """Generate detailed word-level differences using git word diff.""" + error_parts = [ + "FAILED - Document text doesn't match after removing Claude's tracked changes", + "", + "Likely causes:", + " 1. Modified text inside another author's or tags", + " 2. Made edits without proper tracked changes", + " 3. Didn't nest inside when deleting another's insertion", + "", + "For pre-redlined documents, use correct patterns:", + " - To reject another's INSERTION: Nest inside their ", + " - To restore another's DELETION: Add new AFTER their ", + "", + ] + + # Show git word diff + git_diff = self._get_git_word_diff(original_text, modified_text) + if git_diff: + error_parts.extend(["Differences:", "============", git_diff]) + else: + error_parts.append("Unable to generate word diff (git not available)") + + return "\n".join(error_parts) + + def _get_git_word_diff(self, original_text, modified_text): + """Generate word diff using git with character-level precision.""" + try: + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + + # Create two files + original_file = temp_path / "original.txt" + modified_file = temp_path / "modified.txt" + + original_file.write_text(original_text, encoding="utf-8") + modified_file.write_text(modified_text, encoding="utf-8") + + # Try character-level diff first for precise differences + result = subprocess.run( + [ + "git", + "diff", + "--word-diff=plain", + "--word-diff-regex=.", # Character-by-character diff + "-U0", # Zero lines of context - show only changed lines + "--no-index", + str(original_file), + str(modified_file), + ], + capture_output=True, + text=True, + ) + + if result.stdout.strip(): + # Clean up the output - remove git diff header lines + lines = result.stdout.split("\n") + # Skip the header lines (diff --git, index, +++, ---, @@) + content_lines = [] + in_content = False + for line in lines: + if line.startswith("@@"): + in_content = True + continue + if in_content and line.strip(): + content_lines.append(line) + + if content_lines: + return "\n".join(content_lines) + + # Fallback to word-level diff if character-level is too verbose + result = subprocess.run( + [ + "git", + "diff", + "--word-diff=plain", + "-U0", # Zero lines of context + "--no-index", + str(original_file), + str(modified_file), + ], + capture_output=True, + text=True, + ) + + if result.stdout.strip(): + lines = result.stdout.split("\n") + content_lines = [] + in_content = False + for line in lines: + if line.startswith("@@"): + in_content = True + continue + if in_content and line.strip(): + content_lines.append(line) + return "\n".join(content_lines) + + except (subprocess.CalledProcessError, FileNotFoundError, Exception): + # Git not available or other error, return None to use fallback + pass + + return None + + def _remove_claude_tracked_changes(self, root): + """Remove tracked changes authored by Claude from the XML root.""" + ins_tag = f"{{{self.namespaces['w']}}}ins" + del_tag = f"{{{self.namespaces['w']}}}del" + author_attr = f"{{{self.namespaces['w']}}}author" + + # Remove w:ins elements + for parent in root.iter(): + to_remove = [] + for child in parent: + if child.tag == ins_tag and child.get(author_attr) == "Claude": + to_remove.append(child) + for elem in to_remove: + parent.remove(elem) + + # Unwrap content in w:del elements where author is "Claude" + deltext_tag = f"{{{self.namespaces['w']}}}delText" + t_tag = f"{{{self.namespaces['w']}}}t" + + for parent in root.iter(): + to_process = [] + for child in parent: + if child.tag == del_tag and child.get(author_attr) == "Claude": + to_process.append((child, list(parent).index(child))) + + # Process in reverse order to maintain indices + for del_elem, del_index in reversed(to_process): + # Convert w:delText to w:t before moving + for elem in del_elem.iter(): + if elem.tag == deltext_tag: + elem.tag = t_tag + + # Move all children of w:del to its parent before removing w:del + for child in reversed(list(del_elem)): + parent.insert(del_index, child) + parent.remove(del_elem) + + def _extract_text_content(self, root): + """Extract text content from Word XML, preserving paragraph structure. + + Empty paragraphs are skipped to avoid false positives when tracked + insertions add only structural elements without text content. + """ + p_tag = f"{{{self.namespaces['w']}}}p" + t_tag = f"{{{self.namespaces['w']}}}t" + + paragraphs = [] + for p_elem in root.findall(f".//{p_tag}"): + # Get all text elements within this paragraph + text_parts = [] + for t_elem in p_elem.findall(f".//{t_tag}"): + if t_elem.text: + text_parts.append(t_elem.text) + paragraph_text = "".join(text_parts) + # Skip empty paragraphs - they don't affect content validation + if paragraph_text: + paragraphs.append(paragraph_text) + + return "\n".join(paragraphs) + + +if __name__ == "__main__": + raise RuntimeError("This module should not be run directly.") diff --git a/pptx-mcp-server/package.json b/pptx-mcp-server/package.json new file mode 100644 index 0000000..dc8e2f8 --- /dev/null +++ b/pptx-mcp-server/package.json @@ -0,0 +1,25 @@ +{ + "name": "pptx-mcp-server", + "version": "1.0.0", + "description": "MCP server for PowerPoint presentation manipulation", + "main": "script_executor_mcp.py", + "scripts": { + "test": "python test_mcp_server.py", + "postinstall": "npx playwright install chromium" + }, + "keywords": [ + "mcp", + "powerpoint", + "pptx", + "presentation" + ], + "dependencies": { + "pptxgenjs": "^4.0.1", + "playwright": "^1.57.0", + "react-icons": "^5.5.0", + "sharp": "^0.34.5" + }, + "engines": { + "node": ">=18.0.0" + } +} diff --git a/pptx-mcp-server/requirements.txt b/pptx-mcp-server/requirements.txt new file mode 100644 index 0000000..3dfc8bf --- /dev/null +++ b/pptx-mcp-server/requirements.txt @@ -0,0 +1,16 @@ +# MCP Server +mcp>=1.0.0 + +# PowerPoint manipulation +python-pptx>=1.0.0 +Pillow>=10.0.0 + +# Markdown conversion +markitdown[pptx]>=0.0.1 + +# XML processing +defusedxml>=0.7.0 +lxml>=4.9.0 + +# PDF conversion (optional, for thumbnail generation) +# Requires system packages: libreoffice, poppler-utils diff --git a/pptx-mcp-server/script_executor_mcp.py b/pptx-mcp-server/script_executor_mcp.py new file mode 100644 index 0000000..89b7884 --- /dev/null +++ b/pptx-mcp-server/script_executor_mcp.py @@ -0,0 +1,278 @@ +#!/usr/bin/env python3 +""" +MCP Server for PowerPoint Presentation Tools +Executes Python and JavaScript scripts for PPTX manipulation +""" + +import asyncio +import json +import subprocess +import sys +from pathlib import Path +from typing import Any + +from mcp.server import Server +from mcp.types import Tool, TextContent + + +# Script definitions +SCRIPTS = { + "html2pptx": { + "path": "scripts/html2pptx-cli.js", + "interpreter": "node", + "description": "Convert HTML slides to PowerPoint presentation", + "parameters": { + "type": "object", + "properties": { + "html_files": { + "type": "array", + "items": {"type": "string"}, + "description": "Array of HTML file paths for each slide" + }, + "output_file": { + "type": "string", + "description": "Output .pptx file path" + }, + "config": { + "type": "object", + "description": "Optional configuration (charts, tables, etc.)", + "properties": {} + } + }, + "required": ["html_files", "output_file"] + } + }, + "inventory": { + "path": "scripts/inventory.py", + "interpreter": "python", + "description": "Extract all text shapes and properties from a presentation", + "parameters": { + "type": "object", + "properties": { + "input_file": { + "type": "string", + "description": "Input .pptx file path" + }, + "output_file": { + "type": "string", + "description": "Output JSON file path for inventory" + } + }, + "required": ["input_file", "output_file"] + } + }, + "rearrange": { + "path": "scripts/rearrange.py", + "interpreter": "python", + "description": "Duplicate, reorder, and delete slides in a presentation", + "parameters": { + "type": "object", + "properties": { + "input_file": { + "type": "string", + "description": "Input .pptx file path" + }, + "output_file": { + "type": "string", + "description": "Output .pptx file path" + }, + "slide_indices": { + "type": "string", + "description": "Comma-separated slide indices (0-based, can repeat)" + } + }, + "required": ["input_file", "output_file", "slide_indices"] + } + }, + "replace": { + "path": "scripts/replace.py", + "interpreter": "python", + "description": "Replace text content in presentation while preserving formatting", + "parameters": { + "type": "object", + "properties": { + "input_file": { + "type": "string", + "description": "Input .pptx file path" + }, + "replacement_json": { + "type": "string", + "description": "JSON file with replacement text and formatting" + }, + "output_file": { + "type": "string", + "description": "Output .pptx file path" + } + }, + "required": ["input_file", "replacement_json", "output_file"] + } + }, + "thumbnail": { + "path": "scripts/thumbnail.py", + "interpreter": "python", + "description": "Generate visual thumbnail grids of presentation slides", + "parameters": { + "type": "object", + "properties": { + "input_file": { + "type": "string", + "description": "Input .pptx file path" + }, + "output_prefix": { + "type": "string", + "description": "Output file prefix (optional, default: 'thumbnails')" + }, + "columns": { + "type": "integer", + "description": "Number of columns (3-6, default: 5)" + } + }, + "required": ["input_file"] + } + } +} + + +app = Server("pptx-tools") + + +@app.list_tools() +async def list_tools() -> list[Tool]: + """List available PPTX manipulation tools.""" + tools = [] + for name, config in SCRIPTS.items(): + tools.append( + Tool( + name=name, + description=config["description"], + inputSchema=config["parameters"] + ) + ) + return tools + + +@app.call_tool() +async def call_tool(name: str, arguments: Any) -> list[TextContent]: + """Execute a PPTX manipulation script.""" + if name not in SCRIPTS: + return [TextContent( + type="text", + text=f"Error: Unknown tool '{name}'" + )] + + script_config = SCRIPTS[name] + script_path = Path(__file__).parent / script_config["path"] + + if not script_path.exists(): + return [TextContent( + type="text", + text=f"Error: Script not found at {script_path}" + )] + + # Build command based on script type + interpreter = script_config["interpreter"] + + try: + if name == "html2pptx": + # Special handling for html2pptx - needs config file + config_data = { + "html_files": arguments.get("html_files", []), + "output_file": arguments.get("output_file"), + "config": arguments.get("config", {}) + } + config_path = Path(__file__).parent / "temp_config.json" + config_path.write_text(json.dumps(config_data, indent=2)) + + cmd = [interpreter, str(script_path), str(config_path)] + + elif name == "inventory": + cmd = [ + interpreter, + str(script_path), + arguments["input_file"], + arguments["output_file"] + ] + + elif name == "rearrange": + cmd = [ + interpreter, + str(script_path), + arguments["input_file"], + arguments["output_file"], + arguments["slide_indices"] + ] + + elif name == "replace": + cmd = [ + interpreter, + str(script_path), + arguments["input_file"], + arguments["replacement_json"], + arguments["output_file"] + ] + + elif name == "thumbnail": + cmd = [interpreter, str(script_path), arguments["input_file"]] + if "output_prefix" in arguments: + cmd.append(arguments["output_prefix"]) + if "columns" in arguments: + cmd.extend(["--cols", str(arguments["columns"])]) + + else: + return [TextContent( + type="text", + text=f"Error: No command builder for tool '{name}'" + )] + + # Execute the script + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=300 # 5 minute timeout + ) + + # Clean up temp config if created + if name == "html2pptx": + config_path.unlink(missing_ok=True) + + # Format output + output = [] + if result.stdout: + output.append(f"STDOUT:\n{result.stdout}") + if result.stderr: + output.append(f"STDERR:\n{result.stderr}") + if result.returncode != 0: + output.append(f"\nExit code: {result.returncode}") + + return [TextContent( + type="text", + text="\n\n".join(output) if output else "Script executed successfully (no output)" + )] + + except subprocess.TimeoutExpired: + return [TextContent( + type="text", + text=f"Error: Script execution timed out after 300 seconds" + )] + except Exception as e: + return [TextContent( + type="text", + text=f"Error executing script: {str(e)}" + )] + + +async def main(): + """Run the MCP server.""" + from mcp.server.stdio import stdio_server + + async with stdio_server() as (read_stream, write_stream): + await app.run( + read_stream, + write_stream, + app.create_initialization_options() + ) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/pptx-mcp-server/scripts/html2pptx-cli.js b/pptx-mcp-server/scripts/html2pptx-cli.js new file mode 100755 index 0000000..32c6e19 --- /dev/null +++ b/pptx-mcp-server/scripts/html2pptx-cli.js @@ -0,0 +1,92 @@ +#!/usr/bin/env node +/** + * CLI wrapper for html2pptx library + * + * Usage: node html2pptx-cli.js config.json + * + * Config format: + * { + * "html_files": ["slide1.html", "slide2.html"], + * "output_file": "output.pptx", + * "config": {} + * } + */ + +const fs = require('fs'); +const path = require('path'); + +// Save original working directory BEFORE changing it +const originalCwd = process.cwd(); + +// Change to parent directory to find node_modules +const serverDir = path.join(__dirname, '..'); +process.chdir(serverDir); + +const pptxgen = require('pptxgenjs'); +const html2pptx = require(path.join(__dirname, 'html2pptx.js')); + +async function main() { + if (process.argv.length < 3) { + console.error('Usage: node html2pptx-cli.js '); + process.exit(1); + } + + const configPath = process.argv[2]; + + try { + // Read configuration + const configData = JSON.parse(fs.readFileSync(configPath, 'utf8')); + const { html_files, output_file, config = {} } = configData; + + if (!html_files || !Array.isArray(html_files) || html_files.length === 0) { + throw new Error('html_files must be a non-empty array'); + } + + if (!output_file) { + throw new Error('output_file is required'); + } + + // Convert relative paths to absolute based on original working directory + const absoluteHtmlFiles = html_files.map(f => + path.isAbsolute(f) ? f : path.join(originalCwd, f) + ); + const absoluteOutputFile = path.isAbsolute(output_file) ? + output_file : path.join(originalCwd, output_file); + + // Create presentation + const pptx = new pptxgen(); + pptx.layout = 'LAYOUT_16x9'; // Default to 16:9 + + console.log(`Converting ${html_files.length} HTML slides to PowerPoint...`); + + // Process each HTML file + for (let i = 0; i < absoluteHtmlFiles.length; i++) { + const htmlFile = absoluteHtmlFiles[i]; + console.log(` Processing slide ${i + 1}/${html_files.length}: ${path.basename(htmlFile)}`); + + try { + const { slide, placeholders } = await html2pptx(htmlFile, pptx); + + if (placeholders && placeholders.length > 0) { + console.log(` Found ${placeholders.length} placeholder(s)`); + } + } catch (error) { + console.error(` Error processing ${htmlFile}: ${error.message}`); + throw error; + } + } + + // Save presentation + console.log(`Saving presentation to: ${path.basename(absoluteOutputFile)}`); + await pptx.writeFile({ fileName: absoluteOutputFile }); + + console.log(`✓ Successfully created ${absoluteOutputFile}`); + console.log(` Total slides: ${html_files.length}`); + + } catch (error) { + console.error(`Error: ${error.message}`); + process.exit(1); + } +} + +main(); diff --git a/pptx-mcp-server/scripts/html2pptx.js b/pptx-mcp-server/scripts/html2pptx.js new file mode 100644 index 0000000..766ef21 --- /dev/null +++ b/pptx-mcp-server/scripts/html2pptx.js @@ -0,0 +1,995 @@ +/** + * html2pptx - Convert HTML slide to pptxgenjs slide with positioned elements + * + * USAGE: + * const pptx = new pptxgen(); + * pptx.layout = 'LAYOUT_16x9'; // Must match HTML body dimensions + * + * const { slide, placeholders } = await html2pptx('slide.html', pptx); + * slide.addChart(pptx.charts.LINE, data, placeholders[0]); + * + * await pptx.writeFile('output.pptx'); + * + * FEATURES: + * - Converts HTML to PowerPoint with accurate positioning + * - Supports text, images, shapes, and bullet lists + * - Extracts placeholder elements (class="placeholder") with positions + * - Handles CSS gradients, borders, and margins + * + * VALIDATION: + * - Uses body width/height from HTML for viewport sizing + * - Throws error if HTML dimensions don't match presentation layout + * - Throws error if content overflows body (with overflow details) + * + * RETURNS: + * { slide, placeholders } where placeholders is an array of { id, x, y, w, h } + */ + +const { chromium } = require('playwright'); +const path = require('path'); +const sharp = require('sharp'); + +const PT_PER_PX = 0.75; +const PX_PER_IN = 96; +const EMU_PER_IN = 914400; + +// Helper: Get body dimensions and check for overflow +async function getBodyDimensions(page) { + const bodyDimensions = await page.evaluate(() => { + const body = document.body; + const style = window.getComputedStyle(body); + + return { + width: parseFloat(style.width), + height: parseFloat(style.height), + scrollWidth: body.scrollWidth, + scrollHeight: body.scrollHeight + }; + }); + + const errors = []; + const widthOverflowPx = Math.max(0, bodyDimensions.scrollWidth - bodyDimensions.width - 1); + const heightOverflowPx = Math.max(0, bodyDimensions.scrollHeight - bodyDimensions.height - 1); + + const widthOverflowPt = widthOverflowPx * PT_PER_PX; + const heightOverflowPt = heightOverflowPx * PT_PER_PX; + + if (widthOverflowPt > 0 || heightOverflowPt > 0) { + const directions = []; + if (widthOverflowPt > 0) directions.push(`${widthOverflowPt.toFixed(1)}pt horizontally`); + if (heightOverflowPt > 0) directions.push(`${heightOverflowPt.toFixed(1)}pt vertically`); + const reminder = heightOverflowPt > 0 ? ' (Remember: leave 0.5" margin at bottom of slide)' : ''; + errors.push(`HTML content overflows body by ${directions.join(' and ')}${reminder}`); + } + + return { ...bodyDimensions, errors }; +} + +// Helper: Validate dimensions match presentation layout +function validateDimensions(bodyDimensions, pres) { + const errors = []; + const widthInches = bodyDimensions.width / PX_PER_IN; + const heightInches = bodyDimensions.height / PX_PER_IN; + + if (pres.presLayout) { + const layoutWidth = pres.presLayout.width / EMU_PER_IN; + const layoutHeight = pres.presLayout.height / EMU_PER_IN; + + if (Math.abs(layoutWidth - widthInches) > 0.1 || Math.abs(layoutHeight - heightInches) > 0.1) { + errors.push( + `HTML dimensions (${widthInches.toFixed(1)}" × ${heightInches.toFixed(1)}") ` + + `don't match presentation layout (${layoutWidth.toFixed(1)}" × ${layoutHeight.toFixed(1)}")` + ); + } + } + return errors; +} + +function validateTextBoxPosition(slideData, bodyDimensions) { + const errors = []; + const slideHeightInches = bodyDimensions.height / PX_PER_IN; + const minBottomMargin = 0.5; // 0.5 inches from bottom + + for (const el of slideData.elements) { + // Check text elements (p, h1-h6, list) + if (['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'list'].includes(el.type)) { + const fontSize = el.style?.fontSize || 0; + const bottomEdge = el.position.y + el.position.h; + const distanceFromBottom = slideHeightInches - bottomEdge; + + if (fontSize > 12 && distanceFromBottom < minBottomMargin) { + const getText = () => { + if (typeof el.text === 'string') return el.text; + if (Array.isArray(el.text)) return el.text.find(t => t.text)?.text || ''; + if (Array.isArray(el.items)) return el.items.find(item => item.text)?.text || ''; + return ''; + }; + const textPrefix = getText().substring(0, 50) + (getText().length > 50 ? '...' : ''); + + errors.push( + `Text box "${textPrefix}" ends too close to bottom edge ` + + `(${distanceFromBottom.toFixed(2)}" from bottom, minimum ${minBottomMargin}" required)` + ); + } + } + } + + return errors; +} + +// Helper: Add background to slide +async function addBackground(slideData, targetSlide, tmpDir) { + if (slideData.background.type === 'image' && slideData.background.path) { + let imagePath = slideData.background.path.startsWith('file://') + ? slideData.background.path.replace('file://', '') + : slideData.background.path; + targetSlide.background = { path: imagePath }; + } else if (slideData.background.type === 'color' && slideData.background.value) { + targetSlide.background = { color: slideData.background.value }; + } +} + +// Helper: Add elements to slide +function addElements(slideData, targetSlide, pres) { + for (const el of slideData.elements) { + if (el.type === 'image') { + let imagePath = el.src.startsWith('file://') ? el.src.replace('file://', '') : el.src; + targetSlide.addImage({ + path: imagePath, + x: el.position.x, + y: el.position.y, + w: el.position.w, + h: el.position.h + }); + } else if (el.type === 'line') { + targetSlide.addShape(pres.ShapeType.line, { + x: el.x1, + y: el.y1, + w: el.x2 - el.x1, + h: el.y2 - el.y1, + line: { color: el.color, width: el.width } + }); + } else if (el.type === 'shape') { + const shapeOptions = { + x: el.position.x, + y: el.position.y, + w: el.position.w, + h: el.position.h, + shape: el.shape.rectRadius > 0 ? pres.ShapeType.roundRect : pres.ShapeType.rect + }; + + if (el.shape.fill) { + shapeOptions.fill = { color: el.shape.fill }; + if (el.shape.transparency != null) shapeOptions.fill.transparency = el.shape.transparency; + } + if (el.shape.line) shapeOptions.line = el.shape.line; + if (el.shape.rectRadius > 0) shapeOptions.rectRadius = el.shape.rectRadius; + if (el.shape.shadow) shapeOptions.shadow = el.shape.shadow; + + targetSlide.addText(el.text || '', shapeOptions); + } else if (el.type === 'list') { + const listOptions = { + x: el.position.x, + y: el.position.y, + w: el.position.w, + h: el.position.h, + fontSize: el.style.fontSize, + fontFace: el.style.fontFace, + color: el.style.color, + align: el.style.align, + valign: 'top', + lineSpacing: el.style.lineSpacing, + paraSpaceBefore: el.style.paraSpaceBefore, + paraSpaceAfter: el.style.paraSpaceAfter, + margin: el.style.margin + }; + if (el.style.margin) listOptions.margin = el.style.margin; + targetSlide.addText(el.items, listOptions); + } else { + // Check if text is single-line (height suggests one line) + const lineHeight = el.style.lineSpacing || el.style.fontSize * 1.2; + const isSingleLine = el.position.h <= lineHeight * 1.5; + + let adjustedX = el.position.x; + let adjustedW = el.position.w; + + // Make single-line text 2% wider to account for underestimate + if (isSingleLine) { + const widthIncrease = el.position.w * 0.02; + const align = el.style.align; + + if (align === 'center') { + // Center: expand both sides + adjustedX = el.position.x - (widthIncrease / 2); + adjustedW = el.position.w + widthIncrease; + } else if (align === 'right') { + // Right: expand to the left + adjustedX = el.position.x - widthIncrease; + adjustedW = el.position.w + widthIncrease; + } else { + // Left (default): expand to the right + adjustedW = el.position.w + widthIncrease; + } + } + + const textOptions = { + x: adjustedX, + y: el.position.y, + w: adjustedW, + h: el.position.h, + fontSize: el.style.fontSize, + fontFace: el.style.fontFace, + color: el.style.color, + bold: el.style.bold, + italic: el.style.italic, + underline: el.style.underline, + valign: 'top', + lineSpacing: el.style.lineSpacing, + paraSpaceBefore: el.style.paraSpaceBefore, + paraSpaceAfter: el.style.paraSpaceAfter, + inset: 0 // Remove default PowerPoint internal padding + }; + + if (el.style.align) textOptions.align = el.style.align; + if (el.style.margin) textOptions.margin = el.style.margin; + if (el.style.rotate !== undefined) textOptions.rotate = el.style.rotate; + if (el.style.transparency !== null && el.style.transparency !== undefined) textOptions.transparency = el.style.transparency; + + targetSlide.addText(el.text, textOptions); + } + } +} + +// Helper: Extract slide data from HTML page +async function extractSlideData(page) { + return await page.evaluate(() => { + const PT_PER_PX = 0.75; + const PX_PER_IN = 96; + + // Fonts that are single-weight and should not have bold applied + // (applying bold causes PowerPoint to use faux bold which makes text wider) + const SINGLE_WEIGHT_FONTS = ['impact']; + + // Helper: Check if a font should skip bold formatting + const shouldSkipBold = (fontFamily) => { + if (!fontFamily) return false; + const normalizedFont = fontFamily.toLowerCase().replace(/['"]/g, '').split(',')[0].trim(); + return SINGLE_WEIGHT_FONTS.includes(normalizedFont); + }; + + // Unit conversion helpers + const pxToInch = (px) => px / PX_PER_IN; + const pxToPoints = (pxStr) => parseFloat(pxStr) * PT_PER_PX; + const rgbToHex = (rgbStr) => { + // Handle transparent backgrounds by defaulting to white + if (rgbStr === 'rgba(0, 0, 0, 0)' || rgbStr === 'transparent') return 'FFFFFF'; + + const match = rgbStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/); + if (!match) return 'FFFFFF'; + return match.slice(1).map(n => parseInt(n).toString(16).padStart(2, '0')).join(''); + }; + + const extractAlpha = (rgbStr) => { + const match = rgbStr.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)/); + if (!match || !match[4]) return null; + const alpha = parseFloat(match[4]); + return Math.round((1 - alpha) * 100); + }; + + const applyTextTransform = (text, textTransform) => { + if (textTransform === 'uppercase') return text.toUpperCase(); + if (textTransform === 'lowercase') return text.toLowerCase(); + if (textTransform === 'capitalize') { + return text.replace(/\b\w/g, c => c.toUpperCase()); + } + return text; + }; + + // Extract rotation angle from CSS transform and writing-mode + const getRotation = (transform, writingMode) => { + let angle = 0; + + // Handle writing-mode first + // PowerPoint: 90° = text rotated 90° clockwise (reads top to bottom, letters upright) + // PowerPoint: 270° = text rotated 270° clockwise (reads bottom to top, letters upright) + if (writingMode === 'vertical-rl') { + // vertical-rl alone = text reads top to bottom = 90° in PowerPoint + angle = 90; + } else if (writingMode === 'vertical-lr') { + // vertical-lr alone = text reads bottom to top = 270° in PowerPoint + angle = 270; + } + + // Then add any transform rotation + if (transform && transform !== 'none') { + // Try to match rotate() function + const rotateMatch = transform.match(/rotate\((-?\d+(?:\.\d+)?)deg\)/); + if (rotateMatch) { + angle += parseFloat(rotateMatch[1]); + } else { + // Browser may compute as matrix - extract rotation from matrix + const matrixMatch = transform.match(/matrix\(([^)]+)\)/); + if (matrixMatch) { + const values = matrixMatch[1].split(',').map(parseFloat); + // matrix(a, b, c, d, e, f) where rotation = atan2(b, a) + const matrixAngle = Math.atan2(values[1], values[0]) * (180 / Math.PI); + angle += Math.round(matrixAngle); + } + } + } + + // Normalize to 0-359 range + angle = angle % 360; + if (angle < 0) angle += 360; + + return angle === 0 ? null : angle; + }; + + // Get position/dimensions accounting for rotation + const getPositionAndSize = (el, rect, rotation) => { + if (rotation === null) { + return { x: rect.left, y: rect.top, w: rect.width, h: rect.height }; + } + + // For 90° or 270° rotations, swap width and height + // because PowerPoint applies rotation to the original (unrotated) box + const isVertical = rotation === 90 || rotation === 270; + + if (isVertical) { + // The browser shows us the rotated dimensions (tall box for vertical text) + // But PowerPoint needs the pre-rotation dimensions (wide box that will be rotated) + // So we swap: browser's height becomes PPT's width, browser's width becomes PPT's height + const centerX = rect.left + rect.width / 2; + const centerY = rect.top + rect.height / 2; + + return { + x: centerX - rect.height / 2, + y: centerY - rect.width / 2, + w: rect.height, + h: rect.width + }; + } + + // For other rotations, use element's offset dimensions + const centerX = rect.left + rect.width / 2; + const centerY = rect.top + rect.height / 2; + return { + x: centerX - el.offsetWidth / 2, + y: centerY - el.offsetHeight / 2, + w: el.offsetWidth, + h: el.offsetHeight + }; + }; + + // Parse CSS box-shadow into PptxGenJS shadow properties + const parseBoxShadow = (boxShadow) => { + if (!boxShadow || boxShadow === 'none') return null; + + // Browser computed style format: "rgba(0, 0, 0, 0.3) 2px 2px 8px 0px [inset]" + // CSS format: "[inset] 2px 2px 8px 0px rgba(0, 0, 0, 0.3)" + + const insetMatch = boxShadow.match(/inset/); + + // IMPORTANT: PptxGenJS/PowerPoint doesn't properly support inset shadows + // Only process outer shadows to avoid file corruption + if (insetMatch) return null; + + // Extract color first (rgba or rgb at start) + const colorMatch = boxShadow.match(/rgba?\([^)]+\)/); + + // Extract numeric values (handles both px and pt units) + const parts = boxShadow.match(/([-\d.]+)(px|pt)/g); + + if (!parts || parts.length < 2) return null; + + const offsetX = parseFloat(parts[0]); + const offsetY = parseFloat(parts[1]); + const blur = parts.length > 2 ? parseFloat(parts[2]) : 0; + + // Calculate angle from offsets (in degrees, 0 = right, 90 = down) + let angle = 0; + if (offsetX !== 0 || offsetY !== 0) { + angle = Math.atan2(offsetY, offsetX) * (180 / Math.PI); + if (angle < 0) angle += 360; + } + + // Calculate offset distance (hypotenuse) + const offset = Math.sqrt(offsetX * offsetX + offsetY * offsetY) * PT_PER_PX; + + // Extract opacity from rgba + let opacity = 0.5; + if (colorMatch) { + const opacityMatch = colorMatch[0].match(/[\d.]+\)$/); + if (opacityMatch) { + opacity = parseFloat(opacityMatch[0].replace(')', '')); + } + } + + return { + type: 'outer', + angle: Math.round(angle), + blur: blur * 0.75, // Convert to points + color: colorMatch ? rgbToHex(colorMatch[0]) : '000000', + offset: offset, + opacity + }; + }; + + // Parse inline formatting tags (, , , , , ) into text runs + const parseInlineFormatting = (element, baseOptions = {}) => { + const runs = []; + element.childNodes.forEach((node) => { + if (node.nodeType === Node.TEXT_NODE) { + const text = node.textContent.replace(/\s+/g, ' '); + runs.push({ text, options: { ...baseOptions } }); + } else if (node.nodeType === Node.ELEMENT_NODE) { + let text = node.textContent.trim(); + if (text) { + const options = { ...baseOptions }; + const computed = window.getComputedStyle(node); + + // Check for bold from tag or CSS, but skip if single-weight font + if (node.tagName === 'B' || node.tagName === 'STRONG') { + if (!shouldSkipBold(computed.fontFamily)) options.bold = true; + } + if (node.tagName === 'I' || node.tagName === 'EM') options.italic = true; + if (node.tagName === 'U') options.underline = true; + + // Handle inline elements with computed styles + if (node.tagName === 'SPAN' || node.tagName === 'B' || node.tagName === 'STRONG' || node.tagName === 'I' || node.tagName === 'EM' || node.tagName === 'U') { + const isBold = computed.fontWeight === 'bold' || parseInt(computed.fontWeight) >= 600; + if (isBold && !shouldSkipBold(computed.fontFamily)) options.bold = true; + if (computed.fontStyle === 'italic') options.italic = true; + if (computed.textDecoration && computed.textDecoration.includes('underline')) options.underline = true; + if (computed.color && computed.color !== 'rgb(0, 0, 0)') { + options.color = rgbToHex(computed.color); + const transparency = extractAlpha(computed.color); + if (transparency !== null) options.transparency = transparency; + } + if (computed.fontSize) options.fontSize = pxToPoints(computed.fontSize); + + // Apply text-transform on the span element itself + if (computed.textTransform && computed.textTransform !== 'none') { + text = applyTextTransform(text, computed.textTransform); + } + + // Validate: Check for margins on inline elements + if (computed.marginLeft && parseFloat(computed.marginLeft) > 0) { + errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-left which is not supported in PowerPoint. Remove margin from inline elements.`); + } + if (computed.marginRight && parseFloat(computed.marginRight) > 0) { + errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-right which is not supported in PowerPoint. Remove margin from inline elements.`); + } + if (computed.marginTop && parseFloat(computed.marginTop) > 0) { + errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-top which is not supported in PowerPoint. Remove margin from inline elements.`); + } + if (computed.marginBottom && parseFloat(computed.marginBottom) > 0) { + errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-bottom which is not supported in PowerPoint. Remove margin from inline elements.`); + } + } + + runs.push({ text, options }); + } + } + }); + + // Trim leading space from first run and trailing space from last run + if (runs.length > 0) { + runs[0].text = runs[0].text.replace(/^\s+/, ''); + runs[runs.length - 1].text = runs[runs.length - 1].text.replace(/\s+$/, ''); + } + + return runs.filter(r => r.text.length > 0); + }; + + // Extract background from body (image or color) + const body = document.body; + const bodyStyle = window.getComputedStyle(body); + const bgImage = bodyStyle.backgroundImage; + const bgColor = bodyStyle.backgroundColor; + + // Collect validation errors + const errors = []; + + // Validate: Check for
tags + const brTags = document.querySelectorAll('br'); + if (brTags.length > 0) { + errors.push( + '
tags are not allowed. Use separate

,

-

, or
  • elements for each line instead.' + ); + } + + // Validate: Check for CSS gradients + if (bgImage && (bgImage.includes('linear-gradient') || bgImage.includes('radial-gradient'))) { + errors.push( + 'CSS gradients are not supported. Use Sharp to rasterize gradients as PNG images first, ' + + 'then reference with background-image: url(\'gradient.png\')' + ); + } + + let background; + if (bgImage && bgImage !== 'none') { + // Extract URL from url("...") or url(...) + const urlMatch = bgImage.match(/url\(["']?([^"')]+)["']?\)/); + if (urlMatch) { + background = { + type: 'image', + path: urlMatch[1] + }; + } else { + background = { + type: 'color', + value: rgbToHex(bgColor) + }; + } + } else { + background = { + type: 'color', + value: rgbToHex(bgColor) + }; + } + + // Process all elements + const elements = []; + const placeholders = []; + const textTags = ['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'UL', 'OL', 'LI']; + const processed = new Set(); + + document.querySelectorAll('*').forEach((el) => { + if (processed.has(el)) return; + + // Validate text elements don't have backgrounds, borders, or shadows + if (textTags.includes(el.tagName)) { + const computed = window.getComputedStyle(el); + const hasBg = computed.backgroundColor && computed.backgroundColor !== 'rgba(0, 0, 0, 0)'; + const hasBorder = (computed.borderWidth && parseFloat(computed.borderWidth) > 0) || + (computed.borderTopWidth && parseFloat(computed.borderTopWidth) > 0) || + (computed.borderRightWidth && parseFloat(computed.borderRightWidth) > 0) || + (computed.borderBottomWidth && parseFloat(computed.borderBottomWidth) > 0) || + (computed.borderLeftWidth && parseFloat(computed.borderLeftWidth) > 0); + const hasShadow = computed.boxShadow && computed.boxShadow !== 'none'; + + if (hasBg || hasBorder || hasShadow) { + errors.push( + `Text element <${el.tagName.toLowerCase()}> has ${hasBg ? 'background' : hasBorder ? 'border' : 'shadow'}. ` + + 'Backgrounds, borders, and shadows are only supported on
    elements, not text elements.' + ); + return; + } + } + + // Extract placeholder elements (for charts, etc.) + if (el.className && el.className.includes('placeholder')) { + const rect = el.getBoundingClientRect(); + if (rect.width === 0 || rect.height === 0) { + errors.push( + `Placeholder "${el.id || 'unnamed'}" has ${rect.width === 0 ? 'width: 0' : 'height: 0'}. Check the layout CSS.` + ); + } else { + placeholders.push({ + id: el.id || `placeholder-${placeholders.length}`, + x: pxToInch(rect.left), + y: pxToInch(rect.top), + w: pxToInch(rect.width), + h: pxToInch(rect.height) + }); + } + processed.add(el); + return; + } + + // Extract images + if (el.tagName === 'IMG') { + const rect = el.getBoundingClientRect(); + if (rect.width > 0 && rect.height > 0) { + elements.push({ + type: 'image', + src: el.src, + position: { + x: pxToInch(rect.left), + y: pxToInch(rect.top), + w: pxToInch(rect.width), + h: pxToInch(rect.height) + } + }); + processed.add(el); + return; + } + } + + // Extract DIVs with backgrounds/borders as shapes + const isContainer = el.tagName === 'DIV' && !textTags.includes(el.tagName); + if (isContainer) { + const computed = window.getComputedStyle(el); + const hasBg = computed.backgroundColor && computed.backgroundColor !== 'rgba(0, 0, 0, 0)'; + + // Validate: Check for unwrapped text content in DIV + for (const node of el.childNodes) { + if (node.nodeType === Node.TEXT_NODE) { + const text = node.textContent.trim(); + if (text) { + errors.push( + `DIV element contains unwrapped text "${text.substring(0, 50)}${text.length > 50 ? '...' : ''}". ` + + 'All text must be wrapped in

    ,

    -

    ,
      , or
        tags to appear in PowerPoint.' + ); + } + } + } + + // Check for background images on shapes + const bgImage = computed.backgroundImage; + if (bgImage && bgImage !== 'none') { + errors.push( + 'Background images on DIV elements are not supported. ' + + 'Use solid colors or borders for shapes, or use slide.addImage() in PptxGenJS to layer images.' + ); + return; + } + + // Check for borders - both uniform and partial + const borderTop = computed.borderTopWidth; + const borderRight = computed.borderRightWidth; + const borderBottom = computed.borderBottomWidth; + const borderLeft = computed.borderLeftWidth; + const borders = [borderTop, borderRight, borderBottom, borderLeft].map(b => parseFloat(b) || 0); + const hasBorder = borders.some(b => b > 0); + const hasUniformBorder = hasBorder && borders.every(b => b === borders[0]); + const borderLines = []; + + if (hasBorder && !hasUniformBorder) { + const rect = el.getBoundingClientRect(); + const x = pxToInch(rect.left); + const y = pxToInch(rect.top); + const w = pxToInch(rect.width); + const h = pxToInch(rect.height); + + // Collect lines to add after shape (inset by half the line width to center on edge) + if (parseFloat(borderTop) > 0) { + const widthPt = pxToPoints(borderTop); + const inset = (widthPt / 72) / 2; // Convert points to inches, then half + borderLines.push({ + type: 'line', + x1: x, y1: y + inset, x2: x + w, y2: y + inset, + width: widthPt, + color: rgbToHex(computed.borderTopColor) + }); + } + if (parseFloat(borderRight) > 0) { + const widthPt = pxToPoints(borderRight); + const inset = (widthPt / 72) / 2; + borderLines.push({ + type: 'line', + x1: x + w - inset, y1: y, x2: x + w - inset, y2: y + h, + width: widthPt, + color: rgbToHex(computed.borderRightColor) + }); + } + if (parseFloat(borderBottom) > 0) { + const widthPt = pxToPoints(borderBottom); + const inset = (widthPt / 72) / 2; + borderLines.push({ + type: 'line', + x1: x, y1: y + h - inset, x2: x + w, y2: y + h - inset, + width: widthPt, + color: rgbToHex(computed.borderBottomColor) + }); + } + if (parseFloat(borderLeft) > 0) { + const widthPt = pxToPoints(borderLeft); + const inset = (widthPt / 72) / 2; + borderLines.push({ + type: 'line', + x1: x + inset, y1: y, x2: x + inset, y2: y + h, + width: widthPt, + color: rgbToHex(computed.borderLeftColor) + }); + } + } + + if (hasBg || hasBorder) { + const rect = el.getBoundingClientRect(); + if (rect.width > 0 && rect.height > 0) { + const shadow = parseBoxShadow(computed.boxShadow); + + // Only add shape if there's background or uniform border + if (hasBg || hasUniformBorder) { + elements.push({ + type: 'shape', + text: '', // Shape only - child text elements render on top + position: { + x: pxToInch(rect.left), + y: pxToInch(rect.top), + w: pxToInch(rect.width), + h: pxToInch(rect.height) + }, + shape: { + fill: hasBg ? rgbToHex(computed.backgroundColor) : null, + transparency: hasBg ? extractAlpha(computed.backgroundColor) : null, + line: hasUniformBorder ? { + color: rgbToHex(computed.borderColor), + width: pxToPoints(computed.borderWidth) + } : null, + // Convert border-radius to rectRadius (in inches) + // % values: 50%+ = circle (1), <50% = percentage of min dimension + // pt values: divide by 72 (72pt = 1 inch) + // px values: divide by 96 (96px = 1 inch) + rectRadius: (() => { + const radius = computed.borderRadius; + const radiusValue = parseFloat(radius); + if (radiusValue === 0) return 0; + + if (radius.includes('%')) { + if (radiusValue >= 50) return 1; + // Calculate percentage of smaller dimension + const minDim = Math.min(rect.width, rect.height); + return (radiusValue / 100) * pxToInch(minDim); + } + + if (radius.includes('pt')) return radiusValue / 72; + return radiusValue / PX_PER_IN; + })(), + shadow: shadow + } + }); + } + + // Add partial border lines + elements.push(...borderLines); + + processed.add(el); + return; + } + } + } + + // Extract bullet lists as single text block + if (el.tagName === 'UL' || el.tagName === 'OL') { + const rect = el.getBoundingClientRect(); + if (rect.width === 0 || rect.height === 0) return; + + const liElements = Array.from(el.querySelectorAll('li')); + const items = []; + const ulComputed = window.getComputedStyle(el); + const ulPaddingLeftPt = pxToPoints(ulComputed.paddingLeft); + + // Split: margin-left for bullet position, indent for text position + // margin-left + indent = ul padding-left + const marginLeft = ulPaddingLeftPt * 0.5; + const textIndent = ulPaddingLeftPt * 0.5; + + liElements.forEach((li, idx) => { + const isLast = idx === liElements.length - 1; + const hasFormatting = li.querySelector('b, i, u, strong, em, span'); + + if (hasFormatting) { + const runs = parseInlineFormatting(li, { breakLine: false }); + // Clean manual bullets from first run + if (runs.length > 0) { + runs[0].text = runs[0].text.replace(/^[•\-\*▪▸]\s*/, ''); + runs[0].options.bullet = { indent: textIndent }; + } + // Set breakLine on last run + if (runs.length > 0 && !isLast) { + runs[runs.length - 1].options.breakLine = true; + } + items.push(...runs); + } else { + // Plain text - no formatting + const liText = li.textContent.trim().replace(/^[•\-\*▪▸]\s*/, ''); + items.push({ + text: liText, + options: { bullet: { indent: textIndent }, breakLine: !isLast } + }); + } + }); + + const computed = window.getComputedStyle(liElements[0] || el); + + elements.push({ + type: 'list', + items: items, + position: { + x: pxToInch(rect.left), + y: pxToInch(rect.top), + w: pxToInch(rect.width), + h: pxToInch(rect.height) + }, + style: { + fontSize: pxToPoints(computed.fontSize), + fontFace: computed.fontFamily.split(',')[0].replace(/['"]/g, '').trim(), + color: rgbToHex(computed.color), + transparency: extractAlpha(computed.color), + align: computed.textAlign === 'start' ? 'left' : computed.textAlign, + lineSpacing: computed.lineHeight && computed.lineHeight !== 'normal' ? pxToPoints(computed.lineHeight) : null, + paraSpaceBefore: 0, + paraSpaceAfter: pxToPoints(computed.marginBottom), + // PptxGenJS margin array is [left, right, bottom, top] + margin: [marginLeft, 0, 0, 0] + } + }); + + liElements.forEach(li => processed.add(li)); + processed.add(el); + return; + } + + // Extract text elements (P, H1, H2, etc.) + if (!textTags.includes(el.tagName)) return; + + const rect = el.getBoundingClientRect(); + const text = el.textContent.trim(); + if (rect.width === 0 || rect.height === 0 || !text) return; + + // Validate: Check for manual bullet symbols in text elements (not in lists) + if (el.tagName !== 'LI' && /^[•\-\*▪▸○●◆◇■□]\s/.test(text.trimStart())) { + errors.push( + `Text element <${el.tagName.toLowerCase()}> starts with bullet symbol "${text.substring(0, 20)}...". ` + + 'Use
          or
            lists instead of manual bullet symbols.' + ); + return; + } + + const computed = window.getComputedStyle(el); + const rotation = getRotation(computed.transform, computed.writingMode); + const { x, y, w, h } = getPositionAndSize(el, rect, rotation); + + const baseStyle = { + fontSize: pxToPoints(computed.fontSize), + fontFace: computed.fontFamily.split(',')[0].replace(/['"]/g, '').trim(), + color: rgbToHex(computed.color), + align: computed.textAlign === 'start' ? 'left' : computed.textAlign, + lineSpacing: pxToPoints(computed.lineHeight), + paraSpaceBefore: pxToPoints(computed.marginTop), + paraSpaceAfter: pxToPoints(computed.marginBottom), + // PptxGenJS margin array is [left, right, bottom, top] (not [top, right, bottom, left] as documented) + margin: [ + pxToPoints(computed.paddingLeft), + pxToPoints(computed.paddingRight), + pxToPoints(computed.paddingBottom), + pxToPoints(computed.paddingTop) + ] + }; + + const transparency = extractAlpha(computed.color); + if (transparency !== null) baseStyle.transparency = transparency; + + if (rotation !== null) baseStyle.rotate = rotation; + + const hasFormatting = el.querySelector('b, i, u, strong, em, span'); + + if (hasFormatting) { + // Text with inline formatting + const runs = parseInlineFormatting(el); + + // Adjust lineSpacing based on largest fontSize in runs + const adjustedStyle = { ...baseStyle }; + if (adjustedStyle.lineSpacing) { + const maxFontSize = Math.max( + adjustedStyle.fontSize, + ...runs.map(r => r.options?.fontSize || 0) + ); + if (maxFontSize > adjustedStyle.fontSize) { + const lineHeightMultiplier = adjustedStyle.lineSpacing / adjustedStyle.fontSize; + adjustedStyle.lineSpacing = maxFontSize * lineHeightMultiplier; + } + } + + const textTransform = computed.textTransform; + const transformedRuns = runs.map(run => ({ + ...run, + text: applyTextTransform(run.text, textTransform) + })); + + elements.push({ + type: el.tagName.toLowerCase(), + text: transformedRuns, + position: { x: pxToInch(x), y: pxToInch(y), w: pxToInch(w), h: pxToInch(h) }, + style: adjustedStyle + }); + } else { + // Plain text - inherit CSS formatting + const textTransform = computed.textTransform; + const transformedText = applyTextTransform(text, textTransform); + + const isBold = computed.fontWeight === 'bold' || parseInt(computed.fontWeight) >= 600; + + elements.push({ + type: el.tagName.toLowerCase(), + text: transformedText, + position: { x: pxToInch(x), y: pxToInch(y), w: pxToInch(w), h: pxToInch(h) }, + style: { + ...baseStyle, + bold: isBold && !shouldSkipBold(computed.fontFamily), + italic: computed.fontStyle === 'italic', + underline: computed.textDecoration.includes('underline') + } + }); + } + + processed.add(el); + }); + + return { background, elements, placeholders, errors }; + }); +} + +async function html2pptx(htmlFile, pres, options = {}) { + const { + tmpDir = process.env.TMPDIR || '/tmp', + slide = null + } = options; + + try { + // Use Chrome on macOS, default Chromium on Unix + const launchOptions = { env: { TMPDIR: tmpDir } }; + if (process.platform === 'darwin') { + launchOptions.channel = 'chrome'; + } + + const browser = await chromium.launch(launchOptions); + + let bodyDimensions; + let slideData; + + const filePath = path.isAbsolute(htmlFile) ? htmlFile : path.join(process.cwd(), htmlFile); + const validationErrors = []; + + try { + const page = await browser.newPage(); + + await page.goto(`file://${filePath}`); + + bodyDimensions = await getBodyDimensions(page); + + await page.setViewportSize({ + width: Math.round(bodyDimensions.width), + height: Math.round(bodyDimensions.height) + }); + + slideData = await extractSlideData(page); + } finally { + await browser.close(); + } + + // Collect all validation errors + if (bodyDimensions.errors && bodyDimensions.errors.length > 0) { + validationErrors.push(...bodyDimensions.errors); + } + + const dimensionErrors = validateDimensions(bodyDimensions, pres); + if (dimensionErrors.length > 0) { + validationErrors.push(...dimensionErrors); + } + + const textBoxPositionErrors = validateTextBoxPosition(slideData, bodyDimensions); + if (textBoxPositionErrors.length > 0) { + validationErrors.push(...textBoxPositionErrors); + } + + if (slideData.errors && slideData.errors.length > 0) { + validationErrors.push(...slideData.errors); + } + + // Throw all errors at once if any exist + if (validationErrors.length > 0) { + const errorMessage = validationErrors.length === 1 + ? validationErrors[0] + : `Multiple validation errors found:\n${validationErrors.map((e, i) => ` ${i + 1}. ${e}`).join('\n')}`; + throw new Error(errorMessage); + } + + const targetSlide = slide || pres.addSlide(); + + await addBackground(slideData, targetSlide, tmpDir); + addElements(slideData, targetSlide, pres); + + return { slide: targetSlide, placeholders: slideData.placeholders }; + } catch (error) { + if (!error.message.startsWith(htmlFile)) { + throw new Error(`${htmlFile}: ${error.message}`); + } + throw error; + } +} + +module.exports = html2pptx; \ No newline at end of file diff --git a/pptx-mcp-server/scripts/inventory.py b/pptx-mcp-server/scripts/inventory.py new file mode 100644 index 0000000..edda390 --- /dev/null +++ b/pptx-mcp-server/scripts/inventory.py @@ -0,0 +1,1020 @@ +#!/usr/bin/env python3 +""" +Extract structured text content from PowerPoint presentations. + +This module provides functionality to: +- Extract all text content from PowerPoint shapes +- Preserve paragraph formatting (alignment, bullets, fonts, spacing) +- Handle nested GroupShapes recursively with correct absolute positions +- Sort shapes by visual position on slides +- Filter out slide numbers and non-content placeholders +- Export to JSON with clean, structured data + +Classes: + ParagraphData: Represents a text paragraph with formatting + ShapeData: Represents a shape with position and text content + +Main Functions: + extract_text_inventory: Extract all text from a presentation + save_inventory: Save extracted data to JSON + +Usage: + python inventory.py input.pptx output.json +""" + +import argparse +import json +import platform +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +from PIL import Image, ImageDraw, ImageFont +from pptx import Presentation +from pptx.enum.text import PP_ALIGN +from pptx.shapes.base import BaseShape + +# Type aliases for cleaner signatures +JsonValue = Union[str, int, float, bool, None] +ParagraphDict = Dict[str, JsonValue] +ShapeDict = Dict[ + str, Union[str, float, bool, List[ParagraphDict], List[str], Dict[str, Any], None] +] +InventoryData = Dict[ + str, Dict[str, "ShapeData"] +] # Dict of slide_id -> {shape_id -> ShapeData} +InventoryDict = Dict[str, Dict[str, ShapeDict]] # JSON-serializable inventory + + +def main(): + """Main entry point for command-line usage.""" + parser = argparse.ArgumentParser( + description="Extract text inventory from PowerPoint with proper GroupShape support.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + python inventory.py presentation.pptx inventory.json + Extracts text inventory with correct absolute positions for grouped shapes + + python inventory.py presentation.pptx inventory.json --issues-only + Extracts only text shapes that have overflow or overlap issues + +The output JSON includes: + - All text content organized by slide and shape + - Correct absolute positions for shapes in groups + - Visual position and size in inches + - Paragraph properties and formatting + - Issue detection: text overflow and shape overlaps + """, + ) + + parser.add_argument("input", help="Input PowerPoint file (.pptx)") + parser.add_argument("output", help="Output JSON file for inventory") + parser.add_argument( + "--issues-only", + action="store_true", + help="Include only text shapes that have overflow or overlap issues", + ) + + args = parser.parse_args() + + input_path = Path(args.input) + if not input_path.exists(): + print(f"Error: Input file not found: {args.input}") + sys.exit(1) + + if not input_path.suffix.lower() == ".pptx": + print("Error: Input must be a PowerPoint file (.pptx)") + sys.exit(1) + + try: + print(f"Extracting text inventory from: {args.input}") + if args.issues_only: + print( + "Filtering to include only text shapes with issues (overflow/overlap)" + ) + inventory = extract_text_inventory(input_path, issues_only=args.issues_only) + + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + save_inventory(inventory, output_path) + + print(f"Output saved to: {args.output}") + + # Report statistics + total_slides = len(inventory) + total_shapes = sum(len(shapes) for shapes in inventory.values()) + if args.issues_only: + if total_shapes > 0: + print( + f"Found {total_shapes} text elements with issues in {total_slides} slides" + ) + else: + print("No issues discovered") + else: + print( + f"Found text in {total_slides} slides with {total_shapes} text elements" + ) + + except Exception as e: + print(f"Error processing presentation: {e}") + import traceback + + traceback.print_exc() + sys.exit(1) + + +@dataclass +class ShapeWithPosition: + """A shape with its absolute position on the slide.""" + + shape: BaseShape + absolute_left: int # in EMUs + absolute_top: int # in EMUs + + +class ParagraphData: + """Data structure for paragraph properties extracted from a PowerPoint paragraph.""" + + def __init__(self, paragraph: Any): + """Initialize from a PowerPoint paragraph object. + + Args: + paragraph: The PowerPoint paragraph object + """ + self.text: str = paragraph.text.strip() + self.bullet: bool = False + self.level: Optional[int] = None + self.alignment: Optional[str] = None + self.space_before: Optional[float] = None + self.space_after: Optional[float] = None + self.font_name: Optional[str] = None + self.font_size: Optional[float] = None + self.bold: Optional[bool] = None + self.italic: Optional[bool] = None + self.underline: Optional[bool] = None + self.color: Optional[str] = None + self.theme_color: Optional[str] = None + self.line_spacing: Optional[float] = None + + # Check for bullet formatting + if ( + hasattr(paragraph, "_p") + and paragraph._p is not None + and paragraph._p.pPr is not None + ): + pPr = paragraph._p.pPr + ns = "{http://schemas.openxmlformats.org/drawingml/2006/main}" + if ( + pPr.find(f"{ns}buChar") is not None + or pPr.find(f"{ns}buAutoNum") is not None + ): + self.bullet = True + if hasattr(paragraph, "level"): + self.level = paragraph.level + + # Add alignment if not LEFT (default) + if hasattr(paragraph, "alignment") and paragraph.alignment is not None: + alignment_map = { + PP_ALIGN.CENTER: "CENTER", + PP_ALIGN.RIGHT: "RIGHT", + PP_ALIGN.JUSTIFY: "JUSTIFY", + } + if paragraph.alignment in alignment_map: + self.alignment = alignment_map[paragraph.alignment] + + # Add spacing properties if set + if hasattr(paragraph, "space_before") and paragraph.space_before: + self.space_before = paragraph.space_before.pt + if hasattr(paragraph, "space_after") and paragraph.space_after: + self.space_after = paragraph.space_after.pt + + # Extract font properties from first run + if paragraph.runs: + first_run = paragraph.runs[0] + if hasattr(first_run, "font"): + font = first_run.font + if font.name: + self.font_name = font.name + if font.size: + self.font_size = font.size.pt + if font.bold is not None: + self.bold = font.bold + if font.italic is not None: + self.italic = font.italic + if font.underline is not None: + self.underline = font.underline + + # Handle color - both RGB and theme colors + try: + # Try RGB color first + if font.color.rgb: + self.color = str(font.color.rgb) + except (AttributeError, TypeError): + # Fall back to theme color + try: + if font.color.theme_color: + self.theme_color = font.color.theme_color.name + except (AttributeError, TypeError): + pass + + # Add line spacing if set + if hasattr(paragraph, "line_spacing") and paragraph.line_spacing is not None: + if hasattr(paragraph.line_spacing, "pt"): + self.line_spacing = round(paragraph.line_spacing.pt, 2) + else: + # Multiplier - convert to points + font_size = self.font_size if self.font_size else 12.0 + self.line_spacing = round(paragraph.line_spacing * font_size, 2) + + def to_dict(self) -> ParagraphDict: + """Convert to dictionary for JSON serialization, excluding None values.""" + result: ParagraphDict = {"text": self.text} + + # Add optional fields only if they have values + if self.bullet: + result["bullet"] = self.bullet + if self.level is not None: + result["level"] = self.level + if self.alignment: + result["alignment"] = self.alignment + if self.space_before is not None: + result["space_before"] = self.space_before + if self.space_after is not None: + result["space_after"] = self.space_after + if self.font_name: + result["font_name"] = self.font_name + if self.font_size is not None: + result["font_size"] = self.font_size + if self.bold is not None: + result["bold"] = self.bold + if self.italic is not None: + result["italic"] = self.italic + if self.underline is not None: + result["underline"] = self.underline + if self.color: + result["color"] = self.color + if self.theme_color: + result["theme_color"] = self.theme_color + if self.line_spacing is not None: + result["line_spacing"] = self.line_spacing + + return result + + +class ShapeData: + """Data structure for shape properties extracted from a PowerPoint shape.""" + + @staticmethod + def emu_to_inches(emu: int) -> float: + """Convert EMUs (English Metric Units) to inches.""" + return emu / 914400.0 + + @staticmethod + def inches_to_pixels(inches: float, dpi: int = 96) -> int: + """Convert inches to pixels at given DPI.""" + return int(inches * dpi) + + @staticmethod + def get_font_path(font_name: str) -> Optional[str]: + """Get the font file path for a given font name. + + Args: + font_name: Name of the font (e.g., 'Arial', 'Calibri') + + Returns: + Path to the font file, or None if not found + """ + system = platform.system() + + # Common font file variations to try + font_variations = [ + font_name, + font_name.lower(), + font_name.replace(" ", ""), + font_name.replace(" ", "-"), + ] + + # Define font directories and extensions by platform + if system == "Darwin": # macOS + font_dirs = [ + "/System/Library/Fonts/", + "/Library/Fonts/", + "~/Library/Fonts/", + ] + extensions = [".ttf", ".otf", ".ttc", ".dfont"] + else: # Linux + font_dirs = [ + "/usr/share/fonts/truetype/", + "/usr/local/share/fonts/", + "~/.fonts/", + ] + extensions = [".ttf", ".otf"] + + # Try to find the font file + from pathlib import Path + + for font_dir in font_dirs: + font_dir_path = Path(font_dir).expanduser() + if not font_dir_path.exists(): + continue + + # First try exact matches + for variant in font_variations: + for ext in extensions: + font_path = font_dir_path / f"{variant}{ext}" + if font_path.exists(): + return str(font_path) + + # Then try fuzzy matching - find files containing the font name + try: + for file_path in font_dir_path.iterdir(): + if file_path.is_file(): + file_name_lower = file_path.name.lower() + font_name_lower = font_name.lower().replace(" ", "") + if font_name_lower in file_name_lower and any( + file_name_lower.endswith(ext) for ext in extensions + ): + return str(file_path) + except (OSError, PermissionError): + continue + + return None + + @staticmethod + def get_slide_dimensions(slide: Any) -> tuple[Optional[int], Optional[int]]: + """Get slide dimensions from slide object. + + Args: + slide: Slide object + + Returns: + Tuple of (width_emu, height_emu) or (None, None) if not found + """ + try: + prs = slide.part.package.presentation_part.presentation + return prs.slide_width, prs.slide_height + except (AttributeError, TypeError): + return None, None + + @staticmethod + def get_default_font_size(shape: BaseShape, slide_layout: Any) -> Optional[float]: + """Extract default font size from slide layout for a placeholder shape. + + Args: + shape: Placeholder shape + slide_layout: Slide layout containing the placeholder definition + + Returns: + Default font size in points, or None if not found + """ + try: + if not hasattr(shape, "placeholder_format"): + return None + + shape_type = shape.placeholder_format.type # type: ignore + for layout_placeholder in slide_layout.placeholders: + if layout_placeholder.placeholder_format.type == shape_type: + # Find first defRPr element with sz (size) attribute + for elem in layout_placeholder.element.iter(): + if "defRPr" in elem.tag and (sz := elem.get("sz")): + return float(sz) / 100.0 # Convert EMUs to points + break + except Exception: + pass + return None + + def __init__( + self, + shape: BaseShape, + absolute_left: Optional[int] = None, + absolute_top: Optional[int] = None, + slide: Optional[Any] = None, + ): + """Initialize from a PowerPoint shape object. + + Args: + shape: The PowerPoint shape object (should be pre-validated) + absolute_left: Absolute left position in EMUs (for shapes in groups) + absolute_top: Absolute top position in EMUs (for shapes in groups) + slide: Optional slide object to get dimensions and layout information + """ + self.shape = shape # Store reference to original shape + self.shape_id: str = "" # Will be set after sorting + + # Get slide dimensions from slide object + self.slide_width_emu, self.slide_height_emu = ( + self.get_slide_dimensions(slide) if slide else (None, None) + ) + + # Get placeholder type if applicable + self.placeholder_type: Optional[str] = None + self.default_font_size: Optional[float] = None + if hasattr(shape, "is_placeholder") and shape.is_placeholder: # type: ignore + if shape.placeholder_format and shape.placeholder_format.type: # type: ignore + self.placeholder_type = ( + str(shape.placeholder_format.type).split(".")[-1].split(" ")[0] # type: ignore + ) + + # Get default font size from layout + if slide and hasattr(slide, "slide_layout"): + self.default_font_size = self.get_default_font_size( + shape, slide.slide_layout + ) + + # Get position information + # Use absolute positions if provided (for shapes in groups), otherwise use shape's position + left_emu = ( + absolute_left + if absolute_left is not None + else (shape.left if hasattr(shape, "left") else 0) + ) + top_emu = ( + absolute_top + if absolute_top is not None + else (shape.top if hasattr(shape, "top") else 0) + ) + + self.left: float = round(self.emu_to_inches(left_emu), 2) # type: ignore + self.top: float = round(self.emu_to_inches(top_emu), 2) # type: ignore + self.width: float = round( + self.emu_to_inches(shape.width if hasattr(shape, "width") else 0), + 2, # type: ignore + ) + self.height: float = round( + self.emu_to_inches(shape.height if hasattr(shape, "height") else 0), + 2, # type: ignore + ) + + # Store EMU positions for overflow calculations + self.left_emu = left_emu + self.top_emu = top_emu + self.width_emu = shape.width if hasattr(shape, "width") else 0 + self.height_emu = shape.height if hasattr(shape, "height") else 0 + + # Calculate overflow status + self.frame_overflow_bottom: Optional[float] = None + self.slide_overflow_right: Optional[float] = None + self.slide_overflow_bottom: Optional[float] = None + self.overlapping_shapes: Dict[ + str, float + ] = {} # Dict of shape_id -> overlap area in sq inches + self.warnings: List[str] = [] + self._estimate_frame_overflow() + self._calculate_slide_overflow() + self._detect_bullet_issues() + + @property + def paragraphs(self) -> List[ParagraphData]: + """Calculate paragraphs from the shape's text frame.""" + if not self.shape or not hasattr(self.shape, "text_frame"): + return [] + + paragraphs = [] + for paragraph in self.shape.text_frame.paragraphs: # type: ignore + if paragraph.text.strip(): + paragraphs.append(ParagraphData(paragraph)) + return paragraphs + + def _get_default_font_size(self) -> int: + """Get default font size from theme text styles or use conservative default.""" + try: + if not ( + hasattr(self.shape, "part") and hasattr(self.shape.part, "slide_layout") + ): + return 14 + + slide_master = self.shape.part.slide_layout.slide_master # type: ignore + if not hasattr(slide_master, "element"): + return 14 + + # Determine theme style based on placeholder type + style_name = "bodyStyle" # Default + if self.placeholder_type and "TITLE" in self.placeholder_type: + style_name = "titleStyle" + + # Find font size in theme styles + for child in slide_master.element.iter(): + tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag + if tag == style_name: + for elem in child.iter(): + if "sz" in elem.attrib: + return int(elem.attrib["sz"]) // 100 + except Exception: + pass + + return 14 # Conservative default for body text + + def _get_usable_dimensions(self, text_frame) -> Tuple[int, int]: + """Get usable width and height in pixels after accounting for margins.""" + # Default PowerPoint margins in inches + margins = {"top": 0.05, "bottom": 0.05, "left": 0.1, "right": 0.1} + + # Override with actual margins if set + if hasattr(text_frame, "margin_top") and text_frame.margin_top: + margins["top"] = self.emu_to_inches(text_frame.margin_top) + if hasattr(text_frame, "margin_bottom") and text_frame.margin_bottom: + margins["bottom"] = self.emu_to_inches(text_frame.margin_bottom) + if hasattr(text_frame, "margin_left") and text_frame.margin_left: + margins["left"] = self.emu_to_inches(text_frame.margin_left) + if hasattr(text_frame, "margin_right") and text_frame.margin_right: + margins["right"] = self.emu_to_inches(text_frame.margin_right) + + # Calculate usable area + usable_width = self.width - margins["left"] - margins["right"] + usable_height = self.height - margins["top"] - margins["bottom"] + + # Convert to pixels + return ( + self.inches_to_pixels(usable_width), + self.inches_to_pixels(usable_height), + ) + + def _wrap_text_line(self, line: str, max_width_px: int, draw, font) -> List[str]: + """Wrap a single line of text to fit within max_width_px.""" + if not line: + return [""] + + # Use textlength for efficient width calculation + if draw.textlength(line, font=font) <= max_width_px: + return [line] + + # Need to wrap - split into words + wrapped = [] + words = line.split(" ") + current_line = "" + + for word in words: + test_line = current_line + (" " if current_line else "") + word + if draw.textlength(test_line, font=font) <= max_width_px: + current_line = test_line + else: + if current_line: + wrapped.append(current_line) + current_line = word + + if current_line: + wrapped.append(current_line) + + return wrapped + + def _estimate_frame_overflow(self) -> None: + """Estimate if text overflows the shape bounds using PIL text measurement.""" + if not self.shape or not hasattr(self.shape, "text_frame"): + return + + text_frame = self.shape.text_frame # type: ignore + if not text_frame or not text_frame.paragraphs: + return + + # Get usable dimensions after accounting for margins + usable_width_px, usable_height_px = self._get_usable_dimensions(text_frame) + if usable_width_px <= 0 or usable_height_px <= 0: + return + + # Set up PIL for text measurement + dummy_img = Image.new("RGB", (1, 1)) + draw = ImageDraw.Draw(dummy_img) + + # Get default font size from placeholder or use conservative estimate + default_font_size = self._get_default_font_size() + + # Calculate total height of all paragraphs + total_height_px = 0 + + for para_idx, paragraph in enumerate(text_frame.paragraphs): + if not paragraph.text.strip(): + continue + + para_data = ParagraphData(paragraph) + + # Load font for this paragraph + font_name = para_data.font_name or "Arial" + font_size = int(para_data.font_size or default_font_size) + + font = None + font_path = self.get_font_path(font_name) + if font_path: + try: + font = ImageFont.truetype(font_path, size=font_size) + except Exception: + font = ImageFont.load_default() + else: + font = ImageFont.load_default() + + # Wrap all lines in this paragraph + all_wrapped_lines = [] + for line in paragraph.text.split("\n"): + wrapped = self._wrap_text_line(line, usable_width_px, draw, font) + all_wrapped_lines.extend(wrapped) + + if all_wrapped_lines: + # Calculate line height + if para_data.line_spacing: + # Custom line spacing explicitly set + line_height_px = para_data.line_spacing * 96 / 72 + else: + # PowerPoint default single spacing (1.0x font size) + line_height_px = font_size * 96 / 72 + + # Add space_before (except first paragraph) + if para_idx > 0 and para_data.space_before: + total_height_px += para_data.space_before * 96 / 72 + + # Add paragraph text height + total_height_px += len(all_wrapped_lines) * line_height_px + + # Add space_after + if para_data.space_after: + total_height_px += para_data.space_after * 96 / 72 + + # Check for overflow (ignore negligible overflows <= 0.05") + if total_height_px > usable_height_px: + overflow_px = total_height_px - usable_height_px + overflow_inches = round(overflow_px / 96.0, 2) + if overflow_inches > 0.05: # Only report significant overflows + self.frame_overflow_bottom = overflow_inches + + def _calculate_slide_overflow(self) -> None: + """Calculate if shape overflows the slide boundaries.""" + if self.slide_width_emu is None or self.slide_height_emu is None: + return + + # Check right overflow (ignore negligible overflows <= 0.01") + right_edge_emu = self.left_emu + self.width_emu + if right_edge_emu > self.slide_width_emu: + overflow_emu = right_edge_emu - self.slide_width_emu + overflow_inches = round(self.emu_to_inches(overflow_emu), 2) + if overflow_inches > 0.01: # Only report significant overflows + self.slide_overflow_right = overflow_inches + + # Check bottom overflow (ignore negligible overflows <= 0.01") + bottom_edge_emu = self.top_emu + self.height_emu + if bottom_edge_emu > self.slide_height_emu: + overflow_emu = bottom_edge_emu - self.slide_height_emu + overflow_inches = round(self.emu_to_inches(overflow_emu), 2) + if overflow_inches > 0.01: # Only report significant overflows + self.slide_overflow_bottom = overflow_inches + + def _detect_bullet_issues(self) -> None: + """Detect bullet point formatting issues in paragraphs.""" + if not self.shape or not hasattr(self.shape, "text_frame"): + return + + text_frame = self.shape.text_frame # type: ignore + if not text_frame or not text_frame.paragraphs: + return + + # Common bullet symbols that indicate manual bullets + bullet_symbols = ["•", "●", "○"] + + for paragraph in text_frame.paragraphs: + text = paragraph.text.strip() + # Check for manual bullet symbols + if text and any(text.startswith(symbol + " ") for symbol in bullet_symbols): + self.warnings.append( + "manual_bullet_symbol: use proper bullet formatting" + ) + break + + @property + def has_any_issues(self) -> bool: + """Check if shape has any issues (overflow, overlap, or warnings).""" + return ( + self.frame_overflow_bottom is not None + or self.slide_overflow_right is not None + or self.slide_overflow_bottom is not None + or len(self.overlapping_shapes) > 0 + or len(self.warnings) > 0 + ) + + def to_dict(self) -> ShapeDict: + """Convert to dictionary for JSON serialization.""" + result: ShapeDict = { + "left": self.left, + "top": self.top, + "width": self.width, + "height": self.height, + } + + # Add optional fields if present + if self.placeholder_type: + result["placeholder_type"] = self.placeholder_type + + if self.default_font_size: + result["default_font_size"] = self.default_font_size + + # Add overflow information only if there is overflow + overflow_data = {} + + # Add frame overflow if present + if self.frame_overflow_bottom is not None: + overflow_data["frame"] = {"overflow_bottom": self.frame_overflow_bottom} + + # Add slide overflow if present + slide_overflow = {} + if self.slide_overflow_right is not None: + slide_overflow["overflow_right"] = self.slide_overflow_right + if self.slide_overflow_bottom is not None: + slide_overflow["overflow_bottom"] = self.slide_overflow_bottom + if slide_overflow: + overflow_data["slide"] = slide_overflow + + # Only add overflow field if there is overflow + if overflow_data: + result["overflow"] = overflow_data + + # Add overlap field if there are overlapping shapes + if self.overlapping_shapes: + result["overlap"] = {"overlapping_shapes": self.overlapping_shapes} + + # Add warnings field if there are warnings + if self.warnings: + result["warnings"] = self.warnings + + # Add paragraphs after placeholder_type + result["paragraphs"] = [para.to_dict() for para in self.paragraphs] + + return result + + +def is_valid_shape(shape: BaseShape) -> bool: + """Check if a shape contains meaningful text content.""" + # Must have a text frame with content + if not hasattr(shape, "text_frame") or not shape.text_frame: # type: ignore + return False + + text = shape.text_frame.text.strip() # type: ignore + if not text: + return False + + # Skip slide numbers and numeric footers + if hasattr(shape, "is_placeholder") and shape.is_placeholder: # type: ignore + if shape.placeholder_format and shape.placeholder_format.type: # type: ignore + placeholder_type = ( + str(shape.placeholder_format.type).split(".")[-1].split(" ")[0] # type: ignore + ) + if placeholder_type == "SLIDE_NUMBER": + return False + if placeholder_type == "FOOTER" and text.isdigit(): + return False + + return True + + +def collect_shapes_with_absolute_positions( + shape: BaseShape, parent_left: int = 0, parent_top: int = 0 +) -> List[ShapeWithPosition]: + """Recursively collect all shapes with valid text, calculating absolute positions. + + For shapes within groups, their positions are relative to the group. + This function calculates the absolute position on the slide by accumulating + parent group offsets. + + Args: + shape: The shape to process + parent_left: Accumulated left offset from parent groups (in EMUs) + parent_top: Accumulated top offset from parent groups (in EMUs) + + Returns: + List of ShapeWithPosition objects with absolute positions + """ + if hasattr(shape, "shapes"): # GroupShape + result = [] + # Get this group's position + group_left = shape.left if hasattr(shape, "left") else 0 + group_top = shape.top if hasattr(shape, "top") else 0 + + # Calculate absolute position for this group + abs_group_left = parent_left + group_left + abs_group_top = parent_top + group_top + + # Process children with accumulated offsets + for child in shape.shapes: # type: ignore + result.extend( + collect_shapes_with_absolute_positions( + child, abs_group_left, abs_group_top + ) + ) + return result + + # Regular shape - check if it has valid text + if is_valid_shape(shape): + # Calculate absolute position + shape_left = shape.left if hasattr(shape, "left") else 0 + shape_top = shape.top if hasattr(shape, "top") else 0 + + return [ + ShapeWithPosition( + shape=shape, + absolute_left=parent_left + shape_left, + absolute_top=parent_top + shape_top, + ) + ] + + return [] + + +def sort_shapes_by_position(shapes: List[ShapeData]) -> List[ShapeData]: + """Sort shapes by visual position (top-to-bottom, left-to-right). + + Shapes within 0.5 inches vertically are considered on the same row. + """ + if not shapes: + return shapes + + # Sort by top position first + shapes = sorted(shapes, key=lambda s: (s.top, s.left)) + + # Group shapes by row (within 0.5 inches vertically) + result = [] + row = [shapes[0]] + row_top = shapes[0].top + + for shape in shapes[1:]: + if abs(shape.top - row_top) <= 0.5: + row.append(shape) + else: + # Sort current row by left position and add to result + result.extend(sorted(row, key=lambda s: s.left)) + row = [shape] + row_top = shape.top + + # Don't forget the last row + result.extend(sorted(row, key=lambda s: s.left)) + return result + + +def calculate_overlap( + rect1: Tuple[float, float, float, float], + rect2: Tuple[float, float, float, float], + tolerance: float = 0.05, +) -> Tuple[bool, float]: + """Calculate if and how much two rectangles overlap. + + Args: + rect1: (left, top, width, height) of first rectangle in inches + rect2: (left, top, width, height) of second rectangle in inches + tolerance: Minimum overlap in inches to consider as overlapping (default: 0.05") + + Returns: + Tuple of (overlaps, overlap_area) where: + - overlaps: True if rectangles overlap by more than tolerance + - overlap_area: Area of overlap in square inches + """ + left1, top1, w1, h1 = rect1 + left2, top2, w2, h2 = rect2 + + # Calculate overlap dimensions + overlap_width = min(left1 + w1, left2 + w2) - max(left1, left2) + overlap_height = min(top1 + h1, top2 + h2) - max(top1, top2) + + # Check if there's meaningful overlap (more than tolerance) + if overlap_width > tolerance and overlap_height > tolerance: + # Calculate overlap area in square inches + overlap_area = overlap_width * overlap_height + return True, round(overlap_area, 2) + + return False, 0 + + +def detect_overlaps(shapes: List[ShapeData]) -> None: + """Detect overlapping shapes and update their overlapping_shapes dictionaries. + + This function requires each ShapeData to have its shape_id already set. + It modifies the shapes in-place, adding shape IDs with overlap areas in square inches. + + Args: + shapes: List of ShapeData objects with shape_id attributes set + """ + n = len(shapes) + + # Compare each pair of shapes + for i in range(n): + for j in range(i + 1, n): + shape1 = shapes[i] + shape2 = shapes[j] + + # Ensure shape IDs are set + assert shape1.shape_id, f"Shape at index {i} has no shape_id" + assert shape2.shape_id, f"Shape at index {j} has no shape_id" + + rect1 = (shape1.left, shape1.top, shape1.width, shape1.height) + rect2 = (shape2.left, shape2.top, shape2.width, shape2.height) + + overlaps, overlap_area = calculate_overlap(rect1, rect2) + + if overlaps: + # Add shape IDs with overlap area in square inches + shape1.overlapping_shapes[shape2.shape_id] = overlap_area + shape2.overlapping_shapes[shape1.shape_id] = overlap_area + + +def extract_text_inventory( + pptx_path: Path, prs: Optional[Any] = None, issues_only: bool = False +) -> InventoryData: + """Extract text content from all slides in a PowerPoint presentation. + + Args: + pptx_path: Path to the PowerPoint file + prs: Optional Presentation object to use. If not provided, will load from pptx_path. + issues_only: If True, only include shapes that have overflow or overlap issues + + Returns a nested dictionary: {slide-N: {shape-N: ShapeData}} + Shapes are sorted by visual position (top-to-bottom, left-to-right). + The ShapeData objects contain the full shape information and can be + converted to dictionaries for JSON serialization using to_dict(). + """ + if prs is None: + prs = Presentation(str(pptx_path)) + inventory: InventoryData = {} + + for slide_idx, slide in enumerate(prs.slides): + # Collect all valid shapes from this slide with absolute positions + shapes_with_positions = [] + for shape in slide.shapes: # type: ignore + shapes_with_positions.extend(collect_shapes_with_absolute_positions(shape)) + + if not shapes_with_positions: + continue + + # Convert to ShapeData with absolute positions and slide reference + shape_data_list = [ + ShapeData( + swp.shape, + swp.absolute_left, + swp.absolute_top, + slide, + ) + for swp in shapes_with_positions + ] + + # Sort by visual position and assign stable IDs in one step + sorted_shapes = sort_shapes_by_position(shape_data_list) + for idx, shape_data in enumerate(sorted_shapes): + shape_data.shape_id = f"shape-{idx}" + + # Detect overlaps using the stable shape IDs + if len(sorted_shapes) > 1: + detect_overlaps(sorted_shapes) + + # Filter for issues only if requested (after overlap detection) + if issues_only: + sorted_shapes = [sd for sd in sorted_shapes if sd.has_any_issues] + + if not sorted_shapes: + continue + + # Create slide inventory using the stable shape IDs + inventory[f"slide-{slide_idx}"] = { + shape_data.shape_id: shape_data for shape_data in sorted_shapes + } + + return inventory + + +def get_inventory_as_dict(pptx_path: Path, issues_only: bool = False) -> InventoryDict: + """Extract text inventory and return as JSON-serializable dictionaries. + + This is a convenience wrapper around extract_text_inventory that returns + dictionaries instead of ShapeData objects, useful for testing and direct + JSON serialization. + + Args: + pptx_path: Path to the PowerPoint file + issues_only: If True, only include shapes that have overflow or overlap issues + + Returns: + Nested dictionary with all data serialized for JSON + """ + inventory = extract_text_inventory(pptx_path, issues_only=issues_only) + + # Convert ShapeData objects to dictionaries + dict_inventory: InventoryDict = {} + for slide_key, shapes in inventory.items(): + dict_inventory[slide_key] = { + shape_key: shape_data.to_dict() for shape_key, shape_data in shapes.items() + } + + return dict_inventory + + +def save_inventory(inventory: InventoryData, output_path: Path) -> None: + """Save inventory to JSON file with proper formatting. + + Converts ShapeData objects to dictionaries for JSON serialization. + """ + # Convert ShapeData objects to dictionaries + json_inventory: InventoryDict = {} + for slide_key, shapes in inventory.items(): + json_inventory[slide_key] = { + shape_key: shape_data.to_dict() for shape_key, shape_data in shapes.items() + } + + with open(output_path, "w", encoding="utf-8") as f: + json.dump(json_inventory, f, indent=2, ensure_ascii=False) + + +if __name__ == "__main__": + main() diff --git a/pptx-mcp-server/scripts/rearrange.py b/pptx-mcp-server/scripts/rearrange.py new file mode 100644 index 0000000..2519911 --- /dev/null +++ b/pptx-mcp-server/scripts/rearrange.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +""" +Rearrange PowerPoint slides based on a sequence of indices. + +Usage: + python rearrange.py template.pptx output.pptx 0,34,34,50,52 + +This will create output.pptx using slides from template.pptx in the specified order. +Slides can be repeated (e.g., 34 appears twice). +""" + +import argparse +import shutil +import sys +from copy import deepcopy +from pathlib import Path + +import six +from pptx import Presentation + + +def main(): + parser = argparse.ArgumentParser( + description="Rearrange PowerPoint slides based on a sequence of indices.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + python rearrange.py template.pptx output.pptx 0,34,34,50,52 + Creates output.pptx using slides 0, 34 (twice), 50, and 52 from template.pptx + + python rearrange.py template.pptx output.pptx 5,3,1,2,4 + Creates output.pptx with slides reordered as specified + +Note: Slide indices are 0-based (first slide is 0, second is 1, etc.) + """, + ) + + parser.add_argument("template", help="Path to template PPTX file") + parser.add_argument("output", help="Path for output PPTX file") + parser.add_argument( + "sequence", help="Comma-separated sequence of slide indices (0-based)" + ) + + args = parser.parse_args() + + # Parse the slide sequence + try: + slide_sequence = [int(x.strip()) for x in args.sequence.split(",")] + except ValueError: + print( + "Error: Invalid sequence format. Use comma-separated integers (e.g., 0,34,34,50,52)" + ) + sys.exit(1) + + # Check template exists + template_path = Path(args.template) + if not template_path.exists(): + print(f"Error: Template file not found: {args.template}") + sys.exit(1) + + # Create output directory if needed + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + + try: + rearrange_presentation(template_path, output_path, slide_sequence) + except ValueError as e: + print(f"Error: {e}") + sys.exit(1) + except Exception as e: + print(f"Error processing presentation: {e}") + sys.exit(1) + + +def duplicate_slide(pres, index): + """Duplicate a slide in the presentation.""" + source = pres.slides[index] + + # Use source's layout to preserve formatting + new_slide = pres.slides.add_slide(source.slide_layout) + + # Collect all image and media relationships from the source slide + image_rels = {} + for rel_id, rel in six.iteritems(source.part.rels): + if "image" in rel.reltype or "media" in rel.reltype: + image_rels[rel_id] = rel + + # CRITICAL: Clear placeholder shapes to avoid duplicates + for shape in new_slide.shapes: + sp = shape.element + sp.getparent().remove(sp) + + # Copy all shapes from source + for shape in source.shapes: + el = shape.element + new_el = deepcopy(el) + new_slide.shapes._spTree.insert_element_before(new_el, "p:extLst") + + # Handle picture shapes - need to update the blip reference + # Look for all blip elements (they can be in pic or other contexts) + # Using the element's own xpath method without namespaces argument + blips = new_el.xpath(".//a:blip[@r:embed]") + for blip in blips: + old_rId = blip.get( + "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed" + ) + if old_rId in image_rels: + # Create a new relationship in the destination slide for this image + old_rel = image_rels[old_rId] + # get_or_add returns the rId directly, or adds and returns new rId + new_rId = new_slide.part.rels.get_or_add( + old_rel.reltype, old_rel._target + ) + # Update the blip's embed reference to use the new relationship ID + blip.set( + "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed", + new_rId, + ) + + # Copy any additional image/media relationships that might be referenced elsewhere + for rel_id, rel in image_rels.items(): + try: + new_slide.part.rels.get_or_add(rel.reltype, rel._target) + except Exception: + pass # Relationship might already exist + + return new_slide + + +def delete_slide(pres, index): + """Delete a slide from the presentation.""" + rId = pres.slides._sldIdLst[index].rId + pres.part.drop_rel(rId) + del pres.slides._sldIdLst[index] + + +def reorder_slides(pres, slide_index, target_index): + """Move a slide from one position to another.""" + slides = pres.slides._sldIdLst + + # Remove slide element from current position + slide_element = slides[slide_index] + slides.remove(slide_element) + + # Insert at target position + slides.insert(target_index, slide_element) + + +def rearrange_presentation(template_path, output_path, slide_sequence): + """ + Create a new presentation with slides from template in specified order. + + Args: + template_path: Path to template PPTX file + output_path: Path for output PPTX file + slide_sequence: List of slide indices (0-based) to include + """ + # Copy template to preserve dimensions and theme + if template_path != output_path: + shutil.copy2(template_path, output_path) + prs = Presentation(output_path) + else: + prs = Presentation(template_path) + + total_slides = len(prs.slides) + + # Validate indices + for idx in slide_sequence: + if idx < 0 or idx >= total_slides: + raise ValueError(f"Slide index {idx} out of range (0-{total_slides - 1})") + + # Track original slides and their duplicates + slide_map = [] # List of actual slide indices for final presentation + duplicated = {} # Track duplicates: original_idx -> [duplicate_indices] + + # Step 1: DUPLICATE repeated slides + print(f"Processing {len(slide_sequence)} slides from template...") + for i, template_idx in enumerate(slide_sequence): + if template_idx in duplicated and duplicated[template_idx]: + # Already duplicated this slide, use the duplicate + slide_map.append(duplicated[template_idx].pop(0)) + print(f" [{i}] Using duplicate of slide {template_idx}") + elif slide_sequence.count(template_idx) > 1 and template_idx not in duplicated: + # First occurrence of a repeated slide - create duplicates + slide_map.append(template_idx) + duplicates = [] + count = slide_sequence.count(template_idx) - 1 + print( + f" [{i}] Using original slide {template_idx}, creating {count} duplicate(s)" + ) + for _ in range(count): + duplicate_slide(prs, template_idx) + duplicates.append(len(prs.slides) - 1) + duplicated[template_idx] = duplicates + else: + # Unique slide or first occurrence already handled, use original + slide_map.append(template_idx) + print(f" [{i}] Using original slide {template_idx}") + + # Step 2: DELETE unwanted slides (work backwards) + slides_to_keep = set(slide_map) + print(f"\nDeleting {len(prs.slides) - len(slides_to_keep)} unused slides...") + for i in range(len(prs.slides) - 1, -1, -1): + if i not in slides_to_keep: + delete_slide(prs, i) + # Update slide_map indices after deletion + slide_map = [idx - 1 if idx > i else idx for idx in slide_map] + + # Step 3: REORDER to final sequence + print(f"Reordering {len(slide_map)} slides to final sequence...") + for target_pos in range(len(slide_map)): + # Find which slide should be at target_pos + current_pos = slide_map[target_pos] + if current_pos != target_pos: + reorder_slides(prs, current_pos, target_pos) + # Update slide_map: the move shifts other slides + for i in range(len(slide_map)): + if slide_map[i] > current_pos and slide_map[i] <= target_pos: + slide_map[i] -= 1 + elif slide_map[i] < current_pos and slide_map[i] >= target_pos: + slide_map[i] += 1 + slide_map[target_pos] = target_pos + + # Save the presentation + prs.save(output_path) + print(f"\nSaved rearranged presentation to: {output_path}") + print(f"Final presentation has {len(prs.slides)} slides") + + +if __name__ == "__main__": + main() diff --git a/pptx-mcp-server/scripts/replace.py b/pptx-mcp-server/scripts/replace.py new file mode 100644 index 0000000..8f7a8b1 --- /dev/null +++ b/pptx-mcp-server/scripts/replace.py @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +"""Apply text replacements to PowerPoint presentation. + +Usage: + python replace.py + +The replacements JSON should have the structure output by inventory.py. +ALL text shapes identified by inventory.py will have their text cleared +unless "paragraphs" is specified in the replacements for that shape. +""" + +import json +import sys +from pathlib import Path +from typing import Any, Dict, List + +from inventory import InventoryData, extract_text_inventory +from pptx import Presentation +from pptx.dml.color import RGBColor +from pptx.enum.dml import MSO_THEME_COLOR +from pptx.enum.text import PP_ALIGN +from pptx.oxml.xmlchemy import OxmlElement +from pptx.util import Pt + + +def clear_paragraph_bullets(paragraph): + """Clear bullet formatting from a paragraph.""" + pPr = paragraph._element.get_or_add_pPr() + + # Remove existing bullet elements + for child in list(pPr): + if ( + child.tag.endswith("buChar") + or child.tag.endswith("buNone") + or child.tag.endswith("buAutoNum") + or child.tag.endswith("buFont") + ): + pPr.remove(child) + + return pPr + + +def apply_paragraph_properties(paragraph, para_data: Dict[str, Any]): + """Apply formatting properties to a paragraph.""" + # Get the text but don't set it on paragraph directly yet + text = para_data.get("text", "") + + # Get or create paragraph properties + pPr = clear_paragraph_bullets(paragraph) + + # Handle bullet formatting + if para_data.get("bullet", False): + level = para_data.get("level", 0) + paragraph.level = level + + # Calculate font-proportional indentation + font_size = para_data.get("font_size", 18.0) + level_indent_emu = int((font_size * (1.6 + level * 1.6)) * 12700) + hanging_indent_emu = int(-font_size * 0.8 * 12700) + + # Set indentation + pPr.attrib["marL"] = str(level_indent_emu) + pPr.attrib["indent"] = str(hanging_indent_emu) + + # Add bullet character + buChar = OxmlElement("a:buChar") + buChar.set("char", "•") + pPr.append(buChar) + + # Default to left alignment for bullets if not specified + if "alignment" not in para_data: + paragraph.alignment = PP_ALIGN.LEFT + else: + # Remove indentation for non-bullet text + pPr.attrib["marL"] = "0" + pPr.attrib["indent"] = "0" + + # Add buNone element + buNone = OxmlElement("a:buNone") + pPr.insert(0, buNone) + + # Apply alignment + if "alignment" in para_data: + alignment_map = { + "LEFT": PP_ALIGN.LEFT, + "CENTER": PP_ALIGN.CENTER, + "RIGHT": PP_ALIGN.RIGHT, + "JUSTIFY": PP_ALIGN.JUSTIFY, + } + if para_data["alignment"] in alignment_map: + paragraph.alignment = alignment_map[para_data["alignment"]] + + # Apply spacing + if "space_before" in para_data: + paragraph.space_before = Pt(para_data["space_before"]) + if "space_after" in para_data: + paragraph.space_after = Pt(para_data["space_after"]) + if "line_spacing" in para_data: + paragraph.line_spacing = Pt(para_data["line_spacing"]) + + # Apply run-level formatting + if not paragraph.runs: + run = paragraph.add_run() + run.text = text + else: + run = paragraph.runs[0] + run.text = text + + # Apply font properties + apply_font_properties(run, para_data) + + +def apply_font_properties(run, para_data: Dict[str, Any]): + """Apply font properties to a text run.""" + if "bold" in para_data: + run.font.bold = para_data["bold"] + if "italic" in para_data: + run.font.italic = para_data["italic"] + if "underline" in para_data: + run.font.underline = para_data["underline"] + if "font_size" in para_data: + run.font.size = Pt(para_data["font_size"]) + if "font_name" in para_data: + run.font.name = para_data["font_name"] + + # Apply color - prefer RGB, fall back to theme_color + if "color" in para_data: + color_hex = para_data["color"].lstrip("#") + if len(color_hex) == 6: + r = int(color_hex[0:2], 16) + g = int(color_hex[2:4], 16) + b = int(color_hex[4:6], 16) + run.font.color.rgb = RGBColor(r, g, b) + elif "theme_color" in para_data: + # Get theme color by name (e.g., "DARK_1", "ACCENT_1") + theme_name = para_data["theme_color"] + try: + run.font.color.theme_color = getattr(MSO_THEME_COLOR, theme_name) + except AttributeError: + print(f" WARNING: Unknown theme color name '{theme_name}'") + + +def detect_frame_overflow(inventory: InventoryData) -> Dict[str, Dict[str, float]]: + """Detect text overflow in shapes (text exceeding shape bounds). + + Returns dict of slide_key -> shape_key -> overflow_inches. + Only includes shapes that have text overflow. + """ + overflow_map = {} + + for slide_key, shapes_dict in inventory.items(): + for shape_key, shape_data in shapes_dict.items(): + # Check for frame overflow (text exceeding shape bounds) + if shape_data.frame_overflow_bottom is not None: + if slide_key not in overflow_map: + overflow_map[slide_key] = {} + overflow_map[slide_key][shape_key] = shape_data.frame_overflow_bottom + + return overflow_map + + +def validate_replacements(inventory: InventoryData, replacements: Dict) -> List[str]: + """Validate that all shapes in replacements exist in inventory. + + Returns list of error messages. + """ + errors = [] + + for slide_key, shapes_data in replacements.items(): + if not slide_key.startswith("slide-"): + continue + + # Check if slide exists + if slide_key not in inventory: + errors.append(f"Slide '{slide_key}' not found in inventory") + continue + + # Check each shape + for shape_key in shapes_data.keys(): + if shape_key not in inventory[slide_key]: + # Find shapes without replacements defined and show their content + unused_with_content = [] + for k in inventory[slide_key].keys(): + if k not in shapes_data: + shape_data = inventory[slide_key][k] + # Get text from paragraphs as preview + paragraphs = shape_data.paragraphs + if paragraphs and paragraphs[0].text: + first_text = paragraphs[0].text[:50] + if len(paragraphs[0].text) > 50: + first_text += "..." + unused_with_content.append(f"{k} ('{first_text}')") + else: + unused_with_content.append(k) + + errors.append( + f"Shape '{shape_key}' not found on '{slide_key}'. " + f"Shapes without replacements: {', '.join(sorted(unused_with_content)) if unused_with_content else 'none'}" + ) + + return errors + + +def check_duplicate_keys(pairs): + """Check for duplicate keys when loading JSON.""" + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate key found in JSON: '{key}'") + result[key] = value + return result + + +def apply_replacements(pptx_file: str, json_file: str, output_file: str): + """Apply text replacements from JSON to PowerPoint presentation.""" + + # Load presentation + prs = Presentation(pptx_file) + + # Get inventory of all text shapes (returns ShapeData objects) + # Pass prs to use same Presentation instance + inventory = extract_text_inventory(Path(pptx_file), prs) + + # Detect text overflow in original presentation + original_overflow = detect_frame_overflow(inventory) + + # Load replacement data with duplicate key detection + with open(json_file, "r") as f: + replacements = json.load(f, object_pairs_hook=check_duplicate_keys) + + # Validate replacements + errors = validate_replacements(inventory, replacements) + if errors: + print("ERROR: Invalid shapes in replacement JSON:") + for error in errors: + print(f" - {error}") + print("\nPlease check the inventory and update your replacement JSON.") + print( + "You can regenerate the inventory with: python inventory.py " + ) + raise ValueError(f"Found {len(errors)} validation error(s)") + + # Track statistics + shapes_processed = 0 + shapes_cleared = 0 + shapes_replaced = 0 + + # Process each slide from inventory + for slide_key, shapes_dict in inventory.items(): + if not slide_key.startswith("slide-"): + continue + + slide_index = int(slide_key.split("-")[1]) + + if slide_index >= len(prs.slides): + print(f"Warning: Slide {slide_index} not found") + continue + + # Process each shape from inventory + for shape_key, shape_data in shapes_dict.items(): + shapes_processed += 1 + + # Get the shape directly from ShapeData + shape = shape_data.shape + if not shape: + print(f"Warning: {shape_key} has no shape reference") + continue + + # ShapeData already validates text_frame in __init__ + text_frame = shape.text_frame # type: ignore + + text_frame.clear() # type: ignore + shapes_cleared += 1 + + # Check for replacement paragraphs + replacement_shape_data = replacements.get(slide_key, {}).get(shape_key, {}) + if "paragraphs" not in replacement_shape_data: + continue + + shapes_replaced += 1 + + # Add replacement paragraphs + for i, para_data in enumerate(replacement_shape_data["paragraphs"]): + if i == 0: + p = text_frame.paragraphs[0] # type: ignore + else: + p = text_frame.add_paragraph() # type: ignore + + apply_paragraph_properties(p, para_data) + + # Check for issues after replacements + # Save to a temporary file and reload to avoid modifying the presentation during inventory + # (extract_text_inventory accesses font.color which adds empty elements) + import tempfile + + with tempfile.NamedTemporaryFile(suffix=".pptx", delete=False) as tmp: + tmp_path = Path(tmp.name) + prs.save(str(tmp_path)) + + try: + updated_inventory = extract_text_inventory(tmp_path) + updated_overflow = detect_frame_overflow(updated_inventory) + finally: + tmp_path.unlink() # Clean up temp file + + # Check if any text overflow got worse + overflow_errors = [] + for slide_key, shape_overflows in updated_overflow.items(): + for shape_key, new_overflow in shape_overflows.items(): + # Get original overflow (0 if there was no overflow before) + original = original_overflow.get(slide_key, {}).get(shape_key, 0.0) + + # Error if overflow increased + if new_overflow > original + 0.01: # Small tolerance for rounding + increase = new_overflow - original + overflow_errors.append( + f'{slide_key}/{shape_key}: overflow worsened by {increase:.2f}" ' + f'(was {original:.2f}", now {new_overflow:.2f}")' + ) + + # Collect warnings from updated shapes + warnings = [] + for slide_key, shapes_dict in updated_inventory.items(): + for shape_key, shape_data in shapes_dict.items(): + if shape_data.warnings: + for warning in shape_data.warnings: + warnings.append(f"{slide_key}/{shape_key}: {warning}") + + # Fail if there are any issues + if overflow_errors or warnings: + print("\nERROR: Issues detected in replacement output:") + if overflow_errors: + print("\nText overflow worsened:") + for error in overflow_errors: + print(f" - {error}") + if warnings: + print("\nFormatting warnings:") + for warning in warnings: + print(f" - {warning}") + print("\nPlease fix these issues before saving.") + raise ValueError( + f"Found {len(overflow_errors)} overflow error(s) and {len(warnings)} warning(s)" + ) + + # Save the presentation + prs.save(output_file) + + # Report results + print(f"Saved updated presentation to: {output_file}") + print(f"Processed {len(prs.slides)} slides") + print(f" - Shapes processed: {shapes_processed}") + print(f" - Shapes cleared: {shapes_cleared}") + print(f" - Shapes replaced: {shapes_replaced}") + + +def main(): + """Main entry point for command-line usage.""" + if len(sys.argv) != 4: + print(__doc__) + sys.exit(1) + + input_pptx = Path(sys.argv[1]) + replacements_json = Path(sys.argv[2]) + output_pptx = Path(sys.argv[3]) + + if not input_pptx.exists(): + print(f"Error: Input file '{input_pptx}' not found") + sys.exit(1) + + if not replacements_json.exists(): + print(f"Error: Replacements JSON file '{replacements_json}' not found") + sys.exit(1) + + try: + apply_replacements(str(input_pptx), str(replacements_json), str(output_pptx)) + except Exception as e: + print(f"Error applying replacements: {e}") + import traceback + + traceback.print_exc() + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/pptx-mcp-server/scripts/thumbnail.py b/pptx-mcp-server/scripts/thumbnail.py new file mode 100644 index 0000000..5c7fdf1 --- /dev/null +++ b/pptx-mcp-server/scripts/thumbnail.py @@ -0,0 +1,450 @@ +#!/usr/bin/env python3 +""" +Create thumbnail grids from PowerPoint presentation slides. + +Creates a grid layout of slide thumbnails with configurable columns (max 6). +Each grid contains up to cols×(cols+1) images. For presentations with more +slides, multiple numbered grid files are created automatically. + +The program outputs the names of all files created. + +Output: +- Single grid: {prefix}.jpg (if slides fit in one grid) +- Multiple grids: {prefix}-1.jpg, {prefix}-2.jpg, etc. + +Grid limits by column count: +- 3 cols: max 12 slides per grid (3×4) +- 4 cols: max 20 slides per grid (4×5) +- 5 cols: max 30 slides per grid (5×6) [default] +- 6 cols: max 42 slides per grid (6×7) + +Usage: + python thumbnail.py input.pptx [output_prefix] [--cols N] [--outline-placeholders] + +Examples: + python thumbnail.py presentation.pptx + # Creates: thumbnails.jpg (using default prefix) + # Outputs: + # Created 1 grid(s): + # - thumbnails.jpg + + python thumbnail.py large-deck.pptx grid --cols 4 + # Creates: grid-1.jpg, grid-2.jpg, grid-3.jpg + # Outputs: + # Created 3 grid(s): + # - grid-1.jpg + # - grid-2.jpg + # - grid-3.jpg + + python thumbnail.py template.pptx analysis --outline-placeholders + # Creates thumbnail grids with red outlines around text placeholders +""" + +import argparse +import subprocess +import sys +import tempfile +from pathlib import Path + +from inventory import extract_text_inventory +from PIL import Image, ImageDraw, ImageFont +from pptx import Presentation + +# Constants +THUMBNAIL_WIDTH = 300 # Fixed thumbnail width in pixels +CONVERSION_DPI = 100 # DPI for PDF to image conversion +MAX_COLS = 6 # Maximum number of columns +DEFAULT_COLS = 5 # Default number of columns +JPEG_QUALITY = 95 # JPEG compression quality + +# Grid layout constants +GRID_PADDING = 20 # Padding between thumbnails +BORDER_WIDTH = 2 # Border width around thumbnails +FONT_SIZE_RATIO = 0.12 # Font size as fraction of thumbnail width +LABEL_PADDING_RATIO = 0.4 # Label padding as fraction of font size + + +def main(): + parser = argparse.ArgumentParser( + description="Create thumbnail grids from PowerPoint slides." + ) + parser.add_argument("input", help="Input PowerPoint file (.pptx)") + parser.add_argument( + "output_prefix", + nargs="?", + default="thumbnails", + help="Output prefix for image files (default: thumbnails, will create prefix.jpg or prefix-N.jpg)", + ) + parser.add_argument( + "--cols", + type=int, + default=DEFAULT_COLS, + help=f"Number of columns (default: {DEFAULT_COLS}, max: {MAX_COLS})", + ) + parser.add_argument( + "--outline-placeholders", + action="store_true", + help="Outline text placeholders with a colored border", + ) + + args = parser.parse_args() + + # Validate columns + cols = min(args.cols, MAX_COLS) + if args.cols > MAX_COLS: + print(f"Warning: Columns limited to {MAX_COLS} (requested {args.cols})") + + # Validate input + input_path = Path(args.input) + if not input_path.exists() or input_path.suffix.lower() != ".pptx": + print(f"Error: Invalid PowerPoint file: {args.input}") + sys.exit(1) + + # Construct output path (always JPG) + output_path = Path(f"{args.output_prefix}.jpg") + + print(f"Processing: {args.input}") + + try: + with tempfile.TemporaryDirectory() as temp_dir: + # Get placeholder regions if outlining is enabled + placeholder_regions = None + slide_dimensions = None + if args.outline_placeholders: + print("Extracting placeholder regions...") + placeholder_regions, slide_dimensions = get_placeholder_regions( + input_path + ) + if placeholder_regions: + print(f"Found placeholders on {len(placeholder_regions)} slides") + + # Convert slides to images + slide_images = convert_to_images(input_path, Path(temp_dir), CONVERSION_DPI) + if not slide_images: + print("Error: No slides found") + sys.exit(1) + + print(f"Found {len(slide_images)} slides") + + # Create grids (max cols×(cols+1) images per grid) + grid_files = create_grids( + slide_images, + cols, + THUMBNAIL_WIDTH, + output_path, + placeholder_regions, + slide_dimensions, + ) + + # Print saved files + print(f"Created {len(grid_files)} grid(s):") + for grid_file in grid_files: + print(f" - {grid_file}") + + except Exception as e: + print(f"Error: {e}") + sys.exit(1) + + +def create_hidden_slide_placeholder(size): + """Create placeholder image for hidden slides.""" + img = Image.new("RGB", size, color="#F0F0F0") + draw = ImageDraw.Draw(img) + line_width = max(5, min(size) // 100) + draw.line([(0, 0), size], fill="#CCCCCC", width=line_width) + draw.line([(size[0], 0), (0, size[1])], fill="#CCCCCC", width=line_width) + return img + + +def get_placeholder_regions(pptx_path): + """Extract ALL text regions from the presentation. + + Returns a tuple of (placeholder_regions, slide_dimensions). + text_regions is a dict mapping slide indices to lists of text regions. + Each region is a dict with 'left', 'top', 'width', 'height' in inches. + slide_dimensions is a tuple of (width_inches, height_inches). + """ + prs = Presentation(str(pptx_path)) + inventory = extract_text_inventory(pptx_path, prs) + placeholder_regions = {} + + # Get actual slide dimensions in inches (EMU to inches conversion) + slide_width_inches = (prs.slide_width or 9144000) / 914400.0 + slide_height_inches = (prs.slide_height or 5143500) / 914400.0 + + for slide_key, shapes in inventory.items(): + # Extract slide index from "slide-N" format + slide_idx = int(slide_key.split("-")[1]) + regions = [] + + for shape_key, shape_data in shapes.items(): + # The inventory only contains shapes with text, so all shapes should be highlighted + regions.append( + { + "left": shape_data.left, + "top": shape_data.top, + "width": shape_data.width, + "height": shape_data.height, + } + ) + + if regions: + placeholder_regions[slide_idx] = regions + + return placeholder_regions, (slide_width_inches, slide_height_inches) + + +def convert_to_images(pptx_path, temp_dir, dpi): + """Convert PowerPoint to images via PDF, handling hidden slides.""" + # Detect hidden slides + print("Analyzing presentation...") + prs = Presentation(str(pptx_path)) + total_slides = len(prs.slides) + + # Find hidden slides (1-based indexing for display) + hidden_slides = { + idx + 1 + for idx, slide in enumerate(prs.slides) + if slide.element.get("show") == "0" + } + + print(f"Total slides: {total_slides}") + if hidden_slides: + print(f"Hidden slides: {sorted(hidden_slides)}") + + pdf_path = temp_dir / f"{pptx_path.stem}.pdf" + + # Convert to PDF + print("Converting to PDF...") + result = subprocess.run( + [ + "soffice", + "--headless", + "--convert-to", + "pdf", + "--outdir", + str(temp_dir), + str(pptx_path), + ], + capture_output=True, + text=True, + ) + if result.returncode != 0 or not pdf_path.exists(): + raise RuntimeError("PDF conversion failed") + + # Convert PDF to images + print(f"Converting to images at {dpi} DPI...") + result = subprocess.run( + ["pdftoppm", "-jpeg", "-r", str(dpi), str(pdf_path), str(temp_dir / "slide")], + capture_output=True, + text=True, + ) + if result.returncode != 0: + raise RuntimeError("Image conversion failed") + + visible_images = sorted(temp_dir.glob("slide-*.jpg")) + + # Create full list with placeholders for hidden slides + all_images = [] + visible_idx = 0 + + # Get placeholder dimensions from first visible slide + if visible_images: + with Image.open(visible_images[0]) as img: + placeholder_size = img.size + else: + placeholder_size = (1920, 1080) + + for slide_num in range(1, total_slides + 1): + if slide_num in hidden_slides: + # Create placeholder image for hidden slide + placeholder_path = temp_dir / f"hidden-{slide_num:03d}.jpg" + placeholder_img = create_hidden_slide_placeholder(placeholder_size) + placeholder_img.save(placeholder_path, "JPEG") + all_images.append(placeholder_path) + else: + # Use the actual visible slide image + if visible_idx < len(visible_images): + all_images.append(visible_images[visible_idx]) + visible_idx += 1 + + return all_images + + +def create_grids( + image_paths, + cols, + width, + output_path, + placeholder_regions=None, + slide_dimensions=None, +): + """Create multiple thumbnail grids from slide images, max cols×(cols+1) images per grid.""" + # Maximum images per grid is cols × (cols + 1) for better proportions + max_images_per_grid = cols * (cols + 1) + grid_files = [] + + print( + f"Creating grids with {cols} columns (max {max_images_per_grid} images per grid)" + ) + + # Split images into chunks + for chunk_idx, start_idx in enumerate( + range(0, len(image_paths), max_images_per_grid) + ): + end_idx = min(start_idx + max_images_per_grid, len(image_paths)) + chunk_images = image_paths[start_idx:end_idx] + + # Create grid for this chunk + grid = create_grid( + chunk_images, cols, width, start_idx, placeholder_regions, slide_dimensions + ) + + # Generate output filename + if len(image_paths) <= max_images_per_grid: + # Single grid - use base filename without suffix + grid_filename = output_path + else: + # Multiple grids - insert index before extension with dash + stem = output_path.stem + suffix = output_path.suffix + grid_filename = output_path.parent / f"{stem}-{chunk_idx + 1}{suffix}" + + # Save grid + grid_filename.parent.mkdir(parents=True, exist_ok=True) + grid.save(str(grid_filename), quality=JPEG_QUALITY) + grid_files.append(str(grid_filename)) + + return grid_files + + +def create_grid( + image_paths, + cols, + width, + start_slide_num=0, + placeholder_regions=None, + slide_dimensions=None, +): + """Create thumbnail grid from slide images with optional placeholder outlining.""" + font_size = int(width * FONT_SIZE_RATIO) + label_padding = int(font_size * LABEL_PADDING_RATIO) + + # Get dimensions + with Image.open(image_paths[0]) as img: + aspect = img.height / img.width + height = int(width * aspect) + + # Calculate grid size + rows = (len(image_paths) + cols - 1) // cols + grid_w = cols * width + (cols + 1) * GRID_PADDING + grid_h = rows * (height + font_size + label_padding * 2) + (rows + 1) * GRID_PADDING + + # Create grid + grid = Image.new("RGB", (grid_w, grid_h), "white") + draw = ImageDraw.Draw(grid) + + # Load font with size based on thumbnail width + try: + # Use Pillow's default font with size + font = ImageFont.load_default(size=font_size) + except Exception: + # Fall back to basic default font if size parameter not supported + font = ImageFont.load_default() + + # Place thumbnails + for i, img_path in enumerate(image_paths): + row, col = i // cols, i % cols + x = col * width + (col + 1) * GRID_PADDING + y_base = ( + row * (height + font_size + label_padding * 2) + (row + 1) * GRID_PADDING + ) + + # Add label with actual slide number + label = f"{start_slide_num + i}" + bbox = draw.textbbox((0, 0), label, font=font) + text_w = bbox[2] - bbox[0] + draw.text( + (x + (width - text_w) // 2, y_base + label_padding), + label, + fill="black", + font=font, + ) + + # Add thumbnail below label with proportional spacing + y_thumbnail = y_base + label_padding + font_size + label_padding + + with Image.open(img_path) as img: + # Get original dimensions before thumbnail + orig_w, orig_h = img.size + + # Apply placeholder outlines if enabled + if placeholder_regions and (start_slide_num + i) in placeholder_regions: + # Convert to RGBA for transparency support + if img.mode != "RGBA": + img = img.convert("RGBA") + + # Get the regions for this slide + regions = placeholder_regions[start_slide_num + i] + + # Calculate scale factors using actual slide dimensions + if slide_dimensions: + slide_width_inches, slide_height_inches = slide_dimensions + else: + # Fallback: estimate from image size at CONVERSION_DPI + slide_width_inches = orig_w / CONVERSION_DPI + slide_height_inches = orig_h / CONVERSION_DPI + + x_scale = orig_w / slide_width_inches + y_scale = orig_h / slide_height_inches + + # Create a highlight overlay + overlay = Image.new("RGBA", img.size, (255, 255, 255, 0)) + overlay_draw = ImageDraw.Draw(overlay) + + # Highlight each placeholder region + for region in regions: + # Convert from inches to pixels in the original image + px_left = int(region["left"] * x_scale) + px_top = int(region["top"] * y_scale) + px_width = int(region["width"] * x_scale) + px_height = int(region["height"] * y_scale) + + # Draw highlight outline with red color and thick stroke + # Using a bright red outline instead of fill + stroke_width = max( + 5, min(orig_w, orig_h) // 150 + ) # Thicker proportional stroke width + overlay_draw.rectangle( + [(px_left, px_top), (px_left + px_width, px_top + px_height)], + outline=(255, 0, 0, 255), # Bright red, fully opaque + width=stroke_width, + ) + + # Composite the overlay onto the image using alpha blending + img = Image.alpha_composite(img, overlay) + # Convert back to RGB for JPEG saving + img = img.convert("RGB") + + img.thumbnail((width, height), Image.Resampling.LANCZOS) + w, h = img.size + tx = x + (width - w) // 2 + ty = y_thumbnail + (height - h) // 2 + grid.paste(img, (tx, ty)) + + # Add border + if BORDER_WIDTH > 0: + draw.rectangle( + [ + (tx - BORDER_WIDTH, ty - BORDER_WIDTH), + (tx + w + BORDER_WIDTH - 1, ty + h + BORDER_WIDTH - 1), + ], + outline="gray", + width=BORDER_WIDTH, + ) + + return grid + + +if __name__ == "__main__": + main() diff --git a/pptx-mcp-server/test_mcp_server.py b/pptx-mcp-server/test_mcp_server.py new file mode 100644 index 0000000..9996be3 --- /dev/null +++ b/pptx-mcp-server/test_mcp_server.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +""" +Test script for PPTX MCP Server +Tests the MCP server by connecting to it and calling its tools +""" + +import asyncio +import json +import sys +from pathlib import Path + +# Add the current directory to the path so we can import the MCP server +sys.path.insert(0, str(Path(__file__).parent)) + +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client + + +async def test_list_tools(): + """Test listing available tools from the MCP server""" + print("\n" + "="*60) + print("TEST 1: List Available Tools") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["script_executor_mcp.py"], + env=None + ) + + async with stdio_client(server_params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + + # List tools + tools = await session.list_tools() + + print(f"\n✅ Found {len(tools.tools)} tools:") + for tool in tools.tools: + print(f"\n 📦 {tool.name}") + print(f" Description: {tool.description}") + print(f" Parameters: {json.dumps(tool.inputSchema, indent=6)}") + + return tools.tools + + +async def test_tool_schemas(): + """Test that all tool schemas are valid""" + print("\n" + "="*60) + print("TEST 2: Validate Tool Schemas") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["script_executor_mcp.py"], + env=None + ) + + async with stdio_client(server_params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = await session.list_tools() + + for tool in tools.tools: + schema = tool.inputSchema + required = schema.get("required", []) + properties = schema.get("properties", {}) + + print(f"\n ✅ {tool.name}") + print(f" Required params: {required}") + print(f" All params: {list(properties.keys())}") + + +async def test_inventory_tool(): + """Test the inventory tool with a mock call""" + print("\n" + "="*60) + print("TEST 3: Test Inventory Tool (Mock Call)") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["script_executor_mcp.py"], + env=None + ) + + async with stdio_client(server_params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + + # Try to call inventory tool with test parameters + # Note: This will fail because the files don't exist, but we can see if the tool is callable + try: + result = await session.call_tool( + "inventory", + arguments={ + "input_file": "test.pptx", + "output_file": "test_inventory.json" + } + ) + print(f"\n Tool response: {result}") + except Exception as e: + # Expected to fail since test.pptx doesn't exist + print(f"\n ⚠️ Tool call failed (expected): {str(e)[:200]}") + print(f" ✅ But the tool is callable and responds to requests!") + + +async def test_thumbnail_tool(): + """Test the thumbnail tool with a mock call""" + print("\n" + "="*60) + print("TEST 4: Test Thumbnail Tool (Mock Call)") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["script_executor_mcp.py"], + env=None + ) + + async with stdio_client(server_params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + + try: + result = await session.call_tool( + "thumbnail", + arguments={ + "input_file": "test.pptx", + "output_prefix": "test_thumb", + "columns": 4 + } + ) + print(f"\n Tool response: {result}") + except Exception as e: + print(f"\n ⚠️ Tool call failed (expected): {str(e)[:200]}") + print(f" ✅ But the tool is callable and responds to requests!") + + +async def test_server_lifecycle(): + """Test that the server can start and stop cleanly""" + print("\n" + "="*60) + print("TEST 5: Server Lifecycle") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["script_executor_mcp.py"], + env=None + ) + + print("\n Starting server...") + async with stdio_client(server_params) as (read, write): + print(" ✅ Server started successfully") + + async with ClientSession(read, write) as session: + print(" ✅ Session initialized") + await session.initialize() + + # Do a simple operation + tools = await session.list_tools() + print(f" ✅ Listed {len(tools.tools)} tools") + + print(" ✅ Session closed cleanly") + + print(" ✅ Server stopped cleanly") + + +async def main(): + """Run all tests""" + print("\n" + "="*60) + print("PPTX MCP SERVER TEST SUITE") + print("="*60) + print(f"Testing server at: {Path(__file__).parent / 'script_executor_mcp.py'}") + + try: + # Test 1: List tools + await test_list_tools() + + # Test 2: Validate schemas + await test_tool_schemas() + + # Test 3: Test inventory tool + await test_inventory_tool() + + # Test 4: Test thumbnail tool + await test_thumbnail_tool() + + # Test 5: Server lifecycle + await test_server_lifecycle() + + print("\n" + "="*60) + print("✅ ALL TESTS COMPLETED") + print("="*60) + print("\nSummary:") + print(" ✅ MCP server starts successfully") + print(" ✅ All 5 tools are registered") + print(" ✅ Tool schemas are valid") + print(" ✅ Tools are callable") + print(" ✅ Server lifecycle works correctly") + print("\n🎉 The MCP server is working properly!") + + except Exception as e: + print("\n" + "="*60) + print("❌ TEST FAILED") + print("="*60) + print(f"\nError: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/pptx-power-clean/POWER.md b/pptx-power-clean/POWER.md new file mode 100644 index 0000000..b9be616 --- /dev/null +++ b/pptx-power-clean/POWER.md @@ -0,0 +1,397 @@ +--- +name: "pptx" +displayName: "PowerPoint Presentation Tools" +description: "Create, edit, and analyze PowerPoint presentations (.pptx files) with advanced OOXML manipulation, HTML-to-PPTX conversion, and template-based workflows" +keywords: ["pptx", "powerpoint", "presentation", "slides", "ooxml", "html2pptx"] +author: "Converted from Claude Skill" +version: "1.0.0" +--- + +# PowerPoint Presentation Tools + +## ⚠️ CRITICAL: New Presentation Workflow + +**When user requests a NEW presentation, you MUST follow this workflow:** + +1. **FIRST: Read `user-request-to-html.md` steering file** (call readSteering action) +2. **Create HTML preview** (`preview.html`) for user to review in browser +3. **WAIT for user approval** before proceeding +4. **Only after approval**: Create individual slide files and convert to PPTX + +**DO NOT skip the HTML preview step. DO NOT generate PPTX directly from user request.** + +This workflow ensures user can review content/design before PPTX generation. + +--- + +## Overview + +This power enables comprehensive PowerPoint presentation creation, editing, and analysis through MCP tools that provide: + +- **Text extraction and analysis** - Convert presentations to markdown for content review +- **HTML-to-PPTX conversion** - Create new presentations from HTML with precise positioning +- **OOXML editing** - Direct XML manipulation for advanced editing tasks +- **Template-based creation** - Duplicate and customize existing presentation templates +- **Visual analysis** - Generate thumbnail grids and convert slides to images + +**IMPORTANT**: This power provides **MCP tools** for PowerPoint operations. When working with presentations: +- ✅ **USE the MCP tools** (html2pptx, inventory, rearrange, replace, thumbnail) +- ❌ **DO NOT create scripts manually** or try to install libraries yourself +- ✅ **Let the MCP tools handle all PowerPoint operations** + +## Installation + +**IMPORTANT:** This Power requires a separate MCP server installation. + +### Step 1: Install MCP Server + +Choose one of the following installation methods: + +#### Option A: Install to Standard Location (Recommended) + +```bash +# Create MCP servers directory +mkdir -p ~/.kiro/mcp-servers + +# Clone the MCP server repository +git clone https://github.com/your-username/pptx-mcp-server.git ~/.kiro/mcp-servers/pptx-mcp-server + +# Or manually copy if you have the files locally +cp -r pptx-mcp-server ~/.kiro/mcp-servers/ +``` + +#### Option B: Install from Source + +```bash +# If you have the source files +mkdir -p ~/.kiro/mcp-servers/pptx-mcp-server +cd ~/.kiro/mcp-servers/pptx-mcp-server + +# Copy all files from pptx-mcp-server directory +# - script_executor_mcp.py +# - scripts/ +# - ooxml/ +# - requirements.txt +``` + +### Step 2: Install Dependencies + +```bash +cd ~/.kiro/mcp-servers/pptx-mcp-server + +# Install Python dependencies +pip install -r requirements.txt + +# Install Node.js dependencies locally +npm install + +# Install system tools +# macOS: +brew install libreoffice poppler + +# Ubuntu/Debian: +sudo apt-get install libreoffice poppler-utils +``` + +### Step 3: Test MCP Server + +```bash +cd ~/.kiro/mcp-servers/pptx-mcp-server + +# Run test suite +python test_mcp_server.py +``` + +Expected output: +``` +============================================================ +✅ ALL TESTS COMPLETED +============================================================ +🎉 The MCP server is working properly! +``` + +### Step 4: Install the Power + +1. Open Kiro Powers panel +2. Click "Add from local directory" or "Add Custom Power" +3. Select this power directory +4. The Power will automatically connect to the installed MCP server + +**Note:** The MCP server will be **automatically started** by Kiro when the Power is activated. You don't need to manually start the server. + +## Available Tools + +This power provides 5 MCP tools for PowerPoint manipulation. **Always use these MCP tools instead of writing scripts manually.** + +### html2pptx +Convert HTML slides to PowerPoint presentation with precise positioning and styling. + +**How to use:** +``` +"Use the html2pptx tool to convert these HTML files to PowerPoint: +- slide1.html +- slide2.html +- slide3.html +Output: presentation.pptx" +``` + +**Parameters:** +- `html_files` (array): Array of HTML file paths for each slide +- `output_file` (string): Output .pptx file path +- `config` (object, optional): Configuration for charts, tables, etc. + +### inventory +Extract all text shapes and properties from a presentation for analysis or modification. + +**How to use:** +``` +"Use the inventory tool to extract text from presentation.pptx and save to inventory.json" +``` + +**Parameters:** +- `input_file` (string): Input .pptx file path +- `output_file` (string): Output JSON file path for inventory + +### rearrange +Duplicate, reorder, and delete slides in a presentation. + +**How to use:** +``` +"Use the rearrange tool on template.pptx: keep slides 0, 5, 5, 10 and save to working.pptx" +``` + +**Parameters:** +- `input_file` (string): Input .pptx file path +- `output_file` (string): Output .pptx file path +- `slide_indices` (string): Comma-separated slide indices (0-based, can repeat) + +### replace +Replace text content in presentation while preserving all formatting. + +**How to use:** +``` +"Use the replace tool to update working.pptx with replacements from replacements.json, save to output.pptx" +``` + +**Parameters:** +- `input_file` (string): Input .pptx file path +- `replacement_json` (string): JSON file with replacement text and formatting +- `output_file` (string): Output .pptx file path + +### thumbnail +Generate visual thumbnail grids of presentation slides for quick review. + +**How to use:** +``` +"Use the thumbnail tool to generate thumbnails for presentation.pptx with 4 columns" +``` + +**Parameters:** +- `input_file` (string): Input .pptx file path +- `output_prefix` (string, optional): Output file prefix (default: 'thumbnails') +- `columns` (integer, optional): Number of columns 3-6 (default: 5) + +## Common Workflows + +### Creating a New Presentation from User Request (RECOMMENDED) + +**This is the recommended workflow for new presentations.** + +**⚠️ FIRST: Read the `user-request-to-html.md` steering file before starting!** + +1. **Create HTML preview** for user review + - Single-page HTML with all slides + - Larger dimensions for easy reading (960px × 540px) + - Get user approval before proceeding + +2. **After approval, create individual slide files** + - One HTML file per slide (720pt × 405pt) + - Adjust font sizes for smaller dimensions + - Match content from approved preview + +3. **Convert to PowerPoint** + - Use html2pptx tool to convert HTML files + - Generate thumbnails to validate layout + - Make adjustments if needed + +**Why this workflow?** +- User can review content before PPTX generation +- Easier to iterate on HTML than PPTX +- Catches issues early +- Ensures alignment with expectations + +### Creating a New Presentation from HTML (Direct) + +**Use this only if you already have approved HTML slides.** + +1. Create HTML files for each slide (720pt × 405pt) +2. Use html2pptx tool to convert to PowerPoint +3. Generate thumbnails to validate layout +4. Make adjustments as needed + +### Using a Template + +1. Generate thumbnail grid of template +2. Use rearrange tool to duplicate/reorder slides +3. Use inventory tool to extract text shapes +4. Use replace tool to update content with new text + +### Editing Existing Presentations + +1. Use inventory tool to understand structure +2. Modify content as needed +3. Use replace tool to apply changes +4. Generate thumbnails to verify results + +## MCP Server Location + +This power expects the MCP server to be installed at: +``` +~/.kiro/mcp-servers/pptx-mcp-server/ +``` + +If you installed it elsewhere, update the path in `mcp.json`: +```json +{ + "mcpServers": { + "pptx-tools": { + "command": "python", + "args": ["/your/custom/path/pptx-mcp-server/script_executor_mcp.py"] + } + } +} +``` + +## Troubleshooting + +### Error: MCP server not found + +**Symptoms:** +- "Connection refused" or "Server not responding" +- Tools not available + +**Solution:** +1. Verify MCP server is installed: + ```bash + ls -la ~/.kiro/mcp-servers/pptx-mcp-server/script_executor_mcp.py + ``` + +2. Test MCP server directly: + ```bash + cd ~/.kiro/mcp-servers/pptx-mcp-server + python script_executor_mcp.py + # Should start without errors + ``` + +3. Check mcp.json path is correct + +### Error: ModuleNotFoundError + +**Symptoms:** +- "No module named 'mcp'" +- "No module named 'PIL'" +- "No module named 'pptx'" + +**Solution:** +```bash +cd ~/.kiro/mcp-servers/pptx-mcp-server +pip install -r requirements.txt +``` + +### Error: Script not found + +**Symptoms:** +- "Script not found at scripts/..." + +**Solution:** +1. Verify all scripts are present: + ```bash + ls -la ~/.kiro/mcp-servers/pptx-mcp-server/scripts/ + ``` + +2. Reinstall MCP server if files are missing + +### Error: Permission denied + +**Symptoms:** +- "Permission denied" when executing scripts + +**Solution:** +```bash +cd ~/.kiro/mcp-servers/pptx-mcp-server +chmod +x scripts/*.py scripts/*.js +chmod +x ooxml/scripts/*.py +``` + +### Tools not appearing in Kiro + +**Solution:** +1. Restart Kiro +2. Reinstall the Power +3. Check MCP logs in Kiro for errors + +## Available Steering Files + +**IMPORTANT:** Read the appropriate steering file BEFORE starting any workflow. + +| Steering File | When to Read | Description | +|---------------|--------------|-------------| +| `user-request-to-html.md` | **FIRST** - When creating a new presentation from user request | Complete guide for creating HTML preview for user approval | +| `html2pptx-guide.md` | After user approves HTML preview | HTML to PPTX conversion, validation errors, design guidelines | +| `template-workflow.md` | When using an existing PPTX as template | Template-based creation with rearrange/replace tools | +| `ooxml-guide.md` | For advanced XML editing | Direct OOXML manipulation for complex edits | + +**Workflow Decision:** +- User wants a **new presentation** → Read `user-request-to-html.md` first +- User has **approved HTML slides** → Read `html2pptx-guide.md` +- User wants to **modify existing PPTX** → Read `template-workflow.md` or `ooxml-guide.md` + +## Technical Details + +**Architecture:** Script Executor Pattern +- MCP server executes Python and JavaScript scripts +- Zero-context execution for all operations +- Full control over script execution and error handling + +**Supported Formats:** +- Input: .pptx, HTML, JSON +- Output: .pptx, JSON, JPEG (thumbnails) + +**Performance:** +- Startup time: < 1 second +- Tool execution: Depends on file size and operation +- Memory: Low (scripts loaded on demand) + +## Updates and Maintenance + +To update the MCP server: + +```bash +cd ~/.kiro/mcp-servers/pptx-mcp-server + +# Pull latest changes (if using git) +git pull + +# Or manually replace files + +# Reinstall dependencies if needed +pip install -r requirements.txt + +# Test after update +python test_mcp_server.py +``` + +No need to reinstall the Power after MCP server updates. + +## Related Resources + +- **MCP Server Repository:** [GitHub link] +- **Original Claude Skill:** Converted from pptx skill +- **Documentation:** See steering files for detailed guides + +--- + +**Power Type:** Guided MCP Power +**MCP Server:** pptx-tools +**Installation:** Two-step (MCP server + Power) +**Last Updated:** 2026-01-04 diff --git a/pptx-power-clean/README.md b/pptx-power-clean/README.md new file mode 100644 index 0000000..9cc4307 --- /dev/null +++ b/pptx-power-clean/README.md @@ -0,0 +1,157 @@ +# PowerPoint Presentation Tools Power + +A comprehensive Kiro Power for creating, editing, and analyzing PowerPoint presentations (.pptx files). + +## Quick Start + +### 1. Install MCP Server + +```bash +# Clone or copy MCP server to standard location +mkdir -p ~/.kiro/mcp-servers +cp -r pptx-mcp-server ~/.kiro/mcp-servers/ + +# Install dependencies +cd ~/.kiro/mcp-servers/pptx-mcp-server +pip install -r requirements.txt +npm install -g pptxgenjs playwright react-icons sharp + +# Test installation +python test_mcp_server.py +``` + +### 2. Install Power + +1. Open Kiro Powers panel +2. Add from local directory: `powers/pptx-power-clean` +3. Power will connect to the installed MCP server + +### 3. Use in Kiro + +Mention keywords like "pptx", "powerpoint", or "presentation" to activate the power. + +## Features + +- **Create from Scratch**: HTML-to-PPTX conversion with precise positioning +- **Template-Based**: Duplicate and customize existing templates +- **Advanced Editing**: Direct OOXML manipulation +- **Text Analysis**: Extract and analyze content +- **Visual Tools**: Generate thumbnails and convert slides + +### Example Output + +Here's an example of a presentation created with this power: + +![Example Presentation Thumbnails](examples/example-presentation-thumbnails.jpg) + +*8-slide presentation about AI Agents, generated from HTML using the html2pptx tool* + +## Available Tools + +- **html2pptx** - Convert HTML to PowerPoint +- **inventory** - Extract text shapes and properties +- **rearrange** - Duplicate, reorder, delete slides +- **replace** - Replace text while preserving formatting +- **thumbnail** - Generate visual thumbnail grids + +## Documentation + +- **POWER.md** - Main documentation with installation guide +- **steering/html2pptx-guide.md** - HTML conversion workflow +- **steering/ooxml-guide.md** - OOXML editing workflow +- **steering/template-workflow.md** - Template-based creation + +## Architecture + +**Two-Part Structure:** + +1. **MCP Server** (separate installation) + - Location: `~/.kiro/mcp-servers/pptx-mcp-server/` + - Contains: Scripts, MCP server code, dependencies + - Repository: [Link to MCP server repo] + +2. **Power** (this directory) + - Contains: Documentation only (POWER.md, mcp.json, steering/) + - Purpose: Configuration and usage guide + +## Requirements + +### Python Packages +```bash +pip install mcp markitdown[pptx] defusedxml Pillow python-pptx +``` + +### Node.js Packages +```bash +npm install -g pptxgenjs playwright react-icons sharp +``` + +### System Tools +```bash +# macOS +brew install libreoffice poppler + +# Ubuntu/Debian +sudo apt-get install libreoffice poppler-utils +``` + +## Troubleshooting + +### MCP Server Not Found + +```bash +# Verify installation +ls -la ~/.kiro/mcp-servers/pptx-mcp-server/ + +# Test server +cd ~/.kiro/mcp-servers/pptx-mcp-server +python script_executor_mcp.py +``` + +### Missing Dependencies + +```bash +cd ~/.kiro/mcp-servers/pptx-mcp-server +pip install -r requirements.txt +``` + +### Permission Issues + +```bash +cd ~/.kiro/mcp-servers/pptx-mcp-server +chmod +x scripts/*.py scripts/*.js +chmod +x ooxml/scripts/*.py +``` + +## Updates + +To update the MCP server: + +```bash +cd ~/.kiro/mcp-servers/pptx-mcp-server +git pull # If using git +pip install -r requirements.txt +python test_mcp_server.py +``` + +No need to reinstall the Power after MCP server updates. + +## Conversion Notes + +This power was converted from a Claude Agent Skill using the "Convert Skills to Power" tool: +- Original: Claude Agent Skill with 5 scripts +- Conversion approach: Script Executor Pattern with separate MCP server installation +- All scripts preserved as-is for reliability +- Documentation reorganized for Kiro Powers + +## Support + +For issues or questions: +1. Check POWER.md for detailed troubleshooting +2. Review steering files for workflow guidance +3. Test MCP server with `test_mcp_server.py` +4. Check MCP logs in Kiro + +## License + +[Your License Here] diff --git a/pptx-power-clean/examples/README.md b/pptx-power-clean/examples/README.md new file mode 100644 index 0000000..007a43b --- /dev/null +++ b/pptx-power-clean/examples/README.md @@ -0,0 +1,100 @@ +# PPTX Power Examples + +This directory contains example outputs generated by the PPTX Power. + +## Example Files + +### example-presentation-thumbnails.jpg + +**Description:** Thumbnail grid of an 8-slide presentation about AI Agents across different industries. + +**Generated using:** +1. Created HTML preview from user request +2. User approved the design and content +3. Generated individual slide HTML files (720pt × 405pt) +4. Converted to PPTX using `html2pptx` tool +5. Generated thumbnails using `thumbnail` tool + +**Workflow:** +- Tool: `html2pptx` +- Input: 8 HTML slide files +- Output: `ai-agents-presentation.pptx` +- Thumbnails: Generated with 4 columns + +**Design features:** +- Dark blue background (#0A0E27) +- Cyan accent color (#00D9FF) +- Clean, modern layout +- Professional typography +- Consistent visual hierarchy + +**Content:** +1. Title slide: "AI Agents Across Industries" +2. Healthcare applications +3. Finance applications +4. Retail applications +5. Manufacturing applications +6. Education applications +7. Key benefits summary +8. Conclusion and next steps + +## Using These Examples + +These examples demonstrate: +- ✅ What's possible with the PPTX Power +- ✅ Quality of HTML-to-PPTX conversion +- ✅ Thumbnail generation output +- ✅ Professional presentation design + +## Creating Your Own + +To create similar presentations: + +1. **Start with preview:** + - See `steering/user-request-to-html.md` + - Create HTML preview for user review + - Get approval before proceeding + +2. **Generate slides:** + - See `steering/html2pptx-guide.md` + - Create individual slide HTML files + - Use proper dimensions (720pt × 405pt) + +3. **Convert to PPTX:** + - Use `html2pptx` MCP tool + - Generate thumbnails for validation + - Review and iterate if needed + +## Tips for Best Results + +**Design:** +- Choose colors that match your topic +- Use web-safe fonts only +- Maintain consistent visual hierarchy +- Ensure good contrast for readability + +**Content:** +- One key point per slide +- Use bullet points sparingly +- Include visual elements where appropriate +- Keep text concise and clear + +**Technical:** +- Follow dimension guidelines +- Test with thumbnail generation +- Validate with error messages +- Iterate based on feedback + +## More Examples + +Want to contribute more examples? + +1. Create a presentation using the PPTX Power +2. Generate thumbnails +3. Add to this directory with descriptive name +4. Update this README with details +5. Submit a pull request + +--- + +**Note:** All example files in this directory are kept in version control to demonstrate the power's capabilities. diff --git a/pptx-power-clean/examples/example-presentation-thumbnails.jpg b/pptx-power-clean/examples/example-presentation-thumbnails.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a3bfc6e26a749a93f4758859c1f451207abca3e9 GIT binary patch literal 123540 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 z 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 literal 0 HcmV?d00001 diff --git a/pptx-power-clean/mcp.json b/pptx-power-clean/mcp.json new file mode 100644 index 0000000..67c7db1 --- /dev/null +++ b/pptx-power-clean/mcp.json @@ -0,0 +1,9 @@ +{ + "mcpServers": { + "pptx-tools": { + "command": "python", + "args": ["{you-should-replace-this-to-your-home-dir}/.kiro/mcp-servers/pptx-mcp-server/script_executor_mcp.py"], + "env": {} + } + } +} diff --git a/pptx-power-clean/steering/html2pptx-guide.md b/pptx-power-clean/steering/html2pptx-guide.md new file mode 100644 index 0000000..bf6b03d --- /dev/null +++ b/pptx-power-clean/steering/html2pptx-guide.md @@ -0,0 +1,314 @@ +--- +inclusion: manual +--- + +# HTML to PowerPoint Conversion Guide + +This guide covers converting HTML slides to PowerPoint presentations using the html2pptx MCP tool. + +**Prerequisites:** This guide assumes you already have HTML slide files ready for conversion. If you're starting from a user request, see `user-request-to-html.md` first to create and get approval for an HTML preview. + +## Design Principles + +**CRITICAL**: Before creating any presentation, analyze the content and choose appropriate design elements: + +1. **Consider the subject matter**: What is this presentation about? What tone, industry, or mood does it suggest? +2. **Check for branding**: If the user mentions a company/organization, consider their brand colors and identity +3. **Match palette to content**: Select colors that reflect the subject +4. **State your approach**: Explain your design choices before writing code + +**Requirements**: +- ✅ State your content-informed design approach BEFORE writing code +- ✅ Use web-safe fonts only: Arial, Helvetica, Times New Roman, Georgia, Courier New, Verdana, Tahoma, Trebuchet MS, Impact +- ✅ Create clear visual hierarchy through size, weight, and color +- ✅ Ensure readability: strong contrast, appropriately sized text, clean alignment +- ✅ Be consistent: repeat patterns, spacing, and visual language across slides + +## Color Palette Selection + +**Choosing colors creatively**: +- **Think beyond defaults**: What colors genuinely match this specific topic? +- **Consider multiple angles**: Topic, industry, mood, energy level, target audience, brand identity +- **Be adventurous**: Try unexpected combinations +- **Build your palette**: Pick 3-5 colors that work together +- **Ensure contrast**: Text must be clearly readable on backgrounds + +**Example color palettes**: + +1. **Classic Blue**: Deep navy (#1C2833), slate gray (#2E4053), silver (#AAB7B8), off-white (#F4F6F6) +2. **Teal & Coral**: Teal (#5EA8A7), deep teal (#277884), coral (#FE4447), white (#FFFFFF) +3. **Bold Red**: Red (#C0392B), bright red (#E74C3C), orange (#F39C12), yellow (#F1C40F), green (#2ECC71) +4. **Warm Blush**: Mauve (#A49393), blush (#EED6D3), rose (#E8B4B8), cream (#FAF7F2) +5. **Burgundy Luxury**: Burgundy (#5D1D2E), crimson (#951233), rust (#C15937), gold (#997929) +6. **Deep Purple & Emerald**: Purple (#B165FB), dark blue (#181B24), emerald (#40695B), white (#FFFFFF) +7. **Cream & Forest Green**: Cream (#FFE1C7), forest green (#40695B), white (#FCFCFC) +8. **Pink & Purple**: Pink (#F8275B), coral (#FF574A), rose (#FF737D), purple (#3D2F68) +9. **Lime & Plum**: Lime (#C5DE82), plum (#7C3A5F), coral (#FD8C6E), blue-gray (#98ACB5) +10. **Black & Gold**: Gold (#BF9A4A), black (#000000), cream (#F4F6F6) + +## Layout Tips + +**When creating slides with charts or tables:** +- **Two-column layout (PREFERRED)**: Header spanning full width, then two columns - text/bullets in one, featured content in the other +- **Full-slide layout**: Let the featured content take up the entire slide for maximum impact +- **NEVER vertically stack**: Do not place charts/tables below text in a single column + +## Workflow + +**IMPORTANT**: This power provides MCP tools. Do NOT write scripts manually - use the MCP tools instead. + +**Prerequisites**: Before using this guide, you should have: +- HTML preview approved by user (see `user-request-to-html.md`) +- Individual HTML slide files ready for conversion (720pt × 405pt) + +### Step 1: Prepare Individual Slide Files + +After user approves the preview, create individual HTML files for each slide. + +**CRITICAL: File Organization** + +All presentation files MUST be organized in a dedicated folder: + +``` +[presentation-name]/ +├── preview.html # The approved preview +├── slide1.html # Individual slides +├── slide2.html +├── slide3.html +├── ... +├── [presentation-name].pptx # Final output +└── [presentation-name]-thumbnails.jpg # Validation thumbnails +``` + +**Example:** +``` +ai-agents-presentation/ +├── preview.html +├── slide1.html +├── slide2.html +├── slide3.html +├── slide4.html +├── slide5.html +├── slide6.html +├── slide7.html +├── slide8.html +├── ai-agents-presentation.pptx +└── ai-agents-presentation-thumbnails.jpg +``` + +**File naming rules:** +- Folder name: Use kebab-case (lowercase with hyphens) +- Slide files: `slide1.html`, `slide2.html`, etc. (sequential numbering) +- Preview: `preview.html` +- Output PPTX: `[presentation-name].pptx` (matches folder name) +- Thumbnails: `[presentation-name]-thumbnails.jpg` + +**Dimension conversion from preview:** +``` +Preview: 960px × 540px (for easy reading) +Slide files: 720pt × 405pt (for PPTX conversion) + +Font size adjustment: +- Preview h1: 36pt → Slide h1: 14-18pt +- Preview p: 18pt → Slide p: 8-12pt +``` + +**Requirements:** +- Use `

            `, `

            `-`

            `, `
              `, `
                ` for all text content +- Use `class="placeholder"` for areas where charts/tables will be added +- **CRITICAL**: Rasterize gradients and icons as PNG images FIRST using Sharp +- Match the content from the approved preview +- Adjust font sizes for the smaller dimensions + +### Step 2: Convert to PowerPoint using MCP tool + +**Use the `html2pptx` MCP tool** - Do NOT create Node.js scripts manually. + +Example usage: +``` +"Use the html2pptx tool to convert these HTML files to PowerPoint: +- ai-agents-presentation/slide1.html +- ai-agents-presentation/slide2.html +- ai-agents-presentation/slide3.html +- ai-agents-presentation/slide4.html +- ai-agents-presentation/slide5.html +- ai-agents-presentation/slide6.html +- ai-agents-presentation/slide7.html +- ai-agents-presentation/slide8.html +Output file: ai-agents-presentation/ai-agents-presentation.pptx" +``` + +The MCP tool will: +- Process each HTML file +- Convert to PowerPoint slides +- Save as .pptx file in the same folder + +### Step 3: Visual validation + +Generate thumbnails using the `thumbnail` MCP tool + +Example: +``` +"Use the thumbnail tool to generate thumbnails for ai-agents-presentation/ai-agents-presentation.pptx" +``` + +## Handling Validation Errors + +**CRITICAL**: When html2pptx reports validation errors, calculate the correct dimensions ONCE instead of iterating. + +### Common Error: Content Overflow + +**Error message format:** +``` +HTML content overflows body by XXpt horizontally and YYpt vertically +``` + +**How to fix in ONE step:** + +1. **Parse the error message** to extract overflow amounts: + - Horizontal overflow: XXpt + - Vertical overflow: YYpt + +2. **Calculate new dimensions**: + ``` + Current body: width: 720pt; height: 405pt + Current padding: padding: 0pt 15pt 36pt 15pt (top right bottom left) + + Available content area: + - Width: 720pt - 15pt (left) - 15pt (right) = 690pt + - Height: 405pt - 0pt (top) - 36pt (bottom) = 369pt + + If overflow is XXpt horizontally and YYpt vertically: + - Reduce font sizes proportionally + - Or increase padding to constrain content + - Or reduce content amount + ``` + +3. **Calculate font size reduction**: + ``` + If content overflows by XXpt horizontally: + - Reduction factor = (690pt - XXpt) / 690pt + - New font size = current font size × reduction factor + + Example: + - Overflow: 69pt horizontally, 55.5pt vertically + - Horizontal reduction: (690 - 69) / 690 = 0.90 (reduce by 10%) + - Vertical reduction: (369 - 55.5) / 369 = 0.85 (reduce by 15%) + - Use the larger reduction: 15% + - If h1 was 14pt: 14pt × 0.85 = 11.9pt → use 12pt + - If p was 8pt: 8pt × 0.85 = 6.8pt → use 7pt + ``` + +4. **Apply changes to ALL slides at once**: + - Update font sizes in the ` + + + + +
                +

                Your Presentation Title

                +

                Subtitle or tagline

                +
                1
                +
                + + +
                +

                Slide Title

                +

                Main content goes here...

                +
                  +
                • Key point 1
                • +
                • Key point 2
                • +
                • Key point 3
                • +
                +
                2
                +
                + + + + + +``` + +### Preview Dimensions + +**Use larger dimensions for readability:** +- Width: 960px (1.33× the final 720pt) +- Height: 540px (1.33× the final 405pt) +- Maintains 16:9 aspect ratio +- Easier to read and review + +**Font sizes for preview:** +- Title (h1): 36-48pt +- Subtitle (h2): 24-32pt +- Body text (p): 18-20pt +- Small text: 14-16pt + +## Step 4: Present Preview to User + +**Save the file in a dedicated folder:** + +Create a folder for the presentation and save the preview: +```bash +mkdir [presentation-name] +# Save preview.html inside this folder +``` + +**Examples:** +- `ai-agents-presentation/preview.html` +- `quarterly-results/preview.html` +- `product-launch/preview.html` + +**Ask for feedback:** +``` +"I've created a preview HTML file: [folder-name]/preview.html + +Please open it in your browser to review: +- Content and messaging +- Visual design and colors +- Slide flow and structure +- Any missing information + +Let me know if you'd like any changes before I generate the PowerPoint." +``` + +## Step 5: Iterate Based on Feedback + +**Common feedback types:** + +1. **Content changes:** + - Add/remove slides + - Modify text + - Reorder slides + - Add more details + +2. **Design changes:** + - Different colors + - Font adjustments + - Layout modifications + - Visual hierarchy + +3. **Structure changes:** + - Different flow + - Combine/split slides + - Add sections + +**Update the preview HTML** and ask for review again until approved. + +## Step 6: Proceed to PPTX Generation + +**Only after user approval**, proceed to: +1. Create individual slide HTML files in the same folder (720pt × 405pt) +2. Adjust font sizes for smaller dimensions +3. Use html2pptx tool to generate PPTX in the same folder +4. Generate thumbnails for final validation + +**Final folder structure:** +``` +[presentation-name]/ +├── preview.html +├── slide1.html +├── slide2.html +├── slide3.html +├── ... +└── [presentation-name].pptx +``` + +See `html2pptx-guide.md` for detailed instructions. + +## Design Guidelines for Preview + +### Color Palette Selection + +**Match colors to content:** +- **Tech/AI**: Blues, cyans, purples (#00D9FF, #667EEA, #764BA2) +- **Business**: Navy, gray, gold (#1C2833, #5D6D7E, #F39C12) +- **Creative**: Bold colors, high contrast (#E74C3C, #F1C40F, #9B59B6) +- **Healthcare**: Greens, blues, white (#27AE60, #3498DB, #ECF0F1) +- **Finance**: Dark blue, green, gray (#154360, #229954, #566573) + +**Ensure contrast:** +- Text must be clearly readable on backgrounds +- Use light text on dark backgrounds or vice versa +- Test readability at actual size + +### Typography + +**Web-safe fonts only:** +- Arial (clean, modern) +- Helvetica (professional) +- Georgia (elegant, readable) +- Verdana (clear, web-friendly) +- Tahoma (compact, clean) +- Trebuchet MS (modern, friendly) + +**Font hierarchy:** +``` +Title: 36-48pt, bold +Subtitle: 24-32pt, semi-bold +Body: 18-20pt, regular +Small text: 14-16pt, regular +``` + +### Layout Patterns + +**Title slide:** +- Centered content +- Large title +- Subtitle or tagline +- Minimal decoration + +**Content slide:** +- Clear heading +- 3-5 bullet points OR +- 2-3 paragraphs OR +- Combination of text and visual placeholder + +**Section divider:** +- Large section title +- Optional subtitle +- Minimal content + +**Conclusion:** +- Summary points +- Call to action +- Contact info or next steps + +## Common Mistakes to Avoid + +**DON'T:** +- ❌ Skip the preview step +- ❌ Use final slide dimensions (too small to read) +- ❌ Create individual slides before user approval +- ❌ Use non-web-safe fonts +- ❌ Overcrowd slides with too much text +- ❌ Use poor color contrast +- ❌ Forget slide numbers + +**DO:** +- ✅ Create preview first +- ✅ Use readable dimensions (960px × 540px) +- ✅ Get user approval before proceeding +- ✅ Use web-safe fonts +- ✅ Keep slides focused (one idea per slide) +- ✅ Ensure good contrast +- ✅ Number all slides + +## Example: Complete Workflow + +**User request:** +"Create a presentation about AI agents in different industries" + +**Step 1: Clarify** +- How many slides? → 8 slides +- Target audience? → Business executives +- Tone? → Professional but engaging +- Colors? → Tech-focused, modern + +**Step 2: Structure** +``` +1. Title: "AI Agents Across Industries" +2. Overview: What are AI agents? +3. Healthcare applications +4. Finance applications +5. Retail applications +6. Manufacturing applications +7. Key benefits +8. Conclusion +``` + +**Step 3: Create preview** +- Create folder: `ai-agents-presentation/` +- Save as `ai-agents-presentation/preview.html` +- Use blue/cyan color scheme +- Professional layout +- Clear hierarchy + +**Step 4: Get approval** +"Please review ai-agents-presentation/preview.html. Let me know if you'd like any changes." + +**Step 5: User feedback** +"Looks good! Can you add a slide about education?" + +**Step 6: Update preview** +- Add slide 6: Education applications +- Renumber remaining slides +- Get final approval + +**Step 7: Generate PPTX** +- Create individual slide files in `ai-agents-presentation/` +- Adjust dimensions and fonts +- Use html2pptx tool +- Output: `ai-agents-presentation/ai-agents-presentation.pptx` +- Generate thumbnails + +## Tips for Success + +1. **Start with content, then design** + - Get the message right first + - Then make it look good + +2. **Less is more** + - One key point per slide + - Use visuals to support, not decorate + - White space is your friend + +3. **Consistency matters** + - Same fonts throughout + - Consistent colors + - Predictable layout patterns + +4. **Test readability** + - Can you read it from 6 feet away? + - Is the contrast sufficient? + - Are fonts large enough? + +5. **Get feedback early** + - Preview catches issues before PPTX generation + - Easier to iterate on HTML than PPTX + - Saves time and effort + +## Next Steps + +After user approves the preview: +1. Read `html2pptx-guide.md` for conversion instructions +2. Create individual slide HTML files +3. Use html2pptx MCP tool +4. Generate thumbnails for validation + +--- + +**Remember:** The preview step is crucial for success. It ensures alignment with user expectations before investing time in PPTX generation. From 925e7aabc6f7534c67534700868192fa811af298 Mon Sep 17 00:00:00 2001 From: Junxiang Ji Date: Thu, 8 Jan 2026 12:57:36 +0000 Subject: [PATCH 11/18] Add AgentCore Browser Power with MCP server support This PR adds comprehensive web automation capabilities using AWS Bedrock AgentCore Browser through: - agentcore-browser: Power definition with steering files for session management and troubleshooting - agentcore-browser-mcp-server: Full MCP server implementation with browser automation tools Key features: - Persistent browser session management in AWS cloud - Web automation (navigate, click, type, extract content, execute JavaScript) - Live browser viewing through AWS Console or WebSocket - Session recording and replay for debugging - Enterprise security with isolated sessions and CloudTrail logging - Serverless scalability up to 500 concurrent sessions Co-Authored-By: Claude --- agentcore-browser-mcp-server/.gitignore | 41 + agentcore-browser-mcp-server/DESIGN.md | 446 ++++++++++ agentcore-browser-mcp-server/INSTALL.md | 520 +++++++++++ agentcore-browser-mcp-server/POWER_README.md | 208 +++++ agentcore-browser-mcp-server/README.md | 125 +++ .../agentcore_browser_mcp.py | 831 ++++++++++++++++++ agentcore-browser-mcp-server/example_usage.md | 632 +++++++++++++ agentcore-browser-mcp-server/install.sh | 170 ++++ agentcore-browser-mcp-server/pyproject.toml | 43 + agentcore-browser-mcp-server/requirements.txt | 11 + .../test_mcp_server.py | 518 +++++++++++ .../test_structure.py | 0 agentcore-browser/POWER.md | 545 ++++++++++++ agentcore-browser/mcp.json | 17 + agentcore-browser/steering/getting-started.md | 534 +++++++++++ .../steering/session-management.md | 610 +++++++++++++ agentcore-browser/steering/troubleshooting.md | 727 +++++++++++++++ 17 files changed, 5978 insertions(+) create mode 100644 agentcore-browser-mcp-server/.gitignore create mode 100644 agentcore-browser-mcp-server/DESIGN.md create mode 100644 agentcore-browser-mcp-server/INSTALL.md create mode 100644 agentcore-browser-mcp-server/POWER_README.md create mode 100644 agentcore-browser-mcp-server/README.md create mode 100644 agentcore-browser-mcp-server/agentcore_browser_mcp.py create mode 100644 agentcore-browser-mcp-server/example_usage.md create mode 100755 agentcore-browser-mcp-server/install.sh create mode 100644 agentcore-browser-mcp-server/pyproject.toml create mode 100644 agentcore-browser-mcp-server/requirements.txt create mode 100644 agentcore-browser-mcp-server/test_mcp_server.py create mode 100644 agentcore-browser-mcp-server/test_structure.py create mode 100644 agentcore-browser/POWER.md create mode 100644 agentcore-browser/mcp.json create mode 100644 agentcore-browser/steering/getting-started.md create mode 100644 agentcore-browser/steering/session-management.md create mode 100644 agentcore-browser/steering/troubleshooting.md diff --git a/agentcore-browser-mcp-server/.gitignore b/agentcore-browser-mcp-server/.gitignore new file mode 100644 index 0000000..98bafb8 --- /dev/null +++ b/agentcore-browser-mcp-server/.gitignore @@ -0,0 +1,41 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +.venv/ +venv/ +ENV/ +env/ +build/ +dist/ +*.egg-info/ + +# Playwright +.playwright/ + +# Screenshots +screenshots/ +*.png +*.jpg + +# Logs +*.log + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Test outputs +.pytest_cache/ +.coverage +htmlcov/ +test_*.html +test_*.json diff --git a/agentcore-browser-mcp-server/DESIGN.md b/agentcore-browser-mcp-server/DESIGN.md new file mode 100644 index 0000000..32f6402 --- /dev/null +++ b/agentcore-browser-mcp-server/DESIGN.md @@ -0,0 +1,446 @@ +# AgentCore Browser Power - Design Document + +## Overview + +This power provides comprehensive browser automation capabilities using AWS Bedrock AgentCore Browser through an MCP server interface. + +## Key Design Decisions + +### 1. Session Persistence Across Requests + +**Decision:** Maintain session state in MCP server memory + +**Rationale:** +- AgentCore Browser sessions are expensive to create +- Workflows often require multiple operations on the same page +- Authentication state needs to persist across operations +- Enables complex multi-step automations + +**Implementation:** +```python +# Global session dictionary in MCP server +sessions: Dict[str, BrowserSession] = {} + +# Sessions persist across MCP tool calls +# User can reference same session_id in multiple requests +``` + +**Benefits:** +- ✅ Efficient resource usage +- ✅ Maintains cookies and authentication +- ✅ Supports complex workflows +- ✅ Natural user experience + +### 2. Headless Cloud Browser with Live View + +**Decision:** Use AgentCore Browser (cloud-based, headless) with Live View option + +**Rationale:** +- AgentCore Browser runs in AWS cloud (always headless) +- No local browser installation required +- Automatic scaling and isolation +- Live View provides visual monitoring when needed + +**Implementation:** +```python +# Browser runs in AWS cloud +browser_client = BrowserClient(region=region) +session_id = browser_client.start(identifier="aws.browser.v1") + +# Connect via CDP +cdp_url, cdp_headers = browser_client.generate_ws_headers() +browser = await playwright.chromium.connect_over_cdp( + endpoint_url=cdp_url, + headers=cdp_headers +) + +# Live View URL for monitoring +live_view_url = f"https://console.aws.amazon.com/bedrock/home?region={region}#/agentcore/browser/sessions/{session_id}" +``` + +**Benefits:** +- ✅ No local setup required +- ✅ Enterprise-grade security +- ✅ Automatic scaling +- ✅ Visual debugging via Live View +- ✅ Session recording capability + +### 3. Unified Interaction Interface + +**Decision:** Single `interact` tool for multiple action types + +**Rationale:** +- Simpler API surface +- Easier for AI agents to use +- Reduces tool count +- Consistent parameter patterns + +**Implementation:** +```python +@app.tool() +async def interact( + session_id: str, + action: Literal["click", "type", "press_key", "scroll"], + selector: Optional[str] = None, + text: Optional[str] = None, + key: Optional[str] = None, + scroll_amount: Optional[int] = None +) -> dict: + # Single tool handles multiple interaction types +``` + +**Alternative Considered:** +- Separate tools: `click`, `type`, `press_key`, `scroll` +- Rejected because: More tools to manage, harder for agents to discover + +### 4. Session Timeout Management + +**Decision:** Configurable timeout with automatic cleanup + +**Rationale:** +- Prevent resource leaks +- Balance cost and usability +- Support both short and long workflows + +**Implementation:** +```python +@dataclass +class BrowserSession: + timeout: int = 3600 # Default 1 hour + last_used: float = field(default_factory=time.time) + + def is_expired(self) -> bool: + return (time.time() - self.last_used) > self.timeout + +# Periodic cleanup +async def cleanup_expired_sessions(): + expired = [sid for sid, s in sessions.items() if s.is_expired()] + for session_id in expired: + await close_session_internal(session_id) +``` + +**Timeout Options:** +- Short (900s / 15 min): Quick tasks +- Medium (3600s / 1 hour): Standard workflows +- Long (28800s / 8 hours): Extended operations + +### 5. Multi-Tab Support + +**Decision:** Support multiple tabs within a single session + +**Rationale:** +- Common use case: comparing data across sites +- More efficient than multiple sessions +- Natural browser behavior + +**Implementation:** +```python +@dataclass +class BrowserSession: + tabs: Dict[str, Page] = field(default_factory=dict) + active_tab_id: str = "main" + +# Tab management +await manage_tabs(action="new_tab", tab_id="tab2") +await manage_tabs(action="switch_tab", tab_id="tab2") +await manage_tabs(action="close_tab", tab_id="tab2") +``` + +### 6. Error Handling Strategy + +**Decision:** Return descriptive error messages, don't raise exceptions + +**Rationale:** +- MCP tools should return results, not throw +- AI agents can better handle text responses +- Enables graceful degradation + +**Implementation:** +```python +try: + await page.click(selector) + return [TextContent(type="text", text=f"✅ Clicked element: {selector}")] +except Exception as e: + return [TextContent(type="text", text=f"Error: {str(e)}")] +``` + +## Architecture + +### Component Diagram + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Kiro Agent │ +└────────────────────────┬────────────────────────────────────┘ + │ MCP Protocol + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ AgentCore Browser MCP Server │ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ Session Manager │ │ +│ │ - sessions: Dict[str, BrowserSession] │ │ +│ │ - cleanup_expired_sessions() │ │ +│ └──────────────────────────────────────────────────────┘ │ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ Tool Handlers │ │ +│ │ - create_browser_session() │ │ +│ │ - navigate() │ │ +│ │ - interact() │ │ +│ │ - extract_content() │ │ +│ │ - execute_script() │ │ +│ │ - screenshot() │ │ +│ │ - manage_tabs() │ │ +│ │ - list_sessions() │ │ +│ │ - get_session_info() │ │ +│ │ - close_session() │ │ +│ │ - get_live_view_url() │ │ +│ └──────────────────────────────────────────────────────┘ │ +└────────────────────────┬────────────────────────────────────┘ + │ Playwright + CDP + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ AWS Bedrock AgentCore Browser │ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ BrowserClient │ │ +│ │ - start() → session_id │ │ +│ │ - generate_ws_headers() → CDP URL │ │ +│ │ - stop() │ │ +│ └──────────────────────────────────────────────────────┘ │ +│ ┌──────────────────────────────────────────────────────┐ │ +│ │ Cloud Browser Instance (Chromium) │ │ +│ │ - Isolated microVM │ │ +│ │ - Session recording (optional) │ │ +│ │ - Live View streaming │ │ +│ └──────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +``` + +### Data Flow + +1. **Session Creation** + ``` + Agent → MCP Server → BrowserClient.start() → CDP Connection → Browser Instance + ``` + +2. **Browser Operation** + ``` + Agent → MCP Tool → Session Lookup → Playwright API → CDP → Browser + ``` + +3. **Session Cleanup** + ``` + Timeout/Manual → close_session() → Browser.close() → BrowserClient.stop() + ``` + +## Tool Design + +### Tool Categories + +1. **Session Management** (4 tools) + - `create_browser_session` - Initialize + - `list_sessions` - Discover + - `get_session_info` - Inspect + - `close_session` - Cleanup + +2. **Browser Automation** (5 tools) + - `navigate` - Page navigation + - `interact` - Element interaction + - `extract_content` - Data extraction + - `execute_script` - JavaScript execution + - `screenshot` - Visual capture + +3. **Advanced Features** (2 tools) + - `manage_tabs` - Multi-tab workflows + - `get_live_view_url` - Visual monitoring + +### Tool Parameter Design + +**Consistent Patterns:** +- All tools (except `list_sessions`) require `session_id` +- Optional parameters have sensible defaults +- Enums for action types (type-safe) +- Clear parameter descriptions + +**Example:** +```python +{ + "session_id": "required-string", + "action": "enum-value", + "selector": "optional-css-selector", + "text": "optional-text-content" +} +``` + +## Security Considerations + +### 1. AWS Credentials + +- Never hardcode credentials +- Use AWS credential chain (env vars, ~/.aws/credentials, IAM roles) +- Require minimal IAM permissions + +### 2. Session Isolation + +- Each session runs in isolated microVM +- Sessions don't share state +- Automatic cleanup prevents leaks + +### 3. Input Validation + +- Validate session_id format +- Sanitize JavaScript code (user responsibility) +- Validate CSS selectors + +### 4. Resource Limits + +- Maximum 500 concurrent sessions +- Configurable timeouts +- Automatic cleanup of expired sessions + +## Performance Considerations + +### 1. Session Reuse + +- Encourage session reuse for multiple operations +- Avoid creating new session for each operation +- Document session lifecycle best practices + +### 2. Parallel Sessions + +- Support up to 500 concurrent sessions +- Enable batch processing +- Document parallel patterns + +### 3. Network Optimization + +- Use appropriate wait conditions +- Minimize unnecessary screenshots +- Close unused tabs + +### 4. Memory Management + +- Store only essential session data +- Clean up expired sessions automatically +- Limit screenshot storage + +## Testing Strategy + +### Unit Tests + +- Test each tool handler independently +- Mock AWS BrowserClient +- Test error handling + +### Integration Tests + +- Test with real AgentCore Browser +- Verify session persistence +- Test multi-tab workflows + +### End-to-End Tests + +- Complete automation workflows +- Authentication flows +- Error recovery scenarios + +## Future Enhancements + +### Potential Additions + +1. **Cookie Management** + - Export/import cookies + - Cookie-based authentication + +2. **Network Interception** + - Capture API requests + - Mock responses + +3. **Performance Metrics** + - Page load times + - Resource usage + +4. **Advanced Selectors** + - XPath support + - Text-based selection + +5. **File Downloads** + - Handle file downloads + - Upload files + +6. **Mobile Emulation** + - Mobile viewport + - Touch events + +### Not Planned + +- Local browser support (use Playwright directly) +- Browser extensions (not supported by AgentCore) +- Multiple browser engines (AgentCore uses Chromium) + +## Documentation Structure + +### POWER.md +- Overview and quick start +- Tool reference +- Configuration +- Best practices + +### Steering Files +- `getting-started.md` - Complete setup guide +- `session-management.md` - Advanced session techniques +- `troubleshooting.md` - Common issues and solutions + +### Additional Docs +- `README.md` - Installation and quick reference +- `example_usage.md` - Real-world examples +- `DESIGN.md` - This document + +## Comparison with Alternatives + +### vs. Local Playwright + +| Feature | AgentCore Browser | Local Playwright | +|---------|------------------|------------------| +| Setup | No local install | Requires installation | +| Scaling | Automatic | Manual | +| Security | Isolated cloud | Local machine | +| Cost | Pay per use | Free | +| Live View | Built-in | Manual setup | +| Recording | Built-in | Manual setup | + +### vs. Strands Browser Tool + +| Feature | This Power | Strands Tool | +|---------|-----------|--------------| +| Integration | MCP-based | Strands-native | +| Session Mgmt | Explicit | Implicit | +| Documentation | Comprehensive | Code-focused | +| Flexibility | High | Medium | + +## Success Metrics + +### User Experience +- Time to first automation: < 15 minutes +- Session creation success rate: > 95% +- Error message clarity: User can resolve without docs + +### Performance +- Session creation time: < 10 seconds +- Operation latency: < 2 seconds +- Concurrent sessions: Up to 500 + +### Reliability +- Session stability: > 99% +- Automatic cleanup: 100% +- Error recovery: Graceful degradation + +## Conclusion + +This power provides a production-ready browser automation solution with: +- ✅ Persistent session management +- ✅ Cloud-based execution +- ✅ Comprehensive tooling +- ✅ Excellent documentation +- ✅ Real-world examples + +The design balances simplicity, power, and reliability for AI agent workflows. diff --git a/agentcore-browser-mcp-server/INSTALL.md b/agentcore-browser-mcp-server/INSTALL.md new file mode 100644 index 0000000..32e351b --- /dev/null +++ b/agentcore-browser-mcp-server/INSTALL.md @@ -0,0 +1,520 @@ +# Installation and Testing Guide + +Complete guide for installing and testing the AgentCore Browser Power. + +## Prerequisites + +Before installing, ensure you have: + +### 1. AWS Account and Credentials + +```bash +# Install AWS CLI +brew install awscli # macOS +# or +curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" +unzip awscliv2.zip +sudo ./aws/install + +# Configure credentials +aws configure +# Enter: Access Key ID, Secret Access Key, Region (us-east-1), Format (json) + +# Verify +aws sts get-caller-identity +``` + +### 2. IAM Permissions + +Attach this policy to your IAM user/role: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "bedrock-agentcore:CreateBrowser", + "bedrock-agentcore:StartBrowserSession", + "bedrock-agentcore:StopBrowserSession", + "bedrock-agentcore:GetBrowserSession", + "bedrock-agentcore:ListBrowserSessions" + ], + "Resource": "*" + } + ] +} +``` + +### 3. Python and uv + +```bash +# Check Python version (need 3.10+) +python3 --version + +# Install uv +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Restart terminal or source profile +source ~/.bashrc # or ~/.zshrc + +# Verify +uv --version +``` + +## Installation Steps + +### Step 1: Copy Power to Kiro Directory + +```bash +# Create powers directory if it doesn't exist +mkdir -p ~/.kiro/powers + +# Copy the power +cp -r powers/agentcore-browser ~/.kiro/powers/ + +# Verify +ls -la ~/.kiro/powers/agentcore-browser +``` + +### Step 2: Install Python Dependencies + +```bash +# Navigate to power directory +cd ~/.kiro/powers/agentcore-browser + +# Install dependencies with uv +uv sync + +# This creates a virtual environment and installs: +# - mcp +# - playwright +# - bedrock-agentcore +# - boto3 +``` + +### Step 3: Install Playwright Browsers + +```bash +# Still in power directory +uv run playwright install chromium + +# This downloads Chromium browser binaries +# Takes a few minutes on first run +``` + +### Step 4: Verify Installation + +```bash +# Check virtual environment +ls -la .venv + +# Check installed packages +uv pip list + +# Should see: +# - mcp +# - playwright +# - bedrock-agentcore +# - boto3 +``` + +### Step 5: Install Power in Kiro + +**Option A: Via Kiro UI (Recommended)** + +1. Open Kiro +2. Open Command Palette (Cmd/Ctrl + Shift + P) +3. Type "Powers" and select "Open Powers Panel" +4. Click "Install from directory" +5. Navigate to `~/.kiro/powers/agentcore-browser` +6. Click "Install" + +**Option B: Manual Configuration** + +1. Open Kiro settings +2. Navigate to MCP section +3. Add server configuration: + ```json + { + "mcpServers": { + "agentcore-browser": { + "command": "uv", + "args": [ + "--directory", + "~/.kiro/powers/agentcore-browser", + "run", + "agentcore_browser_mcp.py" + ], + "env": { + "AWS_REGION": "us-east-1" + } + } + } + } + ``` + +### Step 6: Restart Kiro + +```bash +# Restart Kiro to load the new power +# Or use Command Palette: "Reload Window" +``` + +### Step 7: Verify Power is Loaded + +1. Open Kiro +2. Check MCP servers status +3. Look for "agentcore-browser" in connected servers +4. Should show "Connected" status + +## Testing the Installation + +### Test 1: Basic Connection + +Ask Kiro: +``` +"List all available browser automation tools" +``` + +Expected response should include: +- create_browser_session +- navigate +- interact +- extract_content +- etc. + +### Test 2: Create Session + +Ask Kiro: +``` +"Create a browser session called 'test-session' for testing" +``` + +Expected response: +``` +✅ Browser session created successfully! +Session ID: test-session +Region: us-east-1 +... +``` + +### Test 3: Navigate + +Ask Kiro: +``` +"Navigate to example.com in test-session" +``` + +Expected response: +``` +✅ Navigated to https://example.com +Current URL: https://example.com/ +``` + +### Test 4: Extract Content + +Ask Kiro: +``` +"Extract the main heading from test-session" +``` + +Expected response: +``` +Extracted text: +Example Domain +``` + +### Test 5: Close Session + +Ask Kiro: +``` +"Close test-session" +``` + +Expected response: +``` +✅ Session 'test-session' closed successfully +``` + +### Test 6: Complete Workflow + +Ask Kiro to run this complete workflow: + +``` +"Create a browser session called 'workflow-test', navigate to example.com, +extract the page title, take a screenshot, and close the session" +``` + +This tests: +- Session creation +- Navigation +- Content extraction +- Screenshot +- Session cleanup + +## Troubleshooting Installation + +### Issue: "uv command not found" + +**Solution:** +```bash +# Reinstall uv +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Add to PATH +export PATH="$HOME/.cargo/bin:$PATH" + +# Add to shell profile +echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.bashrc +source ~/.bashrc +``` + +### Issue: "Python version too old" + +**Solution:** +```bash +# Install Python 3.10+ using pyenv +curl https://pyenv.run | bash + +# Add to shell profile +export PATH="$HOME/.pyenv/bin:$PATH" +eval "$(pyenv init -)" + +# Install Python 3.11 +pyenv install 3.11 +pyenv global 3.11 + +# Verify +python --version +``` + +### Issue: "Playwright install fails" + +**Solution:** +```bash +# Install system dependencies (Linux) +sudo apt-get install -y \ + libnss3 \ + libnspr4 \ + libatk1.0-0 \ + libatk-bridge2.0-0 \ + libcups2 \ + libdrm2 \ + libxkbcommon0 \ + libxcomposite1 \ + libxdamage1 \ + libxfixes3 \ + libxrandr2 \ + libgbm1 \ + libasound2 + +# Then retry +cd ~/.kiro/powers/agentcore-browser +uv run playwright install chromium +``` + +### Issue: "MCP server won't start" + +**Solution:** +```bash +# Check logs in Kiro +# Look for error messages + +# Common fixes: +# 1. Reinstall dependencies +cd ~/.kiro/powers/agentcore-browser +rm -rf .venv +uv sync + +# 2. Check Python path +which python3 + +# 3. Test MCP server manually +cd ~/.kiro/powers/agentcore-browser +uv run python agentcore_browser_mcp.py +# Should start without errors +``` + +### Issue: "AWS credentials not found" + +**Solution:** +```bash +# Configure AWS credentials +aws configure + +# Or set environment variables +export AWS_ACCESS_KEY_ID="your-key" +export AWS_SECRET_ACCESS_KEY="your-secret" +export AWS_REGION="us-east-1" + +# Verify +aws sts get-caller-identity +``` + +### Issue: "AccessDeniedException" + +**Solution:** +1. Check IAM permissions (see Prerequisites) +2. Verify you're using correct AWS account +3. Try different region: + ```bash + export AWS_REGION="us-west-2" + ``` + +## Updating the Power + +### Update from Git + +```bash +# Pull latest changes +cd /path/to/repo +git pull + +# Copy updated files +cp -r powers/agentcore-browser ~/.kiro/powers/ + +# Reinstall dependencies +cd ~/.kiro/powers/agentcore-browser +uv sync + +# Restart Kiro +``` + +### Update Dependencies + +```bash +cd ~/.kiro/powers/agentcore-browser + +# Update all dependencies +uv sync --upgrade + +# Or update specific package +uv pip install --upgrade bedrock-agentcore +``` + +## Uninstalling + +### Remove Power + +```bash +# Remove power directory +rm -rf ~/.kiro/powers/agentcore-browser + +# Remove from Kiro MCP config +# Edit ~/.kiro/settings/mcp.json +# Remove "agentcore-browser" entry + +# Restart Kiro +``` + +## Environment Variables + +Optional environment variables for customization: + +```bash +# AWS Configuration +export AWS_REGION="us-east-1" +export AWS_PROFILE="default" + +# Browser Configuration +export BROWSER_SESSION_TIMEOUT="3600" +export BROWSER_IDENTIFIER="aws.browser.v1" +export BROWSER_SCREENSHOTS_DIR="screenshots" + +# MCP Configuration +export FASTMCP_LOG_LEVEL="INFO" +``` + +Add to `~/.bashrc` or `~/.zshrc` to persist. + +## Verification Checklist + +After installation, verify: + +- [ ] AWS CLI installed and configured +- [ ] IAM permissions attached +- [ ] Python 3.10+ installed +- [ ] uv package manager installed +- [ ] Power copied to ~/.kiro/powers/ +- [ ] Python dependencies installed (uv sync) +- [ ] Playwright browsers installed +- [ ] Power loaded in Kiro +- [ ] MCP server connected +- [ ] Test session creation works +- [ ] Test navigation works +- [ ] Test content extraction works + +## Getting Help + +If you encounter issues: + +1. **Check logs** + - Kiro MCP server logs + - Terminal output from manual test + +2. **Review documentation** + - README.md - Quick reference + - POWER.md - Complete guide + - troubleshooting.md - Common issues + +3. **Test components** + ```bash + # Test AWS credentials + aws sts get-caller-identity + + # Test Python + python3 --version + + # Test uv + uv --version + + # Test Playwright + cd ~/.kiro/powers/agentcore-browser + uv run python -c "from playwright.async_api import async_playwright; print('OK')" + ``` + +4. **Contact support** + - AWS Support for AgentCore issues + - Kiro support for MCP issues + - GitHub issues for power bugs + +## Next Steps + +After successful installation: + +1. **Read getting started guide** + ``` + Ask Kiro: "Show me the getting started guide for AgentCore Browser" + ``` + +2. **Try examples** + - See `example_usage.md` for real-world examples + - Start with simple navigation + - Progress to complex workflows + +3. **Learn advanced features** + - Session management + - Multi-tab workflows + - Live View monitoring + - Session recording + +4. **Build your automation** + - Identify your use case + - Design workflow + - Implement with AgentCore Browser + - Test and refine + +## Summary + +Installation steps: +1. ✅ Install prerequisites (AWS CLI, Python, uv) +2. ✅ Copy power to ~/.kiro/powers/ +3. ✅ Install dependencies (uv sync) +4. ✅ Install Playwright browsers +5. ✅ Load power in Kiro +6. ✅ Test basic functionality +7. ✅ Start automating! + +You're ready to automate! 🚀 diff --git a/agentcore-browser-mcp-server/POWER_README.md b/agentcore-browser-mcp-server/POWER_README.md new file mode 100644 index 0000000..d4bf9fa --- /dev/null +++ b/agentcore-browser-mcp-server/POWER_README.md @@ -0,0 +1,208 @@ +# AgentCore Browser Power + +Automate web interactions with AWS Bedrock AgentCore Browser - a secure, cloud-based browser for AI agents. + +## Features + +- **Session Management** - Persistent browser sessions across multiple operations +- **Web Automation** - Navigate, click, type, extract content, execute JavaScript +- **Live Viewing** - Real-time browser monitoring through AWS Console +- **Session Recording** - Capture and replay for debugging +- **Multi-Tab Support** - Manage multiple tabs within a session +- **Headless Cloud Browser** - No local installation required + +## Installation + +### Prerequisites + +1. **AWS Account** with Bedrock AgentCore access +2. **AWS Credentials** configured: + ```bash + aws configure + ``` + +3. **IAM Permissions**: + ```json + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "bedrock-agentcore:CreateBrowser", + "bedrock-agentcore:StartBrowserSession", + "bedrock-agentcore:StopBrowserSession", + "bedrock-agentcore:GetBrowserSession" + ], + "Resource": "*" + } + ] + } + ``` + +4. **Python 3.10+** + +### Install MCP Server + +```bash +# Navigate to MCP server directory +cd agentcore-browser-mcp-server + +# Run installation script +chmod +x install.sh +./install.sh +``` + +This will: +- Install Python dependencies (mcp, playwright, bedrock-agentcore, boto3) +- Install Playwright Chromium browser +- Copy files to `~/.kiro/mcp-servers/agentcore-browser-mcp-server/` +- Run tests to verify installation + +### Install Power + +1. **Via Kiro UI**: + - Open Powers panel in Kiro + - Click "Install from directory" + - Select `powers/agentcore-browser` + +2. **Manual Installation**: + ```bash + # Copy to Kiro powers directory + cp -r powers/agentcore-browser ~/.kiro/powers/ + ``` + +3. **Restart Kiro** to load the power + +## Quick Start + +### Example 1: Simple Navigation + +```python +# Create session +await create_browser_session( + session_id="my-session", + description="Testing navigation" +) + +# Navigate +await navigate( + session_id="my-session", + url="https://example.com" +) + +# Extract content +await extract_content( + session_id="my-session", + content_type="text", + selector="h1" +) + +# Close +await close_session(session_id="my-session") +``` + +### Example 2: Form Automation + +```python +# Create session +await create_browser_session( + session_id="form-session", + description="Form automation" +) + +# Navigate to form +await navigate( + session_id="form-session", + url="https://example.com/form" +) + +# Fill fields +await interact( + session_id="form-session", + action="type", + selector="input[name='email']", + text="user@example.com" +) + +# Submit +await interact( + session_id="form-session", + action="click", + selector="button[type='submit']" +) + +# Close +await close_session(session_id="form-session") +``` + +## Configuration + +### Environment Variables + +- `AWS_REGION` - AWS region (default: us-east-1) +- `BROWSER_SESSION_TIMEOUT` - Default session timeout in seconds (default: 3600) +- `BROWSER_IDENTIFIER` - Browser identifier (default: aws.browser.v1) +- `BROWSER_SCREENSHOTS_DIR` - Screenshot directory (default: screenshots) + +### Supported Regions + +- us-east-1 (N. Virginia) +- us-west-2 (Oregon) +- eu-central-1 (Frankfurt) +- ap-southeast-2 (Sydney) + +## Available Tools + +- `create_browser_session` - Create persistent browser session +- `navigate` - Navigate to URL +- `interact` - Click, type, press keys, scroll +- `extract_content` - Extract text, HTML, attributes +- `execute_script` - Run JavaScript +- `screenshot` - Capture screenshots +- `manage_tabs` - Multi-tab management +- `list_sessions` - List active sessions +- `get_session_info` - Get session details +- `close_session` - Close and cleanup +- `get_live_view_url` - Get Live View URL + +## Troubleshooting + +### "Session not found" +- Ensure you created the session first +- Check session hasn't expired +- Use `list_sessions` to see active sessions + +### "AccessDeniedException" +- Verify AWS credentials: `aws sts get-caller-identity` +- Check IAM permissions +- Ensure region is supported + +### "Playwright not installed" +```bash +cd ~/.kiro/powers/agentcore-browser +uv run playwright install chromium +``` + +### "Connection timeout" +- Check internet connectivity +- Verify AWS region is accessible +- Try different region + +## Documentation + +For detailed guides, see POWER.md or use steering files: +- `getting-started.md` - Complete setup guide +- `web-automation-patterns.md` - Automation patterns +- `session-management.md` - Advanced session management +- `troubleshooting.md` - Common issues + +## Support + +- [AgentCore Browser Docs](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/browser-tool.html) +- [AWS Support](https://aws.amazon.com/support/) +- [GitHub Issues](https://github.com/your-repo/issues) + +## License + +MIT License - See LICENSE file for details diff --git a/agentcore-browser-mcp-server/README.md b/agentcore-browser-mcp-server/README.md new file mode 100644 index 0000000..5f84006 --- /dev/null +++ b/agentcore-browser-mcp-server/README.md @@ -0,0 +1,125 @@ +# AgentCore Browser MCP Server + +MCP server implementation for AWS Bedrock AgentCore Browser automation. + +## Installation + +### Via uvx (Recommended) + +```bash +# Install and run directly +uvx agentcore-browser-mcp-server +``` + +### Via pip + +```bash +# Install +pip install agentcore-browser-mcp-server + +# Run +python -m agentcore_browser_mcp +``` + +### From Source + +```bash +# Clone repository +git clone +cd agentcore-browser-mcp-server + +# Install with uv +uv sync + +# Install Playwright browsers +uv run playwright install chromium + +# Run +uv run python agentcore_browser_mcp.py +``` + +## Prerequisites + +1. **AWS Credentials** configured: + ```bash + aws configure + ``` + +2. **IAM Permissions**: + ```json + { + "Effect": "Allow", + "Action": [ + "bedrock-agentcore:CreateBrowser", + "bedrock-agentcore:StartBrowserSession", + "bedrock-agentcore:StopBrowserSession", + "bedrock-agentcore:GetBrowserSession" + ], + "Resource": "*" + } + ``` + +3. **Python 3.10+** + +4. **Playwright browsers**: + ```bash + playwright install chromium + ``` + +## Testing + +```bash +# Run tests +uv run pytest + +# Run with coverage +uv run pytest --cov=agentcore_browser_mcp + +# Test manually +uv run python test_mcp_server.py +``` + +## Environment Variables + +- `AWS_REGION` - AWS region (default: us-east-1) +- `BROWSER_SESSION_TIMEOUT` - Default timeout in seconds (default: 3600) +- `BROWSER_IDENTIFIER` - Browser identifier (default: aws.browser.v1) +- `BROWSER_SCREENSHOTS_DIR` - Screenshot directory (default: screenshots) + +## Usage with Kiro + +Add to your Kiro MCP configuration: + +```json +{ + "mcpServers": { + "agentcore-browser": { + "command": "uvx", + "args": ["agentcore-browser-mcp-server"], + "env": { + "AWS_REGION": "us-east-1" + } + } + } +} +``` + +## Development + +```bash +# Install dev dependencies +uv sync --all-extras + +# Run linter +uv run ruff check . + +# Format code +uv run ruff format . + +# Type check +uv run mypy agentcore_browser_mcp.py +``` + +## License + +MIT diff --git a/agentcore-browser-mcp-server/agentcore_browser_mcp.py b/agentcore-browser-mcp-server/agentcore_browser_mcp.py new file mode 100644 index 0000000..7e645bb --- /dev/null +++ b/agentcore-browser-mcp-server/agentcore_browser_mcp.py @@ -0,0 +1,831 @@ +#!/usr/bin/env python3 +""" +AgentCore Browser MCP Server + +Provides browser automation tools using AWS Bedrock AgentCore Browser. +Maintains session state across multiple requests for persistent workflows. +""" + +import asyncio +import logging +import os +import time +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional + +from bedrock_agentcore.tools.browser_client import BrowserClient +from mcp.server import Server +from mcp.types import Tool, TextContent +from playwright.async_api import Browser as PlaywrightBrowser +from playwright.async_api import BrowserContext, Page, async_playwright + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Initialize MCP server +app = Server("agentcore-browser") + +# Global state for session management +sessions: Dict[str, "BrowserSession"] = {} +playwright_instance = None + + +@dataclass +class BrowserSession: + """Browser session state""" + session_id: str + description: str + region: str + browser_client: BrowserClient + browser: Optional[PlaywrightBrowser] = None + context: Optional[BrowserContext] = None + page: Optional[Page] = None + tabs: Dict[str, Page] = field(default_factory=dict) + active_tab_id: str = "main" + created_at: float = field(default_factory=time.time) + last_used: float = field(default_factory=time.time) + timeout: int = 3600 + recording_enabled: bool = False + + def update_last_used(self): + """Update last used timestamp""" + self.last_used = time.time() + + def is_expired(self) -> bool: + """Check if session has expired""" + return (time.time() - self.last_used) > self.timeout + + +async def init_playwright(): + """Initialize Playwright instance""" + global playwright_instance + if playwright_instance is None: + playwright_instance = await async_playwright().start() + return playwright_instance + + +async def cleanup_expired_sessions(): + """Clean up expired sessions""" + expired = [sid for sid, session in sessions.items() if session.is_expired()] + for session_id in expired: + try: + await close_session_internal(session_id) + logger.info(f"Cleaned up expired session: {session_id}") + except Exception as e: + logger.error(f"Error cleaning up session {session_id}: {e}") + + +async def close_session_internal(session_id: str): + """Internal session cleanup""" + if session_id not in sessions: + return + + session = sessions[session_id] + + # Close browser + if session.browser: + try: + await session.browser.close() + except Exception as e: + logger.error(f"Error closing browser: {e}") + + # Stop browser client + if session.browser_client: + try: + session.browser_client.stop() + except Exception as e: + logger.error(f"Error stopping browser client: {e}") + + # Remove from sessions + del sessions[session_id] + + +@app.list_tools() +async def list_tools() -> List[Tool]: + """List available browser automation tools""" + return [ + Tool( + name="create_browser_session", + description="Create a new browser session with persistent state", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Unique identifier for this session (e.g., 'order-processing-001')" + }, + "description": { + "type": "string", + "description": "Description of what this session will be used for" + }, + "region": { + "type": "string", + "description": "AWS region (default: us-east-1)", + "default": "us-east-1" + }, + "session_timeout": { + "type": "integer", + "description": "Session timeout in seconds (default: 3600, max: 28800)", + "default": 3600 + }, + "enable_recording": { + "type": "boolean", + "description": "Enable session recording to S3 (default: false)", + "default": False + } + }, + "required": ["session_id", "description"] + } + ), + Tool( + name="navigate", + description="Navigate to a URL in the browser session", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID from create_browser_session" + }, + "url": { + "type": "string", + "description": "URL to navigate to" + }, + "wait_for": { + "type": "string", + "description": "Wait condition: 'load', 'domcontentloaded', 'networkidle' (default: 'networkidle')", + "default": "networkidle" + } + }, + "required": ["session_id", "url"] + } + ), + Tool( + name="interact", + description="Interact with page elements (click, type, press keys, scroll)", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID" + }, + "action": { + "type": "string", + "enum": ["click", "type", "press_key", "scroll"], + "description": "Action to perform" + }, + "selector": { + "type": "string", + "description": "CSS selector for target element (not needed for scroll)" + }, + "text": { + "type": "string", + "description": "Text to type (for 'type' action)" + }, + "key": { + "type": "string", + "description": "Key to press (for 'press_key' action, e.g., 'Enter', 'Tab')" + }, + "scroll_amount": { + "type": "integer", + "description": "Pixels to scroll (for 'scroll' action, negative for up)" + } + }, + "required": ["session_id", "action"] + } + ), + Tool( + name="extract_content", + description="Extract content from the page (text, HTML, attributes)", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID" + }, + "content_type": { + "type": "string", + "enum": ["text", "html", "attribute"], + "description": "Type of content to extract" + }, + "selector": { + "type": "string", + "description": "CSS selector (optional, extracts from whole page if not provided)" + }, + "attribute": { + "type": "string", + "description": "Attribute name (for 'attribute' content_type)" + } + }, + "required": ["session_id", "content_type"] + } + ), + Tool( + name="execute_script", + description="Execute JavaScript code in the browser context", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID" + }, + "script": { + "type": "string", + "description": "JavaScript code to execute" + } + }, + "required": ["session_id", "script"] + } + ), + Tool( + name="screenshot", + description="Take a screenshot of the page or element", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID" + }, + "path": { + "type": "string", + "description": "File path to save screenshot (optional)" + }, + "selector": { + "type": "string", + "description": "CSS selector for specific element (optional, full page if not provided)" + }, + "full_page": { + "type": "boolean", + "description": "Capture full scrollable page (default: false)", + "default": False + } + }, + "required": ["session_id"] + } + ), + Tool( + name="manage_tabs", + description="Manage browser tabs (new, switch, close, list)", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID" + }, + "action": { + "type": "string", + "enum": ["new_tab", "switch_tab", "close_tab", "list_tabs"], + "description": "Tab management action" + }, + "tab_id": { + "type": "string", + "description": "Tab ID (for switch_tab, close_tab, or custom ID for new_tab)" + } + }, + "required": ["session_id", "action"] + } + ), + Tool( + name="list_sessions", + description="List all active browser sessions", + inputSchema={ + "type": "object", + "properties": {} + } + ), + Tool( + name="get_session_info", + description="Get detailed information about a session", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID" + } + }, + "required": ["session_id"] + } + ), + Tool( + name="close_session", + description="Close a browser session and clean up resources", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID" + } + }, + "required": ["session_id"] + } + ), + Tool( + name="get_live_view_url", + description="Get the Live View URL for real-time browser monitoring", + inputSchema={ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Session ID" + } + }, + "required": ["session_id"] + } + ) + ] + + + +@app.call_tool() +async def call_tool(name: str, arguments: Any) -> List[TextContent]: + """Handle tool calls""" + + # Clean up expired sessions periodically + await cleanup_expired_sessions() + + try: + if name == "create_browser_session": + return await handle_create_session(arguments) + elif name == "navigate": + return await handle_navigate(arguments) + elif name == "interact": + return await handle_interact(arguments) + elif name == "extract_content": + return await handle_extract_content(arguments) + elif name == "execute_script": + return await handle_execute_script(arguments) + elif name == "screenshot": + return await handle_screenshot(arguments) + elif name == "manage_tabs": + return await handle_manage_tabs(arguments) + elif name == "list_sessions": + return await handle_list_sessions(arguments) + elif name == "get_session_info": + return await handle_get_session_info(arguments) + elif name == "close_session": + return await handle_close_session(arguments) + elif name == "get_live_view_url": + return await handle_get_live_view_url(arguments) + else: + return [TextContent(type="text", text=f"Unknown tool: {name}")] + + except Exception as e: + logger.error(f"Error in {name}: {e}", exc_info=True) + return [TextContent(type="text", text=f"Error: {str(e)}")] + + +async def handle_create_session(args: Dict[str, Any]) -> List[TextContent]: + """Create a new browser session""" + session_id = args["session_id"] + description = args["description"] + region = args.get("region", os.getenv("AWS_REGION", "us-east-1")) + session_timeout = args.get("session_timeout", 3600) + enable_recording = args.get("enable_recording", False) + + # Check if session already exists + if session_id in sessions: + return [TextContent( + type="text", + text=f"Error: Session '{session_id}' already exists. Use a different session_id or close the existing session first." + )] + + try: + # Initialize Playwright + playwright = await init_playwright() + + # Create browser client + browser_client = BrowserClient(region=region) + + # Start browser session + identifier = os.getenv("BROWSER_IDENTIFIER", "aws.browser.v1") + aws_session_id = browser_client.start( + identifier=identifier, + session_timeout_seconds=session_timeout + ) + + logger.info(f"Started AgentCore browser session: {aws_session_id}") + + # Get CDP connection details + cdp_url, cdp_headers = browser_client.generate_ws_headers() + + # Connect to browser via CDP + browser = await playwright.chromium.connect_over_cdp( + endpoint_url=cdp_url, + headers=cdp_headers + ) + + # Get default context and create page + if not browser.contexts: + raise RuntimeError("No browser contexts available") + + context = browser.contexts[0] + page = await context.new_page() + + # Create session object + session = BrowserSession( + session_id=session_id, + description=description, + region=region, + browser_client=browser_client, + browser=browser, + context=context, + page=page, + timeout=session_timeout, + recording_enabled=enable_recording + ) + + # Add main tab + session.tabs["main"] = page + + # Store session + sessions[session_id] = session + + # Generate Live View URL + live_view_url = f"https://console.aws.amazon.com/bedrock/home?region={region}#/agentcore/browser/sessions/{aws_session_id}" + + result = f"""✅ Browser session created successfully! + +Session ID: {session_id} +Description: {description} +Region: {region} +Timeout: {session_timeout} seconds +Recording: {'Enabled' if enable_recording else 'Disabled'} + +Live View URL: {live_view_url} + +You can now use this session_id with other tools like navigate, interact, extract_content, etc. +The session will remain active for {session_timeout} seconds or until you close it. +""" + + return [TextContent(type="text", text=result)] + + except Exception as e: + logger.error(f"Failed to create session: {e}", exc_info=True) + return [TextContent(type="text", text=f"Error creating session: {str(e)}")] + + + +async def handle_navigate(args: Dict[str, Any]) -> List[TextContent]: + """Navigate to a URL""" + session_id = args["session_id"] + url = args["url"] + wait_for = args.get("wait_for", "networkidle") + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + session = sessions[session_id] + session.update_last_used() + + try: + page = session.tabs.get(session.active_tab_id, session.page) + await page.goto(url) + await page.wait_for_load_state(wait_for) + + return [TextContent( + type="text", + text=f"✅ Navigated to {url}\nCurrent URL: {page.url}" + )] + + except Exception as e: + return [TextContent(type="text", text=f"Error navigating: {str(e)}")] + + +async def handle_interact(args: Dict[str, Any]) -> List[TextContent]: + """Handle page interactions""" + session_id = args["session_id"] + action = args["action"] + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + session = sessions[session_id] + session.update_last_used() + page = session.tabs.get(session.active_tab_id, session.page) + + try: + if action == "click": + selector = args["selector"] + await page.click(selector) + return [TextContent(type="text", text=f"✅ Clicked element: {selector}")] + + elif action == "type": + selector = args["selector"] + text = args["text"] + await page.fill(selector, text) + return [TextContent(type="text", text=f"✅ Typed text into: {selector}")] + + elif action == "press_key": + key = args["key"] + await page.keyboard.press(key) + return [TextContent(type="text", text=f"✅ Pressed key: {key}")] + + elif action == "scroll": + scroll_amount = args.get("scroll_amount", 500) + await page.evaluate(f"window.scrollBy(0, {scroll_amount})") + return [TextContent(type="text", text=f"✅ Scrolled {scroll_amount} pixels")] + + else: + return [TextContent(type="text", text=f"Error: Unknown action '{action}'")] + + except Exception as e: + return [TextContent(type="text", text=f"Error during {action}: {str(e)}")] + + +async def handle_extract_content(args: Dict[str, Any]) -> List[TextContent]: + """Extract content from page""" + session_id = args["session_id"] + content_type = args["content_type"] + selector = args.get("selector") + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + session = sessions[session_id] + session.update_last_used() + page = session.tabs.get(session.active_tab_id, session.page) + + try: + if content_type == "text": + if selector: + content = await page.text_content(selector) + else: + content = await page.evaluate("document.body.innerText") + return [TextContent(type="text", text=f"Extracted text:\n\n{content}")] + + elif content_type == "html": + if selector: + content = await page.inner_html(selector) + else: + content = await page.content() + # Truncate if too long + if len(content) > 5000: + content = content[:5000] + "\n\n... (truncated)" + return [TextContent(type="text", text=f"Extracted HTML:\n\n{content}")] + + elif content_type == "attribute": + if not selector: + return [TextContent(type="text", text="Error: selector required for attribute extraction")] + attribute = args.get("attribute") + if not attribute: + return [TextContent(type="text", text="Error: attribute name required")] + content = await page.get_attribute(selector, attribute) + return [TextContent(type="text", text=f"Attribute '{attribute}': {content}")] + + else: + return [TextContent(type="text", text=f"Error: Unknown content_type '{content_type}'")] + + except Exception as e: + return [TextContent(type="text", text=f"Error extracting content: {str(e)}")] + + + +async def handle_execute_script(args: Dict[str, Any]) -> List[TextContent]: + """Execute JavaScript""" + session_id = args["session_id"] + script = args["script"] + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + session = sessions[session_id] + session.update_last_used() + page = session.tabs.get(session.active_tab_id, session.page) + + try: + result = await page.evaluate(script) + return [TextContent(type="text", text=f"Script result:\n\n{result}")] + except Exception as e: + return [TextContent(type="text", text=f"Error executing script: {str(e)}")] + + +async def handle_screenshot(args: Dict[str, Any]) -> List[TextContent]: + """Take screenshot""" + session_id = args["session_id"] + path = args.get("path") + selector = args.get("selector") + full_page = args.get("full_page", False) + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + session = sessions[session_id] + session.update_last_used() + page = session.tabs.get(session.active_tab_id, session.page) + + try: + # Generate path if not provided + if not path: + screenshots_dir = os.getenv("BROWSER_SCREENSHOTS_DIR", "screenshots") + os.makedirs(screenshots_dir, exist_ok=True) + path = os.path.join(screenshots_dir, f"screenshot_{int(time.time())}.png") + + # Take screenshot + if selector: + element = await page.query_selector(selector) + if element: + await element.screenshot(path=path) + else: + return [TextContent(type="text", text=f"Error: Element '{selector}' not found")] + else: + await page.screenshot(path=path, full_page=full_page) + + return [TextContent(type="text", text=f"✅ Screenshot saved to: {path}")] + + except Exception as e: + return [TextContent(type="text", text=f"Error taking screenshot: {str(e)}")] + + +async def handle_manage_tabs(args: Dict[str, Any]) -> List[TextContent]: + """Manage browser tabs""" + session_id = args["session_id"] + action = args["action"] + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + session = sessions[session_id] + session.update_last_used() + + try: + if action == "new_tab": + tab_id = args.get("tab_id", f"tab_{len(session.tabs) + 1}") + if tab_id in session.tabs: + return [TextContent(type="text", text=f"Error: Tab '{tab_id}' already exists")] + + new_page = await session.context.new_page() + session.tabs[tab_id] = new_page + session.active_tab_id = tab_id + + return [TextContent(type="text", text=f"✅ Created new tab: {tab_id} (now active)")] + + elif action == "switch_tab": + tab_id = args.get("tab_id") + if not tab_id or tab_id not in session.tabs: + available = ", ".join(session.tabs.keys()) + return [TextContent(type="text", text=f"Error: Tab '{tab_id}' not found. Available: {available}")] + + session.active_tab_id = tab_id + page = session.tabs[tab_id] + await page.bring_to_front() + + return [TextContent(type="text", text=f"✅ Switched to tab: {tab_id}")] + + elif action == "close_tab": + tab_id = args.get("tab_id", session.active_tab_id) + if tab_id not in session.tabs: + return [TextContent(type="text", text=f"Error: Tab '{tab_id}' not found")] + + await session.tabs[tab_id].close() + del session.tabs[tab_id] + + # Switch to another tab if current was closed + if session.active_tab_id == tab_id and session.tabs: + session.active_tab_id = next(iter(session.tabs.keys())) + + return [TextContent(type="text", text=f"✅ Closed tab: {tab_id}")] + + elif action == "list_tabs": + tabs_info = [] + for tab_id, page in session.tabs.items(): + is_active = "✓" if tab_id == session.active_tab_id else " " + tabs_info.append(f"[{is_active}] {tab_id}: {page.url}") + + result = "Active tabs:\n\n" + "\n".join(tabs_info) + return [TextContent(type="text", text=result)] + + else: + return [TextContent(type="text", text=f"Error: Unknown action '{action}'")] + + except Exception as e: + return [TextContent(type="text", text=f"Error managing tabs: {str(e)}")] + + + +async def handle_list_sessions(args: Dict[str, Any]) -> List[TextContent]: + """List all active sessions""" + if not sessions: + return [TextContent(type="text", text="No active sessions")] + + session_list = [] + for sid, session in sessions.items(): + age = int(time.time() - session.created_at) + idle = int(time.time() - session.last_used) + session_list.append( + f"• {sid}\n" + f" Description: {session.description}\n" + f" Region: {session.region}\n" + f" Age: {age}s, Idle: {idle}s\n" + f" Tabs: {len(session.tabs)}, Active: {session.active_tab_id}" + ) + + result = f"Active sessions ({len(sessions)}):\n\n" + "\n\n".join(session_list) + return [TextContent(type="text", text=result)] + + +async def handle_get_session_info(args: Dict[str, Any]) -> List[TextContent]: + """Get session information""" + session_id = args["session_id"] + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + session = sessions[session_id] + page = session.tabs.get(session.active_tab_id, session.page) + + age = int(time.time() - session.created_at) + idle = int(time.time() - session.last_used) + + info = f"""Session Information: + +Session ID: {session_id} +Description: {session.description} +Region: {session.region} +Status: Active +Age: {age} seconds +Idle: {idle} seconds +Timeout: {session.timeout} seconds + +Current URL: {page.url if page else 'N/A'} +Active Tab: {session.active_tab_id} +Total Tabs: {len(session.tabs)} +Recording: {'Enabled' if session.recording_enabled else 'Disabled'} + +Tabs: +""" + + for tab_id, tab_page in session.tabs.items(): + is_active = "✓" if tab_id == session.active_tab_id else " " + info += f" [{is_active}] {tab_id}: {tab_page.url}\n" + + return [TextContent(type="text", text=info)] + + +async def handle_close_session(args: Dict[str, Any]) -> List[TextContent]: + """Close a session""" + session_id = args["session_id"] + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + try: + await close_session_internal(session_id) + return [TextContent(type="text", text=f"✅ Session '{session_id}' closed successfully")] + except Exception as e: + return [TextContent(type="text", text=f"Error closing session: {str(e)}")] + + +async def handle_get_live_view_url(args: Dict[str, Any]) -> List[TextContent]: + """Get Live View URL""" + session_id = args["session_id"] + + if session_id not in sessions: + return [TextContent(type="text", text=f"Error: Session '{session_id}' not found")] + + session = sessions[session_id] + + # Note: This is a simplified URL. In production, you'd get the actual session ID from browser_client + live_view_url = f"https://console.aws.amazon.com/bedrock/home?region={session.region}#/agentcore/browser/sessions" + + result = f"""Live View URL for session '{session_id}': + +{live_view_url} + +Open this URL in your browser to: +• Watch the browser session in real-time +• Interact with the page manually if needed +• Debug automation issues visually +• Take over control when necessary + +Note: You need appropriate AWS IAM permissions to access the Live View. +""" + + return [TextContent(type="text", text=result)] + + +async def main(): + """Main entry point for the MCP server""" + from mcp.server.stdio import stdio_server + + logger.info("Starting AgentCore Browser MCP Server") + + async with stdio_server() as (read_stream, write_stream): + await app.run( + read_stream, + write_stream, + app.create_initialization_options() + ) + + +# Run the server +if __name__ == "__main__": + asyncio.run(main()) diff --git a/agentcore-browser-mcp-server/example_usage.md b/agentcore-browser-mcp-server/example_usage.md new file mode 100644 index 0000000..9a38dd8 --- /dev/null +++ b/agentcore-browser-mcp-server/example_usage.md @@ -0,0 +1,632 @@ +# AgentCore Browser Usage Examples + +Real-world examples of using AgentCore Browser for various automation tasks. + +## Example 1: Simple Web Scraping + +Extract product information from an e-commerce site: + +```python +# Create session +await create_browser_session( + session_id="product-scraper", + description="Scraping product data" +) + +# Navigate to product page +await navigate( + session_id="product-scraper", + url="https://example-shop.com/products/laptop" +) + +# Extract product name +product_name = await extract_content( + session_id="product-scraper", + content_type="text", + selector="h1.product-title" +) + +# Extract price +price = await extract_content( + session_id="product-scraper", + content_type="text", + selector="span.price" +) + +# Extract description +description = await extract_content( + session_id="product-scraper", + content_type="text", + selector="div.product-description" +) + +# Take screenshot for verification +await screenshot( + session_id="product-scraper", + path="product-page.png" +) + +# Close session +await close_session(session_id="product-scraper") + +print(f"Product: {product_name}") +print(f"Price: {price}") +print(f"Description: {description}") +``` + +## Example 2: Form Submission with Validation + +Submit a contact form and verify success: + +```python +# Create session +await create_browser_session( + session_id="contact-form", + description="Contact form submission" +) + +# Navigate to contact page +await navigate( + session_id="contact-form", + url="https://example.com/contact" +) + +# Fill form fields +await interact( + session_id="contact-form", + action="type", + selector="input[name='name']", + text="John Doe" +) + +await interact( + session_id="contact-form", + action="type", + selector="input[name='email']", + text="john.doe@example.com" +) + +await interact( + session_id="contact-form", + action="type", + selector="input[name='phone']", + text="+1-555-0123" +) + +await interact( + session_id="contact-form", + action="type", + selector="textarea[name='message']", + text="I would like to inquire about your services." +) + +# Take screenshot before submission +await screenshot( + session_id="contact-form", + path="form-filled.png" +) + +# Submit form +await interact( + session_id="contact-form", + action="click", + selector="button[type='submit']" +) + +# Wait for submission to complete +await execute_script( + session_id="contact-form", + script="await new Promise(r => setTimeout(r, 2000))" +) + +# Verify success message +success_message = await extract_content( + session_id="contact-form", + content_type="text", + selector="div.success-message" +) + +# Take screenshot of result +await screenshot( + session_id="contact-form", + path="form-submitted.png" +) + +# Close session +await close_session(session_id="contact-form") + +print(f"Submission result: {success_message}") +``` + +## Example 3: Login and Navigate Protected Pages + +Authenticate and access protected content: + +```python +# Create session +await create_browser_session( + session_id="authenticated-session", + description="Login and access protected pages", + session_timeout=7200 # 2 hours for extended session +) + +# Navigate to login page +await navigate( + session_id="authenticated-session", + url="https://example.com/login" +) + +# Enter credentials +await interact( + session_id="authenticated-session", + action="type", + selector="input[name='username']", + text="user@example.com" +) + +await interact( + session_id="authenticated-session", + action="type", + selector="input[name='password']", + text="secure-password" +) + +# Click login button +await interact( + session_id="authenticated-session", + action="click", + selector="button[type='submit']" +) + +# Wait for redirect +await execute_script( + session_id="authenticated-session", + script="await new Promise(r => setTimeout(r, 2000))" +) + +# Now authenticated - navigate to dashboard +await navigate( + session_id="authenticated-session", + url="https://example.com/dashboard" +) + +# Extract user info +user_name = await extract_content( + session_id="authenticated-session", + content_type="text", + selector="span.user-name" +) + +# Navigate to profile (still authenticated) +await navigate( + session_id="authenticated-session", + url="https://example.com/profile" +) + +# Extract profile data +profile_data = await execute_script( + session_id="authenticated-session", + script=""" + return { + name: document.querySelector('.profile-name').textContent, + email: document.querySelector('.profile-email').textContent, + memberSince: document.querySelector('.member-since').textContent + }; + """ +) + +# Close session +await close_session(session_id="authenticated-session") + +print(f"Logged in as: {user_name}") +print(f"Profile: {profile_data}") +``` + +## Example 4: Multi-Tab Price Comparison + +Compare prices across multiple websites: + +```python +# Create session +await create_browser_session( + session_id="price-comparison", + description="Comparing prices across sites" +) + +# Site 1 (main tab) +await navigate( + session_id="price-comparison", + url="https://site1.com/product/laptop-xyz" +) + +price1 = await extract_content( + session_id="price-comparison", + content_type="text", + selector="span.price" +) + +# Site 2 (new tab) +await manage_tabs( + session_id="price-comparison", + action="new_tab", + tab_id="site2" +) + +await navigate( + session_id="price-comparison", + url="https://site2.com/products/laptop-xyz" +) + +price2 = await extract_content( + session_id="price-comparison", + content_type="text", + selector="div.product-price" +) + +# Site 3 (new tab) +await manage_tabs( + session_id="price-comparison", + action="new_tab", + tab_id="site3" +) + +await navigate( + session_id="price-comparison", + url="https://site3.com/item/laptop-xyz" +) + +price3 = await extract_content( + session_id="price-comparison", + content_type="text", + selector="span.current-price" +) + +# Compare prices +prices = { + "Site 1": price1, + "Site 2": price2, + "Site 3": price3 +} + +# Close session +await close_session(session_id="price-comparison") + +print("Price Comparison:") +for site, price in prices.items(): + print(f"{site}: {price}") +``` + +## Example 5: Automated Testing + +Test a web application's functionality: + +```python +# Create session with recording for test evidence +await create_browser_session( + session_id="qa-test-login", + description="QA test: Login functionality", + enable_recording=True +) + +# Test Case 1: Valid Login +await navigate( + session_id="qa-test-login", + url="https://app.example.com/login" +) + +await interact( + session_id="qa-test-login", + action="type", + selector="input#email", + text="test@example.com" +) + +await interact( + session_id="qa-test-login", + action="type", + selector="input#password", + text="ValidPassword123" +) + +await screenshot( + session_id="qa-test-login", + path="test-login-filled.png" +) + +await interact( + session_id="qa-test-login", + action="click", + selector="button#login-btn" +) + +# Verify successful login +await execute_script( + session_id="qa-test-login", + script="await new Promise(r => setTimeout(r, 2000))" +) + +current_url = await execute_script( + session_id="qa-test-login", + script="return window.location.href" +) + +assert "/dashboard" in current_url, "Login failed - not redirected to dashboard" + +await screenshot( + session_id="qa-test-login", + path="test-login-success.png" +) + +# Test Case 2: Logout +await interact( + session_id="qa-test-login", + action="click", + selector="button#logout-btn" +) + +await execute_script( + session_id="qa-test-login", + script="await new Promise(r => setTimeout(r, 1000))" +) + +current_url = await execute_script( + session_id="qa-test-login", + script="return window.location.href" +) + +assert "/login" in current_url, "Logout failed - not redirected to login" + +await screenshot( + session_id="qa-test-login", + path="test-logout-success.png" +) + +# Close session (recording saved to S3) +await close_session(session_id="qa-test-login") + +print("✅ All tests passed!") +``` + +## Example 6: Data Collection with Pagination + +Scrape data across multiple pages: + +```python +# Create session +await create_browser_session( + session_id="paginated-scraper", + description="Scraping paginated data", + session_timeout=7200 # 2 hours for large dataset +) + +all_products = [] +page = 1 +max_pages = 10 + +while page <= max_pages: + # Navigate to page + await navigate( + session_id="paginated-scraper", + url=f"https://example.com/products?page={page}" + ) + + # Extract products from current page + products = await execute_script( + session_id="paginated-scraper", + script=""" + return Array.from(document.querySelectorAll('.product')).map(p => ({ + name: p.querySelector('.name').textContent, + price: p.querySelector('.price').textContent, + rating: p.querySelector('.rating').textContent + })); + """ + ) + + all_products.extend(products) + + # Check if next page exists + has_next = await execute_script( + session_id="paginated-scraper", + script="return document.querySelector('.next-page') !== null" + ) + + if not has_next: + break + + page += 1 + + # Be polite - wait between requests + await execute_script( + session_id="paginated-scraper", + script="await new Promise(r => setTimeout(r, 1000))" + ) + +# Close session +await close_session(session_id="paginated-scraper") + +print(f"Collected {len(all_products)} products from {page} pages") +``` + +## Example 7: Monitoring Website Changes + +Check if website content has changed: + +```python +# Create session +await create_browser_session( + session_id="change-monitor", + description="Monitoring website for changes" +) + +# Navigate to page +await navigate( + session_id="change-monitor", + url="https://example.com/status" +) + +# Extract current content +current_content = await extract_content( + session_id="change-monitor", + content_type="text", + selector="div.status-message" +) + +# Take screenshot +await screenshot( + session_id="change-monitor", + path="status-current.png" +) + +# Compare with previous content (loaded from file/database) +previous_content = load_previous_content() # Your function + +if current_content != previous_content: + print("⚠️ Content has changed!") + print(f"Previous: {previous_content}") + print(f"Current: {current_content}") + + # Send alert (your notification logic) + send_alert(f"Website changed: {current_content}") +else: + print("✅ No changes detected") + +# Save current content for next check +save_content(current_content) # Your function + +# Close session +await close_session(session_id="change-monitor") +``` + +## Example 8: Handling Dynamic Content + +Work with JavaScript-heavy single-page applications: + +```python +# Create session +await create_browser_session( + session_id="spa-interaction", + description="Interacting with SPA" +) + +# Navigate to SPA +await navigate( + session_id="spa-interaction", + url="https://example.com/app" +) + +# Wait for React/Vue/Angular to load +await execute_script( + session_id="spa-interaction", + script="await new Promise(r => setTimeout(r, 3000))" +) + +# Click button that triggers AJAX request +await interact( + session_id="spa-interaction", + action="click", + selector="button.load-data" +) + +# Wait for AJAX to complete +await execute_script( + session_id="spa-interaction", + script=""" + await new Promise(resolve => { + const checkData = () => { + if (document.querySelector('.data-loaded')) { + resolve(); + } else { + setTimeout(checkData, 100); + } + }; + checkData(); + }); + """ +) + +# Extract dynamically loaded data +data = await extract_content( + session_id="spa-interaction", + content_type="text", + selector="div.dynamic-content" +) + +# Close session +await close_session(session_id="spa-interaction") + +print(f"Dynamic data: {data}") +``` + +## Tips for Real-World Usage + +### 1. Error Handling + +Always wrap automation in try-except: + +```python +try: + await create_browser_session(...) + await navigate(...) + await interact(...) +except Exception as e: + print(f"Error: {e}") + await screenshot(session_id="session", path="error.png") +finally: + await close_session(session_id="session") +``` + +### 2. Retries + +Implement retry logic for flaky operations: + +```python +max_retries = 3 +for attempt in range(max_retries): + try: + await interact(session_id="session", action="click", selector="button") + break + except Exception as e: + if attempt == max_retries - 1: + raise + await execute_script( + session_id="session", + script="await new Promise(r => setTimeout(r, 1000))" + ) +``` + +### 3. Logging + +Log important steps: + +```python +print(f"[{datetime.now()}] Creating session...") +await create_browser_session(...) + +print(f"[{datetime.now()}] Navigating to {url}...") +await navigate(...) + +print(f"[{datetime.now()}] Extracting data...") +data = await extract_content(...) +``` + +### 4. Rate Limiting + +Be respectful to websites: + +```python +for url in urls: + await navigate(session_id="session", url=url) + # Extract data... + + # Wait between requests + await execute_script( + session_id="session", + script="await new Promise(r => setTimeout(r, 2000))" + ) +``` + +## Next Steps + +- Read `session-management.md` for advanced session techniques +- Check `troubleshooting.md` for common issues +- Review `web-automation-patterns.md` for more patterns diff --git a/agentcore-browser-mcp-server/install.sh b/agentcore-browser-mcp-server/install.sh new file mode 100755 index 0000000..5357958 --- /dev/null +++ b/agentcore-browser-mcp-server/install.sh @@ -0,0 +1,170 @@ +#!/bin/bash +# AgentCore Browser MCP Server Installation Script + +set -e # Exit on error + +echo "==========================================" +echo "AgentCore Browser MCP Server Installation" +echo "==========================================" +echo "" + +# Check if running on macOS or Linux +if [[ "$OSTYPE" == "darwin"* ]]; then + OS="macos" +elif [[ "$OSTYPE" == "linux-gnu"* ]]; then + OS="linux" +else + echo "❌ Unsupported operating system: $OSTYPE" + exit 1 +fi + +echo "✓ Detected OS: $OS" +echo "" + +# Step 1: Check AWS CLI +echo "Step 1: Checking AWS CLI..." +if command -v aws &> /dev/null; then + echo "✓ AWS CLI found: $(aws --version)" + + # Check if credentials are configured + if aws sts get-caller-identity &> /dev/null; then + echo "✓ AWS credentials configured" + else + echo "⚠️ Warning: AWS credentials not configured" + echo " Please run: aws configure" + fi +else + echo "❌ Error: AWS CLI not found" + echo " Please install AWS CLI first:" + echo " macOS: brew install awscli" + echo " Linux: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html" + exit 1 +fi +echo "" + +# Step 2: Check Python version +echo "Step 2: Checking Python version..." +if command -v python3 &> /dev/null; then + PYTHON_VERSION=$(python3 --version | cut -d' ' -f2) + PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d'.' -f1) + PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d'.' -f2) + + if [ "$PYTHON_MAJOR" -ge 3 ] && [ "$PYTHON_MINOR" -ge 10 ]; then + echo "✓ Python $PYTHON_VERSION found" + else + echo "❌ Error: Python 3.10+ required, found $PYTHON_VERSION" + exit 1 + fi +else + echo "❌ Error: Python 3 not found" + exit 1 +fi +echo "" + +# Step 3: Create directory +echo "Step 3: Creating MCP server directory..." +mkdir -p ~/.kiro/mcp-servers +echo "✓ Directory created: ~/.kiro/mcp-servers" +echo "" + +# Step 4: Copy files +echo "Step 4: Copying MCP server files..." +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +cp -r "$SCRIPT_DIR" ~/.kiro/mcp-servers/agentcore-browser-mcp-server +echo "✓ Files copied to ~/.kiro/mcp-servers/agentcore-browser-mcp-server" +echo "" + +# Step 5: Install Python dependencies +echo "Step 5: Installing Python dependencies..." +cd ~/.kiro/mcp-servers/agentcore-browser-mcp-server + +# Try different installation methods +if command -v conda &> /dev/null; then + echo " Detected conda environment" + # Use conda's pip + pip install -r requirements.txt + echo "✓ Python dependencies installed via conda pip" +elif command -v pip3 &> /dev/null; then + # Try with --break-system-packages for externally managed environments + if pip3 install -r requirements.txt 2>&1 | grep -q "externally-managed-environment"; then + echo " Detected externally managed environment, using --break-system-packages" + pip3 install --break-system-packages -r requirements.txt + else + pip3 install -r requirements.txt + fi + echo "✓ Python dependencies installed" +elif command -v pip &> /dev/null; then + if pip install -r requirements.txt 2>&1 | grep -q "externally-managed-environment"; then + echo " Detected externally managed environment, using --break-system-packages" + pip install --break-system-packages -r requirements.txt + else + pip install -r requirements.txt + fi + echo "✓ Python dependencies installed" +else + echo "❌ Error: pip not found" + echo " Please install pip first" + exit 1 +fi +echo "" + +# Step 6: Install Playwright browsers +echo "Step 6: Installing Playwright browsers..." + +# Use the same Python that has playwright installed +if command -v conda &> /dev/null && [ -n "$CONDA_DEFAULT_ENV" ]; then + # In conda environment, use conda's python + python -m playwright install chromium +elif command -v python3 &> /dev/null; then + python3 -m playwright install chromium +else + python -m playwright install chromium +fi + +echo "✓ Playwright Chromium installed" +echo "" + +# Step 7: Test installation +echo "Step 7: Testing MCP server..." + +# Use the same Python that has the dependencies +if command -v conda &> /dev/null && [ -n "$CONDA_DEFAULT_ENV" ]; then + python test_mcp_server.py +elif command -v python3 &> /dev/null; then + python3 test_mcp_server.py +else + python test_mcp_server.py +fi + +if [ $? -eq 0 ]; then + echo "" + echo "==========================================" + echo "✅ Installation Complete!" + echo "==========================================" + echo "" + echo "MCP Server installed at:" + echo " ~/.kiro/mcp-servers/agentcore-browser-mcp-server/" + echo "" + echo "Next steps:" + echo " 1. Ensure AWS credentials are configured: aws configure" + echo " 2. Verify IAM permissions for AgentCore Browser" + echo " 3. Open Kiro Powers panel" + echo " 4. Add Power from: powers/agentcore-browser" + echo " 5. Start automating with AgentCore Browser!" + echo "" + echo "Test the installation:" + echo " Ask Kiro: 'Create a browser session called test-session'" + echo "" +else + echo "" + echo "==========================================" + echo "⚠️ Installation completed with warnings" + echo "==========================================" + echo "" + echo "Some tests failed. Please check the output above." + echo "Common issues:" + echo " - AWS credentials not configured" + echo " - Missing IAM permissions" + echo " - Python dependencies not installed" + echo "" +fi diff --git a/agentcore-browser-mcp-server/pyproject.toml b/agentcore-browser-mcp-server/pyproject.toml new file mode 100644 index 0000000..e440f71 --- /dev/null +++ b/agentcore-browser-mcp-server/pyproject.toml @@ -0,0 +1,43 @@ +[project] +name = "agentcore-browser-mcp-server" +version = "0.1.0" +description = "MCP server for AWS Bedrock AgentCore Browser automation" +requires-python = ">=3.10" +dependencies = [ + "mcp>=0.9.0", + "playwright>=1.40.0", + "boto3>=1.34.0" +] + +[project.optional-dependencies] +dev = [ + "pytest>=7.0.0", + "pytest-asyncio>=0.21.0", + "pytest-cov>=4.0.0", + "ruff>=0.1.0", + "mypy>=1.0.0" +] + +[project.scripts] +agentcore-browser-mcp-server = "agentcore_browser_mcp:main" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.uv] +dev-dependencies = [] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] + +[tool.ruff] +line-length = 120 +target-version = "py310" + +[tool.mypy] +python_version = "3.10" +warn_return_any = true +warn_unused_configs = true +disallow_untyped_defs = false diff --git a/agentcore-browser-mcp-server/requirements.txt b/agentcore-browser-mcp-server/requirements.txt new file mode 100644 index 0000000..8c97562 --- /dev/null +++ b/agentcore-browser-mcp-server/requirements.txt @@ -0,0 +1,11 @@ +# MCP Server +mcp>=0.9.0 + +# Browser automation +playwright>=1.40.0 + +# AWS Bedrock AgentCore +bedrock-agentcore>=1.1.0 + +# AWS SDK +boto3>=1.34.0 diff --git a/agentcore-browser-mcp-server/test_mcp_server.py b/agentcore-browser-mcp-server/test_mcp_server.py new file mode 100644 index 0000000..b0c09c1 --- /dev/null +++ b/agentcore-browser-mcp-server/test_mcp_server.py @@ -0,0 +1,518 @@ +#!/usr/bin/env python3 +""" +Test script for AgentCore Browser MCP Server + +This script tests the MCP server with real AWS AgentCore Browser. +Requires AWS credentials and proper IAM permissions. +""" + +import asyncio +import json +import os +import sys +from pathlib import Path + +# Add parent directory to path for imports +sys.path.insert(0, str(Path(__file__).parent)) + +from agentcore_browser_mcp import ( + app, + sessions, + handle_create_session, + handle_navigate, + handle_interact, + handle_extract_content, + handle_execute_script, + handle_screenshot, + handle_manage_tabs, + handle_list_sessions, + handle_get_session_info, + handle_close_session, + handle_get_live_view_url +) + + +class TestResults: + """Track test results""" + def __init__(self): + self.passed = 0 + self.failed = 0 + self.skipped = 0 + self.tests = [] + + def add_pass(self, name: str): + self.passed += 1 + self.tests.append((name, "PASS", None)) + print(f"✅ {name}") + + def add_fail(self, name: str, error: str): + self.failed += 1 + self.tests.append((name, "FAIL", error)) + print(f"❌ {name}: {error}") + + def add_skip(self, name: str, reason: str): + self.skipped += 1 + self.tests.append((name, "SKIP", reason)) + print(f"⏭️ {name}: {reason}") + + def summary(self): + total = self.passed + self.failed + self.skipped + print(f"\n{'='*60}") + print(f"Test Results: {self.passed}/{total} passed, {self.skipped} skipped, {self.failed} failed") + print(f"{'='*60}") + if self.failed > 0: + print("\nFailed tests:") + for name, status, error in self.tests: + if status == "FAIL": + print(f" - {name}: {error}") + return self.failed == 0 + + +results = TestResults() + + +def check_aws_credentials(): + """Check if AWS credentials are configured""" + try: + import boto3 + sts = boto3.client('sts') + identity = sts.get_caller_identity() + print(f"✓ AWS credentials configured") + print(f" Account: {identity['Account']}") + print(f" User/Role: {identity['Arn']}") + return True + except Exception as e: + print(f"❌ AWS credentials not configured: {e}") + print(" Please run: aws configure") + return False + + +def check_region(): + """Check if region is supported""" + region = os.getenv('AWS_REGION', 'us-east-1') + supported_regions = ['us-east-1', 'us-west-2', 'eu-central-1', 'ap-southeast-2'] + + if region in supported_regions: + print(f"✓ Using region: {region}") + return True + else: + print(f"⚠️ Warning: Region {region} may not support AgentCore Browser") + print(f" Supported regions: {', '.join(supported_regions)}") + return True # Continue anyway + + +async def test_list_tools(): + """Test that tools are properly defined""" + try: + # list_tools is decorated with @app.list_tools() which makes it a regular function + # We need to call the decorated function directly + tools_func = None + for name, obj in vars(app).items(): + if callable(obj) and hasattr(obj, '__name__') and 'list_tools' in obj.__name__: + tools_func = obj + break + + if tools_func: + tools = await tools_func() + else: + # Fallback: call the function directly + from agentcore_browser_mcp import list_tools as list_tools_func + tools = await list_tools_func() + + expected_tools = [ + "create_browser_session", + "navigate", + "interact", + "extract_content", + "execute_script", + "screenshot", + "manage_tabs", + "list_sessions", + "get_session_info", + "close_session", + "get_live_view_url" + ] + + tool_names = [tool.name for tool in tools] + + missing = [t for t in expected_tools if t not in tool_names] + if missing: + results.add_fail("test_list_tools", f"Missing tools: {missing}") + return + + results.add_pass("test_list_tools") + except Exception as e: + results.add_fail("test_list_tools", str(e)) + + +async def test_create_session(): + """Test session creation with real AWS""" + try: + # Clear any existing sessions + sessions.clear() + + print(" Creating browser session (this may take 10-15 seconds)...") + response = await handle_create_session({ + "session_id": "test-session", + "description": "Automated test session", + "region": os.getenv('AWS_REGION', 'us-east-1'), + "session_timeout": 1800, # 30 minutes + "enable_recording": False + }) + + # Verify response + if len(response) == 0: + results.add_fail("test_create_session", "Empty response") + return + + text = response[0].text + if "✅" not in text or "test-session" not in text: + results.add_fail("test_create_session", f"Unexpected response: {text}") + return + + # Verify session was created + if "test-session" not in sessions: + results.add_fail("test_create_session", "Session not in sessions dict") + return + + print(f" Session created successfully") + results.add_pass("test_create_session") + + except Exception as e: + results.add_fail("test_create_session", str(e)) + + +async def test_list_sessions(): + """Test listing sessions""" + try: + response = await handle_list_sessions({}) + + if len(response) == 0: + results.add_fail("test_list_sessions", "Empty response") + return + + text = response[0].text + if "test-session" not in text: + results.add_fail("test_list_sessions", "Session not in list") + return + + results.add_pass("test_list_sessions") + + except Exception as e: + results.add_fail("test_list_sessions", str(e)) + + +async def test_get_session_info(): + """Test getting session info""" + try: + response = await handle_get_session_info({ + "session_id": "test-session" + }) + + if len(response) == 0: + results.add_fail("test_get_session_info", "Empty response") + return + + text = response[0].text + if "test-session" not in text or "Session Information" not in text: + results.add_fail("test_get_session_info", f"Unexpected response: {text}") + return + + results.add_pass("test_get_session_info") + + except Exception as e: + results.add_fail("test_get_session_info", str(e)) + + +async def test_navigate(): + """Test navigation""" + try: + if "test-session" not in sessions: + results.add_skip("test_navigate", "No test session available") + return + + print(" Navigating to example.com...") + response = await handle_navigate({ + "session_id": "test-session", + "url": "https://example.com", + "wait_for": "networkidle" + }) + + if len(response) == 0: + results.add_fail("test_navigate", "Empty response") + return + + text = response[0].text + if "✅" not in text or "example.com" not in text: + results.add_fail("test_navigate", f"Unexpected response: {text}") + return + + results.add_pass("test_navigate") + + except Exception as e: + results.add_fail("test_navigate", str(e)) + + +async def test_extract_content(): + """Test content extraction""" + try: + if "test-session" not in sessions: + results.add_skip("test_extract_content", "No test session available") + return + + print(" Extracting page title...") + response = await handle_extract_content({ + "session_id": "test-session", + "content_type": "text", + "selector": "h1" + }) + + if len(response) == 0: + results.add_fail("test_extract_content", "Empty response") + return + + text = response[0].text + if "Example Domain" not in text: + results.add_fail("test_extract_content", f"Expected 'Example Domain', got: {text}") + return + + results.add_pass("test_extract_content") + + except Exception as e: + results.add_fail("test_extract_content", str(e)) + + +async def test_execute_script(): + """Test JavaScript execution""" + try: + if "test-session" not in sessions: + results.add_skip("test_execute_script", "No test session available") + return + + print(" Executing JavaScript...") + response = await handle_execute_script({ + "session_id": "test-session", + "script": "document.title" # Remove 'return' keyword + }) + + if len(response) == 0: + results.add_fail("test_execute_script", "Empty response") + return + + text = response[0].text + if "Example Domain" not in text: + results.add_fail("test_execute_script", f"Unexpected result: {text}") + return + + results.add_pass("test_execute_script") + + except Exception as e: + results.add_fail("test_execute_script", str(e)) + + +async def test_screenshot(): + """Test screenshot capture""" + try: + if "test-session" not in sessions: + results.add_skip("test_screenshot", "No test session available") + return + + print(" Taking screenshot...") + + # Create screenshots directory + screenshots_dir = Path("screenshots") + screenshots_dir.mkdir(exist_ok=True) + + response = await handle_screenshot({ + "session_id": "test-session", + "path": "screenshots/test-screenshot.png" + }) + + if len(response) == 0: + results.add_fail("test_screenshot", "Empty response") + return + + text = response[0].text + if "✅" not in text or "screenshot" not in text.lower(): + results.add_fail("test_screenshot", f"Unexpected response: {text}") + return + + # Verify file was created + screenshot_path = Path("screenshots/test-screenshot.png") + if not screenshot_path.exists(): + results.add_fail("test_screenshot", "Screenshot file not created") + return + + results.add_pass("test_screenshot") + + except Exception as e: + results.add_fail("test_screenshot", str(e)) + + +async def test_manage_tabs(): + """Test tab management""" + try: + if "test-session" not in sessions: + results.add_skip("test_manage_tabs", "No test session available") + return + + print(" Creating new tab...") + response = await handle_manage_tabs({ + "session_id": "test-session", + "action": "new_tab", + "tab_id": "tab2" + }) + + if len(response) == 0: + results.add_fail("test_manage_tabs", "Empty response") + return + + text = response[0].text + if "✅" not in text or "tab2" not in text: + results.add_fail("test_manage_tabs", f"Unexpected response: {text}") + return + + # List tabs + response = await handle_manage_tabs({ + "session_id": "test-session", + "action": "list_tabs" + }) + + text = response[0].text + if "tab2" not in text: + results.add_fail("test_manage_tabs", "New tab not in list") + return + + results.add_pass("test_manage_tabs") + + except Exception as e: + results.add_fail("test_manage_tabs", str(e)) + + +async def test_get_live_view_url(): + """Test getting Live View URL""" + try: + if "test-session" not in sessions: + results.add_skip("test_get_live_view_url", "No test session available") + return + + response = await handle_get_live_view_url({ + "session_id": "test-session" + }) + + if len(response) == 0: + results.add_fail("test_get_live_view_url", "Empty response") + return + + text = response[0].text + if "Live View URL" not in text or "console.aws.amazon.com" not in text: + results.add_fail("test_get_live_view_url", f"Unexpected response: {text}") + return + + results.add_pass("test_get_live_view_url") + + except Exception as e: + results.add_fail("test_get_live_view_url", str(e)) + + +async def test_close_session(): + """Test session cleanup""" + try: + if "test-session" not in sessions: + results.add_skip("test_close_session", "No test session available") + return + + print(" Closing session...") + response = await handle_close_session({ + "session_id": "test-session" + }) + + if len(response) == 0: + results.add_fail("test_close_session", "Empty response") + return + + text = response[0].text + if "✅" not in text or "closed" not in text: + results.add_fail("test_close_session", f"Unexpected response: {text}") + return + + # Verify session was removed + if "test-session" in sessions: + results.add_fail("test_close_session", "Session still in sessions dict") + return + + results.add_pass("test_close_session") + + except Exception as e: + results.add_fail("test_close_session", str(e)) + + +async def run_all_tests(): + """Run all tests""" + print("="*60) + print("AgentCore Browser MCP Server - Test Suite") + print("="*60) + print() + + # Check prerequisites + print("Checking prerequisites...") + if not check_aws_credentials(): + print("\n❌ AWS credentials not configured. Cannot run tests.") + print(" Please run: aws configure") + return False + + check_region() + print() + + # Run tests in order + print("Running tests...") + print() + + await test_list_tools() + await test_create_session() + await test_list_sessions() + await test_get_session_info() + await test_navigate() + await test_extract_content() + await test_execute_script() + await test_screenshot() + await test_manage_tabs() + await test_get_live_view_url() + await test_close_session() + + # Print summary + success = results.summary() + + if success: + print("\n✅ All tests passed!") + print("\nThe MCP server is ready to use.") + print("Next steps:") + print(" 1. Add the Power to Kiro") + print(" 2. Start automating with AgentCore Browser!") + else: + print("\n⚠️ Some tests failed.") + print("Please check the errors above and:") + print(" 1. Verify AWS credentials are configured") + print(" 2. Check IAM permissions for AgentCore Browser") + print(" 3. Ensure region supports AgentCore Browser") + + return success + + +def main(): + """Main entry point""" + try: + success = asyncio.run(run_all_tests()) + sys.exit(0 if success else 1) + except KeyboardInterrupt: + print("\n\nTest interrupted by user") + sys.exit(1) + except Exception as e: + print(f"\n\n❌ Fatal error: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/agentcore-browser-mcp-server/test_structure.py b/agentcore-browser-mcp-server/test_structure.py new file mode 100644 index 0000000..e69de29 diff --git a/agentcore-browser/POWER.md b/agentcore-browser/POWER.md new file mode 100644 index 0000000..a1fee8c --- /dev/null +++ b/agentcore-browser/POWER.md @@ -0,0 +1,545 @@ +--- +name: "agentcore-browser" +displayName: "AgentCore Browser" +description: "Automate web interactions with AWS Bedrock AgentCore Browser - a secure, cloud-based browser for AI agents. Navigate websites, fill forms, extract content, and automate workflows with session management, live viewing, and recording capabilities." +keywords: ["browser", "automation", "web", "agentcore", "playwright", "scraping", "testing", "aws", "bedrock"] +author: "Kiro Team" +--- + +# AgentCore Browser + +## Overview + +Automate web interactions using Amazon Bedrock AgentCore Browser - a fully managed, cloud-based browser designed for AI agents. This power provides comprehensive browser automation capabilities including: + +- **Session Management** - Create persistent browser sessions that maintain state across multiple operations +- **Web Automation** - Navigate, click, type, extract content, execute JavaScript +- **Live Viewing** - Real-time browser monitoring through AWS Console or WebSocket +- **Session Recording** - Capture and replay browser interactions for debugging +- **Security** - Isolated sessions, ephemeral environments, CloudTrail logging +- **Scalability** - Serverless infrastructure, up to 500 concurrent sessions + +Unlike local browser automation, AgentCore Browser runs in AWS cloud with enterprise-grade security, automatic scaling, and built-in observability. + +## When to Use This Power + +Use AgentCore Browser when you need to: + +- **Automate web workflows** - Fill forms, submit data, navigate multi-step processes +- **Extract web content** - Scrape data, monitor websites, gather information +- **Test web applications** - Automated QA, visual regression testing +- **Integrate legacy systems** - Interact with web UIs that lack APIs +- **Research and intelligence** - Automated web research, competitive analysis +- **E-commerce automation** - Order processing, inventory monitoring + +**Key Advantages:** +- No local browser installation required +- Runs in secure, isolated cloud environment +- Automatic scaling for parallel sessions +- Built-in recording and replay for debugging +- Live view for human intervention when needed + +## Available MCP Tools + +This power provides a Python MCP server with the following tools: + +### Session Management + +**`create_browser_session`** - Create a new browser session +- Maintains state across multiple operations +- Configurable timeout (up to 8 hours) +- Optional recording to S3 +- Returns session ID and Live View URL + +**`list_sessions`** - List all active browser sessions +- Shows session IDs, descriptions, status +- Useful for managing multiple parallel sessions + +**`get_session_info`** - Get detailed information about a session +- Current URL, tabs, status +- Live View URL for monitoring + +**`close_session`** - Close a browser session and clean up resources +- Releases cloud resources +- Stops recording if enabled + +### Browser Automation + +**`navigate`** - Navigate to a URL +- Waits for page load +- Handles network errors gracefully + +**`interact`** - Unified interaction interface +- Actions: click, type, press_key, scroll +- CSS selector-based element targeting +- Automatic wait for elements + +**`extract_content`** - Extract content from page +- Get text, HTML, or attributes +- CSS selector support +- Full page or specific elements + +**`execute_script`** - Execute JavaScript in browser context +- Run custom scripts +- Access DOM directly +- Return results to agent + +**`screenshot`** - Capture page screenshot +- Full page or specific element +- Saved locally or returned as base64 +- Useful for visual verification + +### Tab Management + +**`manage_tabs`** - Manage browser tabs +- Actions: new_tab, switch_tab, close_tab, list_tabs +- Multi-tab workflows +- Parallel page operations + +### Advanced Features + +**`get_live_view_url`** - Get Live View URL for a session +- Real-time browser monitoring +- Human intervention capability +- WebSocket-based streaming + +**`search_browser_docs`** - Search AgentCore Browser documentation +- Find specific features +- Troubleshooting guidance +- API references + +## Quick Start + +### 1. Create a Browser Session + +```python +# Create a new session +result = await create_browser_session( + session_id="my-automation-session", + description="Automating form submission", + region="us-east-1", + session_timeout=3600, # 1 hour + enable_recording=False +) + +# Result includes: +# - session_id: "my-automation-session" +# - live_view_url: "https://console.aws.amazon.com/..." +# - status: "ready" +``` + +### 2. Navigate and Interact + +```python +# Navigate to a website +await navigate( + session_id="my-automation-session", + url="https://example.com/form" +) + +# Fill out a form +await interact( + session_id="my-automation-session", + action="type", + selector="input[name='email']", + text="user@example.com" +) + +await interact( + session_id="my-automation-session", + action="click", + selector="button[type='submit']" +) +``` + +### 3. Extract Content + +```python +# Extract text from page +result = await extract_content( + session_id="my-automation-session", + content_type="text", + selector="div.result" +) + +print(result["content"]) +``` + +### 4. Clean Up + +```python +# Close session when done +await close_session(session_id="my-automation-session") +``` + +## Session Management Best Practices + +### Session Lifecycle + +1. **Create** - Initialize session with unique ID +2. **Use** - Perform multiple operations with same session_id +3. **Monitor** - Use Live View URL if needed +4. **Close** - Always close when done to free resources + +### Session Naming + +Use descriptive session IDs: +- ✅ Good: `order-processing-2024-01`, `qa-test-login-flow` +- ❌ Bad: `session1`, `test`, `abc123` + +### Timeout Configuration + +Choose appropriate timeout based on workflow: +- **Short tasks** (< 15 min): Use default 900 seconds +- **Medium workflows** (15-60 min): Use 3600 seconds (1 hour) +- **Long-running** (1-8 hours): Use up to 28800 seconds (8 hours) + +### Parallel Sessions + +You can run up to 500 concurrent sessions: + +```python +# Create multiple sessions for parallel processing +for i in range(10): + await create_browser_session( + session_id=f"parallel-session-{i}", + description=f"Processing batch {i}" + ) + +# Process in parallel +# Each session maintains independent state +``` + +## Available Steering Files + +This power includes detailed guides for specific workflows: + +- **getting-started.md** - Complete setup and first automation +- **web-automation-patterns.md** - Common automation patterns and best practices +- **session-management.md** - Advanced session management techniques +- **live-view-recording.md** - Using Live View and session recording +- **integration-strands.md** - Integrating with Strands agents +- **troubleshooting.md** - Common issues and solutions + +Access steering files with: +``` +readSteering("agentcore-browser", "getting-started.md") +``` + +## Tool Usage Examples + +### Example 1: Form Automation + +```python +# Create session +await create_browser_session( + session_id="form-automation", + description="Automated form submission" +) + +# Navigate to form +await navigate( + session_id="form-automation", + url="https://example.com/contact" +) + +# Fill form fields +await interact( + session_id="form-automation", + action="type", + selector="input[name='name']", + text="John Doe" +) + +await interact( + session_id="form-automation", + action="type", + selector="input[name='email']", + text="john@example.com" +) + +await interact( + session_id="form-automation", + action="type", + selector="textarea[name='message']", + text="This is an automated message" +) + +# Submit form +await interact( + session_id="form-automation", + action="click", + selector="button[type='submit']" +) + +# Verify submission +result = await extract_content( + session_id="form-automation", + content_type="text", + selector="div.success-message" +) + +# Clean up +await close_session(session_id="form-automation") +``` + +### Example 2: Web Scraping + +```python +# Create session with recording +await create_browser_session( + session_id="web-scraper", + description="Scraping product data", + enable_recording=True +) + +# Navigate to target page +await navigate( + session_id="web-scraper", + url="https://example.com/products" +) + +# Extract product information +products = await execute_script( + session_id="web-scraper", + script=""" + return Array.from(document.querySelectorAll('.product')).map(p => ({ + name: p.querySelector('.name').textContent, + price: p.querySelector('.price').textContent, + url: p.querySelector('a').href + })); + """ +) + +# Close session (recording saved to S3) +await close_session(session_id="web-scraper") +``` + +### Example 3: Multi-Tab Workflow + +```python +# Create session +await create_browser_session( + session_id="multi-tab-workflow", + description="Comparing data across sites" +) + +# Open first site in main tab +await navigate( + session_id="multi-tab-workflow", + url="https://site1.com" +) + +# Open second site in new tab +await manage_tabs( + session_id="multi-tab-workflow", + action="new_tab", + tab_id="site2" +) + +await navigate( + session_id="multi-tab-workflow", + url="https://site2.com" +) + +# Extract from second tab +data2 = await extract_content( + session_id="multi-tab-workflow", + content_type="text", + selector="div.data" +) + +# Switch back to first tab +await manage_tabs( + session_id="multi-tab-workflow", + action="switch_tab", + tab_id="main" +) + +# Extract from first tab +data1 = await extract_content( + session_id="multi-tab-workflow", + content_type="text", + selector="div.data" +) + +# Compare data... + +await close_session(session_id="multi-tab-workflow") +``` + +## Configuration + +### Installation Steps + +1. **Install MCP Server** (if not already installed): + ```bash + cd agentcore-browser-mcp-server + chmod +x install.sh + ./install.sh + ``` + This installs the MCP server to `~/.kiro/mcp-servers/agentcore-browser-mcp-server/` + +2. **Install Power in Kiro**: + - Open Kiro Powers panel + - Click "Install from directory" + - Select the `powers/agentcore-browser` directory + - Kiro will automatically configure the MCP server connection + +3. **Verify Installation**: + - Restart Kiro + - The power should appear in your installed powers list + - MCP server will connect automatically + +**Note**: The `mcp.json` file contains a placeholder path that Kiro will automatically update to your home directory during installation. If you encounter path issues, you can manually edit the MCP configuration in Kiro's settings. + +### Prerequisites + +1. **AWS Account** with Bedrock AgentCore access +2. **AWS Credentials** configured (via `aws configure` or environment variables) +3. **IAM Permissions** for AgentCore Browser: + ```json + { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "bedrock-agentcore:CreateBrowser", + "bedrock-agentcore:StartBrowserSession", + "bedrock-agentcore:StopBrowserSession", + "bedrock-agentcore:GetBrowserSession" + ], + "Resource": "*" + } + ] + } + ``` + +4. **Python 3.10+** for MCP server +5. **Region Availability** - AgentCore Browser is available in: + - us-east-1 (N. Virginia) + - us-west-2 (Oregon) + - eu-central-1 (Frankfurt) + - ap-southeast-2 (Sydney) + +### Optional: Session Recording + +To enable session recording, add S3 permissions: + +```json +{ + "Effect": "Allow", + "Action": [ + "s3:PutObject", + "s3:GetObject" + ], + "Resource": "arn:aws:s3:::your-recording-bucket/*" +} +``` + +## Troubleshooting + +### Session Creation Fails + +**Error:** `AccessDeniedException` +**Solution:** Verify IAM permissions and AWS credentials + +**Error:** `Region not supported` +**Solution:** Use supported region (us-east-1, us-west-2, eu-central-1, ap-southeast-2) + +### Navigation Timeout + +**Error:** `Navigation timeout exceeded` +**Solution:** +- Check URL is accessible +- Increase timeout in navigate call +- Verify network connectivity + +### Element Not Found + +**Error:** `Selector not found` +**Solution:** +- Verify CSS selector is correct +- Wait for page to fully load +- Use browser DevTools to test selector + +### Session Limit Reached + +**Error:** `Maximum sessions exceeded` +**Solution:** +- Close unused sessions +- Implement session pooling +- Contact AWS for limit increase + +## Best Practices + +### Security + +- **Never hardcode credentials** - Use environment variables or AWS Secrets Manager +- **Close sessions promptly** - Free resources and reduce costs +- **Use session recording** - For audit trails and debugging +- **Limit session timeout** - Use shortest timeout needed for workflow + +### Performance + +- **Reuse sessions** - For multiple operations on same site +- **Parallel sessions** - For batch processing +- **Minimize screenshots** - Only when necessary for verification +- **Use CSS selectors** - More reliable than XPath + +### Reliability + +- **Handle errors gracefully** - Network issues, timeouts, element changes +- **Implement retries** - For transient failures +- **Use Live View** - For debugging complex workflows +- **Enable recording** - For production workflows + +### Cost Optimization + +- **Close idle sessions** - Don't leave sessions running +- **Use appropriate timeouts** - Shorter is cheaper +- **Batch operations** - Minimize session creation overhead +- **Monitor usage** - Track session count and duration + +## Integration with Other Powers + +### With Strands Agents + +```python +from strands import Agent +from strands_tools.browser import AgentCoreBrowser + +# Create browser tool +browser = AgentCoreBrowser(region="us-east-1") + +# Add to agent +agent = Agent( + name="Web Automation Agent", + tools=[browser.browser] +) + +# Agent can now use browser automatically +``` + +### With AWS AgentCore + +AgentCore Browser integrates seamlessly with other AgentCore services: +- **AgentCore Memory** - Store extracted data +- **AgentCore Gateway** - Expose browser automation as API +- **AgentCore Runtime** - Deploy browser agents + +## Additional Resources + +- [AgentCore Browser Documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/browser-tool.html) +- [Strands Browser Integration](https://github.com/strands-agents/tools/tree/main/src/strands_tools/browser) +- [AWS Bedrock AgentCore](https://aws.amazon.com/bedrock/agentcore/) +- [Playwright Documentation](https://playwright.dev/) + +## Support + +For issues or questions: +1. Check the troubleshooting section above +2. Read steering files for detailed guides +3. Search AgentCore Browser documentation +4. Contact AWS Support for service issues diff --git a/agentcore-browser/mcp.json b/agentcore-browser/mcp.json new file mode 100644 index 0000000..ace9705 --- /dev/null +++ b/agentcore-browser/mcp.json @@ -0,0 +1,17 @@ +{ + "mcpServers": { + "agentcore-browser": { + "command": "python3", + "args": [ + "{you-should-replace-this-to-your-home-dir}/.kiro/mcp-servers/agentcore-browser-mcp-server/agentcore_browser_mcp.py" + ], + "env": { + "AWS_REGION": "us-east-1", + "BROWSER_SESSION_TIMEOUT": "3600", + "BROWSER_IDENTIFIER": "aws.browser.v1" + }, + "disabled": false, + "autoApprove": [] + } + } +} diff --git a/agentcore-browser/steering/getting-started.md b/agentcore-browser/steering/getting-started.md new file mode 100644 index 0000000..0a08c9c --- /dev/null +++ b/agentcore-browser/steering/getting-started.md @@ -0,0 +1,534 @@ +# Getting Started with AgentCore Browser + +Complete guide to setting up and using AgentCore Browser for web automation. + +## Prerequisites + +### 1. AWS Account Setup + +You need an AWS account with access to Amazon Bedrock AgentCore: + +1. **Sign up for AWS** (if you don't have an account) + - Visit https://aws.amazon.com/ + - Click "Create an AWS Account" + - Follow the registration process + +2. **Enable Bedrock AgentCore** + - Navigate to AWS Bedrock console + - Enable AgentCore services in your region + - Available regions: us-east-1, us-west-2, eu-central-1, ap-southeast-2 + +### 2. Configure AWS Credentials + +Set up your AWS credentials locally: + +```bash +# Install AWS CLI if not already installed +# macOS +brew install awscli + +# Linux +curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" +unzip awscliv2.zip +sudo ./aws/install + +# Configure credentials +aws configure +``` + +You'll be prompted for: +- AWS Access Key ID +- AWS Secret Access Key +- Default region (e.g., us-east-1) +- Default output format (json) + +**Verify credentials:** +```bash +aws sts get-caller-identity +``` + +### 3. IAM Permissions + +Ensure your IAM user/role has these permissions: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "bedrock-agentcore:CreateBrowser", + "bedrock-agentcore:StartBrowserSession", + "bedrock-agentcore:StopBrowserSession", + "bedrock-agentcore:GetBrowserSession", + "bedrock-agentcore:ListBrowserSessions" + ], + "Resource": "*" + } + ] +} +``` + +**Optional: For session recording, add S3 permissions:** +```json +{ + "Effect": "Allow", + "Action": [ + "s3:PutObject", + "s3:GetObject" + ], + "Resource": "arn:aws:s3:::your-recording-bucket/*" +} +``` + +### 4. Install Python and uv + +AgentCore Browser MCP server requires Python 3.10+: + +```bash +# Check Python version +python3 --version + +# Install uv package manager +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Verify installation +uv --version +``` + +### 5. Install Playwright + +After installing the power, install Playwright browsers: + +```bash +cd ~/.kiro/powers/agentcore-browser +uv run playwright install chromium +``` + +## Installation + +### Method 1: Via Kiro UI (Recommended) + +1. Open Kiro +2. Open Powers panel (Cmd/Ctrl + Shift + P → "Powers") +3. Click "Install from directory" +4. Navigate to `powers/agentcore-browser` +5. Click "Install" + +### Method 2: Manual Installation + +```bash +# Copy power to Kiro directory +mkdir -p ~/.kiro/powers +cp -r powers/agentcore-browser ~/.kiro/powers/ + +# Install dependencies +cd ~/.kiro/powers/agentcore-browser +uv sync + +# Install Playwright browsers +uv run playwright install chromium +``` + +### Verify Installation + +1. Restart Kiro +2. Check MCP servers are connected: + - Open Kiro settings + - Navigate to MCP section + - Verify "agentcore-browser" is listed and connected + +## Your First Automation + +Let's create a simple automation to navigate to a website and extract content. + +### Step 1: Create a Browser Session + +```python +# In Kiro, ask the agent: +"Create a browser session called 'test-session' for testing navigation" + +# This will call: +await create_browser_session( + session_id="test-session", + description="Testing navigation and content extraction", + region="us-east-1", + session_timeout=3600 +) +``` + +**What happens:** +- AgentCore creates a cloud browser instance +- Session is ready for automation +- You receive a Live View URL for monitoring + +### Step 2: Navigate to a Website + +```python +# Ask the agent: +"Navigate to example.com in test-session" + +# This will call: +await navigate( + session_id="test-session", + url="https://example.com" +) +``` + +**What happens:** +- Browser loads the URL +- Waits for page to be fully loaded +- Returns success confirmation + +### Step 3: Extract Content + +```python +# Ask the agent: +"Extract the main heading text from test-session" + +# This will call: +await extract_content( + session_id="test-session", + content_type="text", + selector="h1" +) +``` + +**What happens:** +- Finds the h1 element +- Extracts text content +- Returns the text to you + +### Step 4: Take a Screenshot + +```python +# Ask the agent: +"Take a screenshot of the page in test-session" + +# This will call: +await screenshot( + session_id="test-session" +) +``` + +**What happens:** +- Captures full page screenshot +- Saves to local screenshots directory +- Returns file path + +### Step 5: Close the Session + +```python +# Ask the agent: +"Close test-session" + +# This will call: +await close_session( + session_id="test-session" +) +``` + +**What happens:** +- Browser session is terminated +- Resources are freed +- Session is removed from active sessions + +## Complete Example: Form Automation + +Here's a complete workflow for automating a contact form: + +```python +# 1. Create session +await create_browser_session( + session_id="contact-form", + description="Automating contact form submission" +) + +# 2. Navigate to form +await navigate( + session_id="contact-form", + url="https://example.com/contact" +) + +# 3. Fill name field +await interact( + session_id="contact-form", + action="type", + selector="input[name='name']", + text="John Doe" +) + +# 4. Fill email field +await interact( + session_id="contact-form", + action="type", + selector="input[name='email']", + text="john@example.com" +) + +# 5. Fill message +await interact( + session_id="contact-form", + action="type", + selector="textarea[name='message']", + text="This is an automated test message" +) + +# 6. Submit form +await interact( + session_id="contact-form", + action="click", + selector="button[type='submit']" +) + +# 7. Wait a moment for submission +await execute_script( + session_id="contact-form", + script="await new Promise(r => setTimeout(r, 2000))" +) + +# 8. Verify success +await extract_content( + session_id="contact-form", + content_type="text", + selector=".success-message" +) + +# 9. Take screenshot for verification +await screenshot( + session_id="contact-form", + path="form-submitted.png" +) + +# 10. Close session +await close_session( + session_id="contact-form" +) +``` + +## Understanding Sessions + +### Session Lifecycle + +1. **Create** - Initialize with unique ID +2. **Active** - Perform operations +3. **Idle** - No operations for some time +4. **Expired** - Timeout reached (auto-closed) +5. **Closed** - Manually closed + +### Session State + +Sessions maintain state across operations: +- **Cookies** - Preserved between requests +- **Local Storage** - Maintained +- **Navigation History** - Available for back/forward +- **Tabs** - Multiple tabs in one session + +### Session Timeout + +Choose appropriate timeout: +- **Short tasks** (< 15 min): 900 seconds (default) +- **Medium workflows** (15-60 min): 3600 seconds +- **Long-running** (1-8 hours): Up to 28800 seconds + +**Example:** +```python +await create_browser_session( + session_id="long-running", + description="Multi-hour data collection", + session_timeout=28800 # 8 hours +) +``` + +## Live View + +Monitor your browser sessions in real-time: + +### Getting Live View URL + +```python +await get_live_view_url( + session_id="your-session" +) +``` + +### Using Live View + +1. Open the URL in your browser +2. You'll see real-time video stream +3. Can interact manually if needed +4. Useful for debugging + +### When to Use Live View + +- **Debugging** - See what's happening visually +- **Human intervention** - Take over when needed +- **Verification** - Confirm automation is working +- **Training** - Learn how automation works + +## Session Recording + +Enable recording for audit trails and debugging: + +### Enable Recording + +```python +await create_browser_session( + session_id="recorded-session", + description="Session with recording", + enable_recording=True +) +``` + +### What Gets Recorded + +- All browser interactions +- Network requests +- Console logs +- DOM changes +- Screenshots at key points + +### Accessing Recordings + +Recordings are stored in S3 (if configured): +- Check AWS Console → S3 +- Look for your recording bucket +- Download and replay recordings + +## Best Practices + +### 1. Session Naming + +Use descriptive, unique session IDs: +```python +# Good +"order-processing-2024-01-05" +"qa-test-login-flow" +"scrape-product-data-batch-1" + +# Bad +"session1" +"test" +"abc" +``` + +### 2. Always Close Sessions + +```python +try: + # Your automation + await navigate(...) + await interact(...) +finally: + # Always close, even if error occurs + await close_session(session_id="your-session") +``` + +### 3. Handle Errors Gracefully + +```python +# Check if element exists before interacting +result = await extract_content( + session_id="session", + content_type="html", + selector="button.submit" +) + +if "Error" not in result: + await interact( + session_id="session", + action="click", + selector="button.submit" + ) +``` + +### 4. Use Appropriate Timeouts + +```python +# Short task +await create_browser_session( + session_id="quick-check", + session_timeout=900 # 15 minutes +) + +# Long workflow +await create_browser_session( + session_id="data-collection", + session_timeout=7200 # 2 hours +) +``` + +### 5. Monitor Session Usage + +```python +# List all active sessions +await list_sessions() + +# Get specific session info +await get_session_info(session_id="your-session") +``` + +## Next Steps + +Now that you're set up, explore: + +1. **Web Automation Patterns** - Common automation patterns + - Read: `web-automation-patterns.md` + +2. **Session Management** - Advanced session techniques + - Read: `session-management.md` + +3. **Live View & Recording** - Monitoring and debugging + - Read: `live-view-recording.md` + +4. **Integration with Strands** - Use with Strands agents + - Read: `integration-strands.md` + +## Troubleshooting + +### Common Issues + +**"AWS credentials not configured"** +```bash +aws configure +# Enter your credentials +``` + +**"Region not supported"** +- Use: us-east-1, us-west-2, eu-central-1, or ap-southeast-2 + +**"Playwright not installed"** +```bash +cd ~/.kiro/powers/agentcore-browser +uv run playwright install chromium +``` + +**"Session creation fails"** +- Check IAM permissions +- Verify AWS credentials +- Ensure region is correct + +**"MCP server not connected"** +- Restart Kiro +- Check MCP settings +- Verify uv is installed + +## Getting Help + +- Check `troubleshooting.md` for detailed solutions +- Review AWS AgentCore documentation +- Contact AWS Support for service issues +- Check Kiro documentation for MCP issues + +## Summary + +You've learned: +- ✅ How to set up AWS credentials and permissions +- ✅ How to install the AgentCore Browser power +- ✅ How to create and manage browser sessions +- ✅ How to perform basic automation tasks +- ✅ How to use Live View for monitoring +- ✅ Best practices for session management + +Ready to automate! 🚀 diff --git a/agentcore-browser/steering/session-management.md b/agentcore-browser/steering/session-management.md new file mode 100644 index 0000000..d5e2d97 --- /dev/null +++ b/agentcore-browser/steering/session-management.md @@ -0,0 +1,610 @@ +# Advanced Session Management + +Learn advanced techniques for managing browser sessions effectively. + +## Session Persistence + +### Cross-Request Session Maintenance + +AgentCore Browser sessions persist across multiple MCP tool calls: + +```python +# Request 1: Create session +await create_browser_session( + session_id="persistent-session", + description="Multi-step workflow" +) + +# Request 2: Navigate (same session) +await navigate( + session_id="persistent-session", + url="https://example.com/login" +) + +# Request 3: Login (same session, cookies preserved) +await interact( + session_id="persistent-session", + action="type", + selector="input[name='username']", + text="user@example.com" +) + +# Request 4: Continue workflow (session state maintained) +await navigate( + session_id="persistent-session", + url="https://example.com/dashboard" +) +``` + +**Key Points:** +- Session state is maintained in MCP server memory +- Cookies, local storage, and navigation history persist +- Multiple operations can use the same session_id +- Sessions remain active until timeout or manual close + +### Session Lifecycle Management + +**1. Creation** +```python +session = await create_browser_session( + session_id="workflow-001", + description="Order processing workflow", + session_timeout=7200 # 2 hours +) +``` + +**2. Active Use** +```python +# Session is automatically kept alive during operations +await navigate(session_id="workflow-001", ...) +await interact(session_id="workflow-001", ...) +# Last used timestamp is updated with each operation +``` + +**3. Monitoring** +```python +# Check session status +info = await get_session_info(session_id="workflow-001") +# Shows: age, idle time, current URL, tabs +``` + +**4. Cleanup** +```python +# Manual close +await close_session(session_id="workflow-001") + +# Or let it timeout automatically +# Session expires after idle for session_timeout seconds +``` + +## Parallel Sessions + +Run multiple browser sessions simultaneously for batch processing. + +### Pattern: Parallel Data Collection + +```python +# Create multiple sessions +session_ids = [] +for i in range(5): + session_id = f"scraper-{i}" + await create_browser_session( + session_id=session_id, + description=f"Scraping batch {i}" + ) + session_ids.append(session_id) + +# Process URLs in parallel (conceptually) +urls = [ + "https://site1.com", + "https://site2.com", + "https://site3.com", + "https://site4.com", + "https://site5.com" +] + +for session_id, url in zip(session_ids, urls): + await navigate(session_id=session_id, url=url) + # Extract data from each... + +# Clean up all sessions +for session_id in session_ids: + await close_session(session_id=session_id) +``` + +### Pattern: A/B Testing + +```python +# Session A: Control +await create_browser_session( + session_id="test-control", + description="Control group" +) + +# Session B: Variant +await create_browser_session( + session_id="test-variant", + description="Variant group" +) + +# Run same workflow in both +for session_id in ["test-control", "test-variant"]: + await navigate(session_id=session_id, url="https://example.com") + # Perform actions... + await screenshot(session_id=session_id, path=f"{session_id}.png") + +# Compare results +``` + +### Limits + +- **Maximum concurrent sessions**: 500 per account +- **Recommended**: 10-20 for most use cases +- **Monitor usage**: Use `list_sessions()` to track active sessions + +## Session Timeout Strategies + +### Short-Lived Sessions (< 15 minutes) + +For quick, one-off tasks: + +```python +await create_browser_session( + session_id="quick-check", + description="Quick status check", + session_timeout=900 # 15 minutes +) + +# Perform quick task +await navigate(...) +await extract_content(...) + +# Close immediately +await close_session(session_id="quick-check") +``` + +**Use cases:** +- Status checks +- Quick data extraction +- Simple form submissions + +### Medium Sessions (15-60 minutes) + +For typical workflows: + +```python +await create_browser_session( + session_id="standard-workflow", + description="Standard automation workflow", + session_timeout=3600 # 1 hour (default) +) +``` + +**Use cases:** +- Multi-step forms +- Data collection workflows +- Testing scenarios + +### Long-Running Sessions (1-8 hours) + +For extended operations: + +```python +await create_browser_session( + session_id="long-running", + description="Extended data collection", + session_timeout=28800 # 8 hours (maximum) +) +``` + +**Use cases:** +- Large-scale scraping +- Monitoring tasks +- Complex multi-page workflows + +**Important:** Longer timeouts cost more. Use shortest timeout needed. + +## Session State Management + +### Cookies and Authentication + +Sessions preserve authentication state: + +```python +# Create session +await create_browser_session(session_id="auth-session", ...) + +# Login +await navigate(session_id="auth-session", url="https://example.com/login") +await interact(session_id="auth-session", action="type", selector="input[name='email']", text="user@example.com") +await interact(session_id="auth-session", action="type", selector="input[name='password']", text="password") +await interact(session_id="auth-session", action="click", selector="button[type='submit']") + +# Cookies are now set, navigate to protected pages +await navigate(session_id="auth-session", url="https://example.com/dashboard") +# Still authenticated! + +await navigate(session_id="auth-session", url="https://example.com/profile") +# Still authenticated! +``` + +### Local Storage + +Local storage persists across navigations: + +```python +# Set local storage +await execute_script( + session_id="session", + script="localStorage.setItem('key', 'value')" +) + +# Navigate to another page +await navigate(session_id="session", url="https://example.com/other") + +# Local storage still available +result = await execute_script( + session_id="session", + script="return localStorage.getItem('key')" +) +# Returns: 'value' +``` + +### Navigation History + +Use back/forward navigation: + +```python +# Navigate through pages +await navigate(session_id="session", url="https://example.com/page1") +await navigate(session_id="session", url="https://example.com/page2") +await navigate(session_id="session", url="https://example.com/page3") + +# Go back +await execute_script(session_id="session", script="history.back()") +# Now on page2 + +# Go forward +await execute_script(session_id="session", script="history.forward()") +# Now on page3 +``` + +## Multi-Tab Workflows + +Manage multiple tabs within a single session. + +### Creating Tabs + +```python +# Create session +await create_browser_session(session_id="multi-tab", ...) + +# Main tab is created automatically (id: "main") + +# Create additional tabs +await manage_tabs( + session_id="multi-tab", + action="new_tab", + tab_id="tab2" +) + +await manage_tabs( + session_id="multi-tab", + action="new_tab", + tab_id="tab3" +) +``` + +### Switching Between Tabs + +```python +# List all tabs +await manage_tabs( + session_id="multi-tab", + action="list_tabs" +) + +# Switch to specific tab +await manage_tabs( + session_id="multi-tab", + action="switch_tab", + tab_id="tab2" +) + +# All subsequent operations use tab2 +await navigate(session_id="multi-tab", url="https://example.com") +``` + +### Pattern: Comparing Data Across Sites + +```python +# Create session +await create_browser_session(session_id="comparison", ...) + +# Main tab: Site 1 +await navigate(session_id="comparison", url="https://site1.com/product") +price1 = await extract_content( + session_id="comparison", + content_type="text", + selector=".price" +) + +# New tab: Site 2 +await manage_tabs(session_id="comparison", action="new_tab", tab_id="site2") +await navigate(session_id="comparison", url="https://site2.com/product") +price2 = await extract_content( + session_id="comparison", + content_type="text", + selector=".price" +) + +# New tab: Site 3 +await manage_tabs(session_id="comparison", action="new_tab", tab_id="site3") +await navigate(session_id="comparison", url="https://site3.com/product") +price3 = await extract_content( + session_id="comparison", + content_type="text", + selector=".price" +) + +# Compare prices... +``` + +### Closing Tabs + +```python +# Close specific tab +await manage_tabs( + session_id="multi-tab", + action="close_tab", + tab_id="tab2" +) + +# Close current tab (active tab) +await manage_tabs( + session_id="multi-tab", + action="close_tab" +) +``` + +## Session Monitoring + +### Listing Active Sessions + +```python +# Get all active sessions +sessions = await list_sessions() + +# Shows: +# - Session IDs +# - Descriptions +# - Age and idle time +# - Number of tabs +``` + +### Getting Session Details + +```python +info = await get_session_info(session_id="your-session") + +# Returns: +# - Current URL +# - Active tab +# - All tabs with URLs +# - Age and idle time +# - Recording status +``` + +### Live View Monitoring + +```python +# Get Live View URL +url = await get_live_view_url(session_id="your-session") + +# Open in browser to: +# - Watch real-time video stream +# - See what automation is doing +# - Intervene manually if needed +# - Debug visual issues +``` + +## Error Handling + +### Session Not Found + +```python +# Always check if session exists +sessions = await list_sessions() + +if "my-session" in sessions: + await navigate(session_id="my-session", ...) +else: + # Create session first + await create_browser_session(session_id="my-session", ...) +``` + +### Session Expired + +```python +# Sessions expire after timeout +# Check session info before long operations +info = await get_session_info(session_id="my-session") + +# If idle too long, recreate +if info["idle_time"] > 3000: # 50 minutes + await close_session(session_id="my-session") + await create_browser_session(session_id="my-session", ...) +``` + +### Graceful Cleanup + +```python +try: + # Your automation + await create_browser_session(...) + await navigate(...) + await interact(...) + +except Exception as e: + print(f"Error: {e}") + +finally: + # Always clean up + try: + await close_session(session_id="your-session") + except: + pass # Session might already be closed +``` + +## Best Practices + +### 1. Use Descriptive Session IDs + +```python +# Good +"order-processing-2024-01-05-batch-1" +"qa-test-login-flow-chrome" +"scrape-products-electronics-category" + +# Bad +"session1" +"test" +"temp" +``` + +### 2. Set Appropriate Timeouts + +```python +# Match timeout to workflow duration +# Add buffer for unexpected delays + +# Quick task: 15 minutes +session_timeout=900 + +# Standard workflow: 1 hour +session_timeout=3600 + +# Long operation: 2-4 hours +session_timeout=14400 +``` + +### 3. Monitor Resource Usage + +```python +# Periodically check active sessions +sessions = await list_sessions() + +# Close unused sessions +for session in sessions: + if session["idle_time"] > 1800: # 30 minutes idle + await close_session(session_id=session["id"]) +``` + +### 4. Use Session Recording for Production + +```python +# Enable recording for audit trails +await create_browser_session( + session_id="production-workflow", + description="Production order processing", + enable_recording=True # Important for debugging +) +``` + +### 5. Implement Retry Logic + +```python +max_retries = 3 +for attempt in range(max_retries): + try: + await navigate(session_id="session", url="https://example.com") + break + except Exception as e: + if attempt == max_retries - 1: + raise + # Wait before retry + await execute_script( + session_id="session", + script="await new Promise(r => setTimeout(r, 2000))" + ) +``` + +## Advanced Patterns + +### Pattern: Session Pooling + +Reuse sessions for multiple tasks: + +```python +# Create pool of sessions +pool = [] +for i in range(5): + session_id = f"pool-{i}" + await create_browser_session(session_id=session_id, ...) + pool.append(session_id) + +# Use sessions from pool +def get_available_session(): + # Return least recently used session + sessions_info = await list_sessions() + return min(sessions_info, key=lambda s: s["last_used"]) + +# Process tasks +for task in tasks: + session_id = get_available_session() + await navigate(session_id=session_id, url=task["url"]) + # Process... +``` + +### Pattern: Session Checkpointing + +Save and restore session state: + +```python +# Save checkpoint +checkpoint = { + "url": await execute_script(session_id="session", script="return window.location.href"), + "cookies": await execute_script(session_id="session", script="return document.cookie"), + "localStorage": await execute_script(session_id="session", script="return JSON.stringify(localStorage)") +} + +# Later, restore checkpoint +await navigate(session_id="session", url=checkpoint["url"]) +await execute_script( + session_id="session", + script=f"document.cookie = '{checkpoint['cookies']}'" +) +await execute_script( + session_id="session", + script=f"Object.assign(localStorage, JSON.parse('{checkpoint['localStorage']}'))" +) +``` + +### Pattern: Conditional Session Creation + +Create sessions only when needed: + +```python +def ensure_session(session_id): + sessions = await list_sessions() + if session_id not in [s["id"] for s in sessions]: + await create_browser_session(session_id=session_id, ...) + return session_id + +# Use in workflow +session_id = ensure_session("my-workflow") +await navigate(session_id=session_id, ...) +``` + +## Summary + +Key takeaways: +- ✅ Sessions persist across multiple MCP tool calls +- ✅ Use appropriate timeouts for your workflow +- ✅ Parallel sessions enable batch processing +- ✅ Multi-tab workflows allow complex scenarios +- ✅ Always monitor and clean up sessions +- ✅ Implement error handling and retries +- ✅ Use session recording for production workflows + +Next: Read `web-automation-patterns.md` for automation techniques. diff --git a/agentcore-browser/steering/troubleshooting.md b/agentcore-browser/steering/troubleshooting.md new file mode 100644 index 0000000..56f7a4b --- /dev/null +++ b/agentcore-browser/steering/troubleshooting.md @@ -0,0 +1,727 @@ +# Troubleshooting Guide + +Common issues and solutions for AgentCore Browser. + +## Installation Issues + +### "uv command not found" + +**Problem:** uv package manager not installed + +**Solution:** +```bash +# Install uv +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Restart terminal +source ~/.bashrc # or ~/.zshrc + +# Verify +uv --version +``` + +### "Playwright not installed" + +**Problem:** Playwright browsers not downloaded + +**Solution:** +```bash +cd ~/.kiro/powers/agentcore-browser +uv run playwright install chromium + +# If that fails, try: +uv sync +uv run playwright install chromium +``` + +### "MCP server not connected" + +**Problem:** MCP server failed to start + +**Solutions:** +1. Check MCP server logs in Kiro +2. Verify Python version: `python3 --version` (need 3.10+) +3. Reinstall dependencies: + ```bash + cd ~/.kiro/powers/agentcore-browser + rm -rf .venv + uv sync + ``` +4. Restart Kiro + +## AWS Credential Issues + +### "AWS credentials not configured" + +**Problem:** No AWS credentials found + +**Solution:** +```bash +# Configure AWS CLI +aws configure + +# Enter: +# - AWS Access Key ID +# - AWS Secret Access Key +# - Default region (e.g., us-east-1) +# - Output format (json) + +# Verify +aws sts get-caller-identity +``` + +### "AccessDeniedException" + +**Problem:** Insufficient IAM permissions + +**Solution:** +1. Check your IAM permissions include: + ```json + { + "Effect": "Allow", + "Action": [ + "bedrock-agentcore:CreateBrowser", + "bedrock-agentcore:StartBrowserSession", + "bedrock-agentcore:StopBrowserSession" + ], + "Resource": "*" + } + ``` + +2. Verify you're using correct AWS account: + ```bash + aws sts get-caller-identity + ``` + +3. Try different region: + ```python + await create_browser_session( + session_id="test", + region="us-west-2" # Try different region + ) + ``` + +### "Region not supported" + +**Problem:** AgentCore Browser not available in region + +**Solution:** +Use supported regions: +- us-east-1 (N. Virginia) +- us-west-2 (Oregon) +- eu-central-1 (Frankfurt) +- ap-southeast-2 (Sydney) + +```python +await create_browser_session( + session_id="test", + region="us-east-1" # Use supported region +) +``` + +## Session Issues + +### "Session not found" + +**Problem:** Session doesn't exist or expired + +**Solutions:** +1. List active sessions: + ```python + await list_sessions() + ``` + +2. Create session if missing: + ```python + await create_browser_session( + session_id="your-session", + description="Your workflow" + ) + ``` + +3. Check session hasn't expired: + ```python + info = await get_session_info(session_id="your-session") + # Check idle_time + ``` + +### "Session creation fails" + +**Problem:** Cannot create new session + +**Solutions:** +1. Check AWS credentials: + ```bash + aws sts get-caller-identity + ``` + +2. Verify region is supported + +3. Check session limit (max 500): + ```python + sessions = await list_sessions() + # If too many, close unused ones + ``` + +4. Try with minimal options: + ```python + await create_browser_session( + session_id="test-minimal", + description="Test" + ) + ``` + +### "Session timeout too short" + +**Problem:** Session expires before workflow completes + +**Solution:** +Increase timeout: +```python +await create_browser_session( + session_id="long-workflow", + description="Extended workflow", + session_timeout=28800 # 8 hours (maximum) +) +``` + +## Navigation Issues + +### "Navigation timeout" + +**Problem:** Page takes too long to load + +**Solutions:** +1. Increase wait time: + ```python + await navigate( + session_id="session", + url="https://slow-site.com", + wait_for="domcontentloaded" # Don't wait for all resources + ) + ``` + +2. Check URL is accessible: + ```bash + curl -I https://your-url.com + ``` + +3. Try different wait condition: + ```python + # Options: 'load', 'domcontentloaded', 'networkidle' + await navigate( + session_id="session", + url="https://example.com", + wait_for="load" # Faster but less complete + ) + ``` + +### "ERR_NAME_NOT_RESOLVED" + +**Problem:** Domain doesn't exist or DNS issue + +**Solutions:** +1. Verify URL is correct +2. Check domain exists: + ```bash + nslookup example.com + ``` +3. Try with www prefix: + ```python + await navigate( + session_id="session", + url="https://www.example.com" # Add www + ) + ``` + +### "ERR_CONNECTION_REFUSED" + +**Problem:** Server refusing connections + +**Solutions:** +1. Check if site is up: + ```bash + curl https://example.com + ``` +2. Try different protocol: + ```python + # Try http instead of https + await navigate( + session_id="session", + url="http://example.com" + ) + ``` +3. Check if site blocks automation (use Live View to verify) + +## Element Interaction Issues + +### "Selector not found" + +**Problem:** CSS selector doesn't match any element + +**Solutions:** +1. Verify selector in browser DevTools: + - Open site in regular browser + - Right-click element → Inspect + - Test selector in Console: `document.querySelector("your-selector")` + +2. Wait for element to appear: + ```python + # Wait before interacting + await execute_script( + session_id="session", + script="await new Promise(r => setTimeout(r, 2000))" + ) + + await interact( + session_id="session", + action="click", + selector="button.submit" + ) + ``` + +3. Use more specific selector: + ```python + # Instead of: "button" + # Use: "button[type='submit']" + # Or: "button.primary-button" + # Or: "#submit-btn" + ``` + +4. Check if element is in iframe: + ```python + # Switch to iframe first + await execute_script( + session_id="session", + script=""" + const iframe = document.querySelector('iframe'); + const iframeDoc = iframe.contentDocument; + return iframeDoc.querySelector('button').click(); + """ + ) + ``` + +### "Element not clickable" + +**Problem:** Element is hidden, covered, or disabled + +**Solutions:** +1. Scroll element into view: + ```python + await execute_script( + session_id="session", + script=""" + document.querySelector('button').scrollIntoView(); + """ + ) + + await interact( + session_id="session", + action="click", + selector="button" + ) + ``` + +2. Wait for element to be clickable: + ```python + await execute_script( + session_id="session", + script="await new Promise(r => setTimeout(r, 1000))" + ) + ``` + +3. Use JavaScript click instead: + ```python + await execute_script( + session_id="session", + script="document.querySelector('button').click()" + ) + ``` + +### "Type action fails" + +**Problem:** Cannot type into input field + +**Solutions:** +1. Click field first: + ```python + await interact( + session_id="session", + action="click", + selector="input[name='email']" + ) + + await interact( + session_id="session", + action="type", + selector="input[name='email']", + text="user@example.com" + ) + ``` + +2. Clear field first: + ```python + await execute_script( + session_id="session", + script="document.querySelector('input[name=\"email\"]').value = ''" + ) + + await interact( + session_id="session", + action="type", + selector="input[name='email']", + text="user@example.com" + ) + ``` + +3. Use JavaScript to set value: + ```python + await execute_script( + session_id="session", + script=""" + document.querySelector('input[name="email"]').value = 'user@example.com'; + document.querySelector('input[name="email"]').dispatchEvent(new Event('input')); + """ + ) + ``` + +## Content Extraction Issues + +### "Extracted content is empty" + +**Problem:** Element exists but has no content + +**Solutions:** +1. Wait for content to load: + ```python + await execute_script( + session_id="session", + script="await new Promise(r => setTimeout(r, 2000))" + ) + + await extract_content( + session_id="session", + content_type="text", + selector=".content" + ) + ``` + +2. Check if content is in different element: + ```python + # Try parent element + await extract_content( + session_id="session", + content_type="html", + selector=".parent-container" + ) + ``` + +3. Use JavaScript to extract: + ```python + await execute_script( + session_id="session", + script="return document.querySelector('.content').textContent" + ) + ``` + +### "HTML extraction truncated" + +**Problem:** HTML content is too large + +**Solution:** +Extract specific parts: +```python +# Instead of full page HTML +await extract_content( + session_id="session", + content_type="html" +) + +# Extract specific section +await extract_content( + session_id="session", + content_type="html", + selector="#main-content" +) +``` + +## JavaScript Execution Issues + +### "Script execution fails" + +**Problem:** JavaScript error in executed script + +**Solutions:** +1. Test script in browser console first + +2. Check for syntax errors: + ```python + # Bad: Missing return + script = "document.title" + + # Good: Explicit return + script = "return document.title" + ``` + +3. Handle async operations: + ```python + # For async operations + await execute_script( + session_id="session", + script=""" + return await new Promise(resolve => { + setTimeout(() => resolve('done'), 1000); + }); + """ + ) + ``` + +4. Wrap in try-catch: + ```python + await execute_script( + session_id="session", + script=""" + try { + return document.querySelector('.element').textContent; + } catch (e) { + return 'Error: ' + e.message; + } + """ + ) + ``` + +## Screenshot Issues + +### "Screenshot is blank" + +**Problem:** Page not fully loaded + +**Solutions:** +1. Wait before screenshot: + ```python + await navigate(session_id="session", url="https://example.com") + + # Wait for page to render + await execute_script( + session_id="session", + script="await new Promise(r => setTimeout(r, 2000))" + ) + + await screenshot(session_id="session") + ``` + +2. Use full_page option: + ```python + await screenshot( + session_id="session", + full_page=True + ) + ``` + +### "Screenshot file not found" + +**Problem:** Screenshot directory doesn't exist + +**Solution:** +```bash +# Create screenshots directory +mkdir -p screenshots + +# Or specify full path +await screenshot( + session_id="session", + path="/full/path/to/screenshot.png" +) +``` + +## Performance Issues + +### "Operations are slow" + +**Problem:** Browser operations taking too long + +**Solutions:** +1. Use faster wait conditions: + ```python + await navigate( + session_id="session", + url="https://example.com", + wait_for="domcontentloaded" # Faster than 'networkidle' + ) + ``` + +2. Disable images (if not needed): + ```python + # Note: This requires custom browser configuration + # Contact AWS support for advanced options + ``` + +3. Use parallel sessions for batch operations + +4. Close unused tabs: + ```python + await manage_tabs( + session_id="session", + action="close_tab", + tab_id="unused-tab" + ) + ``` + +### "Too many sessions" + +**Problem:** Hitting session limit + +**Solution:** +```python +# Clean up old sessions +sessions = await list_sessions() + +for session in sessions: + if session["idle_time"] > 1800: # 30 minutes + await close_session(session_id=session["id"]) +``` + +## Live View Issues + +### "Live View URL doesn't work" + +**Problem:** Cannot access Live View + +**Solutions:** +1. Check IAM permissions for console access + +2. Verify you're logged into correct AWS account + +3. Check region matches session region + +4. Try opening in incognito/private window + +### "Live View shows black screen" + +**Problem:** Session not active or expired + +**Solutions:** +1. Check session is active: + ```python + await get_session_info(session_id="your-session") + ``` + +2. Perform an operation to activate: + ```python + await navigate( + session_id="your-session", + url="https://example.com" + ) + ``` + +## Debugging Strategies + +### Enable Verbose Logging + +Check MCP server logs in Kiro for detailed error messages. + +### Use Live View + +Monitor automation visually: +```python +url = await get_live_view_url(session_id="your-session") +# Open URL in browser to watch +``` + +### Take Screenshots + +Capture state at each step: +```python +await screenshot(session_id="session", path="step1.png") +await interact(...) +await screenshot(session_id="session", path="step2.png") +await interact(...) +await screenshot(session_id="session", path="step3.png") +``` + +### Extract Page HTML + +See what browser sees: +```python +html = await extract_content( + session_id="session", + content_type="html" +) +# Save to file for inspection +``` + +### Check Console Logs + +```python +logs = await execute_script( + session_id="session", + script=""" + return console.logs || []; + """ +) +``` + +## Getting Help + +### Check Documentation + +1. Read POWER.md for overview +2. Check steering files for specific topics +3. Review AWS AgentCore Browser docs + +### AWS Support + +For AWS service issues: +1. Open AWS Support case +2. Include: + - Session ID + - Error messages + - Region + - Timestamp + +### Kiro Support + +For MCP/Kiro issues: +1. Check Kiro documentation +2. Review MCP server logs +3. Report issues with: + - MCP server logs + - Steps to reproduce + - Expected vs actual behavior + +## Common Error Messages + +| Error | Cause | Solution | +|-------|-------|----------| +| "Session not found" | Session expired or doesn't exist | Create new session | +| "AccessDeniedException" | Missing IAM permissions | Add required permissions | +| "Region not supported" | Invalid region | Use supported region | +| "Selector not found" | Element doesn't exist | Verify selector, wait for element | +| "Navigation timeout" | Page load too slow | Increase timeout, check URL | +| "Connection refused" | Server down or blocking | Check site status, try different URL | +| "Maximum sessions exceeded" | Too many active sessions | Close unused sessions | +| "Script execution failed" | JavaScript error | Test script in console, add error handling | + +## Prevention Tips + +1. **Always close sessions** when done +2. **Use appropriate timeouts** for your workflow +3. **Implement error handling** and retries +4. **Test selectors** in browser DevTools first +5. **Monitor session usage** regularly +6. **Enable recording** for production workflows +7. **Use Live View** for debugging complex issues +8. **Keep sessions under limit** (< 20 concurrent) + +## Summary + +Most issues can be resolved by: +- ✅ Verifying AWS credentials and permissions +- ✅ Using correct regions +- ✅ Testing selectors in browser first +- ✅ Adding appropriate waits +- ✅ Implementing error handling +- ✅ Using Live View for visual debugging +- ✅ Checking MCP server logs + +Still stuck? Check AWS AgentCore Browser documentation or contact support. From 0740d10483d6f3807380fd731017bb0c6adfaa02 Mon Sep 17 00:00:00 2001 From: Junxiang Ji Date: Thu, 8 Jan 2026 12:59:54 +0000 Subject: [PATCH 12/18] Add Skill Conversion Power for migrating Claude Skills to Kiro Powers This PR adds comprehensive documentation and guidance for converting Claude Agent Skills to Kiro Powers through: - convert-skills-to-power: Complete conversion guide with steering files for different aspects Key features: - Automated SKILL.md to POWER.md conversion guidance with frontmatter transformation - Script-to-MCP conversion strategies and best practices - Installation and distribution mechanism migration guide - Decision trees for choosing the right conversion approach - Complete code examples and templates Documentation includes: - Quick Start: 5-minute decision flow and conversion checklist - Script Conversion: Detailed guide for converting Skills scripts to MCP tools (2170 lines) - Installation Migration: Installation mechanism comparison and strategies - Troubleshooting: Common conversion issues and solutions Co-Authored-By: Claude --- convert-skills-to-power/POWER.md | 572 +++++ convert-skills-to-power/README.md | 158 ++ .../steering/installation-migration.md | 534 ++++ .../steering/quick-start.md | 523 ++++ .../steering/script-conversion.md | 2170 +++++++++++++++++ .../steering/troubleshooting.md | 660 +++++ 6 files changed, 4617 insertions(+) create mode 100644 convert-skills-to-power/POWER.md create mode 100644 convert-skills-to-power/README.md create mode 100644 convert-skills-to-power/steering/installation-migration.md create mode 100644 convert-skills-to-power/steering/quick-start.md create mode 100644 convert-skills-to-power/steering/script-conversion.md create mode 100644 convert-skills-to-power/steering/troubleshooting.md diff --git a/convert-skills-to-power/POWER.md b/convert-skills-to-power/POWER.md new file mode 100644 index 0000000..fc3a1ec --- /dev/null +++ b/convert-skills-to-power/POWER.md @@ -0,0 +1,572 @@ +--- +name: "convert-skills-to-power" +displayName: "Convert Skills to Power" +description: "Convert Claude Agent Skills to Kiro Powers with automated tools, best practices, and step-by-step guidance for script conversion and MCP integration." +keywords: ["claude", "skills", "conversion", "migration", "mcp", "power", "transform"] +author: "Kiro Community" +--- + +# Convert Skills to Power + +## Overview + +This power helps you convert Claude Agent Skills to Kiro Powers efficiently and correctly. It provides comprehensive guidance, automated conversion tools, and best practices based on detailed research comparing the two systems. + +**Key capabilities:** +- Automated conversion of SKILL.md to POWER.md with proper frontmatter transformation +- Script-to-MCP conversion strategies (the correct way to handle Skills scripts) +- Installation and distribution mechanism guidance +- Decision trees for choosing the right conversion approach +- Complete code examples and templates + +**What you'll learn:** +- Why Skills scripts should become MCP tools (not Hooks) +- How to create your own Script Executor MCP server for reliable conversions +- When to create dedicated MCP servers vs using script executor pattern +- Installation flow differences and migration strategies + +## Available Steering Files + +This power includes comprehensive guides for different aspects of the conversion process: + +- **quick-start** - 5-minute decision flow and conversion checklist +- **script-conversion** - Detailed guide for converting Skills scripts to MCP tools +- **installation-migration** - Installation mechanism comparison and migration strategies +- **troubleshooting** - Common conversion issues and solutions + +## Onboarding + +### Prerequisites + +**Required knowledge:** +- Basic understanding of Claude Skills structure +- Familiarity with Kiro Powers concept +- Command line basics + +**Required tools:** +- Python 3.8+ (for conversion scripts) +- Git (for version control) +- Text editor or IDE + +**Optional but recommended:** +- Node.js 16+ (if working with MCP servers) +- Docker (optional, for containerized deployments) + +### Installation + +No installation required! This is a Knowledge Base Power that provides documentation and guidance. + +**To get started:** +1. Activate this power by mentioning "convert skills" or "skill migration" +2. Read the appropriate steering file based on your needs +3. Follow the step-by-step instructions + +### Quick Setup + +**Python MCP SDK:** +```bash +# Install MCP SDK +pip install mcp + +# Verify installation +python -c "from mcp.server import Server; print('✅ MCP SDK installed')" +``` + +**Optional tools for script execution:** +```bash +# If you need subprocess management +pip install asyncio + +# For JSON schema validation +pip install jsonschema +``` + +## Core Concepts + +### Understanding the Conversion + +**Claude Skills** and **Kiro Powers** are similar but have key differences: + +| Aspect | Claude Skills | Kiro Powers | +|--------|--------------|-------------| +| **Main file** | SKILL.md | POWER.md | +| **Installation** | Manual file creation | IDE one-click / CLI | +| **Activation** | Description matching | Keyword triggering | +| **Scripts** | Zero-context execution | MCP tools (recommended) | +| **Updates** | Manual replacement | Version management | +| **Market** | No official market | Official + community | + +### Critical Decision: Scripts Conversion + +**⚠️ IMPORTANT:** Skills scripts should be converted to **MCP tools**, NOT Hooks. + +**Why?** +- Skills scripts are **on-demand** (AI decides when to run) +- Hooks are **event-triggered** (automatic on file save, etc.) +- MCP tools preserve zero-context execution +- MCP tools support on-demand invocation + +**Conversion options:** +1. **1-3 scripts** → Create dedicated MCP server (2-4 hours) +2. **4-10 scripts** → Use Script Executor Pattern (3-5 hours, recommended) +3. **10+ scripts** → Modular MCP server with dynamic script loading (1-2 days) + +**Note:** We recommend creating your own MCP server using the Script Executor Pattern for better control, reliability, and maintenance. This approach is self-contained and doesn't rely on external dependencies. + +## Common Workflows + +### Workflow 1: Simple Skill Conversion (Pure Documentation) + +**Goal:** Convert a Skill that only contains documentation/guidance (no scripts) + +**Time:** 1-2 hours + +**Steps:** + +1. **Analyze the Skill** + ```bash + # Check Skill structure + ls -la ~/.claude/skills/my-skill/ + + # Verify it's documentation-only (no scripts) + find ~/.claude/skills/my-skill/ -name "*.py" -o -name "*.sh" + ``` + +2. **Create Power directory** + ```bash + mkdir -p ./powers/my-power + cd ./powers/my-power + ``` + +3. **Convert SKILL.md to POWER.md** + + **Transform frontmatter:** + ```yaml + # Original SKILL.md + --- + name: pr-reviewer + description: Reviews pull requests for code quality + --- + + # New POWER.md + --- + name: "pr-reviewer" + displayName: "PR Reviewer" + description: "Reviews pull requests for code quality and team standards" + keywords: ["pr", "pull request", "review", "code review"] + author: "Your Name" + --- + ``` + +4. **Move documentation** + ```bash + # If Skill has docs/ directory + mkdir steering + cp -r ~/.claude/skills/my-skill/docs/* ./steering/ + ``` + +5. **Test the Power** + - Open Kiro Powers panel + - Add from local directory + - Test keyword activation + +**Example:** + +See `steering/quick-start.md` for a complete example with code. + +### Workflow 2: Skill with Scripts Conversion + +**Goal:** Convert a Skill that includes executable scripts + +**Time:** 3-5 hours (using Script Executor Pattern) or 2-4 hours (dedicated MCP for 1-3 scripts) + +**⚠️ IMPORTANT:** Kiro Powers cannot contain script files. You must install the MCP server separately. + +**Steps:** + +1. **Analyze scripts** + ```bash + # List all scripts + find ~/.claude/skills/my-skill/scripts/ -type f + + # Count scripts + find ~/.claude/skills/my-skill/scripts/ -type f | wc -l + ``` + +2. **Choose conversion strategy** + + **Decision tree:** + ``` + Number of scripts? + ├─ 1-3 scripts → Dedicated MCP server + ├─ 4-10 scripts → Script Executor Pattern (recommended) + └─ 10+ scripts → Modular MCP server + ``` + +3. **Create MCP Server (Separate from Power)** + + Install MCP server to a separate location (e.g., `~/my-mcp-servers/my-server/`) + + See `steering/script-conversion.md` for complete code examples and templates. + + **Key benefits:** + - ✅ No external dependencies + - ✅ Full control over execution + - ✅ Easy to customize + - ✅ Complies with Kiro Powers restrictions + +4. **Create Power Directory (Only Documentation)** + + Power contains ONLY: + - `POWER.md` - Documentation with installation instructions + - `mcp.json` - Configuration pointing to installed MCP server + - `steering/` - Optional workflow guides + +5. **Update POWER.md with Installation Instructions** + + Include clear instructions for users to install the MCP server: + ```markdown + ## Installation + + ### Step 1: Install MCP Server + ```bash + git clone https://github.com/user/my-server.git ~/my-mcp-servers/my-server + cd ~/my-mcp-servers/my-server + pip install -r requirements.txt + ``` + + ### Step 2: Install the Power + Install this Power through Kiro Powers panel. + ``` + +6. **Create mcp.json with Absolute Path** + ```json + { + "mcpServers": { + "my-scripts": { + "command": "python", + "args": ["~/my-mcp-servers/my-server/script_executor_mcp.py"] + } + } + } + ``` + +7. **Test the MCP Server** ⚠️ **CRITICAL STEP** + + Before deploying, test your MCP server to ensure it works: + + ```bash + # Create a test script (see steering/script-conversion.md for full template) + python test_mcp_server.py + ``` + + **What to verify:** + - ✅ Server starts without errors + - ✅ All tools are registered + - ✅ Tool schemas are valid + - ✅ Tools can be called successfully + - ✅ Dependencies are installed + + **If tests fail:** + - Check for missing dependencies (`pip install `) + - Verify script paths are correct + - Ensure scripts have execute permissions + - Review error messages carefully + + See `steering/script-conversion.md` → "Testing Your MCP Server" section for detailed testing guide. + +**Complete example:** + +See `steering/script-conversion.md` for full code examples and templates. + +### Workflow 3: Batch Conversion + +**Goal:** Convert multiple Skills at once + +**Time:** Varies based on number and complexity + +**Steps:** + +1. **Prepare conversion environment** + ```bash + mkdir -p ./converted-powers + ``` + +2. **Use automated conversion tool** + ```bash + # Download conversion script + # (See documentation for actual tool location) + + # Run batch conversion + python batch_convert_skills.sh ~/.claude/skills ./converted-powers + ``` + +3. **Review each converted Power** + ```bash + # Check conversion results + for power in ./converted-powers/*; do + echo "=== $(basename $power) ===" + cat "$power/POWER.md" | head -20 + echo "" + done + ``` + +4. **Test each Power individually** + - Install via Kiro Powers panel + - Test keyword activation + - Verify functionality + +5. **Iterate and fix issues** + - Adjust keywords if activation is incorrect + - Fix any conversion errors + - Update documentation as needed + +## Best Practices + +### Conversion Strategy + +1. **Start Simple** + - Begin with 2-3 simple documentation-only Skills + - Build confidence with the process + - Learn the conversion patterns + +2. **Scripts → MCP Tools** + - Always convert scripts to MCP tools (not Hooks) + - Use Script Executor Pattern for reliable deployment + - Create dedicated MCP for complex logic + +3. **Keywords Matter** + - Extract specific keywords from Skill descriptions + - Avoid overly broad terms ("test", "debug", "help") + - Test keyword activation thoroughly + +4. **Preserve Zero-Context** + - MCP tools maintain zero-context execution + - Don't inline scripts into POWER.md + - Keep tool definitions separate + +5. **Version Control** + - Keep original Skills as backup + - Use Git for converted Powers + - Tag versions for easy rollback + +### Installation Migration + +1. **Gradual Migration** + - Don't convert all Skills at once + - Test each Power thoroughly + - Gather feedback before proceeding + +2. **Team Communication** + - Inform team about the migration + - Provide training on Powers + - Share conversion experiences + +3. **Documentation** + - Document conversion decisions + - Keep notes on issues encountered + - Share lessons learned + +### Quality Assurance + +1. **Test MCP Server First** ⚠️ **CRITICAL** + - Create and run test script before deployment + - Verify all tools are registered correctly + - Test tool execution with sample data + - Check for missing dependencies + - Validate error handling + - See `steering/script-conversion.md` for testing guide + +2. **Test Thoroughly** + - Functional testing (does it work?) + - Performance testing (context usage) + - Integration testing (with other Powers) + +3. **Validate Metadata** + - Check frontmatter syntax + - Verify keywords trigger correctly + - Ensure descriptions are clear + +4. **Review Documentation** + - Update examples to Kiro context + - Fix broken links + - Clarify Power-specific instructions + +## Troubleshooting + +### Issue: Power Not Activating + +**Symptoms:** +- Mention keywords but Power doesn't load +- Power not appearing in list + +**Causes:** +- Keywords too generic or incorrect +- Frontmatter syntax error +- Power not installed correctly + +**Solutions:** + +1. **Check keywords** + ```bash + # View Power frontmatter + head -20 powers/my-power/POWER.md + + # Verify keywords are specific + # Bad: ["test", "help"] + # Good: ["pytest", "unit-testing"] + ``` + +2. **Validate YAML syntax** + ```bash + # Use Python to check YAML + python -c "import yaml; yaml.safe_load(open('powers/my-power/POWER.md').read().split('---')[1])" + ``` + +3. **Reinstall Power** + - Remove from Powers panel + - Re-add from local directory + - Test activation again + +### Issue: Scripts Not Working as MCP Tools + +**Symptoms:** +- MCP tools not found +- Script execution fails +- Timeout errors + +**Causes:** +- MCP server not configured correctly +- Script paths incorrect +- Dependencies missing + +**Solutions:** + +1. **Verify MCP configuration** + ```bash + # Check mcp.json syntax + cat powers/my-power/mcp.json | python -m json.tool + + # Test MCP server + cd powers/my-power + python script_executor_mcp.py + ``` + +2. **Check script paths** + ```json + // Ensure paths are relative + { + "scripts": { + "my_script": { + "path": "scripts/my_script.py", // ✅ Relative + // NOT: "/absolute/path/script.py" // ❌ Absolute + } + } + } + ``` + +3. **Install dependencies** + ```bash + # Check script requirements + head -20 scripts/my_script.py + + # Install missing packages + pip install required-package + ``` + +### Issue: Conversion Tool Errors + +**Symptoms:** +- Conversion script fails +- Generated files incomplete +- Syntax errors in output + +**Causes:** +- Invalid SKILL.md format +- Unsupported Skill features +- Tool bugs + +**Solutions:** + +1. **Validate Skill format** + ```bash + # Check SKILL.md structure + head -30 ~/.claude/skills/my-skill/SKILL.md + + # Ensure frontmatter is valid + ``` + +2. **Manual conversion** + - If automated tool fails, convert manually + - Follow templates in steering files + - Copy and adapt from examples + +3. **Report issues** + - Document the error + - Share Skill structure (sanitized) + - Help improve conversion tools + +### Issue: Performance Degradation + +**Symptoms:** +- Kiro slower after installing Powers +- High context usage +- Delayed responses + +**Causes:** +- Too many Powers installed +- Powers with broad keywords +- Large POWER.md files + +**Solutions:** + +1. **Audit installed Powers** + ```bash + # List all Powers + # (Use Kiro Powers panel) + + # Identify unused Powers + # Uninstall what you don't need + ``` + +2. **Refine keywords** + - Make keywords more specific + - Reduce false activations + - Test keyword precision + +3. **Split large Powers** + - If POWER.md > 500 lines, consider splitting + - Move content to steering files + - Use progressive disclosure + +## Configuration + +**No additional configuration required** - this is a Knowledge Base Power. + +**To use the conversion tools:** +- Follow installation steps in Onboarding section +- Configure paths in conversion scripts +- Set up your own MCP server using provided templates + +## Additional Resources + +### Documentation +- [Claude Skills Official Docs](https://code.claude.com/docs/en/skills) +- [Kiro Powers Documentation](https://kiro.dev/docs/powers/) +- [MCP Protocol Specification](https://modelcontextprotocol.io/) + +### Tools +- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) +- [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) +- [MCP Servers Directory](https://mcpservers.org/) + +### Community +- [Kiro Community Forum](https://community.kiro.dev/) +- [MCP Servers Directory](https://mcpservers.org/) +- [Powers Marketplace](https://kiro.dev/powers/) + +--- + +**Knowledge Base Power** - No MCP server required +**Documentation Source:** Comprehensive research comparing Claude Skills and Kiro Powers +**Last Updated:** 2026-01-04 diff --git a/convert-skills-to-power/README.md b/convert-skills-to-power/README.md new file mode 100644 index 0000000..3dbb208 --- /dev/null +++ b/convert-skills-to-power/README.md @@ -0,0 +1,158 @@ +# Convert Skills to Power + +A comprehensive Kiro Power for converting Claude Agent Skills to Kiro Powers. + +## What This Power Does + +This Knowledge Base Power provides complete guidance for converting Claude Agent Skills to Kiro Powers, including: + +- **Automated conversion strategies** for different Skill types +- **Script-to-MCP conversion** (the correct approach, not Hooks!) +- **Installation mechanism comparison** and migration strategies +- **Step-by-step workflows** with code examples +- **Troubleshooting guide** for common issues + +## Power Type + +**Knowledge Base Power** - No MCP server required. This is pure documentation and guidance. + +## Installation + +### Option 1: Install in Kiro (Recommended) + +1. Open Kiro IDE +2. Click Kiro icon → Powers panel +3. Click "Add Custom Power" +4. Select "Local Directory" +5. Navigate to this directory: `powers/convert-skills-to-power` +6. Click "Add" + +### Option 2: Copy to Powers Directory + +```bash +# Copy to Kiro powers directory +cp -r powers/convert-skills-to-power ~/.kiro/powers/ +``` + +## Usage + +Once installed, activate this power by mentioning relevant keywords: + +- "convert skills" +- "skill migration" +- "claude to kiro" +- "skill conversion" + +Then ask for specific guidance: + +- "How do I convert a Skill with scripts?" +- "Show me the quick start guide" +- "What's the installation migration strategy?" +- "Help me troubleshoot conversion issues" + +## Available Steering Files + +This power includes four comprehensive guides: + +1. **quick-start.md** - 5-minute decision flow and conversion checklist +2. **script-conversion.md** - Detailed guide for converting Skills scripts to MCP tools +3. **installation-migration.md** - Installation mechanism comparison and migration strategies +4. **troubleshooting.md** - Common conversion issues and solutions + +## Key Insights + +### Critical: Scripts → MCP Tools, Not Hooks! + +**Why?** +- Skills scripts are **on-demand** (AI decides when to run) +- Hooks are **event-triggered** (automatic on file save, etc.) +- MCP tools preserve zero-context execution +- MCP tools support on-demand invocation + +### Conversion Options + +| Scripts | Recommended Approach | Time | +|---------|---------------------|------| +| 1-3 scripts | Dedicated MCP server | 2-4 hours | +| 4-10 scripts | Script Executor Pattern | 3-5 hours | +| 10+ scripts | Modular MCP server | 1-2 days | + +### Installation Comparison + +| Feature | Claude Skills | Kiro Powers | +|---------|--------------|-------------| +| Installation | Manual files | One-click | +| Time | 5-10 minutes | 30 seconds | +| Restart | Required | Not required | +| Versions | Manual | Automatic | +| Market | None | Official + community | + +## Structure + +``` +convert-skills-to-power/ +├── POWER.md # Main documentation +├── README.md # This file +└── steering/ + ├── quick-start.md # Quick start guide + ├── script-conversion.md # Script conversion details + ├── installation-migration.md # Installation strategies + └── troubleshooting.md # Common issues +``` + +## Testing + +After installation, test the power: + +1. **Test activation:** + ``` + "Help me convert skills to powers" + ``` + Power should activate and provide overview. + +2. **Test steering files:** + ``` + "Show me the quick start guide" + ``` + Should load quick-start.md content. + +3. **Test specific queries:** + ``` + "How do I convert scripts to MCP tools?" + ``` + Should provide relevant guidance. + +## Contributing + +This power is based on comprehensive research comparing Claude Skills and Kiro Powers. If you find issues or have suggestions: + +1. Document the issue clearly +2. Provide examples if possible +3. Suggest improvements +4. Share your conversion experiences + +## Resources + +### Related Documentation +- [Claude Skills Official Docs](https://code.claude.com/docs/en/skills) +- [Kiro Powers Documentation](https://kiro.dev/docs/powers/) +- [MCP Protocol Specification](https://modelcontextprotocol.io/) + +### Tools +- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) +- [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) +- [MCP Servers Directory](https://mcpservers.org/) + +## License + +This power is provided as-is for educational and practical use in converting Claude Skills to Kiro Powers. + +## Version + +**Version:** 1.0.0 +**Last Updated:** 2026-01-04 +**Author:** Kiro Community + +--- + +**Ready to convert your Skills?** Install this power and start with the quick-start guide! diff --git a/convert-skills-to-power/steering/installation-migration.md b/convert-skills-to-power/steering/installation-migration.md new file mode 100644 index 0000000..57a7263 --- /dev/null +++ b/convert-skills-to-power/steering/installation-migration.md @@ -0,0 +1,534 @@ +# Installation and Migration Guide + +## Installation Mechanism Comparison + +### Claude Skills Installation + +**Process:** +``` +1. Create directory: mkdir ~/.claude/skills/my-skill +2. Create SKILL.md file +3. Add supporting files (optional) +4. Restart Claude Code +5. Wait for Skills to load +``` + +**Time:** 5-10 minutes (including restart) + +**Characteristics:** +- ❌ Manual file creation +- ❌ Requires restart +- ❌ No version management +- ❌ No dependency checking +- ❌ No official market + +### Kiro Powers Installation + +**Process:** +``` +1. Open Powers panel in Kiro +2. Search or browse Powers +3. Click "Install" +4. Configure if needed (API keys, etc.) +5. Use immediately +``` + +**Time:** 30 seconds - 1 minute + +**Characteristics:** +- ✅ One-click installation +- ✅ Immediate effect (no restart) +- ✅ Automatic version management +- ✅ Dependency detection +- ✅ Official marketplace + +## Installation Methods Comparison + +| Method | Claude Skills | Kiro Powers | +|--------|--------------|-------------| +| **Official Market** | ❌ None | ✅ kiro.dev | +| **GitHub** | Manual clone | ✅ URL import | +| **Local** | Copy files | ✅ Directory import | +| **Enterprise** | Admin config | ✅ Enterprise market | +| **CLI** | ❌ None | ✅ `kiro power install` | + +## Migration Strategies + +### Strategy 1: Gradual Migration (Recommended) + +**Best for:** Teams with many Skills, production environments + +**Approach:** +``` +Week 1-2: Convert 2-3 simple Skills + ├─ Test thoroughly + ├─ Gather feedback + └─ Refine process + +Week 3-4: Convert script-based Skills + ├─ Use Script Executor Pattern + ├─ Test MCP integration + └─ Document issues + +Week 5-6: Convert remaining Skills + ├─ Batch conversion + ├─ Team training + └─ Full deployment + +Week 7+: Maintenance and optimization + ├─ Monitor performance + ├─ Collect feedback + └─ Iterate improvements +``` + +**Benefits:** +- Lower risk +- Time to learn +- Feedback incorporation +- Team adaptation + +### Strategy 2: Big Bang Migration + +**Best for:** Small teams, few Skills, non-critical environments + +**Approach:** +``` +Day 1: Convert all Skills + ├─ Use automated tools + ├─ Batch conversion + └─ Quick testing + +Day 2: Deploy and test + ├─ Install all Powers + ├─ Functional testing + └─ Fix critical issues + +Day 3+: Refinement + ├─ Address feedback + ├─ Optimize performance + └─ Update documentation +``` + +**Benefits:** +- Fast completion +- Clean cutover +- Immediate benefits + +**Risks:** +- Higher initial disruption +- More issues at once +- Less learning time + +### Strategy 3: Hybrid Approach + +**Best for:** Medium teams, mixed Skill complexity + +**Approach:** +``` +Phase 1: Critical Skills (Week 1-2) + └─ Convert most-used Skills first + +Phase 2: Script-based Skills (Week 3-4) + └─ Focus on MCP conversion using Script Executor Pattern + +Phase 3: Remaining Skills (Week 5-6) + └─ Batch convert simple Skills + +Phase 4: Optimization (Week 7+) + └─ Refine and improve +``` + +## Team Migration Checklist + +### Pre-Migration (1-2 weeks before) + +- [ ] Audit all existing Skills +- [ ] Identify dependencies +- [ ] Prioritize conversion order +- [ ] Set up conversion environment +- [ ] Train conversion team +- [ ] Create backup of Skills +- [ ] Communicate plan to team + +### During Migration + +- [ ] Convert Skills to Powers +- [ ] Test each Power thoroughly +- [ ] Document conversion decisions +- [ ] Track issues and solutions +- [ ] Update team documentation +- [ ] Provide training sessions +- [ ] Gather feedback continuously + +### Post-Migration + +- [ ] Monitor Power usage +- [ ] Collect performance metrics +- [ ] Address feedback +- [ ] Optimize as needed +- [ ] Update documentation +- [ ] Share lessons learned +- [ ] Plan future improvements + +## Installation Workflows + +### Workflow 1: Individual Developer + +**Installing a Power:** +``` +1. Open Kiro IDE +2. Click Kiro icon → Powers +3. Search for Power +4. Click "Install" +5. Configure if prompted +6. Start using immediately +``` + +**Installing from GitHub:** +``` +1. Open Powers panel +2. Click "Import from GitHub" +3. Enter URL: https://github.com/user/power +4. Click "Import" +5. Power installs automatically +``` + +**Installing from Local:** +``` +1. Open Powers panel +2. Click "Import from Folder" +3. Select Power directory +4. Click "Import" +5. Power installs immediately +``` + +### Workflow 2: Team Distribution + +**Option A: GitHub Repository** +```bash +# 1. Create team Powers repository +git init team-powers +cd team-powers + +# 2. Add converted Powers +cp -r ../converted-powers/* ./ + +# 3. Push to GitHub +git add . +git commit -m "Add team Powers" +git remote add origin https://github.com/team/powers +git push -u origin main + +# 4. Share with team +# Team members install via GitHub URL +``` + +**Option B: Internal Package Registry** +```bash +# 1. Package Powers +tar -czf team-powers.tar.gz converted-powers/ + +# 2. Upload to internal registry +# (Company-specific process) + +# 3. Team installs from registry +kiro power install internal://team-powers +``` + +### Workflow 3: Enterprise Deployment + +**Setup Enterprise Market:** +``` +1. Access enterprise control panel +2. Create private market +3. Upload Powers +4. Configure permissions: + - Mandatory Powers (auto-install) + - Recommended Powers (suggested) + - Restricted Powers (blocked) +5. Set update policies +6. Enable usage tracking +``` + +**User Experience:** +``` +1. User opens Kiro +2. Mandatory Powers auto-install +3. Recommended Powers show notification +4. User can browse enterprise market +5. Updates apply automatically +``` + +## Version Management + +### Claude Skills (Manual) + +```bash +# No built-in versioning +# Manual approach: + +# 1. Tag in Git +git tag v1.0.0 +git push --tags + +# 2. Users manually update +cd ~/.claude/skills/my-skill +git pull +# Restart Claude Code +``` + +### Kiro Powers (Automatic) + +```bash +# Check for updates +kiro power list +# Shows: my-power v1.0.0 → v1.2.0 available + +# Update single Power +kiro power update my-power + +# Update all Powers +kiro power update --all + +# Rollback if needed +kiro power install my-power@1.0.0 +``` + +## Dependency Management + +### Claude Skills + +**Manual approach:** +```markdown +# In SKILL.md +## Dependencies +- Python 3.8+ +- PyPDF2: `pip install PyPDF2` +- Pillow: `pip install Pillow` + +## Installation +```bash +pip install -r requirements.txt +``` +``` + +**User must:** +- Read documentation +- Install dependencies manually +- Verify versions +- Troubleshoot conflicts + +### Kiro Powers + +**Automatic approach:** +```yaml +# In POWER.md frontmatter +dependencies: + system: + - python: ">=3.8" + python: + - PyPDF2: "^2.0.0" + - Pillow: "~8.3.0" + powers: + - name: file-utils + version: "^1.0.0" +``` + +**System handles:** +- Dependency detection +- Automatic installation +- Version validation +- Conflict resolution + +## Performance Comparison + +### Context Usage + +**Claude Skills:** +``` +All Skills loaded at startup +├─ Skill 1: 2KB +├─ Skill 2: 5KB +├─ Skill 3: 3KB +├─ Skill 4: 8KB +└─ Skill 5: 4KB +Total: 22KB always in context +``` + +**Kiro Powers:** +``` +Powers loaded on-demand +├─ Power 1: Activated → 2KB +├─ Power 2: Not used → 0KB +├─ Power 3: Activated → 3KB +├─ Power 4: Not used → 0KB +└─ Power 5: Activated → 4KB +Total: 9KB (59% reduction) +``` + +### Startup Time + +| Metric | Claude Skills | Kiro Powers | +|--------|--------------|-------------| +| **Initial Load** | All Skills | None | +| **Activation** | N/A | On keyword | +| **Deactivation** | N/A | Automatic | +| **Restart Required** | Yes | No | + +## Migration Timeline Example + +### Small Team (5 Skills) + +``` +Week 1: + Mon-Tue: Convert 2 simple Skills + Wed-Thu: Convert 2 script Skills + Fri: Convert 1 complex Skill + +Week 2: + Mon-Tue: Test all Powers + Wed: Deploy to team + Thu-Fri: Support and fixes + +Total: 2 weeks +``` + +### Medium Team (15 Skills) + +``` +Week 1-2: Convert simple Skills (5) +Week 3-4: Convert script Skills (7) +Week 5-6: Convert complex Skills (3) +Week 7: Testing and refinement +Week 8: Deployment and training + +Total: 8 weeks +``` + +### Large Team (50+ Skills) + +``` +Month 1: Pilot (10 Skills) + ├─ Convert and test + ├─ Gather feedback + └─ Refine process + +Month 2-3: Main conversion (30 Skills) + ├─ Batch conversion + ├─ Parallel testing + └─ Gradual deployment + +Month 4: Remaining Skills (10+ Skills) + ├─ Complex conversions + ├─ Edge cases + └─ Final deployment + +Month 5+: Optimization + ├─ Performance tuning + ├─ User feedback + └─ Continuous improvement + +Total: 5+ months +``` + +## Cost-Benefit Analysis + +### Conversion Costs + +| Activity | Time per Skill | Cost Factor | +|----------|---------------|-------------| +| Simple conversion | 1-2 hours | Low | +| Script conversion | 2-4 hours | Medium | +| Complex conversion | 1-2 days | High | +| Testing | 30 min - 1 hour | Low | +| Documentation | 1-2 hours | Low | + +### Benefits + +| Benefit | Impact | Timeline | +|---------|--------|----------| +| Reduced context usage | 30-50% | Immediate | +| Faster installation | 10x faster | Immediate | +| Version management | High | Immediate | +| Team productivity | 20-40% | 1-3 months | +| Maintenance reduction | 50% | 3-6 months | + +### ROI Calculation + +``` +Example: 10 Skills, 5-person team + +Conversion Cost: +- 10 Skills × 3 hours avg = 30 hours +- 30 hours × $100/hour = $3,000 + +Monthly Benefit: +- Context savings: 8 hours/month +- Installation time: 2 hours/month +- Maintenance: 5 hours/month +- Total: 15 hours/month × $100/hour = $1,500/month + +ROI: 2 months to break even +Year 1 savings: $15,000 +``` + +## Best Practices + +### Communication + +1. **Announce Early** + - Share migration plan + - Explain benefits + - Address concerns + +2. **Provide Training** + - Powers overview + - Installation guide + - Troubleshooting tips + +3. **Gather Feedback** + - Regular check-ins + - Issue tracking + - Continuous improvement + +### Technical + +1. **Test Thoroughly** + - Functional testing + - Performance testing + - Integration testing + +2. **Document Everything** + - Conversion decisions + - Issues encountered + - Solutions applied + +3. **Monitor Performance** + - Context usage + - Activation patterns + - Error rates + +### Organizational + +1. **Phased Rollout** + - Start with volunteers + - Expand gradually + - Full deployment last + +2. **Support Plan** + - Dedicated support channel + - FAQ document + - Quick response team + +3. **Success Metrics** + - Adoption rate + - User satisfaction + - Performance improvements + +--- + +**Next Steps:** +- Choose migration strategy +- Create detailed timeline +- Communicate with team +- Begin conversion process diff --git a/convert-skills-to-power/steering/quick-start.md b/convert-skills-to-power/steering/quick-start.md new file mode 100644 index 0000000..50c1ef6 --- /dev/null +++ b/convert-skills-to-power/steering/quick-start.md @@ -0,0 +1,523 @@ +# Quick Start Guide: Convert Skills to Power + +## 5-Minute Decision Flow + +``` +Your Skill contains what? + │ + ├─ Only documentation/guidance ────────────────┐ + │ │ + ├─ Scripts (1-3 files) ────────────────────────┤ + │ │ + ├─ Scripts (4-10 files) ───────────────────────┤ + │ │ + ├─ Scripts (10+ files) ────────────────────────┤ + │ │ + └─ Uses allowed-tools ─────────────────────────┘ + │ + ▼ +┌────────────────────────────────────────────────────────┐ +│ Conversion Approach │ +├────────────────────────────────────────────────────────┤ +│ ✅ Simple Conversion (1-2 hours) │ +│ - Rename SKILL.md → POWER.md │ +│ - Add keywords field │ +│ - Move docs/ to steering/ │ +│ │ +│ 🔧 Dedicated MCP Server (2-4 hours) │ +│ - Create custom MCP server │ +│ - Migrate script logic to MCP tools │ +│ - Add mcpServers to frontmatter │ +│ │ +│ ⚡ Script Executor Pattern (3-5 hours) │ +│ - Create reusable script executor MCP │ +│ - Configure SCRIPTS dictionary │ +│ - Full control, zero external dependencies │ +│ │ +│ 🎨 Modular MCP Server (1-2 days) │ +│ - Organize scripts by category │ +│ - Create modular MCP architecture │ +│ - Best for 10+ scripts │ +│ │ +│ 🔐 Create MCP Server (4-8 hours) │ +│ - Analyze tool requirements │ +│ - Develop MCP server │ +│ - Implement permissions │ +└────────────────────────────────────────────────────────┘ +``` + +## Conversion Checklist + +### Phase 0: Understand Installation Differences (5 min) + +**Claude Skills Installation:** +- [ ] Manual file creation +- [ ] Requires restart +- [ ] No version management + +**Kiro Powers Installation:** +- [ ] IDE one-click or CLI command +- [ ] Immediate effect, no restart +- [ ] Automatic version management + +**Key Difference:** +``` +Claude Skills: Create files → Restart → Use (5-10 min) +Kiro Powers: Click install → Use immediately (30 sec) +``` + +### Phase 1: Evaluate (15 min) + +- [ ] List all your Skills +- [ ] Identify each Skill type: + - [ ] Pure documentation + - [ ] Contains scripts + - [ ] Uses allowed-tools + - [ ] External API integration +- [ ] Count scripts in each Skill +- [ ] Prioritize conversion order + +### Phase 2: Prepare (30 min) + +- [ ] Install MCP SDK + ```bash + pip install mcp + ``` +- [ ] Create output directory + ```bash + mkdir -p ./converted-powers + ``` +- [ ] Backup original Skills + ```bash + cp -r ~/.claude/skills ~/.claude/skills.backup + ``` + +### Phase 3: Convert (Varies by type) + +#### For Pure Documentation Skills (1-2 hours each) + +- [ ] Copy SKILL.md to POWER.md +- [ ] Transform frontmatter: + ```yaml + # Add + displayName: "Friendly Name" + keywords: [keyword1, keyword2] + + # Remove (if present) + model: ... + allowed-tools: ... + ``` +- [ ] Move documentation: + ```bash + mv docs/ steering/ + ``` +- [ ] Test activation in Kiro + +#### For Skills with Scripts (3-5 hours each) + +**Using Script Executor Pattern (Recommended for 4+ scripts):** + +- [ ] Create script_executor_mcp.py +- [ ] Configure SCRIPTS dictionary: + ```python + SCRIPTS = { + "script_name": { + "path": "scripts/script.py", + "description": "What it does", + "args": ["arg1"], + "timeout": 30 + } + } + ``` +- [ ] Copy scripts to Power directory +- [ ] Create mcp.json configuration +- [ ] Add MCP config to POWER.md: + ```yaml + mcpServers: + - my-scripts + ``` +- [ ] Test script execution + +**Using Dedicated MCP (For 1-3 scripts):** + +- [ ] Create MCP server file +- [ ] Migrate script logic to MCP tools +- [ ] Define tool schemas +- [ ] Implement tool handlers +- [ ] Test MCP server +- [ ] Update POWER.md + +### Phase 4: Test (30 min per Power) + +- [ ] Functional testing + - [ ] Keywords trigger correctly + - [ ] Tools work as expected + - [ ] Documentation links valid +- [ ] Performance testing + - [ ] Context loading time + - [ ] Dynamic loading/unloading +- [ ] Integration testing + - [ ] Compatible with other Powers + - [ ] Works in different projects + +### Phase 5: Deploy (15 min per Power) + +- [ ] Commit to version control + ```bash + git add converted-powers/ + git commit -m "Convert Skills to Powers" + ``` +- [ ] Install in Kiro + - [ ] Via IDE import + - [ ] Or copy to Powers directory +- [ ] Verify installation +- [ ] Update team documentation + +## Quick Examples + +### Example 1: Simple PR Review Skill (5 min) + +**Original Skill:** +```yaml +--- +name: pr-reviewer +description: Reviews pull requests for code quality +--- +# PR Review Skill +Check code style, tests, and security. +``` + +**Conversion:** +```bash +# 1. Create Power directory +mkdir -p converted-powers/pr-reviewer + +# 2. Convert frontmatter +cat > converted-powers/pr-reviewer/POWER.md << 'EOF' +--- +name: "pr-reviewer" +displayName: "PR Reviewer" +description: "Reviews pull requests for code quality" +keywords: ["pr", "pull request", "review", "code review"] +author: "Your Name" +--- +# PR Review Power +Check code style, tests, and security. +EOF + +# 3. Done! +``` + +### Example 2: PDF Processing with Scripts (3-4 hours) + +**Original Skill Structure:** +``` +skills/pdf-processor/ +├── SKILL.md +└── scripts/ + ├── extract.py + └── fill.py +``` + +**Conversion Steps:** +```bash +# 1. Create Power structure +mkdir -p converted-powers/pdf-processor/scripts +cp skills/pdf-processor/scripts/* converted-powers/pdf-processor/scripts/ + +# 2. Create Script Executor MCP +cat > converted-powers/pdf-processor/script_executor_mcp.py << 'EOF' +from mcp.server import Server +from mcp.types import Tool, TextContent +import subprocess +import sys +from pathlib import Path + +app = Server("pdf-scripts") + +SCRIPTS = { + "pdf_extract": { + "path": "scripts/extract.py", + "description": "Extract PDF form data", + "args": ["pdf_path"], + "timeout": 30 + }, + "pdf_fill": { + "path": "scripts/fill.py", + "description": "Fill PDF forms", + "args": ["template", "data", "output"], + "timeout": 30 + } +} + +@app.list_tools() +async def list_tools() -> list[Tool]: + tools = [] + for name, config in SCRIPTS.items(): + properties = {arg: {"type": "string"} for arg in config["args"]} + tools.append(Tool( + name=name, + description=config["description"], + inputSchema={ + "type": "object", + "properties": properties, + "required": config["args"] + } + )) + return tools + +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[TextContent]: + if name not in SCRIPTS: + return [TextContent(type="text", text=f"Unknown tool: {name}")] + + config = SCRIPTS[name] + cmd = [sys.executable, config["path"]] + [arguments[arg] for arg in config["args"]] + + result = subprocess.run(cmd, capture_output=True, text=True, timeout=config["timeout"]) + return [TextContent(type="text", text=result.stdout if result.returncode == 0 else result.stderr)] + +if __name__ == "__main__": + import asyncio + asyncio.run(app.run()) +EOF + +# 3. Create MCP configuration +cat > converted-powers/pdf-processor/mcp.json << 'EOF' +{ + "mcpServers": { + "pdf-scripts": { + "command": "python", + "args": ["script_executor_mcp.py"] + } + } +} +EOF + +# 4. Create POWER.md +cat > converted-powers/pdf-processor/POWER.md << 'EOF' +--- +name: "pdf-processor" +displayName: "PDF Processor" +description: "Extract and fill PDF forms" +keywords: ["pdf", "form", "extract", "fill"] +author: "Your Name" +mcpServers: + - pdf-scripts +--- +# PDF Processing Power + +## Tools +- **pdf_extract**: Extract form data +- **pdf_fill**: Fill PDF forms + +## Usage +"Extract data from contract.pdf" +"Fill template.pdf with this data" +EOF + +# 5. Test +cd converted-powers/pdf-processor +python script_executor_mcp.py +``` + +### Example 3: Batch Convert All Skills (1 hour) + +```bash +# 1. Download conversion tool +# (Assuming tool is available) + +# 2. Batch convert +for skill in ~/.claude/skills/*; do + skill_name=$(basename "$skill") + echo "Converting $skill_name..." + python skill_to_power_converter.py \ + "$skill/SKILL.md" \ + "./converted-powers/$skill_name" +done + +# 3. Review results +ls -la ./converted-powers/ + +# 4. Test each Power individually +``` + +## Common Commands + +### Conversion Commands + +```bash +# Convert single Skill +python skill_to_power_converter.py \ + ~/.claude/skills/my-skill/SKILL.md \ + ./converted-powers/my-skill + +# Batch convert +./batch_convert_skills.sh ~/.claude/skills ./converted-powers + +# Validate YAML +python -c "import yaml; yaml.safe_load(open('POWER.md').read().split('---')[1])" +``` + +### MCP Commands + +```bash +# Test Script Executor MCP +python script_executor_mcp.py + +# Test custom MCP server +python my_mcp_server.py + +# Validate MCP config +python -c "import json; print(json.load(open('mcp.json')))" +``` + +### Debugging Commands + +```bash +# Check Power structure +tree converted-powers/my-power/ + +# View frontmatter +head -n 20 converted-powers/my-power/POWER.md + +# Test script execution +python scripts/my_script.py --test + +# List MCP tools (in Kiro) +# Ask: "List all available MCP tools" +``` + +## Common Pitfalls + +### ❌ Pitfall 1: Moving Scripts to Hooks + +**Wrong:** +```bash +mv scripts/ hooks/ # ❌ Don't do this! +``` + +**Right:** +```bash +# Convert scripts to MCP tools +# Use Script Executor Pattern or create dedicated MCP +``` + +**Why:** Hooks are event-triggered, not on-demand like Skills scripts. + +### ❌ Pitfall 2: Forgetting Keywords + +**Wrong:** +```yaml +--- +displayName: My Power +description: Does something useful +# ❌ Missing keywords +--- +``` + +**Right:** +```yaml +--- +displayName: My Power +description: Does something useful +keywords: ["keyword1", "keyword2"] # ✅ Required! +--- +``` + +### ❌ Pitfall 3: Using Absolute Paths + +**Wrong:** +```json +{ + "scripts": { + "my_script": { + "path": "/absolute/path/script.py" // ❌ Absolute + } + } +} +``` + +**Right:** +```json +{ + "scripts": { + "my_script": { + "path": "scripts/script.py" // ✅ Relative + } + } +} +``` + +### ❌ Pitfall 4: Broad Keywords + +**Wrong:** +```yaml +keywords: ["test", "debug", "help", "api"] # ❌ Too generic +``` + +**Right:** +```yaml +keywords: ["pytest", "unit-test", "python-testing"] # ✅ Specific +``` + +**Why:** Generic keywords cause false activations and annoy users. + +## Progress Tracking Template + +```markdown +# Skills Conversion Progress + +## Statistics +- Total Skills: __ +- Converted: __ +- In Progress: __ +- Pending: __ + +## Detailed List + +| Skill Name | Type | Scripts | Approach | Status | Time | Notes | +|-----------|------|---------|----------|--------|------|-------| +| pr-reviewer | Doc | 0 | Simple | ✅ Done | 1h | - | +| pdf-processor | Scripts | 3 | Dedicated MCP | 🔄 In Progress | 3h | Testing | +| data-analyzer | Scripts | 8 | Script Executor | ⏳ Pending | 4h | - | +| code-formatter | Tools | 1 | Simple | ✅ Done | 0.5h | - | + +## Next Steps +1. [ ] Complete pdf-processor MCP server +2. [ ] Start data-analyzer conversion +3. [ ] Test all converted Powers +``` + +## Time Estimates + +| Skill Type | Conversion Time | Testing Time | Total | +|-----------|----------------|--------------|-------| +| Pure documentation | 1-2 hours | 30 min | 1.5-2.5 hours | +| 1-3 scripts (dedicated MCP) | 2-4 hours | 1 hour | 3-5 hours | +| 4-10 scripts (Script Executor) | 3-5 hours | 1 hour | 4-6 hours | +| 10+ scripts (modular MCP) | 1-2 days | 2-3 hours | 1.5-2.5 days | +| Complex integration | 2-5 days | 1 day | 3-6 days | + +## Success Criteria + +✅ **Conversion is successful when:** +- Power activates with correct keywords +- All tools/scripts work as expected +- Documentation is clear and complete +- No context performance issues +- Team can use it without training + +✅ **Ready to share when:** +- Thoroughly tested in multiple scenarios +- Documentation includes examples +- Common errors documented +- Version controlled +- Team feedback incorporated + +--- + +**Next Steps:** +- For detailed script conversion: Read `script-conversion.md` +- For installation migration: Read `installation-migration.md` +- For troubleshooting: Read `troubleshooting.md` diff --git a/convert-skills-to-power/steering/script-conversion.md b/convert-skills-to-power/steering/script-conversion.md new file mode 100644 index 0000000..5040d61 --- /dev/null +++ b/convert-skills-to-power/steering/script-conversion.md @@ -0,0 +1,2170 @@ +# Script Conversion Guide: Skills Scripts to MCP Tools + +## Critical Understanding + +**⚠️ IMPORTANT:** Skills scripts should be converted to **MCP tools**, NOT Hooks. + +### Why MCP Tools, Not Hooks? + +| Feature | Skills Scripts | MCP Tools ✅ | Hooks ❌ | +|---------|---------------|-------------|---------| +| **Execution Timing** | AI decides when | AI decides when | Event-triggered | +| **Trigger Method** | On-demand | On-demand | Automatic (file save, etc.) | +| **Context Usage** | Zero-context | Zero-context | May consume context | +| **Use Case** | Data processing, tools | Data processing, tools | Automation workflows | + +**Example:** +``` +Skills: "Extract data from PDF" → AI runs script when needed +MCP: "Extract data from PDF" → AI calls MCP tool when needed ✅ +Hooks: File saved → Automatically runs script ❌ (Wrong timing!) +``` + +## Conversion Strategy Selection + +### Decision Matrix + +``` +Number of scripts in your Skill? + │ + ├─ 1-3 scripts + │ └─→ Create Dedicated MCP Server + │ Time: 2-4 hours + │ Control: Full + │ Best for: Complex logic, type safety + │ + ├─ 4-10 scripts + │ └─→ Use Script Executor Pattern + │ Time: 3-5 hours + │ Control: Full, reusable + │ Best for: Multiple independent scripts + │ + └─ 10+ scripts + └─→ Modular MCP Server + Time: 1-2 days + Control: Full, scalable + Best for: Large script collections +``` + +## Method 1: Dedicated MCP Server (1-3 Scripts) + +### When to Use +- 1-3 scripts with complex logic +- Need type safety and validation +- Want full control over execution +- Scripts have interdependencies + +### ⚠️ CRITICAL: Kiro Powers File Restrictions + +**Kiro Powers can ONLY contain:** +- ✅ `POWER.md` +- ✅ `mcp.json` +- ✅ `steering/*.md` files + +**NOT allowed in Powers:** +- ❌ Python scripts (`.py`) +- ❌ JavaScript files (`.js`) +- ❌ Shell scripts (`.sh`) +- ❌ Binary executables +- ❌ Any other code files + +**Solution:** Install MCP server separately, Power only contains documentation and configuration pointing to the installed server. + +### Step-by-Step Guide + +#### Step 1: Analyze Original Script + +**Original Skills Script:** +```python +# scripts/pdf_extract.py +import sys +import json +from PyPDF2 import PdfReader + +def extract_form_data(pdf_path): + """Extract form fields from PDF""" + reader = PdfReader(pdf_path) + fields = reader.get_form_text_fields() + return fields + +if __name__ == "__main__": + result = extract_form_data(sys.argv[1]) + print(json.dumps(result)) +``` + +**Usage in Skills:** +```markdown +Use `scripts/pdf_extract.py` to extract form data: +```bash +python scripts/pdf_extract.py input.pdf +``` +``` + +#### Step 2: Create MCP Server + +**Create `pdf_mcp_server.py`:** +```python +from mcp.server import Server +from mcp.types import Tool, TextContent +import json +from PyPDF2 import PdfReader, PdfWriter + +app = Server("pdf-tools") + +@app.list_tools() +async def list_tools() -> list[Tool]: + """Define available tools""" + return [ + Tool( + name="extract_pdf_data", + description="Extract form field data from a PDF file", + inputSchema={ + "type": "object", + "properties": { + "pdf_path": { + "type": "string", + "description": "Path to the PDF file" + } + }, + "required": ["pdf_path"] + } + ), + Tool( + name="fill_pdf_form", + description="Fill a PDF form with provided data", + inputSchema={ + "type": "object", + "properties": { + "template_path": { + "type": "string", + "description": "Path to PDF template" + }, + "data": { + "type": "object", + "description": "Form data as key-value pairs" + }, + "output_path": { + "type": "string", + "description": "Path for output PDF" + } + }, + "required": ["template_path", "data", "output_path"] + } + ) + ] + +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[TextContent]: + """Handle tool execution""" + + if name == "extract_pdf_data": + # Original script logic here + reader = PdfReader(arguments["pdf_path"]) + fields = reader.get_form_text_fields() + return [TextContent( + type="text", + text=json.dumps(fields, indent=2) + )] + + elif name == "fill_pdf_form": + # Fill form logic + reader = PdfReader(arguments["template_path"]) + writer = PdfWriter() + writer.append(reader) + writer.update_page_form_field_values( + writer.pages[0], + arguments["data"] + ) + + with open(arguments["output_path"], "wb") as output: + writer.write(output) + + return [TextContent( + type="text", + text=f"PDF form filled: {arguments['output_path']}" + )] + + else: + return [TextContent( + type="text", + text=f"Unknown tool: {name}" + )] + +if __name__ == "__main__": + import asyncio + asyncio.run(app.run()) +``` + +#### Step 3: Install MCP Server Separately + +**IMPORTANT:** MCP server must be installed separately from the Power. + +```bash +# Create MCP server directory +mkdir -p ~/my-mcp-servers/pdf-tools-server +cd ~/my-mcp-servers/pdf-tools-server + +# Copy the MCP server file created in Step 2 +# Save pdf_mcp_server.py here + +# Install dependencies +pip install PyPDF2 mcp +``` + +#### Step 4: Create Power Directory (Only Documentation) + +**Create Power directory with ONLY allowed files:** + +```bash +mkdir -p ./powers/pdf-processor +cd ./powers/pdf-processor +``` + +**Create `mcp.json`** (points to installed MCP server): +```json +{ + "mcpServers": { + "pdf-tools": { + "command": "python", + "args": ["~/my-mcp-servers/pdf-tools-server/pdf_mcp_server.py"], + "env": { + "PYTHONPATH": "~/my-mcp-servers/pdf-tools-server" + } + } + } +} +``` + +**Create `POWER.md`:** +```markdown +--- +name: "pdf-processor" +displayName: "PDF Processor" +description: "Extract, fill, and merge PDF forms and documents" +keywords: ["pdf", "document", "form", "extract", "fill"] +author: "Your Name" +--- + +# PDF Processing Power + +## Installation + +**IMPORTANT:** This Power requires a separate MCP server installation. + +### Step 1: Install MCP Server + +```bash +# Clone or download the MCP server +git clone https://github.com/your-username/pdf-tools-server.git ~/my-mcp-servers/pdf-tools-server + +# Or manually create and copy files +mkdir -p ~/my-mcp-servers/pdf-tools-server +# Copy pdf_mcp_server.py to this directory +``` + +### Step 2: Install Dependencies + +```bash +cd ~/my-mcp-servers/pdf-tools-server + +# Install Python dependencies +pip install PyPDF2 mcp + +# If using Node.js scripts, install dependencies LOCALLY +# Create package.json first if needed +npm install +``` + +**CRITICAL: Node.js Dependencies** + +If your MCP server uses Node.js scripts: +- ✅ Install dependencies locally: `npm install package-name` +- ❌ Don't use global install: `npm install -g package-name` +- Scripts executed via subprocess need local node_modules + +### Step 3: Install the Power + +Install this Power through Kiro Powers panel. + +## Available Tools + +### extract_pdf_data +Extract form field data from PDF files. + +**Usage:** "Extract the form data from contract.pdf" + +**Parameters:** +- `pdf_path` (string, required): Path to the PDF file + +**Returns:** JSON object with form field data + +### fill_pdf_form +Fill PDF forms with structured data. + +**Usage:** "Fill template.pdf with {name: 'John', email: 'john@example.com'}" + +**Parameters:** +- `template_path` (string, required): Path to PDF template +- `data` (object, required): Form data as key-value pairs +- `output_path` (string, required): Path for output PDF + +**Returns:** Confirmation message with output path + +## MCP Server Location + +This power expects the MCP server to be installed at: +``` +~/my-mcp-servers/pdf-tools-server/ +``` + +If you install it elsewhere, update the path in mcp.json. + +## Troubleshooting + +### Error: MCP server not found + +**Solution:** Verify the MCP server is installed: +```bash +ls -la ~/my-mcp-servers/pdf-tools-server/pdf_mcp_server.py +``` +``` + +#### Step 5: Test + +```bash +# Test MCP server +python pdf_mcp_server.py + +# In another terminal, test with MCP client +# Or install Power in Kiro and test +``` + +### Complete Template + +**MCP Server Template:** +```python +from mcp.server import Server +from mcp.types import Tool, TextContent +import json + +app = Server("your-server-name") + +@app.list_tools() +async def list_tools() -> list[Tool]: + return [ + Tool( + name="tool_name", + description="What the tool does", + inputSchema={ + "type": "object", + "properties": { + "param1": { + "type": "string", + "description": "Parameter description" + } + }, + "required": ["param1"] + } + ) + ] + +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[TextContent]: + if name == "tool_name": + # Your script logic here + result = your_function(arguments["param1"]) + return [TextContent( + type="text", + text=json.dumps(result) + )] + + return [TextContent( + type="text", + text=f"Unknown tool: {name}" + )] + +if __name__ == "__main__": + import asyncio + asyncio.run(app.run()) +``` + +## Method 2: Script Executor Pattern (4-10 Scripts) + +### When to Use +- 4-10 independent scripts +- Scripts are relatively simple +- Want a reusable, maintainable pattern +- Need full control without external dependencies + +### ⚠️ CRITICAL: Kiro Powers File Restrictions + +**Kiro Powers can ONLY contain:** +- ✅ `POWER.md` +- ✅ `mcp.json` +- ✅ `steering/*.md` files + +**NOT allowed in Powers:** +- ❌ Python scripts (`.py`) +- ❌ JavaScript files (`.js`) +- ❌ Shell scripts (`.sh`) +- ❌ Binary executables +- ❌ Any other code files + +**This means:** Your MCP server and scripts MUST be installed separately from the Power. + +### Solution: Separate Installation + +**Two-part structure:** + +1. **MCP Server Package** (separate from Power) + - Contains: MCP server code, scripts, dependencies + - Location: User installs to `~/.kiro/mcp-servers/your-server/` + - Distribution: GitHub repo, npm package, or manual installation + +2. **Power Package** (only documentation) + - Contains: POWER.md, mcp.json, steering/*.md + - Location: Installed via Kiro Powers panel + - Purpose: Documentation and MCP server configuration + +### Overview + +The Script Executor Pattern is a proven approach that provides a generic script execution framework within your own MCP server. You maintain full control while getting the benefits of a reusable pattern. + +**Key Benefits:** +- ✅ No external dependencies +- ✅ Full control over execution +- ✅ Easy to customize +- ✅ Simple configuration +- ✅ Production-ready +- ✅ Complies with Kiro Powers restrictions + +### Step-by-Step Guide + +#### Step 1: Create Script Executor MCP Server + +**Create `script_executor_mcp.py`:** +```python +from mcp.server import Server +from mcp.types import Tool, TextContent +import subprocess +import json +from pathlib import Path +import sys + +app = Server("script-executor") + +# Configuration: Define your scripts here +SCRIPTS = { + "pdf_extract": { + "path": "scripts/pdf_extract.py", + "description": "Extract form data from PDF files", + "args": ["pdf_path"], + "timeout": 30 + }, + "pdf_fill": { + "path": "scripts/pdf_fill.py", + "description": "Fill PDF form with data", + "args": ["template_path", "data_json", "output_path"], + "timeout": 30 + }, + "pdf_merge": { + "path": "scripts/pdf_merge.py", + "description": "Merge multiple PDF files", + "args": ["pdf_paths", "output_path"], + "timeout": 60 + }, + "data_analyzer": { + "path": "scripts/analyze.py", + "description": "Analyze CSV data and generate report", + "args": ["csv_path", "output_format"], + "timeout": 60 + }, + "code_formatter": { + "path": "scripts/format_code.sh", + "description": "Format code files using team standards", + "args": ["file_path"], + "timeout": 10 + } +} + +@app.list_tools() +async def list_tools() -> list[Tool]: + """Generate tools from script configuration""" + tools = [] + + for name, config in SCRIPTS.items(): + # Build schema from args + properties = {} + required = [] + + for arg in config["args"]: + properties[arg] = { + "type": "string", + "description": f"Argument: {arg}" + } + required.append(arg) + + tools.append(Tool( + name=name, + description=config["description"], + inputSchema={ + "type": "object", + "properties": properties, + "required": required + } + )) + + return tools + +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[TextContent]: + """Execute script with arguments""" + + if name not in SCRIPTS: + return [TextContent( + type="text", + text=f"Error: Unknown script '{name}'" + )] + + config = SCRIPTS[name] + script_path = Path(config["path"]) + + # Verify script exists + if not script_path.exists(): + return [TextContent( + type="text", + text=f"Error: Script not found: {script_path}" + )] + + # Determine interpreter + if script_path.suffix == '.py': + cmd = [sys.executable, str(script_path)] + elif script_path.suffix == '.sh': + cmd = ["bash", str(script_path)] + else: + cmd = [str(script_path)] + + # Add arguments + for arg in config["args"]: + if arg in arguments: + cmd.append(str(arguments[arg])) + else: + return [TextContent( + type="text", + text=f"Error: Missing required argument '{arg}'" + )] + + try: + # Execute script + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=config["timeout"], + cwd=Path.cwd() + ) + + if result.returncode == 0: + return [TextContent( + type="text", + text=result.stdout if result.stdout else "Script completed successfully" + )] + else: + return [TextContent( + type="text", + text=f"Error (exit code {result.returncode}):\n{result.stderr}" + )] + + except subprocess.TimeoutExpired: + return [TextContent( + type="text", + text=f"Error: Script timeout after {config['timeout']} seconds" + )] + + except Exception as e: + return [TextContent( + type="text", + text=f"Error: {type(e).__name__}: {str(e)}" + )] + +if __name__ == "__main__": + import asyncio + asyncio.run(app.run()) +``` + +#### Step 2: Create MCP Server Directory (Separate from Power) + +**IMPORTANT:** MCP server and scripts go in a SEPARATE directory, NOT in the Power. + +```bash +# Create MCP server directory (outside of Power) +mkdir -p ~/my-mcp-servers/my-scripts-server +cd ~/my-mcp-servers/my-scripts-server + +# Copy MCP server file +# (Create script_executor_mcp.py from Step 1) + +# Create scripts directory +mkdir -p scripts + +# Copy all scripts from Skills +cp ~/.claude/skills/my-skill/scripts/* scripts/ + +# Make scripts executable +chmod +x scripts/*.sh +chmod +x scripts/*.py +``` + +**Directory structure:** +``` +~/my-mcp-servers/my-scripts-server/ +├── script_executor_mcp.py # MCP server +├── scripts/ # Your scripts +│ ├── script1.py +│ ├── script2.py +│ └── script3.sh +└── requirements.txt # Python dependencies +``` + +#### Step 3: Configure Your Scripts + +Edit the `SCRIPTS` dictionary in `script_executor_mcp.py`: + +```python +SCRIPTS = { + "your_script_name": { + "path": "scripts/your_script.py", # Relative path + "description": "What your script does", + "args": ["arg1", "arg2"], # Argument names + "timeout": 30 # Timeout in seconds + }, + # Add more scripts here +} +``` + +**CRITICAL: JavaScript Library Modules vs CLI Scripts** + +If your Skill includes JavaScript files, check if they are: + +1. **CLI Scripts** (can be executed directly) + - Has `if (require.main === module)` or similar entry point + - Can run with: `node script.js arg1 arg2` + - ✅ Can be used directly in SCRIPTS configuration + +2. **Library Modules** (exports functions, not executable) + - Ends with `module.exports = functionName;` + - Cannot be run directly from command line + - ❌ Needs a CLI wrapper script + +**CRITICAL: Python Library Modules vs CLI Scripts** + +Python scripts can also be library modules: + +1. **CLI Scripts** (can be executed directly) + - Has `if __name__ == "__main__": main()` + - Can run with: `python script.py arg1 arg2` + - ✅ Can be used directly in SCRIPTS configuration + +2. **Library Modules** (imports only, not executable) + - Has `if __name__ == "__main__": raise RuntimeError(...)` + - Or no `if __name__ == "__main__":` block at all + - Defines classes/functions for import by other scripts + - ❌ Should NOT be added to SCRIPTS configuration + +**Example: Detecting Library Modules** + +**JavaScript:** +```javascript +// This is a LIBRARY MODULE (not CLI) +async function html2pptx(htmlFile, pres, options = {}) { + // ... function code ... +} + +module.exports = html2pptx; // ← Exports function, no CLI entry +``` + +**Python:** +```python +# This is a LIBRARY MODULE (not CLI) +class BaseValidator: + def validate(self, data): + # ... validation code ... + +if __name__ == "__main__": + raise RuntimeError("This module should not be run directly.") +``` + +**Solution for JavaScript: Create CLI Wrapper** + +If you have a JavaScript library module, create a CLI wrapper script: + +```javascript +#!/usr/bin/env node +// html2pptx-cli.js - CLI wrapper for html2pptx library + +const fs = require('fs'); +const path = require('path'); + +// CRITICAL: Save original working directory BEFORE changing it +const originalCwd = process.cwd(); + +// Change to parent directory to find node_modules +const serverDir = path.join(__dirname, '..'); +process.chdir(serverDir); + +const pptxgen = require('pptxgenjs'); +const html2pptx = require(path.join(__dirname, 'html2pptx.js')); + +async function main() { + if (process.argv.length < 3) { + console.error('Usage: node html2pptx-cli.js '); + process.exit(1); + } + + const configPath = process.argv[2]; + + try { + const configData = JSON.parse(fs.readFileSync(configPath, 'utf8')); + const { html_files, output_file } = configData; + + // Convert relative paths to absolute based on original working directory + const absoluteHtmlFiles = html_files.map(f => + path.isAbsolute(f) ? f : path.join(originalCwd, f) + ); + const absoluteOutputFile = path.isAbsolute(output_file) ? + output_file : path.join(originalCwd, output_file); + + // Create presentation + const pptx = new pptxgen(); + pptx.layout = 'LAYOUT_16x9'; + + console.log(`Converting ${html_files.length} HTML slides...`); + + // Process each HTML file + for (let i = 0; i < absoluteHtmlFiles.length; i++) { + const htmlFile = absoluteHtmlFiles[i]; + console.log(` Processing slide ${i + 1}/${html_files.length}`); + await html2pptx(htmlFile, pptx); + } + + // Save presentation + await pptx.writeFile({ fileName: absoluteOutputFile }); + console.log(`✓ Successfully created ${absoluteOutputFile}`); + + } catch (error) { + console.error(`Error: ${error.message}`); + process.exit(1); + } +} + +main(); +``` + +**Key points for CLI wrappers:** +- **CRITICAL**: Save original working directory BEFORE calling process.chdir() +- Change to parent directory to find node_modules +- Convert relative paths to absolute (preserve original working directory) +- Provide clear progress output +- Handle errors properly + +Then configure the CLI wrapper in SCRIPTS: + +```python +SCRIPTS = { + "html2pptx": { + "path": "scripts/html2pptx-cli.js", # Use CLI wrapper, not library + "interpreter": "node", + "description": "Convert HTML slides to PowerPoint", + "args": ["config_file"], + "timeout": 300 + } +} +``` + +**Solution for Python: Skip Library Modules** + +Python library modules should NOT be added to SCRIPTS configuration. They are meant to be imported by other scripts. + +**Example: Correct SCRIPTS configuration** + +```python +SCRIPTS = { + # ✅ CLI scripts - include these + "validate": { + "path": "ooxml/scripts/validate.py", # Has main() entry point + "interpreter": "python", + "description": "Validate OOXML structure", + "args": ["directory", "original_file"], + "timeout": 60 + }, + + # ❌ Library modules - DO NOT include these + # "base_validator": { # Has RuntimeError in __main__ + # "path": "ooxml/scripts/validation/base.py", + # ... + # } +} +``` + +**How to identify what to include:** + +1. **Check the file:** + ```bash + tail -10 script.py + ``` + +2. **Look for:** + - ✅ `if __name__ == "__main__": main()` → Include in SCRIPTS + - ❌ `if __name__ == "__main__": raise RuntimeError(...)` → Skip + - ❌ No `if __name__ == "__main__":` block → Skip (pure library) + +3. **Test execution:** + ```bash + python script.py --help + # If it runs and shows usage, it's a CLI script + # If it raises RuntimeError or does nothing, it's a library + ``` + +**Summary:** +- **JavaScript library modules** → Create CLI wrapper +- **Python library modules** → Skip, don't add to SCRIPTS +- **Both CLI scripts** → Add directly to SCRIPTS + +#### Step 4: Create Power Directory (Separate from MCP Server) + +**Now create the Power directory with ONLY allowed files:** + +```bash +# Create Power directory +mkdir -p ./powers/my-power +cd ./powers/my-power +``` + +**Create `mcp.json`** (points to the MCP server location): +```json +{ + "mcpServers": { + "my-scripts": { + "command": "python", + "args": ["~/my-mcp-servers/my-scripts-server/script_executor_mcp.py"], + "env": { + "PYTHONPATH": "~/my-mcp-servers/my-scripts-server" + } + } + } +} +``` + +**Note:** Use absolute path to the MCP server file. + +#### Step 5: Create POWER.md + +```markdown +--- +name: "my-power" +displayName: "My Power" +description: "Collection of utility scripts for development" +keywords: ["scripts", "utilities", "tools"] +author: "Your Name" +--- + +# My Power + +## Installation + +**IMPORTANT:** This Power requires a separate MCP server installation. + +### Step 1: Install MCP Server + +```bash +# Clone or download the MCP server +git clone https://github.com/your-username/my-scripts-server.git ~/my-mcp-servers/my-scripts-server + +# Or manually create the directory and copy files +mkdir -p ~/my-mcp-servers/my-scripts-server +# Copy script_executor_mcp.py and scripts/ to this directory +``` + +### Step 2: Install Dependencies + +```bash +cd ~/my-mcp-servers/my-scripts-server + +# Install Python dependencies +pip install mcp +# Install any other Python dependencies your scripts need + +# If your scripts use Node.js, install dependencies LOCALLY +# IMPORTANT: Use npm install (not npm install -g) for script dependencies +npm install +# Or if you don't have package.json: +npm install package1 package2 package3 +``` + +**CRITICAL: Node.js Dependencies** + +If your MCP server executes Node.js scripts that require modules (like playwright, sharp, etc.): + +- ✅ **DO**: Install dependencies locally in the MCP server directory using `npm install` +- ❌ **DON'T**: Use `npm install -g` for script dependencies +- **Why**: Node.js scripts executed by subprocess cannot find globally installed modules + +**Example package.json for Node.js dependencies:** +```json +{ + "name": "my-scripts-server", + "version": "1.0.0", + "dependencies": { + "playwright": "^1.57.0", + "sharp": "^0.34.5", + "pptxgenjs": "^4.0.1" + } +} +``` + +Then run `npm install` to install all dependencies locally. + +### Step 3: Install the Power + +Install this Power through Kiro Powers panel. The mcp.json will automatically connect to your installed MCP server. + +## Available Scripts + +All scripts are executed with zero-context consumption through MCP. + +### pdf_extract +Extract form data from PDF files. +**Usage:** "Extract data from contract.pdf" + +### pdf_fill +Fill PDF forms with structured data. +**Usage:** "Fill template.pdf with this data: {name: 'John'}" + +### data_analyzer +Analyze CSV data and generate reports. +**Usage:** "Analyze sales_data.csv and output as JSON" + +## MCP Server Location + +This power expects the MCP server to be installed at: +``` +~/my-mcp-servers/my-scripts-server/ +``` + +If you install it elsewhere, update the path in mcp.json. + +## Troubleshooting + +### Error: MCP server not found + +**Solution:** Verify the MCP server is installed at the correct location: +```bash +ls -la ~/my-mcp-servers/my-scripts-server/script_executor_mcp.py +``` + +### Error: Permission denied + +**Solution:** Make sure scripts are executable: +```bash +chmod +x ~/my-mcp-servers/my-scripts-server/scripts/*.py +chmod +x ~/my-mcp-servers/my-scripts-server/scripts/*.sh +``` +``` + +#### Step 6: Test MCP Server (Before Installing Power) + +```bash +# Test MCP server directly +cd ~/my-mcp-servers/my-scripts-server +python script_executor_mcp.py + +# Should start without errors +# Press Ctrl+C to stop + +# Run test script (see Testing section) +python test_mcp_server.py +``` + +#### Step 7: Install Power in Kiro + +```bash +# Power directory structure (ONLY these files): +powers/my-power/ +├── POWER.md # Documentation +└── mcp.json # MCP server configuration +``` + +1. Open Kiro Powers panel +2. Add from local directory: `./powers/my-power` +3. Test by mentioning keywords in conversation + +### Final Directory Structure + +**Complete setup:** +``` +# MCP Server (separate location) +~/my-mcp-servers/my-scripts-server/ +├── script_executor_mcp.py +├── scripts/ +│ ├── script1.py +│ ├── script2.py +│ └── script3.sh +├── requirements.txt +└── test_mcp_server.py + +# Power (only documentation) +./powers/my-power/ +├── POWER.md +└── mcp.json +``` + +### Distribution Options + +**Option 1: GitHub Repository** +```bash +# Create repo for MCP server +cd ~/my-mcp-servers/my-scripts-server +git init +git add . +git commit -m "Initial commit" +git remote add origin https://github.com/your-username/my-scripts-server.git +git push -u origin main +``` + +Users install with: +```bash +git clone https://github.com/your-username/my-scripts-server.git ~/my-mcp-servers/my-scripts-server +``` + +**Option 2: npm Package** (if using Node.js) +```bash +# Publish to npm +npm publish +``` + +Users install with: +```bash +npm install -g my-scripts-server +``` + +Update mcp.json to use: +```json +{ + "mcpServers": { + "my-scripts": { + "command": "npx", + "args": ["-y", "my-scripts-server"] + } + } +} +``` + +**Option 3: Manual Installation** + +Provide a zip file with installation instructions in POWER.md. + +### Advantages of Script Executor Pattern + +| Aspect | Script Executor Pattern | External Tools | +|--------|------------------------|----------------| +| **Control** | ✅ Full | ⚠️ Limited | +| **Dependencies** | ✅ None | ❌ External | +| **Maintenance** | ✅ You control | ❌ Depends on others | +| **Customization** | ✅ Easy | ⚠️ Limited | +| **Reliability** | ✅ High | ⚠️ Unknown | +| **Security** | ✅ You audit | ⚠️ Trust required | + +### Customization Examples + +**Add error handling:** +```python +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[TextContent]: + try: + # ... execution code ... + except FileNotFoundError as e: + return [TextContent( + type="text", + text=f"Error: File not found - {str(e)}" + )] + except PermissionError as e: + return [TextContent( + type="text", + text=f"Error: Permission denied - {str(e)}" + )] +``` + +**Add logging:** +```python +import logging + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[TextContent]: + logger.info(f"Executing script: {name} with args: {arguments}") + # ... execution code ... +``` + +**Add validation:** +```python +def validate_arguments(script_name: str, arguments: dict) -> tuple[bool, str]: + """Validate arguments before execution""" + config = SCRIPTS[script_name] + + # Check all required args present + for arg in config["args"]: + if arg not in arguments: + return False, f"Missing required argument: {arg}" + + # Add custom validation + if script_name == "pdf_extract": + if not arguments["pdf_path"].endswith(".pdf"): + return False, "pdf_path must be a PDF file" + + return True, "" +``` + +## Method 3: Modular MCP Server (10+ Scripts) + +### When to Use +- 10+ scripts with mixed complexity +- Scripts organized by category/domain +- Want scalable architecture +- Need to balance maintainability and performance + +### Strategy + +Organize scripts into logical modules and create a modular MCP server architecture. + +**Organization Pattern:** +``` +Core Domain Scripts → Dedicated MCP Module +Utility Scripts → Utility MCP Module +Integration Scripts → Integration MCP Module +``` + +### Example Structure + +``` +my-power/ +├── POWER.md +├── mcp.json # Single MCP server config +├── modular_mcp_server.py # Main MCP server +├── modules/ # MCP modules +│ ├── __init__.py +│ ├── core_tools.py # Core business logic +│ ├── utility_tools.py # Utility functions +│ └── integration_tools.py # External integrations +└── scripts/ # Original scripts (if needed) + ├── core/ + ├── utils/ + └── integrations/ +``` + +### Step-by-Step Guide + +#### Step 1: Analyze and Categorize Scripts + +**Example categorization:** +``` +Core Business Logic (5 scripts): +- process_data.py +- generate_report.py +- validate_input.py +- transform_data.py +- export_results.py + +Utilities (4 scripts): +- format_output.py +- cleanup_temp.py +- log_activity.py +- send_notification.py + +Integrations (3 scripts): +- fetch_api_data.py +- upload_to_s3.py +- send_email.py +``` + +#### Step 2: Create Modular MCP Server + +**Create `modular_mcp_server.py`:** +```python +from mcp.server import Server +from mcp.types import Tool, TextContent +from modules import core_tools, utility_tools, integration_tools + +app = Server("modular-tools") + +@app.list_tools() +async def list_tools() -> list[Tool]: + """Aggregate tools from all modules""" + tools = [] + tools.extend(core_tools.get_tools()) + tools.extend(utility_tools.get_tools()) + tools.extend(integration_tools.get_tools()) + return tools + +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[TextContent]: + """Route tool calls to appropriate module""" + + # Try core tools + if name in core_tools.TOOL_NAMES: + return await core_tools.execute(name, arguments) + + # Try utility tools + if name in utility_tools.TOOL_NAMES: + return await utility_tools.execute(name, arguments) + + # Try integration tools + if name in integration_tools.TOOL_NAMES: + return await integration_tools.execute(name, arguments) + + return [TextContent( + type="text", + text=f"Unknown tool: {name}" + )] + +if __name__ == "__main__": + import asyncio + asyncio.run(app.run()) +``` + +#### Step 3: Create Module Files + +**Create `modules/core_tools.py`:** +```python +from mcp.types import Tool, TextContent +import subprocess +import sys +from pathlib import Path + +TOOL_NAMES = ["process_data", "generate_report", "validate_input"] + +SCRIPTS = { + "process_data": { + "path": "scripts/core/process_data.py", + "description": "Process input data and apply transformations", + "args": ["input_file", "output_file"], + "timeout": 60 + }, + "generate_report": { + "path": "scripts/core/generate_report.py", + "description": "Generate analysis report from processed data", + "args": ["data_file", "report_format"], + "timeout": 30 + }, + "validate_input": { + "path": "scripts/core/validate_input.py", + "description": "Validate input data against schema", + "args": ["input_file", "schema_file"], + "timeout": 10 + } +} + +def get_tools() -> list[Tool]: + """Return tool definitions""" + tools = [] + for name, config in SCRIPTS.items(): + properties = {arg: {"type": "string"} for arg in config["args"]} + tools.append(Tool( + name=name, + description=config["description"], + inputSchema={ + "type": "object", + "properties": properties, + "required": config["args"] + } + )) + return tools + +async def execute(name: str, arguments: dict) -> list[TextContent]: + """Execute core tool""" + if name not in SCRIPTS: + return [TextContent(type="text", text=f"Unknown core tool: {name}")] + + config = SCRIPTS[name] + script_path = Path(config["path"]) + + if not script_path.exists(): + return [TextContent(type="text", text=f"Script not found: {script_path}")] + + cmd = [sys.executable, str(script_path)] + cmd.extend([arguments[arg] for arg in config["args"]]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=config["timeout"] + ) + + if result.returncode == 0: + return [TextContent(type="text", text=result.stdout)] + else: + return [TextContent(type="text", text=f"Error: {result.stderr}")] + + except subprocess.TimeoutExpired: + return [TextContent(type="text", text=f"Timeout after {config['timeout']}s")] + except Exception as e: + return [TextContent(type="text", text=f"Error: {str(e)}")] +``` + +**Create `modules/utility_tools.py`:** +```python +from mcp.types import Tool, TextContent +import subprocess +import sys +from pathlib import Path + +TOOL_NAMES = ["format_output", "cleanup_temp", "log_activity"] + +SCRIPTS = { + "format_output": { + "path": "scripts/utils/format_output.py", + "description": "Format output data for display", + "args": ["input_file", "format_type"], + "timeout": 10 + }, + "cleanup_temp": { + "path": "scripts/utils/cleanup_temp.sh", + "description": "Clean up temporary files", + "args": ["directory"], + "timeout": 5 + }, + "log_activity": { + "path": "scripts/utils/log_activity.py", + "description": "Log activity to system log", + "args": ["message", "level"], + "timeout": 5 + } +} + +def get_tools() -> list[Tool]: + """Return tool definitions""" + tools = [] + for name, config in SCRIPTS.items(): + properties = {arg: {"type": "string"} for arg in config["args"]} + tools.append(Tool( + name=name, + description=config["description"], + inputSchema={ + "type": "object", + "properties": properties, + "required": config["args"] + } + )) + return tools + +async def execute(name: str, arguments: dict) -> list[TextContent]: + """Execute utility tool""" + if name not in SCRIPTS: + return [TextContent(type="text", text=f"Unknown utility tool: {name}")] + + config = SCRIPTS[name] + script_path = Path(config["path"]) + + if not script_path.exists(): + return [TextContent(type="text", text=f"Script not found: {script_path}")] + + # Determine command based on file extension + if script_path.suffix == '.py': + cmd = [sys.executable, str(script_path)] + elif script_path.suffix == '.sh': + cmd = ["bash", str(script_path)] + else: + cmd = [str(script_path)] + + cmd.extend([arguments[arg] for arg in config["args"]]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=config["timeout"] + ) + + if result.returncode == 0: + return [TextContent(type="text", text=result.stdout or "Success")] + else: + return [TextContent(type="text", text=f"Error: {result.stderr}")] + + except Exception as e: + return [TextContent(type="text", text=f"Error: {str(e)}")] +``` + +**Create `modules/__init__.py`:** +```python +"""MCP tool modules""" +from . import core_tools, utility_tools, integration_tools + +__all__ = ["core_tools", "utility_tools", "integration_tools"] +``` + +#### Step 4: Create MCP Configuration + +**Create `mcp.json`:** +```json +{ + "mcpServers": { + "modular-tools": { + "command": "python", + "args": ["modular_mcp_server.py"], + "env": { + "PYTHONPATH": "." + } + } + } +} +``` + +#### Step 5: Update POWER.md + +```markdown +--- +name: "data-processor" +displayName: "Data Processor" +description: "Comprehensive data processing toolkit with 12+ tools" +keywords: ["data", "processing", "analysis", "reporting"] +author: "Your Name" +mcpServers: + - modular-tools +--- + +# Data Processing Power + +## Tool Categories + +### Core Tools +- **process_data**: Process and transform input data +- **generate_report**: Generate analysis reports +- **validate_input**: Validate data against schemas + +### Utility Tools +- **format_output**: Format data for display +- **cleanup_temp**: Clean temporary files +- **log_activity**: Log system activities + +### Integration Tools +- **fetch_api_data**: Fetch data from external APIs +- **upload_to_s3**: Upload files to S3 +- **send_email**: Send email notifications + +## Usage Examples + +**Data Processing:** +"Process the sales_data.csv file and save to processed_sales.json" + +**Report Generation:** +"Generate a PDF report from processed_sales.json" + +**Validation:** +"Validate input.json against schema.json" + +## Installation + +```bash +pip install mcp +``` + +## Architecture + +This power uses a modular MCP server architecture for scalability and maintainability. +``` + +### Advantages of Modular Approach + +| Aspect | Modular MCP | Monolithic MCP | +|--------|-------------|----------------| +| **Organization** | ✅ Clear separation | ⚠️ Single file | +| **Maintainability** | ✅ Easy to update | ⚠️ Complex | +| **Scalability** | ✅ Add modules easily | ⚠️ File grows large | +| **Testing** | ✅ Test per module | ⚠️ Test everything | +| **Team Work** | ✅ Parallel development | ⚠️ Merge conflicts | + +### Best Practices for Modular MCP + +1. **Clear Module Boundaries** + - One domain per module + - Minimal inter-module dependencies + - Clear naming conventions + +2. **Consistent Module Structure** + ```python + # Each module should have: + TOOL_NAMES = [...] # List of tool names + SCRIPTS = {...} # Script configurations + get_tools() -> list # Tool definitions + execute() -> list # Tool execution + ``` + +3. **Error Handling** + ```python + # Consistent error handling across modules + try: + result = execute_script() + return [TextContent(type="text", text=result)] + except SpecificError as e: + return [TextContent(type="text", text=f"Error: {e}")] + ``` + +4. **Documentation** + ```python + # Document each module + """ + Core Tools Module + + Provides data processing and transformation tools. + + Tools: + - process_data: Main data processing + - generate_report: Report generation + - validate_input: Input validation + """ + ``` + +## Comparison: All Methods + +| Method | Scripts | Setup Time | Maintenance | Flexibility | Best For | +|--------|---------|-----------|-------------|-------------|----------| +| **Dedicated MCP** | 1-3 | 2-4h | Low | High | Complex logic | +| **Script Executor** | 4-10 | 3-5h | Low | Medium | Independent scripts | +| **Modular MCP** | 10+ | 1-2 days | Medium | High | Large collections | + +## Comparison: Dedicated vs Script Executor vs Modular + +| Aspect | Dedicated MCP | Script Executor | Modular MCP | +|--------|--------------|-----------------|-------------| +| **Setup Time** | 2-4 hours | 3-5 hours | 1-2 days | +| **Code Required** | Yes (Python/TS) | Yes (Python/TS) | Yes (Python/TS) | +| **Type Safety** | ✅ Full | ✅ Full | ✅ Full | +| **Validation** | ✅ Custom | ✅ Custom | ✅ Custom | +| **Performance** | ✅ Optimized | ✅ Good | ✅ Optimized | +| **Flexibility** | ✅ Full control | ✅ Full control | ✅ Full control | +| **Maintenance** | ⚠️ More code | ✅ Simple pattern | ✅ Modular | +| **Scalability** | ⚠️ Limited | ⚠️ Limited | ✅ Excellent | +| **Best For** | 1-3 complex scripts | 4-10 scripts | 10+ scripts | + +## Testing Your MCP Server + +**⚠️ CRITICAL:** After creating your MCP server, you MUST test it before deploying to ensure all tools work correctly. + +### Why Test? + +Testing your MCP server directly helps you: +- ✅ Verify all tools are registered correctly +- ✅ Validate tool schemas and parameters +- ✅ Catch missing dependencies early +- ✅ Ensure scripts execute properly +- ✅ Identify permission or path issues +- ✅ Confirm error handling works + +### Testing Strategy + +**Test in this order:** +1. **Server Startup** - Can the server start without errors? +2. **Tool Registration** - Are all tools listed correctly? +3. **Schema Validation** - Are parameter schemas valid? +4. **Tool Execution** - Can tools be called and do they respond? +5. **Error Handling** - Do errors get caught and reported properly? + +### Method 1: Create a Test Script (Recommended) + +Create a comprehensive test script that validates your MCP server. + +**Create `test_mcp_server.py`:** +```python +#!/usr/bin/env python3 +""" +Test script for MCP Server +Tests the MCP server by connecting to it and calling its tools +""" + +import asyncio +import json +import sys +from pathlib import Path + +# Add the current directory to the path +sys.path.insert(0, str(Path(__file__).parent)) + +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client + + +async def test_list_tools(): + """Test listing available tools from the MCP server""" + print("\n" + "="*60) + print("TEST 1: List Available Tools") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["your_mcp_server.py"], # Replace with your server file + env=None + ) + + async with stdio_client(server_params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + + # List tools + tools = await session.list_tools() + + print(f"\n✅ Found {len(tools.tools)} tools:") + for tool in tools.tools: + print(f"\n 📦 {tool.name}") + print(f" Description: {tool.description}") + print(f" Parameters: {json.dumps(tool.inputSchema, indent=6)}") + + return tools.tools + + +async def test_tool_schemas(): + """Test that all tool schemas are valid""" + print("\n" + "="*60) + print("TEST 2: Validate Tool Schemas") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["your_mcp_server.py"], + env=None + ) + + async with stdio_client(server_params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = await session.list_tools() + + for tool in tools.tools: + schema = tool.inputSchema + required = schema.get("required", []) + properties = schema.get("properties", {}) + + print(f"\n ✅ {tool.name}") + print(f" Required params: {required}") + print(f" All params: {list(properties.keys())}") + + +async def test_tool_execution(): + """Test calling a tool with mock parameters""" + print("\n" + "="*60) + print("TEST 3: Test Tool Execution") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["your_mcp_server.py"], + env=None + ) + + async with stdio_client(server_params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + + # Replace with your actual tool name and parameters + try: + result = await session.call_tool( + "your_tool_name", + arguments={ + "param1": "test_value" + } + ) + print(f"\n ✅ Tool executed successfully") + print(f" Response: {result}") + except Exception as e: + print(f"\n ⚠️ Tool call failed: {str(e)[:200]}") + print(f" (This may be expected if test data doesn't exist)") + + +async def test_server_lifecycle(): + """Test that the server can start and stop cleanly""" + print("\n" + "="*60) + print("TEST 4: Server Lifecycle") + print("="*60) + + server_params = StdioServerParameters( + command="python", + args=["your_mcp_server.py"], + env=None + ) + + print("\n Starting server...") + async with stdio_client(server_params) as (read, write): + print(" ✅ Server started successfully") + + async with ClientSession(read, write) as session: + print(" ✅ Session initialized") + await session.initialize() + + # Do a simple operation + tools = await session.list_tools() + print(f" ✅ Listed {len(tools.tools)} tools") + + print(" ✅ Session closed cleanly") + + print(" ✅ Server stopped cleanly") + + +async def main(): + """Run all tests""" + print("\n" + "="*60) + print("MCP SERVER TEST SUITE") + print("="*60) + print(f"Testing server at: {Path(__file__).parent / 'your_mcp_server.py'}") + + try: + # Test 1: List tools + await test_list_tools() + + # Test 2: Validate schemas + await test_tool_schemas() + + # Test 3: Test tool execution + await test_tool_execution() + + # Test 4: Server lifecycle + await test_server_lifecycle() + + print("\n" + "="*60) + print("✅ ALL TESTS COMPLETED") + print("="*60) + print("\nSummary:") + print(" ✅ MCP server starts successfully") + print(" ✅ All tools are registered") + print(" ✅ Tool schemas are valid") + print(" ✅ Tools are callable") + print(" ✅ Server lifecycle works correctly") + print("\n🎉 The MCP server is working properly!") + + except Exception as e: + print("\n" + "="*60) + print("❌ TEST FAILED") + print("="*60) + print(f"\nError: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) +``` + +**Run the test:** +```bash +# Make sure you have the MCP client library +pip install mcp + +# Run the test script +python test_mcp_server.py +``` + +**Expected output:** +``` +============================================================ +MCP SERVER TEST SUITE +============================================================ +Testing server at: /path/to/your_mcp_server.py + +============================================================ +TEST 1: List Available Tools +============================================================ + +✅ Found 5 tools: + + 📦 tool1 + Description: What tool1 does + Parameters: {...} + + 📦 tool2 + Description: What tool2 does + Parameters: {...} + +... + +============================================================ +✅ ALL TESTS COMPLETED +============================================================ + +🎉 The MCP server is working properly! +``` + +### Method 2: Manual Testing with MCP Inspector + +If you prefer interactive testing, use the MCP Inspector tool: + +```bash +# Install MCP Inspector +npm install -g @modelcontextprotocol/inspector + +# Run your MCP server with inspector +mcp-inspector python your_mcp_server.py +``` + +This opens a web interface where you can: +- See all registered tools +- Inspect tool schemas +- Call tools with custom parameters +- View responses in real-time + +### Method 3: Quick Smoke Test + +For a quick validation, run the server directly: + +```bash +# Start the server +python your_mcp_server.py + +# If it starts without errors, that's a good sign +# Press Ctrl+C to stop +``` + +**What to look for:** +- ✅ No import errors +- ✅ No syntax errors +- ✅ Server starts and waits for input +- ❌ Any error messages or stack traces + +### Common Test Failures and Solutions + +#### Test Failure: ModuleNotFoundError + +**Error:** +``` +ModuleNotFoundError: No module named 'mcp' +``` + +**Solution:** +```bash +pip install mcp +``` + +#### Test Failure: Script Not Found + +**Error:** +``` +Error: Script not found at scripts/my_script.py +``` + +**Solution:** +```bash +# Verify script exists +ls -la scripts/my_script.py + +# Check path in MCP server code +# Use relative paths from the MCP server file location +``` + +#### Test Failure: Permission Denied + +**Error:** +``` +PermissionError: [Errno 13] Permission denied +``` + +**Solution:** +```bash +# Make scripts executable +chmod +x scripts/*.py +chmod +x scripts/*.sh +``` + +#### Test Failure: Missing Dependencies + +**Error:** +``` +ModuleNotFoundError: No module named 'PIL' +``` + +**Solution:** +```bash +# Install missing dependencies +pip install Pillow + +# Or create requirements.txt +cat > requirements.txt << 'EOF' +mcp>=1.0.0 +Pillow>=10.0.0 +# Add other dependencies +EOF + +pip install -r requirements.txt +``` + +### Testing Checklist + +Before considering your MCP server ready: + +- [ ] **Server starts without errors** +- [ ] **All expected tools are listed** +- [ ] **Tool schemas are valid JSON Schema** +- [ ] **Required parameters are marked correctly** +- [ ] **Optional parameters work as expected** +- [ ] **Tools can be called successfully** +- [ ] **Error messages are clear and helpful** +- [ ] **Server shuts down cleanly** +- [ ] **All dependencies are documented** +- [ ] **Scripts have correct permissions** + +### Integration Testing in Kiro + +After your MCP server passes standalone tests, test it in Kiro: + +1. **Install the Power** in Kiro Powers panel +2. **Activate the Power** by mentioning keywords +3. **Try using a tool** in conversation +4. **Verify the response** is correct +5. **Test error cases** (missing files, invalid params) + +**Example conversation:** +``` +You: "Use the pdf_extract tool to extract data from contract.pdf" +Kiro: [Calls MCP tool and returns result] +``` + +### Continuous Testing + +**Add testing to your workflow:** + +```bash +# Create a test script that runs before commits +cat > test.sh << 'EOF' +#!/bin/bash +echo "Testing MCP server..." +python test_mcp_server.py +if [ $? -eq 0 ]; then + echo "✅ Tests passed" +else + echo "❌ Tests failed" + exit 1 +fi +EOF + +chmod +x test.sh + +# Run before committing +./test.sh && git commit -m "Update MCP server" +``` + +### Documentation of Test Results + +**Create a test report:** + +```markdown +# MCP Server Test Report + +**Date:** 2026-01-04 +**Server:** my_mcp_server.py +**Tools:** 5 + +## Test Results + +✅ Server Startup: PASS +✅ Tool Registration: PASS (5/5 tools) +✅ Schema Validation: PASS +✅ Tool Execution: PASS +✅ Error Handling: PASS +✅ Server Lifecycle: PASS + +## Dependencies Verified + +- mcp==1.25.0 +- Pillow==12.1.0 +- python-pptx==1.0.2 + +## Issues Found + +None + +## Conclusion + +MCP server is ready for deployment. +``` + +--- + +## Best Practices + +### Script Organization + +``` +✅ Good Structure: +my-power/ +├── scripts/ +│ ├── category1/ +│ │ ├── script1.py +│ │ └── script2.py +│ └── category2/ +│ ├── script3.sh +│ └── script4.py +├── .mcp-config.json +└── POWER.md + +❌ Bad Structure: +my-power/ +├── script1.py # Scripts scattered +├── another_script.sh +├── random.py +└── POWER.md +``` + +### Error Handling + +**In Dedicated MCP:** +```python +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[TextContent]: + try: + if name == "process_data": + result = process(arguments["data"]) + return [TextContent(type="text", text=json.dumps(result))] + except FileNotFoundError as e: + return [TextContent( + type="text", + text=f"Error: File not found - {str(e)}" + )] + except Exception as e: + return [TextContent( + type="text", + text=f"Error: {type(e).__name__} - {str(e)}" + )] +``` + +**In Script Executor config:** +```python +# In script_executor_mcp.py SCRIPTS dictionary +SCRIPTS = { + "process_data": { + "path": "scripts/process.py", + "description": "Process data file", + "args": ["data_path"], + "timeout": 30 + } +} + +# Error handling is built into the executor +# Errors are automatically captured and returned +``` + +### Testing Strategy + +**Test Checklist:** +- [ ] Script executes successfully +- [ ] Arguments passed correctly +- [ ] Output format is correct +- [ ] Error handling works +- [ ] Timeout is appropriate +- [ ] Dependencies are available +- [ ] Permissions are correct + +**Test Script:** +```bash +#!/bin/bash +# test_scripts.sh + +echo "Testing MCP tools..." + +# Test each script +for script in pdf_extract pdf_fill pdf_merge; do + echo "Testing $script..." + # Add test command here +done + +echo "All tests passed!" +``` + +## Troubleshooting + +### Issue: Script Not Found + +**Error:** +``` +FileNotFoundError: [Errno 2] No such file or directory: 'scripts/my_script.py' +``` + +**Solution:** +```bash +# Check script exists +ls -la scripts/my_script.py + +# Verify path in config +cat .mcp-config.json | grep "my_script" -A 3 + +# Use relative path +{ + "path": "scripts/my_script.py" // ✅ Relative + // NOT: "/absolute/path/script.py" // ❌ Absolute +} +``` + +### Issue: Permission Denied + +**Error:** +``` +PermissionError: [Errno 13] Permission denied: 'scripts/script.sh' +``` + +**Solution:** +```bash +# Make scripts executable +chmod +x scripts/*.sh +chmod +x scripts/*.py + +# Verify permissions +ls -la scripts/ +``` + +### Issue: Timeout + +**Error:** +``` +TimeoutError: Script execution exceeded 30 seconds +``` + +**Solution:** +```json +{ + "scripts": { + "long_running": { + "path": "scripts/long.py", + "timeout": 300 // Increase timeout to 5 minutes + } + } +} +``` + +### Issue: Missing Dependencies + +**Error:** +``` +ModuleNotFoundError: No module named 'PyPDF2' +``` + +**Solution:** +```bash +# Install dependencies +pip install PyPDF2 + +# Or create requirements.txt +cat > requirements.txt << 'EOF' +PyPDF2==2.1.0 +mcp==1.0.0 +EOF + +pip install -r requirements.txt +``` + +--- + +**Next Steps:** +- Test your converted scripts thoroughly +- Document any script-specific requirements +- Share your Power with the team +- Read `installation-migration.md` for deployment strategies diff --git a/convert-skills-to-power/steering/troubleshooting.md b/convert-skills-to-power/steering/troubleshooting.md new file mode 100644 index 0000000..8d0251b --- /dev/null +++ b/convert-skills-to-power/steering/troubleshooting.md @@ -0,0 +1,660 @@ +# Troubleshooting Guide + +## Common Conversion Issues + +### Issue 1: Power Not Activating + +**Symptoms:** +- Mention keywords but Power doesn't load +- Power not appearing in available list +- No response when using expected triggers + +**Diagnostic Steps:** + +1. **Check Power installation** + ```bash + # Verify Power is installed + # Open Powers panel in Kiro + # Look for your Power in the list + ``` + +2. **Verify frontmatter** + ```bash + # Check POWER.md frontmatter + head -20 powers/my-power/POWER.md + + # Ensure keywords are present + # keywords: ["keyword1", "keyword2"] + ``` + +3. **Test keyword specificity** + ``` + # Try exact keyword match + "Use keyword1 to do something" + + # If still not working, keywords may be too generic + ``` + +**Solutions:** + +**Solution A: Fix Keywords** +```yaml +# Bad keywords (too generic) +keywords: ["test", "help", "debug"] + +# Good keywords (specific) +keywords: ["pytest", "unit-testing", "python-test"] +``` + +**Solution B: Validate YAML Syntax** +```bash +# Check YAML is valid +python -c " +import yaml +with open('powers/my-power/POWER.md') as f: + content = f.read() + frontmatter = content.split('---')[1] + yaml.safe_load(frontmatter) +print('✅ YAML is valid') +" +``` + +**Solution C: Reinstall Power** +``` +1. Open Powers panel +2. Find your Power +3. Click "Uninstall" +4. Click "Add Custom Power" +5. Select "Local Directory" +6. Choose Power directory +7. Click "Add" +``` + +### Issue 2: Scripts Not Converting to MCP Tools + +**Symptoms:** +- MCP tools not found +- "Tool not available" errors +- Script execution fails + +**Diagnostic Steps:** + +1. **Verify MCP configuration** + ```bash + # Check mcp.json exists + ls -la powers/my-power/mcp.json + + # Validate JSON syntax + cat powers/my-power/mcp.json | python -m json.tool + ``` + +2. **Check script paths** + ```bash + # Verify scripts exist + ls -la powers/my-power/scripts/ + + # Check paths in config + cat powers/my-power/.mcp-config.json + ``` + +3. **Test MCP server** + ```bash + # For Script Executor Pattern + cd powers/my-power + python script_executor_mcp.py + + # For custom MCP + python powers/my-power/my_mcp_server.py + ``` + +**Solutions:** + +**Solution A: Fix Script Paths** +```json +// Wrong (absolute path) +{ + "scripts": { + "my_script": { + "path": "/Users/john/scripts/script.py" // ❌ + } + } +} + +// Correct (relative path) +{ + "scripts": { + "my_script": { + "path": "scripts/script.py" // ✅ + } + } +} +``` + +**Solution B: Fix Permissions** +```bash +# Make scripts executable +chmod +x powers/my-power/scripts/*.sh +chmod +x powers/my-power/scripts/*.py + +# Verify +ls -la powers/my-power/scripts/ +``` + +**Solution C: Install Dependencies** +```bash +# Check script requirements +head -20 powers/my-power/scripts/my_script.py + +# Install missing packages +pip install required-package + +# Or use requirements.txt +pip install -r powers/my-power/requirements.txt +``` + +### Issue 3: Frontmatter Validation Errors + +**Symptoms:** +- "Invalid frontmatter" error +- Power won't install +- YAML parsing errors + +**Diagnostic Steps:** + +1. **Check frontmatter structure** + ```yaml + # Must start with --- on line 1 + --- + name: "power-name" + displayName: "Display Name" + description: "Description" + keywords: ["key1", "key2"] + --- + ``` + +2. **Validate required fields** + ```yaml + # Required fields: + name: "..." # ✅ Required + displayName: "..." # ✅ Required + description: "..." # ✅ Required + + # Optional fields: + keywords: [...] # Recommended + author: "..." # Optional + ``` + +3. **Check for invalid fields** + ```yaml + # These fields DO NOT exist: + version: "1.0.0" # ❌ Invalid + tags: ["tag1"] # ❌ Invalid + repository: "..." # ❌ Invalid + license: "MIT" # ❌ Invalid + ``` + +**Solutions:** + +**Solution A: Fix Structure** +```yaml +# Wrong +name: power-name # ❌ Missing quotes +keywords: key1, key2 # ❌ Not an array + +# Correct +name: "power-name" # ✅ Quoted +keywords: ["key1", "key2"] # ✅ Array +``` + +**Solution B: Remove Invalid Fields** +```yaml +# Before +--- +name: "my-power" +version: "1.0.0" # ❌ Remove this +tags: ["tag1"] # ❌ Remove this +--- + +# After +--- +name: "my-power" +displayName: "My Power" +description: "What it does" +keywords: ["keyword1"] +--- +``` + +**Solution C: Validate with Tool** +```bash +# Use Python to validate +python -c " +import yaml +import sys + +with open('powers/my-power/POWER.md') as f: + content = f.read() + parts = content.split('---') + if len(parts) < 3: + print('❌ Invalid frontmatter structure') + sys.exit(1) + + try: + meta = yaml.safe_load(parts[1]) + required = ['name', 'displayName', 'description'] + for field in required: + if field not in meta: + print(f'❌ Missing required field: {field}') + sys.exit(1) + print('✅ Frontmatter is valid') + except yaml.YAMLError as e: + print(f'❌ YAML error: {e}') + sys.exit(1) +" +``` + +### Issue 4: MCP Server Connection Failures + +**Symptoms:** +- "MCP server not responding" +- "Connection refused" +- Tools timeout + +**Diagnostic Steps:** + +1. **Check MCP server status** + ```bash + # Test server manually + python -m mcp_script_runner.server + # Should start without errors + ``` + +2. **Verify configuration** + ```json + // Check mcp.json + { + "mcpServers": { + "my-server": { + "command": "python", // Correct command? + "args": ["server.py"], // Correct args? + "env": {} // Required env vars? + } + } + } + ``` + +3. **Check logs** + ```bash + # Look for error messages in Kiro logs + # (Location varies by OS) + ``` + +**Solutions:** + +**Solution A: Fix Command Path** +```json +// Wrong +{ + "command": "python3", // May not be in PATH + "args": ["server.py"] +} + +// Correct +{ + "command": "python", // Use standard name + "args": ["-m", "mcp_script_runner.server"] +} +``` + +**Solution B: Add Environment Variables** +```json +{ + "mcpServers": { + "my-server": { + "command": "python", + "args": ["server.py"], + "env": { + "PYTHONPATH": ".", + "API_KEY": "API_KEY_ENV_VAR" + } + } + } +} +``` + +**Solution C: Use Absolute Path** +```json +{ + "mcpServers": { + "my-server": { + "command": "/usr/bin/python3", + "args": ["/full/path/to/server.py"] + } + } +} +``` + +### Issue 5: Performance Degradation + +**Symptoms:** +- Kiro slower after installing Powers +- High memory usage +- Delayed responses + +**Diagnostic Steps:** + +1. **Check number of installed Powers** + ``` + # Open Powers panel + # Count installed Powers + # More than 10-15 may cause issues + ``` + +2. **Identify large Powers** + ```bash + # Check POWER.md sizes + find powers/ -name "POWER.md" -exec wc -l {} \; + + # Powers > 500 lines should use steering files + ``` + +3. **Review keyword specificity** + ```yaml + # Generic keywords cause false activations + keywords: ["test", "debug"] # ❌ Too broad + + # Specific keywords reduce false activations + keywords: ["pytest", "python-unittest"] # ✅ Specific + ``` + +**Solutions:** + +**Solution A: Uninstall Unused Powers** +``` +1. Review installed Powers +2. Identify rarely used ones +3. Uninstall unnecessary Powers +4. Keep only essential Powers +``` + +**Solution B: Split Large Powers** +```bash +# If POWER.md > 500 lines +# Move content to steering files + +mkdir powers/my-power/steering +# Move sections to separate files +# Update POWER.md to reference them +``` + +**Solution C: Refine Keywords** +```yaml +# Before (causes false activations) +keywords: ["api", "test", "data"] + +# After (more specific) +keywords: ["rest-api", "integration-test", "json-data"] +``` + +### Issue 6: Conversion Tool Errors + +**Symptoms:** +- Automated conversion fails +- Generated files incomplete +- Syntax errors in output + +**Diagnostic Steps:** + +1. **Validate input Skill** + ```bash + # Check SKILL.md format + head -30 ~/.claude/skills/my-skill/SKILL.md + + # Ensure frontmatter is valid + # Ensure content is readable + ``` + +2. **Check tool version** + ```bash + # Verify conversion tool is up to date + python skill_to_power_converter.py --version + + # Update if needed + git pull + ``` + +3. **Run with debug mode** + ```bash + # Enable verbose output + python skill_to_power_converter.py \ + --debug \ + input.md \ + output/ + ``` + +**Solutions:** + +**Solution A: Manual Conversion** +```bash +# If automated tool fails +# Convert manually using templates + +# 1. Copy template +cp templates/POWER.md.template powers/my-power/POWER.md + +# 2. Fill in manually +# Edit frontmatter +# Copy content from SKILL.md +# Adjust formatting +``` + +**Solution B: Fix Input Format** +```yaml +# Ensure SKILL.md has valid frontmatter +--- +name: my-skill +description: What it does +--- + +# Content starts here +``` + +**Solution C: Report Issue** +```bash +# Document the error +# Create minimal reproduction +# Report to tool maintainer +``` + +## Script-Specific Issues + +### Python Script Issues + +**Issue: Module Not Found** +```bash +# Error +ModuleNotFoundError: No module named 'PyPDF2' + +# Solution +pip install PyPDF2 + +# Or install all requirements +pip install -r requirements.txt +``` + +**Issue: Python Version** +```bash +# Error +SyntaxError: invalid syntax (Python 2.7) + +# Solution +# Use Python 3.8+ +python3 --version +# Update shebang in scripts +#!/usr/bin/env python3 +``` + +### Shell Script Issues + +**Issue: Command Not Found** +```bash +# Error +bash: jq: command not found + +# Solution (macOS) +brew install jq + +# Solution (Linux) +apt-get install jq +``` + +**Issue: Line Endings** +```bash +# Error +/bin/bash^M: bad interpreter + +# Solution +# Convert line endings +dos2unix scripts/*.sh + +# Or use sed +sed -i 's/\r$//' scripts/*.sh +``` + +## MCP-Specific Issues + +### Tool Not Found + +**Error:** +``` +Error: Tool 'my_tool' not found +``` + +**Solution:** +```python +# Check tool is registered +@app.list_tools() +async def list_tools() -> list[Tool]: + return [ + Tool( + name="my_tool", # Must match exactly + description="...", + inputSchema={...} + ) + ] +``` + +### Invalid Tool Schema + +**Error:** +``` +Error: Invalid tool schema +``` + +**Solution:** +```python +# Ensure schema is valid JSON Schema +Tool( + name="my_tool", + description="What it does", + inputSchema={ + "type": "object", + "properties": { + "param1": { + "type": "string", # Valid JSON Schema type + "description": "Parameter description" + } + }, + "required": ["param1"] # List required params + } +) +``` + +## Getting Help + +### Self-Help Resources + +1. **Check Documentation** + - Read POWER.md thoroughly + - Review steering files + - Check examples + +2. **Search Issues** + - GitHub issues + - Community forum + - Stack Overflow + +3. **Test Incrementally** + - Test each component + - Isolate the problem + - Verify assumptions + +### Community Support + +1. **Kiro Community Forum** + - Post detailed questions + - Include error messages + - Share minimal reproduction + +2. **GitHub Issues** + - Report bugs + - Request features + - Contribute fixes + +3. **Discord/Slack** + - Real-time help + - Quick questions + - Community discussion + +### Creating Good Bug Reports + +**Include:** +- Kiro version +- Power name and version +- Steps to reproduce +- Expected behavior +- Actual behavior +- Error messages +- Relevant configuration + +**Template:** +```markdown +## Bug Report + +**Environment:** +- Kiro Version: 1.0.0 +- OS: macOS 14.0 +- Power: my-power v1.0.0 + +**Steps to Reproduce:** +1. Install Power +2. Mention keyword "test" +3. Observe error + +**Expected:** +Power should activate + +**Actual:** +Error: "Tool not found" + +**Error Message:** +``` +[Full error message here] +``` + +**Configuration:** +```json +{ + "mcpServers": { + ... + } +} +``` +``` + +--- + +**Still having issues?** +- Review the main POWER.md +- Check other steering files +- Ask in community forum +- Report bugs on GitHub From 2066040bce511650be9f3d97d80ad14691065f0b Mon Sep 17 00:00:00 2001 From: catface Date: Sun, 18 Jan 2026 17:32:11 +0800 Subject: [PATCH 13/18] feat(requirements-analyst): Add requirements analyst power Co-Authored-By: Claude --- requirements-analyst/POWER.md | 212 ++++ requirements-analyst/mcp.json | 3 + .../steering/00-interaction-protocol.md | 173 ++++ .../steering/command-prototype.md | 187 ++++ .../steering/command-reverse.md | 467 +++++++++ .../steering/helper-diagram-standards.md | 556 +++++++++++ .../steering/helper-multi-role-validation.md | 187 ++++ .../steering/phase1-requirements-discovery.md | 245 +++++ .../phase2-requirements-value-sorting.md | 354 +++++++ .../steering/phase3-requirements-analysis.md | 932 ++++++++++++++++++ .../phase4-requirements-clarification.md | 461 +++++++++ .../phase5-requirements-validation.md | 711 +++++++++++++ .../phase6-requirements-specification.md | 370 +++++++ .../steering/template-analysis.md | 489 +++++++++ .../steering/template-clarification.md | 186 ++++ .../steering/template-data-model.md | 304 ++++++ .../steering/template-discovery.md | 123 +++ .../steering/template-openapi.md | 194 ++++ requirements-analyst/steering/template-prd.md | 889 +++++++++++++++++ requirements-analyst/steering/template-rtm.md | 181 ++++ .../steering/template-sort.md | 132 +++ .../steering/template-validation.md | 477 +++++++++ 22 files changed, 7833 insertions(+) create mode 100644 requirements-analyst/POWER.md create mode 100644 requirements-analyst/mcp.json create mode 100644 requirements-analyst/steering/00-interaction-protocol.md create mode 100644 requirements-analyst/steering/command-prototype.md create mode 100644 requirements-analyst/steering/command-reverse.md create mode 100644 requirements-analyst/steering/helper-diagram-standards.md create mode 100644 requirements-analyst/steering/helper-multi-role-validation.md create mode 100644 requirements-analyst/steering/phase1-requirements-discovery.md create mode 100644 requirements-analyst/steering/phase2-requirements-value-sorting.md create mode 100644 requirements-analyst/steering/phase3-requirements-analysis.md create mode 100644 requirements-analyst/steering/phase4-requirements-clarification.md create mode 100644 requirements-analyst/steering/phase5-requirements-validation.md create mode 100644 requirements-analyst/steering/phase6-requirements-specification.md create mode 100644 requirements-analyst/steering/template-analysis.md create mode 100644 requirements-analyst/steering/template-clarification.md create mode 100644 requirements-analyst/steering/template-data-model.md create mode 100644 requirements-analyst/steering/template-discovery.md create mode 100644 requirements-analyst/steering/template-openapi.md create mode 100644 requirements-analyst/steering/template-prd.md create mode 100644 requirements-analyst/steering/template-rtm.md create mode 100644 requirements-analyst/steering/template-sort.md create mode 100644 requirements-analyst/steering/template-validation.md diff --git a/requirements-analyst/POWER.md b/requirements-analyst/POWER.md new file mode 100644 index 0000000..a5374cc --- /dev/null +++ b/requirements-analyst/POWER.md @@ -0,0 +1,212 @@ +--- +name: "requirements-analyst" +displayName: "Requirements Analyst" +description: "6-phase requirements engineering: Discovery → Sort → Analysis → Clarification → Validation → Specification" +keywords: ["requirements", "PRD", "user stories", "MoSCoW", "FURPS+"] +author: "Kiro User" +--- + +# Requirements Analyst Power + +## General Principles + +1. **Cross-Platform**: Detect OS, use appropriate commands +2. **Intent-Based**: Instructions describe *what*, AI determines *how* +3. **Semantic Recognition**: Understand user intent, not keyword matching + +--- + +## Startup Flow + +### 1. Language Detection (AUTO) + +**Auto-detect language from user's input**: +- If user writes in Chinese → Use Chinese for all outputs +- If user writes in English → Use English for all outputs + +**Language applies to**: +- All conversation outputs +- All generated document content +- **ALL template headings, labels, and field names** + +### 2. Load Core Protocol + +After language confirmed, load `steering/00-interaction-protocol.md`. + +### 3. Spec Selection + +1. Check `.kiro/specs/` for existing spec folders +2. If exists: List specs with phase status, let user select or create new +3. If empty: Ask for new spec name (lowercase, alphanumeric, hyphens only) +4. Detect phase status: + - `reverse.md` → Reverse command done (can proceed to Phase 2 or 3) + - `discovery.md` → Phase 1 done + - `sort.md` → Phase 2 done + - `requirements.md` → Phase 3 done + - `clarification.md` → Phase 4 done + - `validation.md` → Phase 5 done + - `prd.md` → Phase 6 done +5. Suggest next phase based on status + +--- + +## Phase Intent Recognition + +Recognize user intent semantically → load corresponding phase file: + +| Phase | Intent | Steering File | +|-------|--------|---------------| +| Reverse | Extract requirements from existing code | `command-reverse.md` | +| 1 | Discover/collect requirements | `phase1-requirements-discovery.md` | +| 2 | Prioritize/sort by value | `phase2-requirements-value-sorting.md` | +| 3 | Analyze into stories/use cases | `phase3-requirements-analysis.md` | +| 4 | Clarify ambiguities | `phase4-requirements-clarification.md` | +| 5 | Validate quality | `phase5-requirements-validation.md` | +| 6 | Formalize into PRD | `phase6-requirements-specification.md` | + +**Rules**: +- If user has existing codebase without documentation → Reverse command +- If user provides raw requirements document → Phase 3 (no need to "discover") +- Skip completed phases based on existing files +- Ask if intent is ambiguous + +--- + +## Steering Files + +All in `steering/` directory: + +- `00-interaction-protocol.md` - Core interaction guidelines +- `command-*.md` - Auxiliary commands (reverse, prototype) +- `phase[1-6]-*.md` - Phase instructions +- `helper-*.md` - Standards (diagram, multi-role validation) +- `template-*.md` - Output templates + +--- + +## File Dependencies + +When loading a phase, also load its dependencies: + +| Phase | Output Template | Helper | Deliverables | +|-------|-----------------|--------|--------------| +| 1 | `template-discovery.md` | - | - | +| 2 | `template-sort.md` | - | - | +| 3 | `template-analysis.md`, `template-data-model.md` | `helper-diagram-standards.md` | - | +| 4 | `template-clarification.md` | - | - | +| 5 | `template-validation.md` | `helper-multi-role-validation.md` | - | +| 6 | `template-prd.md` | - | `template-openapi.md`, `template-rtm.md` | + +## ⛔ Context Loading Rule (MANDATORY) + +**CRITICAL**: Track loaded files in memory. NEVER reload files already in current conversation context. + +**DO**: +- ✅ Check if steering/template file was already loaded in this conversation +- ✅ Skip loading if file content is already in context +- ✅ Reference previously loaded content directly + +**DO NOT**: +- ❌ Reload the same steering file multiple times +- ❌ Reload the same template file multiple times +- ❌ Re-read files that are already in conversation context + +**Verification**: +- [ ] Before loading any file, confirm it's NOT already in context +- [ ] If already loaded, use existing content without re-reading + +--- + +### Execution Rules (MANDATORY) + +1. **Load Before Execute**: MUST load template + helper files BEFORE starting phase work (if not already loaded) +2. **Copy Then Edit Workflow**: + - First, copy template file to target location (e.g., `cp template-analysis.md .kiro/specs/[name]/requirements.md`) + - Then edit the copied file section by section using Edit tool + - This allows user to see progress immediately instead of waiting for full generation +3. **Section by Section**: Edit ONE section at a time, do NOT generate entire document at once +4. **Incremental Edit**: Complete each section before moving to the next +5. **Language Compliance**: Translate ALL template headings, labels, table headers, and field names to match user's input language. English templates are structure references only + +**Language Compliance Checklist (MANDATORY)**: +Before submitting ANY output, verify: +- [ ] User language detected: Chinese/English +- [ ] ALL headings translated to detected language +- [ ] ALL labels translated to detected language +- [ ] ALL field names translated to detected language +- [ ] ALL table headers translated to detected language +- [ ] NO mixed language content (Chinese user = 100% Chinese output) + +## ⛔ Phase Completion Prompt (MANDATORY) + +**CRITICAL**: After completing ANY phase, MUST prompt user with available next steps using AskUserQuestion tool. + +**DO**: +- ✅ Summarize what was completed in current phase +- ✅ List all valid next phase options +- ✅ Use AskUserQuestion tool to let user choose +- ✅ Wait for user selection before proceeding + +**DO NOT**: +- ❌ Auto-proceed to next phase without asking +- ❌ Only show one option when multiple are valid +- ❌ Skip the prompt and continue working +- ❌ Use text prompt instead of AskUserQuestion tool + +**Phase Flow Table**: + +| Completed | Next Options | Load Files (if iterating) | Notes | +|-----------|--------------|---------------------------|-------| +| Phase 1 | Phase 2 | - | - | +| Phase 2 | Phase 3 | - | - | +| Phase 3 | Phase 4 | - | - | +| Phase 4 | Phase 5, **Phase 3** | `clarification.md` | Re-analyze if scope changed | +| Phase 5 (Pass) | Phase 6 | - | All validations passed | +| Phase 5 (Fail: Authenticity) | **Phase 4** | `validation.md` | Need stakeholder confirmation | +| Phase 5 (Fail: Completeness-missing) | **Phase 3** | `validation.md` | Need to add requirements | +| Phase 5 (Fail: Completeness-unclear) | **Phase 4** | `validation.md` | Need to resolve ambiguities | +| Phase 5 (Fail: Consistency) | **Phase 3** | `validation.md` | Need to restructure | +| Phase 5 (Fail: Feasibility) | **Phase 3/4** | `validation.md` | Depends on issue type | +| Phase 5 (Fail: Verifiability) | **Phase 4** | `validation.md` | Need acceptance criteria | +| Phase 6 | Prototype, Complete | `.kiro/templates/` (if custom) | - | + +**Verification** (Check BEFORE completing phase): +- [ ] Phase deliverable file written to `.kiro/specs/` +- [ ] Summary of completed work prepared +- [ ] AskUserQuestion called with valid next options +- [ ] NOT proceeding until user responds + +--- + +## Auxiliary Commands + +| Command | Intent | Steering File | Description | +|---------|--------|---------------|-------------| +| Reverse | Extract requirements from code | `command-reverse.md` | Reverse engineer existing codebase to extract requirements | +| Prototype | Generate UI prototype | `command-prototype.md` | Create static HTML prototype from requirements | + +**Triggers**: +- **Reverse**: User says "逆向", "reverse", "提取需求", "extract requirements", "分析代码", "analyze codebase", "现有项目" +- **Prototype**: User says "原型", "prototype", "生成原型", "create prototype" + +--- + +## Output Structure + +``` +.kiro/specs/[spec-name]/ +├── reverse.md # From Reverse command (optional entry point) +├── discovery.md # Phase 1 +├── sort.md # Phase 2 +├── requirements.md # Phase 3 +├── data-model.md # Phase 3 +├── clarification.md # Phase 4 +├── validation.md # Phase 5 +├── prd.md # Phase 6 +├── api.yaml # Phase 6 +├── rtm.md # Phase 6 +└── prototype/ # Prototype command + ├── index.html + ├── css/ + └── pages/ +``` diff --git a/requirements-analyst/mcp.json b/requirements-analyst/mcp.json new file mode 100644 index 0000000..da39e4f --- /dev/null +++ b/requirements-analyst/mcp.json @@ -0,0 +1,3 @@ +{ + "mcpServers": {} +} diff --git a/requirements-analyst/steering/00-interaction-protocol.md b/requirements-analyst/steering/00-interaction-protocol.md new file mode 100644 index 0000000..fb09dc5 --- /dev/null +++ b/requirements-analyst/steering/00-interaction-protocol.md @@ -0,0 +1,173 @@ +--- +inclusion: always +--- + +# Interaction Protocol + +## Language Rule + +**Auto-detect language from user's input**: +- User writes in Chinese → All outputs in Chinese (including template headings, labels, field names) +- User writes in English → All outputs in English + +--- + +## Roles + +Two professional roles working together: + +- **Product Manager**: Starting from user needs, define product direction and feature scope +- **Requirements Analyst**: Transform product vision into detailed, executable requirement documents + +--- + +## Workflow Options + +### Complete Workflow (6 Phases) +For complex projects: +1. **Discovery** - Stakeholder interviews, personas, journey maps +2. **Value Sorting** - MoSCoW, RICE scoring, business value prioritization +3. **Analysis** - User stories, use cases, domain modeling +4. **Clarification** - Systematic questioning to eliminate ambiguity +5. **Validation** - Reviews, acceptance criteria, prototype testing +6. **Specification** - PRD writing, RTM, baseline management + +### Simplified Workflow (3 Phases) +For quick requirements: +1. **Understanding** - Capture and clarify what user wants +2. **Clarification** - Ask questions to eliminate ambiguity +3. **Validation** - Confirm understanding with acceptance criteria + +--- + +## Output Directory Structure + +``` +.kiro/specs/[feature-name]/ +├── discovery.md +├── sort.md +├── requirements.md +├── data-model.md +├── clarification.md +├── validation.md +├── prd.md +└── assets/ + ├── diagrams/ + └── attachments/ +``` + +**Naming Rules**: +- Directory: kebab-case (e.g., `user-authentication`, `payment-gateway`) +- Files: numbered prefix + phase name +- Diagrams: Mermaid syntax + +**When to Create**: +- Create directory when user starts a new requirement/feature +- Ask user to confirm feature name before creating +- Each phase appends to or creates its corresponding file + +--- + +## Core Principles + +### Product Manager Principles +- **User Value First**: All decisions centered on user value +- **MVP Mindset**: Define minimum viable product first, validate, then expand +- **Data-Driven**: Priority decisions based on data and user feedback +- **Clarification First**: When encountering ambiguity, clarify first, never assume + +### Requirements Analyst Principles +- **Completeness First**: Cover main flow, branch flows, and exception handling +- **No Ambiguity**: Descriptions must have only one interpretation +- **Verifiable**: Every requirement must have clear acceptance criteria (Given-When-Then) +- **Clear Boundaries**: Mark boundary conditions, null handling, concurrent scenarios + +--- + +## Core Rule: WAIT FOR USER INSTRUCTIONS + +**You are a guide, not an executor.** Do NOT automatically start doing requirements work. + +1. Understand what the user needs +2. Confirm the scope and phase +3. Guide them through the appropriate methodology +4. Execute ONLY when explicitly instructed + +--- + +## Response Decision Tree + +| User Input | Response | +|------------|----------| +| Just activated / No specific request | List phases, ask what they need | +| Vague request ("help with requirements") | Ask: What project? What phase? What help needed? | +| Has project context but no phase | Summarize understanding, suggest phase(s), wait for confirmation | +| Specifies phase + project | Confirm understanding, ask if ready, proceed only after "yes" | +| Shares existing documents | Read, summarize, suggest action, wait for instruction | +| Explicit instruction | Confirm scope, execute, stop and ask before doing more | + +--- + +## Prohibited Behaviors + +| ❌ Don't | ✅ Do Instead | +|----------|---------------| +| Auto-start example analysis | Ask what project user is working on | +| Generate sample requirements | Wait for user to provide context | +| Assume user wants full 6-phase | Ask which phase(s) they need | +| Proceed to next phase automatically | Ask if user wants to continue | +| Show lengthy explanations unprompted | Give concise options, expand on request | +| Make decisions for the user | Present options, let user choose | + +--- + +## Phase Transition Protocol + +When completing a phase, ALWAYS: +1. **Summarize** what was accomplished +2. **List** the deliverables created +3. **Ask** what user wants next: + - Continue to next phase? + - Refine current phase outputs? + - Pause and review? + - Something else? + +**NEVER** automatically start the next phase. + +--- + +## Handling User Requests + +### "Just do it" / "Go ahead" +Even with blanket permission, confirm scope: +- What specific scope +- What methods +- What outputs +Then check in at key decision points. + +### "I don't know which phase" +Help them figure out: +1. No clear idea of what to build? → Phase 1 +2. Have requirements list? → Phase 2-3 +3. Need to prioritize? → Phase 4 +4. Need to verify correctness? → Phase 5 +5. Need formal documentation? → Phase 6 + +### "Do everything" +Manage expectations: +- Full 6-phase: New products, major features, formal projects +- Lighter approach: Small features, quick iterations, internal tools +Ask about their situation to recommend appropriate rigor. + +--- + +## Remember + +**Your value is in guiding users through the right process, not generating content automatically.** + +A good requirements analyst: +- Listens first +- Asks clarifying questions +- Confirms understanding +- Executes precisely what's needed +- Checks in frequently diff --git a/requirements-analyst/steering/command-prototype.md b/requirements-analyst/steering/command-prototype.md new file mode 100644 index 0000000..f005d34 --- /dev/null +++ b/requirements-analyst/steering/command-prototype.md @@ -0,0 +1,187 @@ +--- +inclusion: agent +--- + +# Command: Prototype + +**Objective**: Generate static HTML prototype from requirements to visualize UI flows and validate user experience. + +--- + +## Quick Reference + +| Aspect | Guideline | +|--------|-----------| +| Input | `requirements.md` (user stories, use cases) | +| Output | `prototype/` directory with static HTML | +| Style | Clean, minimal CSS (no frameworks) | +| Generation | ONE page at a time | + +### STRICT: Pure Static Files Only + +**MUST**: +- Pure HTML + CSS only +- Open `index.html` directly in browser (file:// protocol) +- All links use relative paths +- Inline or local CSS (no CDN) + +**FORBIDDEN**: +- JavaScript (no .js files) +- External CDN/dependencies +- Server-side technology +- Build tools (npm, webpack, etc.) +- CSS frameworks (Bootstrap, Tailwind, etc.) + +--- + +## Pre-Check + +**MUST verify before starting**: + +- [ ] `requirements.md` exists with user stories +- [ ] User flows/use cases are documented +- [ ] Spec folder path confirmed + +**If check fails**: Ask user to complete Phase 3 first. + +--- + +## Output Structure (STRICT) + +``` +.kiro/specs/[spec-name]/prototype/ +├── index.html # ONLY index.html in root +├── css/ +│ └── style.css # Shared styles +└── pages/ + ├── [flow-1].html # ALL other HTML files MUST be here + ├── [flow-2].html + └── ... +``` + +### Directory Rules (MANDATORY) + +| Rule | Description | +|------|-------------| +| **index.html** | ONLY file in prototype root (besides css/) | +| **pages/** | ALL other HTML files MUST go here | +| **css/** | All CSS files here | + +**FORBIDDEN**: Creating HTML files outside `pages/` (except index.html) + +--- + +## Execution Flow + +### Step 1: Analyze Requirements + +Read `requirements.md` and extract: +- User stories with UI implications +- Use case flows (main + alternative) +- Data entities to display +- User actions/interactions + +### Step 2: Plan Pages + +List pages to generate based on flows: + +```markdown +## Prototype Plan + +| # | Page | Source | Description | +|---|------|--------|-------------| +| 1 | index.html | - | Navigation hub | +| 2 | [name].html | US-XXX | [Flow description] | +| ... | ... | ... | ... | + +Proceed with generation? (Y/N) +``` + +**Wait for user confirmation before generating.** + +### Step 3: Generate Shared CSS + +Create `prototype/css/style.css` with: +- Clean, minimal design +- Responsive layout +- Consistent color scheme +- Form and button styles +- Navigation styles + +### Step 4: Generate Pages (ONE AT A TIME) + +For each page: + +1. **Announce**: "Generating [page-name].html for [user-story]" +2. **Create HTML** with: + - Semantic HTML5 structure + - Link to shared CSS + - Navigation to other pages + - Mock data based on data model + - Interactive states (hover, active) + - Form inputs where applicable +3. **Write to file** immediately +4. **Confirm**: "Created [page-name].html" + +### Step 5: Generate Index + +Create `prototype/index.html`: +- List all prototype pages +- Brief description of each flow +- Links to all pages + +--- + +## HTML Requirements + +### Structure +```html + + + + + + [Page Title] - Prototype + + + + +
                +
                + + +``` + +### Content Guidelines +- Use realistic mock data (not "Lorem ipsum") +- Show all UI states (empty, loading, error, success) +- Include form validation hints +- Add comments linking to requirement IDs + +--- + +## Completion Report + +```markdown +## Prototype Generated + +**Location**: `.kiro/specs/[spec-name]/prototype/` + +### Pages Created + +| Page | Source | Status | +|------|--------|--------| +| index.html | - | Created | +| [page].html | US-XXX | Created | +| ... | ... | ... | + +### How to View + +Open `prototype/index.html` in a browser. + +### Next Steps + +- Review prototype with stakeholders +- Note feedback for requirement updates +- Return to Clarify/Analyze if changes needed +``` diff --git a/requirements-analyst/steering/command-reverse.md b/requirements-analyst/steering/command-reverse.md new file mode 100644 index 0000000..5a46d64 --- /dev/null +++ b/requirements-analyst/steering/command-reverse.md @@ -0,0 +1,467 @@ +--- +inclusion: agent +description: "Reverse engineering workflow - extract requirements from existing codebase" +keywords: ["reverse", "逆向", "extract", "codebase", "existing", "legacy", "现有代码", "提取需求"] +--- + +# Reverse Command + +**Command Objective**: Reverse engineer an existing codebase to extract and document requirements, enabling requirements analysis for legacy or undocumented projects. + +**Your Role**: Professional Requirements Analyst with Code Analysis Skills + +--- + +## Purpose + +Extract requirements from existing projects by: +- **Analyzing codebase**: Understand technology stack, architecture, and patterns +- **Extracting product context**: Identify purpose, users, and business logic +- **Documenting features**: Map functionality and user-facing capabilities +- **Synthesizing requirements**: Convert code analysis into structured requirements + +## When to Use + +- Onboarding to an existing project without documentation +- Adopting requirements methodology for legacy codebases +- Creating requirements documentation for undocumented projects +- Understanding unfamiliar codebases quickly +- Preparing for major refactoring or modernization +- Generating requirements baseline before enhancement projects + +## Prerequisites + +**Required**: +- An existing codebase to analyze +- Access to source files, configuration files, and package manifests + +**Helpful but optional**: +- Existing README or documentation +- Git history for context +- Running application for behavior observation +- Access to stakeholders who understand the system + +--- + +## Quick Reference + +| Step | Focus | Output | Critical? | +|------|-------|--------|-----------| +| 1. Project Discovery | Scan codebase structure | Project overview | ✅ Yes | +| 2. Tech Stack Analysis | Identify technologies | Technology inventory | ✅ Yes | +| 3. Architecture Analysis | Map structure & patterns | Architecture summary | ✅ Yes | +| 4. Product Context | Understand purpose & users | Product context summary | ✅ Yes | +| 5. Feature Extraction | Identify business features | Feature inventory | ✅ Yes | +| 6. Requirements Synthesis | Convert to requirements | Requirements list | ✅ Yes | +| 7. User Review | Validate with user | Confirmed requirements | ✅ Yes | + +--- + +## Output + +**File**: `.kiro/specs/[spec-name]/reverse.md` + +> After completion, user can proceed to Phase 2 (Sort) or Phase 3 (Analysis) with the extracted requirements. + +--- + +## Pre-Check (GATE CHECK) + +**MUST satisfy these conditions before starting**: + +| Check Item | Requirement | Status | +|-----------|-------------|--------| +| Codebase Access | MUST have read access to source code | [ ] | +| Project Scope | MUST identify analysis boundaries | [ ] | +| User Available | MUST have user available to validate findings | [ ] | + +**If check fails**: STOP. Resolve access issues before proceeding. + +--- + +## Operating Constraints + +**NON-DESTRUCTIVE**: This workflow only reads and analyzes; it generates new files but does NOT modify existing code. + +**USER CONFIRMATION**: All extracted requirements require user review and approval. + +**ITERATIVE REFINEMENT**: Generated requirements are drafts; expect multiple rounds of refinement with user input. + +**EVIDENCE-BASED**: Every requirement must trace back to specific code evidence. + +**MERMAID FIRST (MANDATORY)**: When documenting flows, processes, sequences, or relationships: +- **MUST** use Mermaid syntax as the primary representation +- **NEVER** use plain text descriptions as a substitute for diagrams +- Supported diagram types: + - `sequenceDiagram` - For API calls, service interactions, user journeys + - `flowchart` - For business logic, decision trees, process flows + - `erDiagram` - For data models and entity relationships + - `classDiagram` - For component structures and dependencies +- Plain text descriptions are supplementary only, not replacements + +--- + +## Execution Flow + +### Step 1: Project Discovery + +Scan the project to gather initial context: + +**File System Analysis**: +- Identify root directory and project boundaries +- Detect monorepo vs single project structure +- Find configuration files (package.json, pyproject.toml, Cargo.toml, etc.) +- Locate source directories and entry points + +**Version Control Analysis** (if available): +- Check git history for project age and activity +- Identify main contributors +- Review recent changes for active areas + +**Output**: Project overview summary for user confirmation + +```markdown +## Project Overview + +**Root**: [path] +**Type**: [monorepo/single-project/library/application] +**Primary Language**: [detected language] +**Package Manager**: [npm/pip/cargo/etc.] +**Age**: [first commit date if available] +**Activity**: [last commit, commit frequency] +``` + +### Step 2: Technology Stack Analysis + +Analyze dependencies and configuration to determine the tech stack: + +**Dependency Analysis**: +- Parse package manifests (package.json, requirements.txt, Cargo.toml, go.mod, etc.) +- Identify frameworks (React, Django, Spring, etc.) +- Detect testing frameworks +- Find build tools and CI/CD configuration + +**Configuration Analysis**: +- Parse config files (tsconfig.json, .eslintrc, pytest.ini, etc.) +- Identify linting and formatting tools +- Detect environment configuration patterns + +**Infrastructure Detection**: +- Find Dockerfile, docker-compose.yml +- Detect cloud provider configurations (AWS, GCP, Azure) +- Identify database configurations + +**Output**: Technology inventory + +### Step 3: Architecture Analysis + +Understand the project's architecture and patterns: + +**Directory Structure Analysis**: +- Map folder hierarchy +- Identify architectural patterns (MVC, Clean Architecture, Hexagonal, etc.) +- Detect module boundaries +- Find shared/common code locations + +**Code Pattern Detection**: +- Identify naming conventions (files, functions, classes) +- Detect API patterns (REST, GraphQL, gRPC) +- Find data access patterns (ORM, raw SQL, repositories) +- Identify error handling approaches + +**Dependency Graph**: +- Map internal module dependencies +- Identify circular dependencies +- Find entry points and core modules + +**Data Model Extraction** (MERMAID REQUIRED): +- Parse ORM models (Sequelize, TypeORM, Prisma, Django models, etc.) → generate `erDiagram` +- Analyze database migration files for schema structure → update `erDiagram` +- Extract TypeScript/Java/Python type definitions +- Identify foreign key relationships and constraints → reflect in `erDiagram` + +**Output**: Architecture summary with Mermaid diagrams + +### Step 4: Product Context Extraction + +Understand what the product does and who it serves: + +**Documentation Analysis**: +- Parse existing README files +- Extract from code comments and docstrings +- Review API documentation if present +- Check for user guides or wikis + +**Code Semantics Analysis**: +- Analyze route handlers/controllers for features +- Identify domain models and their relationships +- Extract business logic from service layers +- Detect user-facing functionality + +**Configuration Clues**: +- Environment variables for feature flags +- Localization files for user-facing text +- Permission/role configurations + +**Output**: Product context summary + +### Step 5: Feature Extraction + +Extract business features from code analysis: + +**Route/Endpoint Analysis**: +- Scan all HTTP endpoints +- Extract WebSocket handlers +- Identify background jobs/tasks +- Map event handlers + +**Business Logic Analysis**: +- Analyze service layer code +- Extract validation rules +- Identify business workflows +- Find authorization rules + +**User Interface Analysis** (if applicable): +- Map UI components to features +- Extract form fields and validations +- Identify user workflows +- Document navigation flows + +**Business Flow Extraction** (MERMAID REQUIRED): +- Scan route handlers for user-initiated flows → generate `sequenceDiagram` +- Trace service method call chains → generate `sequenceDiagram` +- Identify decision logic and branches → generate `flowchart` +- Map async/event-driven flows → generate `sequenceDiagram` with async notation + +**Service Interface Extraction**: +- Scan route definitions for all HTTP endpoints +- Parse OpenAPI/Swagger specs if available +- Identify WebSocket handlers and event emitters +- Document authentication requirements per endpoint +- Extract rate limiting configurations + +**Technical Debt Detection**: +- Scan for TODO, FIXME, HACK comments +- Identify deprecated code and APIs +- Find commented-out code blocks +- Detect inconsistent patterns suggesting rushed implementation + +**Output**: Feature inventory with code evidence + +```markdown +## Feature Inventory + +| Feature ID | Feature Name | Code Location | Evidence | +|------------|--------------|---------------|----------| +| F-001 | User Login | `src/auth/login.ts:45` | POST /api/login endpoint | +| F-002 | Data Export | `src/export/csv.ts:12` | exportToCSV function | +``` + +### Step 6: Requirements Synthesis + +Convert extracted features into requirements format: + +**For Each Feature**: +1. Identify the user need it serves +2. Extract functional behavior +3. Document constraints and validations +4. Identify non-functional aspects (performance, security) + +**Requirements Format**: + +```markdown +### REQ-001: [Requirement Name] + +**Source**: [Feature ID and code location] +**Type**: Functional / Non-Functional +**Priority**: [To be determined in Sort phase] + +**Description**: +[What the system does, derived from code analysis] + +**Evidence**: +- File: [path] +- Function/Class: [name] +- Behavior: [observed behavior] + +**Acceptance Criteria** (inferred): +- [ ] [Criterion derived from code] +- [ ] [Criterion derived from tests if available] + +**Notes**: +[Any uncertainties or assumptions marked with [INFERRED]] +``` + +### Step 7: User Review and Validation + +Present findings for user validation: + +```text +Reverse Engineering Complete +============================ + +Project: [PROJECT_NAME] +Language: [PRIMARY_LANGUAGE] +Framework: [MAIN_FRAMEWORK] +Type: [APPLICATION_TYPE] + +Analysis Summary: + - Files scanned: [N] + - Modules detected: [N] + - Features identified: [N] + - API endpoints found: [N] + - Requirements extracted: [N] + - Technical debt items: [N] + +Would you like to: + A) Review each requirement before saving + B) Save all and review later + C) Ask questions about specific findings + D) Re-analyze specific areas +``` + +**Interactive Refinement**: + +**Review Mode**: +- Display each extracted requirement section by section +- Allow user to approve, modify, or reject each item +- Mark uncertain items with [NEEDS CLARIFICATION] +- Incorporate user corrections into final output + +**Question Mode**: +- Answer questions about detected patterns +- Explain reasoning for specific conclusions +- Provide evidence from code for each assertion + +**Regeneration Mode**: +- Re-analyze specific aspects with user guidance +- Incorporate additional context provided by user +- Update extracted requirements with new information + +--- + +## Analysis Guidelines + +### Evidence-Based Conclusions + +- **Every requirement must have code evidence** +- Quote specific files and line numbers when possible +- Mark uncertain conclusions with [INFERRED] tag +- Distinguish between detected facts and assumptions + +### Handling Ambiguity + +- When patterns are inconsistent, document all variations +- Ask user to clarify when multiple interpretations exist +- Default to most common pattern when choosing conventions +- Mark areas needing user input with [NEEDS CLARIFICATION] + +### Scope Boundaries + +- Focus on primary application code, not vendored/generated code +- Skip node_modules, __pycache__, build artifacts +- Respect .gitignore patterns for exclusion +- Limit analysis depth for very large monorepos + +--- + +## Exit Criteria + +**CRITICAL**: Complete ALL items below to finish: + +| Exit Item | Qualification Standard | Status | +|-----------|----------------------|--------| +| **Project Overview** | Project scope and tech stack documented | [ ] | +| **Architecture Diagram** | At least one Mermaid diagram created | [ ] | +| **Feature Inventory** | All major features identified with evidence | [ ] | +| **Requirements List** | Requirements extracted (≥10 items for typical project) | [ ] | +| **Technical Debt** | TODO/FIXME/deprecated items catalogued | [ ] | +| **User Validation** | User has reviewed and confirmed findings | [ ] | + +--- + +## Output File Template + +Generate `.kiro/specs/[spec-name]/reverse.md`: + +```markdown +# Reverse Engineering Report + +## 1. Project Overview + +**Project**: [Name] +**Analyzed**: [Date] +**Scope**: [What was analyzed] + +## 2. Technology Stack + +| Category | Technology | +|----------|------------| +| Language | [e.g., TypeScript] | +| Framework | [e.g., React, Express] | +| Database | [e.g., PostgreSQL] | +| Testing | [e.g., Jest, Cypress] | + +## 3. Architecture + +[Mermaid diagram here] + +### Key Patterns +- [Pattern 1] +- [Pattern 2] + +## 4. Data Model + +[erDiagram here] + +## 5. Feature Inventory + +| ID | Feature | Location | Status | +|----|---------|----------|--------| +| F-001 | [Name] | [Path] | Confirmed | + +## 6. Extracted Requirements + +### Functional Requirements + +#### REQ-001: [Name] +... + +### Non-Functional Requirements + +#### NFR-001: [Name] +... + +## 7. Technical Debt & Known Issues + +| ID | Type | Location | Description | +|----|------|----------|-------------| +| TD-001 | TODO | [Path:Line] | [Description] | +| TD-002 | Deprecated | [Path] | [What is deprecated] | + +## 8. Gaps and Uncertainties + +- [Items marked INFERRED] +- [Items marked NEEDS CLARIFICATION] + +## 9. Recommended Next Steps + +1. Proceed to Phase 2 (Sort) to prioritize requirements +2. Or proceed to Phase 3 (Analysis) if priorities are clear +``` + +--- + +## Next Steps + +After completing this command: + +``` +Reverse engineering complete. + +Next, you can: +1. Run **Phase 2 (Sort)** to prioritize the extracted requirements +2. Run **Phase 3 (Analysis)** to analyze into user stories +3. Review and refine the extracted requirements manually +4. Share findings with stakeholders for validation +``` diff --git a/requirements-analyst/steering/helper-diagram-standards.md b/requirements-analyst/steering/helper-diagram-standards.md new file mode 100644 index 0000000..3a937b4 --- /dev/null +++ b/requirements-analyst/steering/helper-diagram-standards.md @@ -0,0 +1,556 @@ +--- +inclusion: agent +--- + +# Diagram and Documentation Standards + +This document defines the mandatory standards for UML diagrams and documentation format in requirements analysis. + +--- + +## Expression Priority (FUNDAMENTAL RULE) + +**ALWAYS follow this priority when expressing requirements:** + +``` +1st Priority: Diagram (Visual representation) + └── 2nd Priority: UML Diagram (Standard notation) + └── 3rd Priority: Mermaid Syntax (Generation method) +``` + +### Priority Matrix + +| Expression Method | Priority | Usage | +|-------------------|----------|-------| +| **UML Diagram (Mermaid)** | 🥇 Highest | Default choice - ALWAYS use first | +| **Other Diagrams (Mermaid)** | 🥈 Second | When UML type not applicable | +| **Table + Diagram** | 🥉 Third | Supplementary details only | +| **Text/Table only** | ❌ Avoid | Only when diagram is impossible | + +### UML Diagram Selection Guide + +| Requirement Type | UML Diagram | Mermaid Type | +|------------------|-------------|--------------| +| System interactions | Use Case Diagram | `graph TB` with actors | +| **Process flow** | **Activity Diagram** | **`stateDiagram-v2`** | +| Time-based interactions | Sequence Diagram | `sequenceDiagram` | +| **Domain model** | **Class Diagram** | **`classDiagram`** | +| **Data model** | **ER Diagram** | **`erDiagram`** | +| State transitions | State Diagram | `stateDiagram-v2` | +| Component structure | Component Diagram | `graph TB` with subgraphs | + +> ⚠️ **Class Diagram vs ER Diagram**: Do NOT mix their syntax! See sections 4 and 5 for correct usage. + +### Non-UML Diagram Guide + +| Visualization Type | Purpose | Mermaid Type | +|--------------------|---------|--------------| +| User Story Map | Release planning matrix | `graph TB` with subgraphs | +| Dependency Graph | Requirement relationships | `graph LR/TD` | +| Traceability | Mapping connections | `graph LR` | +| Mind Map | Brainstorming | `mindmap` | +| Timeline | Milestones | `timeline` | + +> **IMPORTANT**: For **user activity flows** and **business processes**, ALWAYS use `stateDiagram-v2` (UML Activity Diagram), NOT `graph` (flowchart). + +--- + +## ⛔ Mermaid Syntax Constraints (MANDATORY) + +**CRITICAL**: Mermaid has strict syntax rules. Violating these will cause parse errors. + +### Special Characters in Node Text + +| Character | Problem | Solution | +|-----------|---------|----------| +| `()` | Parsed as node shape | Use quotes: `["text (note)"]` | +| `[]` | Parsed as node shape | Use quotes: `["text [note]"]` | +| `{}` | Parsed as node shape | Use quotes: `["text {note}"]` | +| `<>` | Parsed as HTML/link | Use quotes or escape: `["text "]` | +| `/` | May cause issues | Use quotes: `["A/B"]` | + +### Node Definition Rules + +**DO**: +```mermaid +graph TD + A["External Library (G6/Cytoscape)"] + B["Config File [JSON]"] + C["Status {Active}"] +``` + +**DO NOT**: +``` +graph TD + A[External Library (G6/Cytoscape)] ❌ Parse error + B[Config File [JSON]] ❌ Parse error + C[Status {Active}] ❌ Parse error +``` + +### Text with Line Breaks + +**DO**: +```mermaid +graph TD + A["Line 1
                Line 2"] +``` + +**DO NOT**: +``` +graph TD + A[Line 1
                (Note)] ❌ Parentheses cause parse error +``` + +### Verification Checklist + +Before generating ANY Mermaid diagram, verify: +- [ ] All node text with special characters `()[]{}/<>` wrapped in quotes `""` +- [ ] No unescaped parentheses in node labels +- [ ] No unescaped brackets in node labels +- [ ] Line breaks `
                ` only used inside quoted strings + +--- + +## 1. UML Use Case Diagram Standards + +### MANDATORY Rules + +- **Actors**: Must use stick figure icon (not rectangles) +- **Use Cases**: Must use ellipse shape +- **System Boundary**: Must use dashed rectangle +- **Relationships**: Must use correct stereotypes + - `<>`: Mandatory dependency (always executed) + - `<>`: Optional extension (conditionally executed) + - `<>`: Inheritance relationship + +### ❌ PROHIBITED + +- Using simple flowcharts to represent use case diagrams +- Omitting system boundary +- Using incorrect relationship markers + +### Mermaid Syntax for Use Case Diagram + +```mermaid +graph TB + subgraph System["System Boundary"] + direction TB + UC1((Use Case 1)) + UC2((Use Case 2)) + UC3((Use Case 3)) + + UC1 -->|<>| UC2 + UC1 -.->|<>| UC3 + end + + Actor1[/"👤 Actor 1"\] + Actor2[/"👤 Actor 2"\] + + Actor1 --> UC1 + Actor2 --> UC2 + + style UC1 fill:#e1f5fe + style UC2 fill:#e1f5fe + style UC3 fill:#fff3e0 +``` + +--- + +## 2. Business Process Standards (Activity Diagram) + +### MANDATORY Rules + +- **Core user activity flows MUST use UML Activity Diagram** +- **Tables alone are NOT sufficient** - must have accompanying diagram +- **Parallel processing MUST be explicitly marked** using fork/join or `par` syntax +- **Decision points MUST use diamond shape** +- **Start/End MUST use standard notation** (filled circle / bull's eye) + +### Activity Diagram Syntax + +```mermaid +stateDiagram-v2 + [*] --> Activity1 + Activity1 --> Decision1 + + state Decision1 <> + Decision1 --> Activity2: [condition A] + Decision1 --> Activity3: [condition B] + + state ParallelProcessing { + direction LR + [*] --> Task1 + [*] --> Task2 + Task1 --> [*] + Task2 --> [*] + } + + Activity2 --> ParallelProcessing + Activity3 --> ParallelProcessing + ParallelProcessing --> Activity4 + Activity4 --> [*] +``` + +### Alternative: Flowchart with Swim Lanes + +```mermaid +flowchart TB + subgraph User["👤 User"] + A1[Start Request] + A4[Receive Result] + end + + subgraph System["System"] + A2[Process Request] + A3[Generate Response] + end + + A1 --> A2 + A2 --> A3 + A3 --> A4 +``` + +--- + +## 3. Use Case Main Flow Standards (Sequence Diagram) + +### MANDATORY Rules + +- **Use Case main flows MUST use Sequence Diagram** +- **Actor-System tables alone are NOT sufficient** +- **All key participants MUST be included**: User, UI, System, Agent, Database, External Services +- **Parallel execution MUST use `par` syntax** +- **Alternative flows use `alt` syntax** +- **Optional flows use `opt` syntax** + +### ❌ PROHIBITED + +Simple table format like: + +| Step | Actor | System | +|------|-------|--------| +| 1 | Action | | +| 2 | | Response | + +### ✅ REQUIRED + +```mermaid +sequenceDiagram + autonumber + + actor User as 👤 User + participant UI as 🖥️ Interface + participant System as ⚙️ System + participant Agent as 🤖 Agent + participant DB as 🗄️ Database + + User->>UI: 1. Initiate Request + activate UI + UI->>System: 2. Forward Request + activate System + + par Parallel Processing + System->>Agent: 3a. Analyze Request + Agent-->>System: 3a. Analysis Result + and + System->>DB: 3b. Query Data + DB-->>System: 3b. Return Data + end + + alt Success + System-->>UI: 4. Success Response + UI-->>User: 5. Display Result + else Failure + System-->>UI: 4. Error Response + UI-->>User: 5. Display Error + end + + deactivate System + deactivate UI +``` + +### Sequence Diagram Syntax Reference + +| Syntax | Purpose | Example | +|--------|---------|---------| +| `par ... and ... end` | Parallel execution | Concurrent operations | +| `alt ... else ... end` | Alternative flows | Success/failure paths | +| `opt ... end` | Optional flow | Conditional execution | +| `loop ... end` | Repeated execution | Iteration | +| `break ... end` | Exit flow | Exception handling | +| `activate/deactivate` | Lifeline activation | Active processing | + +--- + +## 4. Class Diagram Standards (Domain Model) + +### When to Use + +- **Domain modeling**: Core business entities and relationships +- **Data structure design**: Object attributes and methods +- **Inheritance hierarchies**: Class specialization + +### MANDATORY Rules + +- Use `classDiagram` syntax for object relationships +- Define attributes with visibility (`+` public, `-` private, `#` protected) +- Use correct relationship notation + +### Class Diagram Syntax + +```mermaid +classDiagram + class ResourceNode { + +String id + +String name + +ResourceType type + +getStatus() Status + } + + class ResourceType { + +String typeName + +String description + } + + class Agent { + +String agentId + +String version + +Status status + +start() void + +stop() void + } + + ResourceNode "1" -- "1" ResourceType : has + ResourceNode "1" -- "0..*" Agent : monitors + Agent <|-- MonitorAgent : extends + Agent <|-- CollectorAgent : extends +``` + +### Relationship Syntax Reference + +| Relationship | Syntax | Description | +|--------------|--------|-------------| +| Association | `A -- B` | Basic relationship | +| Association (labeled) | `A "1" -- "0..*" B : has` | With cardinality and label | +| Inheritance | `Parent <\|-- Child` | Generalization | +| Composition | `A *-- B` | Strong ownership (lifecycle bound) | +| Aggregation | `A o-- B` | Weak ownership (independent lifecycle) | +| Dependency | `A ..> B` | Uses relationship | +| Realization | `A ..\|> B` | Interface implementation | + +### ⚠️ COMMON MISTAKE + +``` +❌ WRONG (ER Diagram syntax in Class Diagram): +classDiagram + ResourceNode ||--|| ResourceType + +✅ CORRECT (Class Diagram syntax): +classDiagram + ResourceNode "1" -- "1" ResourceType : has +``` + +--- + +## 5. ER Diagram Standards (Data Model) + +### When to Use + +- **Database design**: Entity relationships for persistence +- **Data modeling**: Tables and foreign key relationships +- **System integration**: Data exchange structures + +### MANDATORY Rules + +- Use `erDiagram` syntax for entity relationships +- Define attributes with data types +- Use correct cardinality notation + +### ER Diagram Syntax + +```mermaid +erDiagram + RESOURCE_NODE ||--|| RESOURCE_TYPE : has + RESOURCE_NODE ||--o{ AGENT : monitors + AGENT ||--o{ METRIC : collects + + RESOURCE_NODE { + string id PK + string name + string type_id FK + datetime created_at + } + + RESOURCE_TYPE { + string id PK + string type_name + string description + } + + AGENT { + string id PK + string resource_id FK + string version + string status + } + + METRIC { + string id PK + string agent_id FK + string metric_name + float value + datetime timestamp + } +``` + +### Cardinality Notation + +| Syntax | Meaning | +|--------|---------| +| `\|\|--\|\|` | One to One | +| `\|\|--o{` | One to Many | +| `o{--o{` | Many to Many | +| `\|\|--o\|` | One to Zero or One | +| `}o--o{` | Zero or Many to Zero or Many | + +### Comparison: Class Diagram vs ER Diagram + +| Aspect | Class Diagram (`classDiagram`) | ER Diagram (`erDiagram`) | +|--------|-------------------------------|--------------------------| +| **Purpose** | Domain/Object modeling | Database/Data modeling | +| **Relationship** | `"1" -- "0..*"` | `\|\|--o{` | +| **Inheritance** | `<\|--` (supported) | Not supported | +| **Methods** | Supported | Not supported | +| **Primary Key** | Not explicit | `PK` notation | +| **Foreign Key** | Not explicit | `FK` notation | + +### ⚠️ DO NOT MIX SYNTAX + +``` +❌ WRONG (mixing syntax): +classDiagram + A ||--o{ B + +❌ WRONG (mixing syntax): +erDiagram + A <|-- B + +✅ CORRECT: +Use classDiagram for OOP relationships +Use erDiagram for database relationships +``` + +--- + +## 6. Document Format Standards + +### MANDATORY Rules + +#### Text Formatting +- **Each analysis item MUST be on a separate line** +- **Key terms MUST be bold** +- **Consistent indentation** throughout document +- **Clear visual hierarchy** with proper heading levels + +#### Example - CORRECT Format + +```markdown +## Analysis Summary + +**User Roles**: +- Operations personnel +- DevOps engineers +- Development engineers + +**Core Activities**: +- Resource topology management +- Agent configuration +- Monitoring and inspection +- Problem diagnosis +- Fault handling + +**Key Findings**: +- **Finding 1**: Description of first finding +- **Finding 2**: Description of second finding +``` + +#### Example - INCORRECT Format + +```markdown +## Analysis Summary +User Roles: Operations personnel, DevOps engineers, Development engineers +Core Activities: Resource topology management, Agent configuration, Monitoring... +``` + +--- + +## 7. Diagram Quality Standards + +### MANDATORY Rules + +1. **All UML diagrams MUST follow standard syntax** +2. **Use Mermaid syntax for all diagrams** +3. **Apply appropriate styling and color coding**: + - Primary elements: `fill:#e1f5fe` (light blue) + - Secondary elements: `fill:#f3e5f5` (light purple) + - Warning/attention: `fill:#fff3e0` (light orange) + - Success/completion: `fill:#e8f5e9` (light green) + - Error/critical: `fill:#ffebee` (light red) + +4. **Complex processes MUST be decomposed** into multiple diagrams +5. **Each diagram MUST have a clear title** + +### Style Template + +```mermaid +graph TD + A[Primary Element] + B[Secondary Element] + C[Warning Element] + D[Success Element] + E[Error Element] + + style A fill:#e1f5fe,stroke:#01579b + style B fill:#f3e5f5,stroke:#4a148c + style C fill:#fff3e0,stroke:#e65100 + style D fill:#e8f5e9,stroke:#1b5e20 + style E fill:#ffebee,stroke:#b71c1c +``` + +--- + +## 8. Diagram Decomposition Guidelines + +### When to Decompose + +| Condition | Action | +|-----------|--------| +| More than 10 nodes | Split into sub-diagrams | +| Multiple swimlanes (>3) | Create separate diagrams per domain | +| Complex parallel flows | Separate detailed sequence diagram | +| Multiple abstraction levels | Use overview + detail diagrams | + +### Decomposition Pattern + +``` +Overview Diagram (High-level) + │ + ├── Detail Diagram 1 (Subprocess A) + ├── Detail Diagram 2 (Subprocess B) + └── Detail Diagram 3 (Subprocess C) +``` + +--- + +## Quick Reference Card + +| Element | Standard | Mermaid Syntax | +|---------|----------|----------------| +| Actor | Stick figure | `[/"👤 Name"\]` | +| Use Case | Ellipse | `((Use Case))` | +| Activity | Rectangle | `[Activity]` | +| Decision | Diamond | `{Decision}` or `<>` | +| Parallel | Fork/Join | `par ... and ... end` | +| System Boundary | Dashed box | `subgraph` | +| Include | Dashed arrow with label | `-->|<>|` | +| Extend | Dashed arrow with label | `-.->|<>|` | diff --git a/requirements-analyst/steering/helper-multi-role-validation.md b/requirements-analyst/steering/helper-multi-role-validation.md new file mode 100644 index 0000000..4744e94 --- /dev/null +++ b/requirements-analyst/steering/helper-multi-role-validation.md @@ -0,0 +1,187 @@ +--- +inclusion: agent +--- + +# Multi-Role Validation Perspectives + +In the **Validate** phase, requirements MUST be validated from multiple role perspectives to ensure completeness and feasibility. Each role brings unique concerns and validation criteria. + +--- + +## Validation Dimensions by Role + +### Product Manager (PM) Perspective + +**Focus**: Business value and user alignment + +| Dimension | Validation Questions | +|-----------|---------------------| +| **Business Value** | Does this requirement deliver clear business value? What's the ROI? | +| **User Need** | Does this solve a real user problem? Is the user pain point validated? | +| **Market Fit** | How does this compare to competitors? Is there market demand? | +| **Strategic Alignment** | Does this align with product vision and roadmap? | +| **Priority Justification** | Is the priority (MoSCoW/RICE) justified by business metrics? | +| **Success Metrics** | Are success metrics defined? How will we measure value delivered? | + +**PM Validation Checklist**: +- [ ] Business case is clear and justified +- [ ] User personas and needs are validated +- [ ] Feature aligns with product strategy +- [ ] Success metrics are measurable +- [ ] Stakeholder buy-in is obtained + +--- + +### Requirements Analyst (RA) Perspective + +**Focus**: Completeness, clarity, and traceability + +| Dimension | Validation Questions | +|-----------|---------------------| +| **Completeness** | Are all functional and non-functional requirements captured? | +| **Clarity** | Is each requirement unambiguous with only one interpretation? | +| **Consistency** | Are there conflicts between requirements? | +| **Traceability** | Can each requirement be traced to business goals? | +| **Boundary Conditions** | Are edge cases and error conditions defined? | +| **Dependencies** | Are all dependencies identified and documented? | + +**RA Validation Checklist**: +- [ ] All requirements have unique IDs +- [ ] No ambiguous terms (e.g., "fast", "user-friendly") +- [ ] Main flow, alternate flows, and exception flows documented +- [ ] Boundary conditions explicitly stated +- [ ] Traceability matrix is complete +- [ ] No conflicting requirements + +--- + +### Software Architect (SA) Perspective + +**Focus**: Technical feasibility and system impact + +| Dimension | Validation Questions | +|-----------|---------------------| +| **Technical Feasibility** | Can this be implemented with current technology stack? | +| **Architecture Impact** | How does this affect existing system architecture? | +| **Scalability** | Will this scale to expected load? What are the limits? | +| **Security** | What are the security implications? Authentication? Authorization? | +| **Performance** | Are performance requirements realistic and measurable? | +| **Integration** | What systems need to integrate? Are APIs defined? | +| **Technical Debt** | Does this introduce or reduce technical debt? | + +**SA Validation Checklist**: +- [ ] NFRs (performance, security, scalability) are quantified +- [ ] Architecture constraints are identified +- [ ] Integration points are documented +- [ ] No impossible or impractical requirements +- [ ] Technology choices are justified +- [ ] Security requirements are OWASP-aligned + +--- + +### Software Engineer (SE) Perspective + +**Focus**: Implementation clarity and effort estimation + +| Dimension | Validation Questions | +|-----------|---------------------| +| **Implementation Clarity** | Is it clear how to implement this? | +| **Effort Estimation** | Can development effort be estimated accurately? | +| **Technical Constraints** | Are technical constraints and limitations documented? | +| **Error Handling** | What happens when things go wrong? | +| **Data Validation** | What input validation rules apply? | +| **Logging & Monitoring** | What needs to be logged or monitored? | +| **Backward Compatibility** | Does this break existing functionality? | + +**SE Validation Checklist**: +- [ ] Implementation approach is clear +- [ ] Data models and schemas are defined +- [ ] Error handling scenarios are specified +- [ ] Input validation rules are documented +- [ ] No hidden complexity or ambiguity +- [ ] Backward compatibility is addressed + +--- + +### Test Engineer (TE) Perspective + +**Focus**: Testability and quality assurance + +| Dimension | Validation Questions | +|-----------|---------------------| +| **Testability** | Can this requirement be tested? How? | +| **Acceptance Criteria** | Are acceptance criteria in GWT format and verifiable? | +| **Test Coverage** | What test types are needed? (Unit, Integration, E2E, Performance) | +| **Test Data** | What test data is required? | +| **Edge Cases** | Are edge cases and boundary conditions testable? | +| **Regression Impact** | What existing tests might be affected? | +| **Automation Feasibility** | Can tests be automated? | + +**TE Validation Checklist**: +- [ ] Every requirement has acceptance criteria (GWT) +- [ ] Happy path scenarios defined +- [ ] Error scenarios defined (at least 2-3 per requirement) +- [ ] Edge cases identified and testable +- [ ] Performance test criteria specified (if applicable) +- [ ] Test data requirements documented + +--- + +## Multi-Role Validation Process + +### Step 1: Individual Role Review +Review requirements from each role's perspective using the checklists above. + +### Step 2: Cross-Role Conflict Detection +Identify conflicts between role perspectives: + +| Conflict Type | Example | Resolution Approach | +|---------------|---------|---------------------| +| **PM vs SA** | PM wants feature, SA says infeasible | Negotiate scope or timeline | +| **RA vs SE** | RA defines requirement, SE says unclear | Clarify implementation details | +| **SA vs TE** | SA designs system, TE says untestable | Adjust design for testability | +| **PM vs TE** | PM prioritizes speed, TE needs quality | Balance scope, time, quality | + +### Step 3: Consolidated Validation Report +Create a validation report summarizing findings from all perspectives: + +```markdown +## Multi-Role Validation Report + +### Requirement: [REQ-XXX] + +| Role | Status | Issues | Recommendations | +|------|--------|--------|-----------------| +| PM | ✅/⚠️/❌ | [Issues] | [Recommendations] | +| RA | ✅/⚠️/❌ | [Issues] | [Recommendations] | +| SA | ✅/⚠️/❌ | [Issues] | [Recommendations] | +| SE | ✅/⚠️/❌ | [Issues] | [Recommendations] | +| TE | ✅/⚠️/❌ | [Issues] | [Recommendations] | + +### Overall Status: [APPROVED / NEEDS REVISION / REJECTED] + +### Action Items: +1. [Action item from validation] +2. [Action item from validation] +``` + +--- + +## Validation Question Templates + +Use these templates when validating requirements: + +### From PM Perspective: +> "As a Product Manager, I need to understand: What user problem does [REQ-XXX] solve, and how will we measure its success?" + +### From RA Perspective: +> "As a Requirements Analyst, I need to verify: Is [REQ-XXX] complete, unambiguous, and traceable to business goals?" + +### From SA Perspective: +> "As a Software Architect, I need to assess: Is [REQ-XXX] technically feasible within our architecture, and what are the NFR implications?" + +### From SE Perspective: +> "As a Software Engineer, I need to clarify: How will [REQ-XXX] be implemented, and what are the error handling requirements?" + +### From TE Perspective: +> "As a Test Engineer, I need to confirm: How will [REQ-XXX] be tested, and are the acceptance criteria verifiable?" diff --git a/requirements-analyst/steering/phase1-requirements-discovery.md b/requirements-analyst/steering/phase1-requirements-discovery.md new file mode 100644 index 0000000..885b799 --- /dev/null +++ b/requirements-analyst/steering/phase1-requirements-discovery.md @@ -0,0 +1,245 @@ +--- +inclusion: agent +--- + +# Phase 1: Requirements Discovery + +**Phase Objective**: Discover and elicit user requirements from scratch, understand business context and user pain points. +**Time Allocation**: 40% of total effort +**Your Role**: Professional Requirements Analyst + +--- + +## Quick Reference + +| Method | Focus | Output | Time | Critical? | +|--------|-------|--------|------|-----------| +| Stakeholder Analysis | Power-Interest Matrix | Stakeholder list + Interview plans | 10% | ✅ Yes | +| User Personas | 3-5 typical personas | Detailed persona documents | 15% | ✅ Yes | +| Journey Mapping | Core business flows | Visual journey maps | 15% | ✅ Yes | +| Field Observation | Actual usage scenarios | Pain points list | 20% | Optional | +| Competitive Analysis | 2-3 competitors | Feature comparison matrix | 20% | ✅ Yes | +| Requirements Collection | All raw requirements | Preliminary requirements list | 20% | ✅ Yes | + +**Minimum Viable Discovery**: Stakeholder Interviews + User Personas + Journey Map + Competitive Analysis + +--- + +## Output + +**File**: `.kiro/specs/[feature-name]/discovery.md` + +> **Dependencies**: See `POWER.md` → File Dependencies for required template and helper files. + +--- + +## Pre-Check (GATE CHECK) + +**MUST satisfy these conditions before starting**: + +| Check Item | Requirement | Status | +|-----------|-------------|--------| +| Project Authorization | MUST have formal approval to start | [ ] | +| Stakeholder Access | MUST be able to contact key stakeholders | [ ] | +| Time Allocation | MUST have at least 40% of total time | [ ] | + +**If check fails**: STOP. Resolve access and authorization issues before proceeding. + +--- + +## Your Tasks (NON-NEGOTIABLE) + +1. **Identify Stakeholders**: Use power-interest matrix for systematic identification +2. **Create User Personas**: Create detailed personas for each key role +3. **Map User Journeys**: Visualize complete user journeys +4. **Conduct Competitive Analysis**: Analyze 2-3 major competitors +5. **Uncover Pain Points**: Discover unexpressed implicit needs + +## Professional Qualities You MUST Demonstrate + +- ✅ MUST use professional methods (power-interest matrix, user personas, journey maps) +- ✅ MUST think systematically (don't miss any stakeholder) +- ✅ MUST explore deeply (discover implicit needs and pain points) +- ✅ MUST provide competitive insights (identify differentiation opportunities) +- ✅ MUST provide structured output + +## What You MUST NOT Do (STRICTLY PROHIBITED) + +- ❌ NEVER assume existing requirements - this phase MUST start from scratch +- ❌ NEVER miss key stakeholders - MUST identify all affected parties +- ❌ NEVER focus only on explicit needs - MUST discover implicit requirements +- ❌ NEVER skip competitive analysis - MUST analyze at least 1 core competitor + +--- + +## Method 1: Stakeholder Identification and Interviews + +### Power-Interest Matrix + +``` + High Interest + │ + ┌───────────┼───────────┐ + │ Manage │ Engage │ ← Key Players (High Priority) + │ Closely │ Closely │ +────┼───────────┼───────────┼──── + │ Monitor │ Keep │ ← Secondary (Lower Priority) + │ │ Informed │ + └───────────┼───────────┘ + │ + Low Interest + Low Power High Power +``` + +### Interview Plan Template + +```markdown +## Interview Plan + +**Interview Subject**: [Name/Role] +**Interview Time**: [Date Time] +**Interview Location**: [Location/Online] +**Interview Objectives**: [What to understand from this interview] + +**Question List**: +1. What are your main responsibilities related to this project? +2. What problems do you face in your daily work? +3. What would an ideal solution look like? +4. What constraints should we be aware of? +5. Who else should we talk to? +``` + +### Interview Techniques + +- Use open-ended questions to elicit requirements +- Use "5 Whys" to find root causes +- Record user quotes verbatim +- Observe non-verbal cues +- Follow up on vague answers + +--- + +## Method 2: User Personas + +### Persona Template + +```markdown +## User Persona: [Name] + +**Photo**: [Avatar/Stock photo] + +### Demographics +- **Age**: [Range] +- **Role/Occupation**: [Title] +- **Technical Proficiency**: [Novice/Intermediate/Expert] +- **Company Size**: [Startup/SMB/Enterprise] + +### Goals & Motivations +- Primary: [Main goal] +- Secondary: [Supporting goals] + +### Pain Points & Frustrations +- [Pain point 1 with severity: High/Medium/Low] +- [Pain point 2 with severity] +- [Pain point 3 with severity] + +### Behaviors & Preferences +- [How they currently solve the problem] +- [Tools they use] +- [Communication preferences] + +### Usage Context +- **When**: [Time/Frequency of use] +- **Where**: [Environment - office, mobile, etc.] +- **How**: [Devices, access methods] + +### Quote +> "[Verbatim quote from interviews that captures their perspective]" + +### Key Requirements (inferred) +1. [Requirement derived from this persona] +2. [Requirement derived from this persona] +``` + +--- + +## Method 3: User Journey Map + +### Journey Map Structure + +```markdown +## User Journey: [Journey Name] + +**Persona**: [Which persona] +**Scenario**: [What they're trying to accomplish] + +| Stage | Discovery | Consideration | Use | Completion | +|-------|-----------|---------------|-----|------------| +| **Actions** | [What user does] | [What user does] | [What user does] | [What user does] | +| **Thoughts** | [What user thinks] | [What user thinks] | [What user thinks] | [What user thinks] | +| **Emotions** | 😊/😐/😞 | 😊/😐/😞 | 😊/😐/😞 | 😊/😐/😞 | +| **Pain Points** | [Issues faced] | [Issues faced] | [Issues faced] | [Issues faced] | +| **Opportunities** | [Improvement ideas] | [Improvement ideas] | [Improvement ideas] | [Improvement ideas] | +| **Touchpoints** | [Systems/people involved] | [Systems/people involved] | [Systems/people involved] | [Systems/people involved] | +``` + +--- + +## Method 4: Competitive Analysis + +### Competitive Analysis Template + +```markdown +## Competitive Analysis Report + +### Competitors Analyzed +1. [Competitor A] - [Market position] +2. [Competitor B] - [Market position] +3. [Competitor C] - [Market position] + +### Feature Comparison Matrix + +| Feature | Our Product | Competitor A | Competitor B | Competitor C | +|---------|-------------|--------------|--------------|--------------| +| [Feature 1] | ❓ Planned | ✅ Yes | ✅ Yes | ❌ No | +| [Feature 2] | ❓ Planned | ✅ Yes | ❌ No | ✅ Yes | +| [Feature 3] | ❓ Planned | ❌ No | ✅ Yes | ✅ Yes | + +### SWOT Analysis (Per Competitor) + +**Competitor A**: +- Strengths: [List] +- Weaknesses: [List] +- Opportunities for us: [How we can differentiate] +- Threats: [What they do better] + +### Differentiation Opportunities +1. [Gap in market we can fill] +2. [Underserved user need] +3. [Better approach to existing feature] +``` + +--- + +## Exit Criteria + +**CRITICAL**: Complete ALL items below to proceed to Phase 2: + +| Exit Item | Qualification Standard | Status | +|-----------|----------------------|--------| +| **Stakeholder List** | All key stakeholders identified (≥5 interviews) | [ ] | +| **User Personas** | 3-5 typical personas created | [ ] | +| **Journey Map** | Core business process mapped | [ ] | +| **Raw Requirements** | Preliminary list compiled (≥20 items) | [ ] | +| **Competitive Analysis** | 1-2 competitors analyzed | [ ] | +| **Pain Points** | Core pain points identified (≥5 items) | [ ] | + +--- + +## Next Step + +After completing this phase, proceed to: + +**Phase 2: Value Sorting** +- Use MoSCoW and RICE models to prioritize requirements +- Establish business value hierarchy diff --git a/requirements-analyst/steering/phase2-requirements-value-sorting.md b/requirements-analyst/steering/phase2-requirements-value-sorting.md new file mode 100644 index 0000000..147d4c6 --- /dev/null +++ b/requirements-analyst/steering/phase2-requirements-value-sorting.md @@ -0,0 +1,354 @@ +--- +inclusion: agent +--- + +# Phase 2: Value Sorting + +**Phase Objective**: Prioritize requirements and develop release plans. +**Time Allocation**: 10% of total effort +**Your Role**: Professional Requirements Analyst + +--- + +## Quick Reference + +| Method | Focus | Output | When to Use | +|--------|-------|--------|-------------| +| MoSCoW | Categorical priority | MUST/SHOULD/COULD/WONT list | All projects | +| RICE Scoring | Quantitative ranking | Scored priority list | Many requirements (>20) | +| Value-Cost Matrix | Trade-off visualization | Quadrant placement | Resource constraints | +| Weighted Scoring | Multi-factor evaluation | Composite scores | Complex decisions | + +**CRITICAL CONSTRAINT**: MUST requirements MUST NOT exceed 30% of total. + +--- + +## Output + +**File**: `.kiro/specs/[feature-name]/sort.md` + +> **Dependencies**: See `POWER.md` → File Dependencies for required template and helper files. + +--- + +## Pre-Check (GATE CHECK) + +**MUST pass this check before starting**: + +- [ ] **Phase 3 completed?** All requirements analyzed with dependencies mapped? +- [ ] **Inputs available?** Domain model, feasibility assessment, dependency graph ready? +- [ ] **Unclear items identified?** Any requirements with unclear business value flagged? + +**If ANY check fails**: STOP. NEVER proceed. Return to Phase 3. + +--- + +## Your Tasks (NON-NEGOTIABLE) + +1. **MoSCoW Classification**: Classify ALL requirements into MUST/SHOULD/COULD/WONT +2. **RICE Scoring**: Use RICE method for quantitative evaluation +3. **Value-Cost Analysis**: Use value-cost matrix for trade-off decisions +4. **Develop Release Plan**: Plan MVP and subsequent versions + +## What You MUST NEVER Do + +- ❌ NEVER prioritize based on intuition alone - use scientific methods +- ❌ NEVER let MUST priorities exceed 30% - this is a hard limit +- ❌ NEVER ignore requirement dependencies - validate against dependency graph +- ❌ NEVER develop release plan without stakeholder input + +--- + +## Method 1: MoSCoW Classification + +### MoSCoW Categories + +| Category | Definition | Guidance | Typical % | +|----------|------------|----------|-----------| +| **Must Have** | Cannot launch without these | Core functionality, legal/compliance | ≤30% | +| **Should Have** | Important but not critical | Significant value, can workaround | 20-30% | +| **Could Have** | Nice to have if time permits | Enhances experience, low urgency | 20-30% | +| **Won't Have** | Not in this release | Future consideration, descoped | 10-20% | + +### MoSCoW Decision Questions + +| Question | If Yes → | +|----------|----------| +| Does the product fail without it? | MUST | +| Is there a legal/regulatory requirement? | MUST | +| Is there a workaround possible? | SHOULD (not MUST) | +| Will users be significantly impacted without it? | SHOULD | +| Is it a "delight" feature? | COULD | +| Can it wait for next release? | COULD or WON'T | + +### MoSCoW Template + +```markdown +## MoSCoW Classification: [Release/Version] + +### MUST Have (≤30% of total) +| Req ID | Requirement | Justification | +|--------|-------------|---------------| +| REQ-001 | [Description] | [Why it's MUST] | +| REQ-002 | [Description] | [Why it's MUST] | + +**MUST Count**: X / Y total = Z% ✅/❌ (must be ≤30%) + +### SHOULD Have +| Req ID | Requirement | Impact if Deferred | +|--------|-------------|-------------------| +| REQ-003 | [Description] | [Impact] | +| REQ-004 | [Description] | [Impact] | + +### COULD Have +| Req ID | Requirement | Value Add | +|--------|-------------|-----------| +| REQ-005 | [Description] | [Benefit] | + +### WON'T Have (This Release) +| Req ID | Requirement | Reason for Exclusion | +|--------|-------------|---------------------| +| REQ-006 | [Description] | [Why not now] | +``` + +--- + +## Method 2: RICE Scoring + +### RICE Formula + +``` +RICE Score = (Reach × Impact × Confidence) / Effort +``` + +### RICE Factors + +| Factor | Scale | Description | How to Estimate | +|--------|-------|-------------|-----------------| +| **Reach** | Number | Users affected per quarter | Analytics, user research | +| **Impact** | 0.25, 0.5, 1, 2, 3 | Per-user impact | Minimal(0.25) → Massive(3) | +| **Confidence** | 0-100% | How certain are we | Data-backed(100%) → Gut(20%) | +| **Effort** | Person-months | Development cost | Engineering estimate | + +### Impact Scale Guide + +| Score | Level | Description | Example | +|-------|-------|-------------|---------| +| 3 | Massive | Fundamental improvement | Core workflow optimization | +| 2 | High | Significant improvement | Major pain point solved | +| 1 | Medium | Noticeable improvement | Useful enhancement | +| 0.5 | Low | Minor improvement | Small convenience | +| 0.25 | Minimal | Barely noticeable | Micro optimization | + +### RICE Scoring Template + +```markdown +## RICE Scoring Results + +| Req ID | Reach | Impact | Confidence | Effort | RICE Score | Rank | +|--------|-------|--------|------------|--------|------------|------| +| REQ-001 | 10,000 | 2 | 80% | 2 | 8,000 | 1 | +| REQ-002 | 5,000 | 3 | 90% | 3 | 4,500 | 2 | +| REQ-003 | 8,000 | 1 | 70% | 1 | 5,600 | 3 | +| REQ-004 | 2,000 | 2 | 50% | 4 | 500 | 4 | + +### Calculation Example +REQ-001: (10,000 × 2 × 0.80) / 2 = 8,000 + +### Priority Recommendation +1. REQ-001 (Score: 8,000) - Highest impact per effort +2. REQ-003 (Score: 5,600) - Quick win +3. REQ-002 (Score: 4,500) - High value but costly +4. REQ-004 (Score: 500) - Defer to later release +``` + +--- + +## Method 3: Value-Cost Matrix + +### Value-Cost Quadrants + +``` + High Value + │ + ┌────────────┼────────────┐ + │ P1 │ P0 │ + │ Strategic │ Quick Win │ + │ │ │ + │ High Cost │ Low Cost │ + │ High Value │ High Value │ + ───────┼────────────┼────────────┼─────── + │ P3 │ P2 │ + │ Avoid │ Fill-in │ + │ │ │ + │ High Cost │ Low Cost │ + │ Low Value │ Low Value │ + └────────────┼────────────┘ + │ + Low Value +``` + +### Decision Rules + +| Quadrant | Strategy | Action | +|----------|----------|--------| +| **P0 (Quick Win)** | Do First | High value, low effort - prioritize immediately | +| **P1 (Strategic)** | Plan Carefully | High value, high effort - worth investment but plan | +| **P2 (Fill-in)** | If Time Permits | Low value, low effort - easy add-ons | +| **P3 (Avoid)** | Deprioritize | Low value, high effort - usually not worth it | + +### Value-Cost Matrix Template + +```markdown +## Value-Cost Analysis + +### Scoring Criteria +- **Value**: Business impact (1-10) +- **Cost**: Development effort (1-10, where 10 = highest cost) + +### Requirements Placement +| Req ID | Value (1-10) | Cost (1-10) | Quadrant | Action | +|--------|--------------|-------------|----------|--------| +| REQ-001 | 9 | 3 | P0 (Quick Win) | Do First | +| REQ-002 | 8 | 8 | P1 (Strategic) | Plan Carefully | +| REQ-003 | 3 | 2 | P2 (Fill-in) | If Time Permits | +| REQ-004 | 4 | 9 | P3 (Avoid) | Deprioritize | + +### Visual Placement +[Draw or describe the quadrant placement] +``` + +--- + +## Method 4: Release Planning + +### MVP Definition + +```markdown +## MVP (Minimum Viable Product) + +**Goal**: Validate core hypotheses with minimum feature set + +### MVP Criteria +- [ ] Solves the core user problem +- [ ] Technically feasible within timeline +- [ ] Provides basis for learning/iteration +- [ ] Contains only MUST requirements + +### MVP Scope +| Req ID | Requirement | Why MVP | +|--------|-------------|---------| +| REQ-001 | [Description] | [Core to value proposition] | +| REQ-002 | [Description] | [Required for basic flow] | + +### Not in MVP (Explicitly Excluded) +| Req ID | Requirement | Deferred To | +|--------|-------------|-------------| +| REQ-003 | [Description] | V1.1 | +| REQ-004 | [Description] | V2.0 | + +### MVP Success Metrics +- [ ] [Metric 1]: [Target] +- [ ] [Metric 2]: [Target] +``` + +### Release Roadmap + +```markdown +## Release Roadmap + +### MVP (Target: [Date]) +**Theme**: Core functionality +**Scope**: +- [Feature 1] +- [Feature 2] +- [Feature 3] +**Success Criteria**: [Metrics] + +### Version 1.1 (Target: [Date]) +**Theme**: Enhanced usability +**Scope**: +- [Feature 4] +- [Feature 5] +**Dependencies**: MVP complete + +### Version 2.0 (Target: [Date]) +**Theme**: Scale and advanced features +**Scope**: +- [Feature 6] +- [Feature 7] +**Dependencies**: V1.1 complete, [External dependency] + +### Release Timeline + +\`\`\`mermaid +gantt + title Release Timeline + dateFormat YYYY-MM-DD + section Releases + MVP :milestone, m1, [Date], 0d + V1.1 :milestone, m2, [Date], 0d + V2.0 :milestone, m3, [Date], 0d + V3.0 :milestone, m4, [Date], 0d +\`\`\` + +### Risk Factors +| Release | Risk | Mitigation | +|---------|------|------------| +| MVP | [Risk] | [Plan] | +| V1.1 | [Risk] | [Plan] | +``` + +--- + +## Stakeholder Alignment + +### Priority Review Session + +```markdown +## Priority Review Meeting + +**Date**: [Date] +**Attendees**: [List] + +### Decisions Made +1. [Decision 1] +2. [Decision 2] + +### Conflicts Resolved +| Issue | Resolution | Rationale | +|-------|------------|-----------| +| [Conflict] | [How resolved] | [Why] | + +### Open Items +1. [Item needing follow-up] + +### Approvals +- [ ] Product Owner: _______________ +- [ ] Technical Lead: _______________ +- [ ] Business Stakeholder: _______________ +``` + +--- + +## Exit Criteria (NON-NEGOTIABLE) + +| Criteria | Standard | Verification | Status | +|----------|----------|--------------|--------| +| MoSCoW Classification | 100% requirements classified | MUST ≤ 30% | [ ] | +| RICE Scoring | Core requirements scored | Scores documented | [ ] | +| Priority List | Ranked by final score | No dependency conflicts | [ ] | +| Release Plan | MVP and versions defined | Timeline clear | [ ] | +| Stakeholder Approval | Priorities confirmed | Sign-off obtained | [ ] | + +--- + +## Next Step + +After completing this phase, proceed to: + +**Phase 5: Validation** +- Requirements review meetings +- GWT acceptance criteria +- Prototype testing +- Traceability matrix diff --git a/requirements-analyst/steering/phase3-requirements-analysis.md b/requirements-analyst/steering/phase3-requirements-analysis.md new file mode 100644 index 0000000..5823406 --- /dev/null +++ b/requirements-analyst/steering/phase3-requirements-analysis.md @@ -0,0 +1,932 @@ +--- +inclusion: agent +--- + +# Phase 3: Requirements Analysis + +**Phase Objective**: Deep analysis of dependencies, feasibility, and implementation approaches. +**Time Allocation**: 20% of total effort +**Your Role**: Professional Requirements Analyst + +--- + +## Quick Reference + +| Method | Focus | Output | When to Use | +|--------|-------|--------|-------------| +| User Story Mapping | User activities and priorities | Story map with MVP | All projects | +| Use Case Analysis | Actor-system interactions | Use case documents | Complex interactions | +| Success Criteria | Measurable outcomes | SMART criteria list | All requirements | +| Event Storming | Domain events and commands | Domain model | Complex business logic | +| Dependency Analysis | Requirement relationships | Dependency graph | Multi-requirement projects | +| Domain Data Modeling | Entities and relationships | data-model.md | Projects with data entities | +| NFR Analysis | System qualities | NFR specification | All projects | + +--- + +## Output + +**Files**: +- `.kiro/specs/[feature-name]/requirements.md` - User stories, use cases, success criteria, dependencies +- `.kiro/specs/[feature-name]/data-model.md` - Entity definitions, relationships, state diagrams + +> **Dependencies**: See `POWER.md` → File Dependencies for required template and helper files. + +--- + +## MANDATORY: Diagram and Documentation Standards + +**CRITICAL**: Follow `helper-diagram-standards.md` standards for all diagrams and documentation. + +### Expression Priority (MUST FOLLOW) + +``` +1st Priority: Diagram (Visual representation) + └── 2nd Priority: UML Diagram (Standard notation) + └── 3rd Priority: Mermaid Syntax (Generation method) +``` + +**Rule**: ALWAYS prefer diagrams over text/tables. When using diagrams, ALWAYS prefer UML. When generating UML, ALWAYS use Mermaid syntax. + +| Expression Method | Priority | When to Use | +|-------------------|----------|-------------| +| **UML Diagram (Mermaid)** | 🥇 Highest | Default choice for all requirements | +| **Other Diagrams (Mermaid)** | 🥈 Second | When UML is not applicable | +| **Table + Diagram** | 🥉 Third | Supplementary details only | +| **Text/Table only** | ❌ Avoid | Only when diagram is impossible | + +### Key Rules Summary + +1. **UML Use Case Diagram**: + - Actors: stick figure icon + - Use Cases: ellipse shape + - System Boundary: dashed rectangle + - Relationships: `<>` and `<>` stereotypes + - ❌ PROHIBITED: Simple flowcharts instead of UML + +2. **Business Process (Activity Diagram)**: + - Core user flows MUST use UML Activity Diagram + - Tables alone are NOT sufficient + - Parallel processing MUST use fork/join or `par` syntax + +3. **Use Case Main Flow (Sequence Diagram)**: + - Main flows MUST use Sequence Diagram + - Include all participants: User, UI, System, Agent, Database + - Parallel execution MUST use `par` syntax + - ✅ ALWAYS accompany tables with Sequence Diagrams (tables alone are insufficient) + +4. **Document Format**: + - Each analysis item on separate line + - Key terms in **bold** + - Consistent indentation + - Clear visual hierarchy + +5. **Diagram Quality**: + - Use Mermaid syntax for all diagrams + - Apply color coding for element types + - Complex processes MUST be decomposed + +--- + +## Pre-Check (GATE CHECK) + +**MUST pass this check before starting**: + +- [ ] **Phase 2 completed?** Verify `sort.md` exists with value sorting matrix +- [ ] **Inputs available?** Confirm prioritization (MoSCoW/RICE) is complete +- [ ] **Unclear items identified?** List requirements flagged for clarification + +**If ANY check fails**: STOP. NEVER proceed. Return to Phase 2. + +--- + +## MANDATORY: Reference Existing Clarification & Validation Files + +**CRITICAL**: If clarification or validation files already exist, you MUST load and reference them. + +### Check for Existing Files + +``` +.kiro/specs/[feature-name]/ +├── clarification.md ← If exists, MUST reference +└── validation.md ← If exists, MUST reference +``` + +### When Files Exist (Iterative Analysis) + +| File Exists | Action Required | +|-------------|-----------------| +| `clarification.md` | Load and apply all resolved clarifications to analysis | +| `validation.md` | Load and address all validation findings in analysis | +| Both files exist | This is an iteration - update analysis based on both | + +### How to Apply Existing Clarifications + +1. **Read `clarification.md`** completely +2. **Extract all resolved Q&A** from the clarification log +3. **Apply to analysis**: + - User Stories must reflect clarified scope + - Use Cases must incorporate clarified flows + - Success Criteria must align with clarified requirements + - Mark in analysis: `[Updated per Clarification Q1]` + +### How to Apply Existing Validation Findings + +1. **Read `validation.md`** completely +2. **Extract all issues and findings** by dimension: + - Authenticity issues → Verify requirement sources + - Completeness gaps → Fill missing specifications + - Consistency conflicts → Resolve contradictions + - Feasibility concerns → Adjust scope or approach + - Verifiability issues → Add measurable criteria +3. **Apply to analysis**: + - Address each validation issue in relevant section + - Mark in analysis: `[Updated per Validation V-001]` + +### Cross-Reference Requirements + +```markdown +## Analysis Update Log + +### Applied from clarification.md +| Q# | Clarification | Applied To | Section | +|----|---------------|------------|---------| +| Q1 | [Summary] | US-001 | User Stories | +| Q2 | [Summary] | UC-002 | Use Cases | + +### Applied from validation.md +| Issue | Finding | Applied To | Section | +|-------|---------|------------|---------| +| V-001 | [Summary] | SC-003 | Success Criteria | +| V-002 | [Summary] | REQ-005 | Dependency Analysis | +``` + +**WARNING**: Ignoring existing clarification or validation files will result in inconsistent requirements and rework. + +--- + +## Your Tasks (NON-NEGOTIABLE) + +1. **User Story Mapping**: Create complete user story maps +2. **Use Case Analysis**: Draw main use case diagrams and write use case documents +3. **Success Criteria Definition**: Define measurable success criteria for each requirement +4. **Dependency Analysis**: Map requirement dependencies and identify conflicts +5. **Feasibility Assessment**: Evaluate technical feasibility and risks +6. **Domain Data Modeling**: Define entities, relationships, and state diagrams in `data-model.md` + +## Professional Qualities You MUST Demonstrate + +- ✅ Use professional methods (user story mapping, use case analysis, event storming) +- ✅ Deep analysis (requirement dependencies, technical feasibility) +- ✅ Domain modeling (identify bounded contexts, aggregates) +- ✅ Visual output (story maps, use case diagrams, domain models) + +## What You MUST NEVER Do + +- ❌ NEVER be superficial - deep analysis is mandatory +- ❌ NEVER ignore requirement dependencies - document all relationships +- ❌ NEVER skip technical feasibility assessment - it is required +- ❌ NEVER force-fit DDD just to use it (DDD suits complex business; simple projects can use simplified models) + +--- + +## Method 1: User Story Mapping + +**OUTPUT TEMPLATE**: Use `template-analysis.md` for output format. + +### Core User Activity Flow (UML Activity Diagram) + +**MUST use `stateDiagram-v2` for user activity flows:** + +```mermaid +stateDiagram-v2 + [*] --> Browse: Start + + Browse --> Select + Select --> Decision1 + + state Decision1 <> + Decision1 --> Purchase: [Add to Cart] + Decision1 --> Browse: [Continue Shopping] + + Purchase --> Payment + Payment --> Decision2 + + state Decision2 <> + Decision2 --> Receive: [Success] + Decision2 --> Purchase: [Retry] + + Receive --> Support + Support --> [*]: End + + Browse: 浏览商品 (Browse) + Select: 选择商品 (Select) + Purchase: 下单购买 (Purchase) + Payment: 支付处理 (Payment) + Receive: 收货确认 (Receive) + Support: 售后支持 (Support) +``` + +**Activity Diagram Elements:** +| Element | UML Standard | Mermaid Syntax | +|---------|--------------|----------------| +| Start Node | Filled circle | `[*] -->` | +| End Node | Bull's eye | `--> [*]` | +| Activity | Rounded rectangle | `StateName: Label` | +| Decision | Diamond | `state Name <>` | +| Transition | Arrow with guard | `--> Target: [condition]` | +| Fork/Join | Thick bar | `state Name { ... }` | + +### User Story Format + +``` +As a [role], +I want [feature/capability], +So that [business value/benefit]. +``` + +### INVEST Criteria + +Each user story MUST be: +- **I**ndependent: Can be developed separately +- **N**egotiable: Details can be discussed +- **V**aluable: Delivers value to user/business +- **E**stimable: Can be sized/estimated +- **S**mall: Fits within a sprint +- **T**estable: Has clear acceptance criteria + +### User Story Map Visualization + +> **Note**: Story Map is an Agile visualization technique (not UML). Use `graph TB` with subgraphs for matrix layout. + +```mermaid +graph TB + subgraph Activities["USER ACTIVITY FLOW →"] + direction LR + A1["📦 Activity 1
                Browse"] + A2["🔍 Activity 2
                Select"] + A3["💳 Activity 3
                Purchase"] + A4["📬 Activity 4
                Receive"] + A5["🛠️ Activity 5
                Support"] + A1 --> A2 --> A3 --> A4 --> A5 + end + + subgraph MVP["MVP Release"] + direction LR + S11[US-1.1] --> S21[US-2.1] --> S31[US-3.1] --> S41[US-4.1] + S12[US-1.2] --> S22[US-2.2] --> S32[US-3.2] + end + + subgraph V11["Version 1.1"] + direction LR + S13[US-1.3] --> S23[US-2.3] --> S33[US-3.3] --> S42[US-4.2] --> S51[US-5.1] + end + + subgraph V20["Version 2.0"] + direction LR + S14[US-1.4] --> S24[US-2.4] --> S35[US-3.5] --> S43[US-4.3] --> S52[US-5.2] + end + + A1 -.-> S11 + A1 -.-> S13 + A1 -.-> S14 + + style A1 fill:#e1f5fe,stroke:#01579b + style A2 fill:#e1f5fe,stroke:#01579b + style A3 fill:#e1f5fe,stroke:#01579b + style A4 fill:#e1f5fe,stroke:#01579b + style A5 fill:#e1f5fe,stroke:#01579b +``` + +**Story Map Structure:** +| Row | Description | Priority | +|-----|-------------|----------| +| **Activities** | User journey steps (left to right) | - | +| **MVP** | Minimum stories to launch | P0 | +| **V1.1** | First enhancement release | P1 | +| **V2.0** | Future features | P2 | + +### Story Map Documentation + +```markdown +## User Story Map: [Feature/Epic Name] + +### User Activities (Left to Right = User Flow) +1. **[Activity 1]**: [Description of what user is trying to do] +2. **[Activity 2]**: [Description] +3. **[Activity 3]**: [Description] + +### MVP Stories (Minimum to launch) +| Activity | Story ID | Story | Priority | +|----------|----------|-------|----------| +| Activity 1 | US-001 | As a [role], I want... | P0 | +| Activity 2 | US-002 | As a [role], I want... | P0 | + +### V1.1 Stories (First enhancement) +| Activity | Story ID | Story | Priority | +|----------|----------|-------|----------| +| Activity 1 | US-003 | As a [role], I want... | P1 | + +### V2.0 Stories (Future) +| Activity | Story ID | Story | Priority | +|----------|----------|-------|----------| +| Activity 1 | US-004 | As a [role], I want... | P2 | +``` + +--- + +## Method 2: Use Case Analysis + +### Use Case Diagram Elements + +```mermaid +graph TB + subgraph System["System Boundary"] + direction TB + UCA((Use Case A)) + UCB((Use Case B)) + UCC((Use Case C)) + UCD((Use Case D)) + + UCA -->|<>| UCC + UCA --> UCB + UCB -.->|<>| UCD + end + + Actor1[/"👤 Actor 1"\] + Actor2[/"👤 Actor 2"\] + + Actor1 --> UCA + Actor2 --> UCB + + style UCA fill:#e1f5fe,stroke:#01579b + style UCB fill:#e1f5fe,stroke:#01579b + style UCC fill:#e1f5fe,stroke:#01579b + style UCD fill:#fff3e0,stroke:#e65100 +``` + +**Diagram Elements:** +| Element | Mermaid Syntax | Description | +|---------|----------------|-------------| +| Actor | `[/"👤 Name"\]` | Stick figure representation | +| Use Case | `((Name))` | Ellipse shape | +| System Boundary | `subgraph` | Dashed rectangle container | +| Include | `-->\|<>\|` | Mandatory dependency | +| Extend | `-.->\|<>\|` | Optional extension | + +### Use Case Document Template + +```markdown +## Use Case: [UC-XXX] [Use Case Name] + +### Basic Information +| Field | Value | +|-------|-------| +| **Use Case ID** | UC-XXX | +| **Name** | [Descriptive name] | +| **Primary Actor** | [Who initiates] | +| **Secondary Actors** | [Other participants] | +| **Level** | User Goal / Subfunction | +| **Priority** | P0 / P1 / P2 | + +### Description +[Brief description of what this use case accomplishes] + +### Preconditions +1. [Condition that must be true before starting] +2. [Another precondition] + +### Postconditions (Success) +1. [State after successful completion] +2. [Another post-condition] + +### Main Flow (Happy Path) +| Step | Actor | System | +|------|-------|--------| +| 1 | [Actor action] | | +| 2 | | [System response] | +| 3 | [Actor action] | | +| 4 | | [System response] | + +### Alternative Flows +**A1: [Alternative scenario name]** +- Branches from step: [X] +- Condition: [When this alternative applies] +- Steps: + 1. [Alternative step] + 2. [Alternative step] +- Rejoins at step: [Y] or ends + +### Exception Flows +**E1: [Error scenario name]** +- Trigger: [What causes this exception] +- Steps: + 1. System displays error message: "[Exact message]" + 2. [Recovery action] +- End state: [How it ends] + +### Business Rules +| Rule ID | Rule Description | +|---------|------------------| +| BR-001 | [Rule that applies to this use case] | +| BR-002 | [Another rule] | + +### Non-Functional Requirements +- **Performance**: [Specific metrics] +- **Security**: [Security requirements] +``` + +--- + +## Method 3: Success Criteria Definition + +### Purpose + +Success Criteria define **measurable outcomes** that determine whether a requirement has been successfully implemented. They bridge the gap between user stories and acceptance tests. + +### SMART Criteria + +Each success criterion MUST be **SMART**: + +| Attribute | Description | Example | +|-----------|-------------|---------| +| **S**pecific | Clear and unambiguous | "Page loads in under 2 seconds" not "Page loads fast" | +| **M**easurable | Quantifiable metric | "95% of users complete checkout" | +| **A**chievable | Realistic given constraints | Consider technical limitations | +| **R**elevant | Aligned with business goals | Ties to user value | +| **T**ime-bound | Has defined timeframe | "Within first 30 days of launch" | + +### Success Criteria Categories + +| Category | Focus | Example Metrics | +|----------|-------|-----------------| +| **Functional** | Feature behavior | Task completion rate, error rate | +| **Performance** | Speed and efficiency | Response time, throughput | +| **Usability** | User experience | Task success rate, time-on-task | +| **Business** | Business outcomes | Conversion rate, revenue impact | +| **Quality** | System quality | Defect density, uptime | + +### Success Criteria Template + +```markdown +## Success Criteria: [Requirement/Feature ID] + +### SC-001: [Criterion Name] + +| Field | Value | +|-------|-------| +| **Requirement** | REQ-XXX / US-XXX | +| **Category** | Functional / Performance / Usability / Business / Quality | +| **Metric** | [What to measure] | +| **Target** | [Quantified goal] | +| **Baseline** | [Current state, if applicable] | +| **Measurement Method** | [How to measure] | +| **Verification Point** | [When to verify] | + +**Definition of Success**: +> [Clear statement of what success looks like] + +**Definition of Failure**: +> [Clear statement of what constitutes failure] +``` + +### Success Criteria Traceability + +```mermaid +graph LR + subgraph Requirements + REQ[REQ-001
                Requirement] + US[US-001
                User Story] + end + + subgraph SuccessCriteria[Success Criteria] + SC1[SC-001
                Functional] + SC2[SC-002
                Performance] + SC3[SC-003
                Business] + end + + subgraph Verification + TC[Test Cases] + KPI[KPIs] + MON[Monitoring] + end + + REQ --> SC1 + REQ --> SC2 + US --> SC3 + SC1 --> TC + SC2 --> MON + SC3 --> KPI + + style REQ fill:#e1f5fe,stroke:#01579b + style US fill:#e1f5fe,stroke:#01579b + style SC1 fill:#e8f5e9,stroke:#1b5e20 + style SC2 fill:#e8f5e9,stroke:#1b5e20 + style SC3 fill:#e8f5e9,stroke:#1b5e20 +``` + +### Example Success Criteria + +| SC ID | Requirement | Category | Metric | Target | +|-------|-------------|----------|--------|--------| +| SC-001 | US-001 Login | Functional | Login success rate | ≥ 99.5% | +| SC-002 | US-001 Login | Performance | Login response time | < 1 second | +| SC-003 | US-001 Login | Security | Failed login lockout | After 5 attempts | +| SC-004 | US-002 Search | Usability | Search result relevance | ≥ 90% accuracy | +| SC-005 | REQ-010 | Business | User retention | ≥ 80% after 30 days | + +--- + +## Method 4: Event Storming (for Complex Systems) + +### Event Storming Elements + +| Element | Color | Description | Example | +|---------|-------|-------------|---------| +| **Domain Event** | Orange | Something that happened | "Order Placed" | +| **Command** | Blue | Action that triggers event | "Place Order" | +| **Aggregate** | Yellow | Entity that receives command | "Order" | +| **Policy** | Purple | Reaction rule | "When order placed, notify warehouse" | +| **Read Model** | Green | Data needed for decision | "Available inventory" | +| **External System** | Pink | Third-party integration | "Payment Gateway" | +| **User/Actor** | Small yellow | Who triggers command | "Customer" | +| **Hot Spot** | Red | Unresolved question | "How to handle split shipment?" | + +### Event Storming Output + +```markdown +## Event Storming Results: [Domain Name] + +### Timeline (Left to Right) +``` +[User] → [Command] → [Aggregate] → [Domain Event] → [Policy] → [Next Command] +``` + +### Domain Events Identified +| Event | Aggregate | Triggered By | Triggers | +|-------|-----------|--------------|----------| +| Order Created | Order | Place Order command | Inventory Reserved | +| Payment Received | Payment | Process Payment command | Order Confirmed | +| Order Shipped | Order | Ship Order command | Customer Notified | + +### Commands Identified +| Command | Actor | Aggregate | Preconditions | +|---------|-------|-----------|---------------| +| Place Order | Customer | Order | Cart not empty | +| Process Payment | System | Payment | Order created | +| Ship Order | Warehouse Staff | Order | Payment received | + +### Aggregates Identified +| Aggregate | Responsibilities | Key Attributes | +|-----------|------------------|----------------| +| Order | Manage order lifecycle | items, status, total | +| Payment | Handle payment processing | amount, status, method | +| Inventory | Track stock levels | quantity, reserved | + +### Hot Spots (Unresolved Questions) +1. 🔴 [Question 1 - needs clarification] +2. 🔴 [Question 2 - needs decision] +``` + +--- + +## Method 5: Dependency Analysis + +### Dependency Types + +| Type | Description | Example | Risk Level | +|------|-------------|---------|------------| +| **Mandatory** | Must complete A before B | Login before checkout | High | +| **Optional** | A enhances B | Search filters enhance search | Low | +| **Conflicting** | A and B cannot coexist | Two auth methods | Critical | +| **External** | Depends on outside system | Payment gateway | High | + +### Dependency Matrix + +```markdown +## Requirements Dependency Matrix + +| Req ID | Depends On | Dependency Type | Impact if Delayed | +|--------|------------|-----------------|-------------------| +| REQ-005 | REQ-001, REQ-002 | Mandatory | Blocks entire feature | +| REQ-008 | REQ-005 | Mandatory | Blocks payment flow | +| REQ-010 | External API | External | Risk: API availability | +| REQ-012 | REQ-003 | Optional | Degraded experience | + +### Dependency Graph + +```mermaid +graph LR + REQ001[REQ-001] + REQ002[REQ-002] + REQ003[REQ-003] + REQ005[REQ-005] + REQ008[REQ-008] + REQ009[REQ-009] + REQ011[REQ-011] + REQ012[REQ-012] + + REQ001 --> REQ005 + REQ002 --> REQ005 + REQ005 --> REQ008 + REQ005 --> REQ009 + REQ008 --> REQ011 + REQ003 -.->|optional| REQ012 + + style REQ001 fill:#e1f5fe,stroke:#01579b + style REQ002 fill:#e1f5fe,stroke:#01579b + style REQ011 fill:#e8f5e9,stroke:#1b5e20 + style REQ012 fill:#fff3e0,stroke:#e65100 +``` + +### Critical Path + +```mermaid +graph LR + CP1[REQ-001
                User Registration] --> CP2[REQ-005
                Profile Setup] + CP2 --> CP3[REQ-008
                Data Validation] + CP3 --> CP4[REQ-011
                Account Activation] + + style CP1 fill:#ffebee,stroke:#b71c1c + style CP2 fill:#ffebee,stroke:#b71c1c + style CP3 fill:#ffebee,stroke:#b71c1c + style CP4 fill:#ffebee,stroke:#b71c1c +``` + +| Step | Req ID | Requirement | Depends On | Impact | +|------|--------|-------------|------------|--------| +| 1 | REQ-001 | User Registration | - | Entry point | +| 2 | REQ-005 | Profile Setup | REQ-001 | Core flow | +| 3 | REQ-008 | Data Validation | REQ-005 | Quality gate | +| 4 | REQ-011 | Account Activation | REQ-008 | **Blocks release** | + +**Path Summary**: 4 sequential dependencies, blocks release +**Bottleneck**: REQ-008 (Data Validation) - highest complexity + +### Risks Identified +| Risk | Requirements | Mitigation | +|------|--------------|------------| +| Circular dependency | [List] | [Solution] | +| External dependency | [List] | [Fallback plan] | +``` + +--- + +## Method 6: Domain Data Modeling + +### Purpose + +Create a comprehensive data model that defines all entities, their attributes, relationships, and state lifecycles. This model serves as the foundation for database design and API contracts. + +**OUTPUT FILE**: `.kiro/specs/[feature-name]/data-model.md` + +**OUTPUT TEMPLATE**: Use `template-data-model.md` for output format. + +### When to Create Data Model + +| Condition | Action | +|-----------|--------| +| New feature with data entities | Create complete data model | +| Existing entities being modified | Update relevant sections | +| Simple UI-only changes | May skip (reference existing model) | + +### Data Model Components + +| Component | Description | Diagram Type | +|-----------|-------------|--------------| +| **Entity Definitions** | All entities with attributes | Table format | +| **Relationships** | Entity relationships and cardinality | ER Diagram | +| **State Diagrams** | Entity lifecycle states | State Diagram | +| **Constraints** | Validation rules, referential integrity | Table format | +| **Data Dictionary** | Standard types, enumerations | Table format | + +### Entity Relationship Diagram (Mermaid) + +```mermaid +erDiagram + USER ||--o{ ORDER : "places" + USER { + string id PK + string email UK + string name + enum status + datetime created_at + } + ORDER ||--|{ ORDER_ITEM : "contains" + ORDER { + string id PK + string user_id FK + decimal total + enum status + datetime created_at + } + ORDER_ITEM { + string id PK + string order_id FK + string product_id FK + int quantity + decimal price + } + PRODUCT ||--o{ ORDER_ITEM : "included_in" + PRODUCT { + string id PK + string name + decimal price + int stock + } +``` + +### State Diagram (Mermaid) + +```mermaid +stateDiagram-v2 + [*] --> Draft: Create + + Draft --> Submitted: Submit + Draft --> Cancelled: Cancel + + Submitted --> Approved: Approve + Submitted --> Rejected: Reject + + Approved --> Active: Activate + Rejected --> Draft: Revise + + Active --> Completed: Complete + Active --> Cancelled: Cancel + + Completed --> [*] + Cancelled --> [*] +``` + +### Data Model Checklist + +- [ ] All entities from user stories identified +- [ ] Primary keys defined for all entities +- [ ] Foreign keys and relationships mapped +- [ ] Attribute types and constraints specified +- [ ] State diagrams for entities with lifecycle +- [ ] Validation rules documented +- [ ] Data volume estimates provided +- [ ] Glossary terms defined + +--- + +## Method 7: Non-Functional Requirements (NFR) Analysis + +### Purpose + +Systematically identify, categorize, and specify non-functional requirements that define system qualities beyond functional behavior. NFRs are critical for system architecture decisions and quality assurance. + +### NFR Categories (FURPS+ Model) + +| Category | Focus | Key Questions | +|----------|-------|---------------| +| **Performance** | Speed & Efficiency | Response time? Throughput? Concurrent users? | +| **Security** | Protection | Authentication? Authorization? Data encryption? Audit? | +| **Reliability** | Availability | Uptime SLA? Failover? Data backup? Recovery time? | +| **Usability** | User Experience | Accessibility (WCAG)? Learnability? Error handling? | +| **Scalability** | Growth Capacity | Horizontal/vertical scaling? Data volume growth? | +| **Maintainability** | Operational | Logging? Monitoring? Deployment? Documentation? | +| **Compatibility** | Integration | Browsers? Devices? OS? Third-party systems? | + +### NFR Specification Template + +```markdown +### NFR-001: [Requirement Name] + +| Field | Value | +|-------|-------| +| **Category** | Performance / Security / Reliability / Usability / Scalability / Maintainability / Compatibility | +| **Priority** | P0 / P1 / P2 | +| **Related FR** | US-XXX, UC-XXX (functional requirements this NFR applies to) | + +**Requirement Statement**: +> The system SHALL [measurable requirement statement] + +**Metric & Target**: +| Metric | Target | Measurement Method | +|--------|--------|-------------------| +| [What to measure] | [Quantified goal] | [How to verify] | + +**Rationale**: [Why this NFR is needed] + +**Constraints**: [Technical or business constraints affecting this NFR] +``` + +### NFR by Category Examples + +#### Performance + +| NFR ID | Requirement | Metric | Target | +|--------|-------------|--------|--------| +| NFR-P01 | Page load time | Time to First Contentful Paint | < 1.5s | +| NFR-P02 | API response time | 95th percentile latency | < 200ms | +| NFR-P03 | Concurrent users | Simultaneous active sessions | ≥ 10,000 | +| NFR-P04 | Throughput | Transactions per second | ≥ 1,000 TPS | + +#### Security + +| NFR ID | Requirement | Metric | Target | +|--------|-------------|--------|--------| +| NFR-S01 | Authentication | Multi-factor authentication | Required for admin | +| NFR-S02 | Data encryption | Encryption at rest | AES-256 | +| NFR-S03 | Data encryption | Encryption in transit | TLS 1.3 | +| NFR-S04 | Session management | Session timeout | 30 min inactive | +| NFR-S05 | Audit logging | Security events logged | 100% coverage | + +#### Reliability + +| NFR ID | Requirement | Metric | Target | +|--------|-------------|--------|--------| +| NFR-R01 | Availability | Uptime SLA | 99.9% (8.76h downtime/year) | +| NFR-R02 | Disaster recovery | Recovery Time Objective (RTO) | < 4 hours | +| NFR-R03 | Data durability | Recovery Point Objective (RPO) | < 1 hour | +| NFR-R04 | Backup | Backup frequency | Daily full, hourly incremental | + +#### Usability + +| NFR ID | Requirement | Metric | Target | +|--------|-------------|--------|--------| +| NFR-U01 | Accessibility | WCAG compliance | Level AA | +| NFR-U02 | Learnability | Time to complete key task (new user) | < 5 min | +| NFR-U03 | Error recovery | User can recover from error | Without data loss | +| NFR-U04 | Localization | Supported languages | EN, ZH-CN | + +#### Scalability + +| NFR ID | Requirement | Metric | Target | +|--------|-------------|--------|--------| +| NFR-SC01 | Horizontal scaling | Auto-scale trigger | CPU > 70% | +| NFR-SC02 | Data growth | Storage capacity plan | 100GB/year growth | +| NFR-SC03 | User growth | Support user base | 1M users by Year 2 | + +#### Maintainability + +| NFR ID | Requirement | Metric | Target | +|--------|-------------|--------|--------| +| NFR-M01 | Logging | Log retention | 90 days | +| NFR-M02 | Monitoring | System health dashboard | Real-time | +| NFR-M03 | Deployment | Deployment frequency | On-demand, < 30min | +| NFR-M04 | Documentation | API documentation | 100% coverage | + +#### Compatibility + +| NFR ID | Requirement | Metric | Target | +|--------|-------------|--------|--------| +| NFR-C01 | Browser support | Supported browsers | Chrome, Firefox, Safari, Edge (latest 2 versions) | +| NFR-C02 | Mobile support | Responsive design | iOS 14+, Android 10+ | +| NFR-C03 | API compatibility | API versioning | Backward compatible for 2 major versions | + +### NFR Prioritization Matrix + +```mermaid +quadrantChart + title NFR Priority Matrix + x-axis Low Impact --> High Impact + y-axis Low Effort --> High Effort + quadrant-1 Plan Carefully + quadrant-2 High Priority + quadrant-3 Low Priority + quadrant-4 Quick Wins + Performance: [0.8, 0.6] + Security: [0.9, 0.7] + Reliability: [0.85, 0.8] + Usability: [0.6, 0.4] + Scalability: [0.7, 0.75] +``` + +### NFR Checklist + +- [ ] All NFR categories reviewed (Performance, Security, Reliability, Usability, Scalability, Maintainability, Compatibility) +- [ ] Each NFR has measurable target and verification method +- [ ] NFRs linked to related functional requirements +- [ ] Priority assigned to each NFR +- [ ] Constraints and trade-offs documented +- [ ] Stakeholder sign-off on NFR targets + +--- + +## Exit Criteria (NON-NEGOTIABLE) + +| Criteria | Standard | Verification | Status | +|----------|----------|--------------|--------| +| **Diagram Standards** | All diagrams follow UML/Mermaid standards | Check against `helper-diagram-standards.md` | [ ] | +| **Expression Priority** | Diagrams used over tables/text | Verify no text-only requirements | [ ] | +| User Story Map | Core user journeys mapped | Verify activity flow | [ ] | +| Use Case Diagrams | Main use cases documented with Sequence Diagrams | Review interactions | [ ] | +| **Success Criteria** | SMART criteria defined for key requirements | Verify measurability | [ ] | +| **Data Model** | `data-model.md` created with entities and relationships | Verify ER diagram and state diagrams | [ ] | +| **NFR Analysis** | All NFR categories reviewed with measurable targets | Verify NFR completeness | [ ] | +| Dependency Graph | Dependencies mapped | Check for circular | [ ] | +| Feasibility Assessment | Technical risks evaluated | Risk assessment complete | [ ] | + +--- + +## Next Step + +After completing this phase, proceed to: + +**Phase 4: Clarification** +- Systematic questioning to eliminate ambiguity +- Requirement refinement and validation +- Release planning diff --git a/requirements-analyst/steering/phase4-requirements-clarification.md b/requirements-analyst/steering/phase4-requirements-clarification.md new file mode 100644 index 0000000..d7070f5 --- /dev/null +++ b/requirements-analyst/steering/phase4-requirements-clarification.md @@ -0,0 +1,461 @@ +--- +inclusion: agent +--- + +# Phase 4: Requirements Clarification + +**Phase Objective**: Eliminate ambiguity through targeted questioning and document all clarification decisions. +**Time Allocation**: 15% of total effort +**Your Role**: Professional Requirements Analyst + +--- + +## Quick Reference + +| Aspect | Guideline | +|--------|-----------| +| Goal | Clarify ALL critical ambiguities (no fixed limit) | +| Question Format | Multiple-choice (2-4 options) or Short phrase | +| Delivery | ONE question at a time, wait for answer | +| Output Files | `clarification.md` (log) + update Phase 3 outputs | + +### ⚠️ CRITICAL: Update Files After EACH Answer + +**After user answers EACH question, you MUST IMMEDIATELY:** +1. Write Q&A to `clarification.md` +2. Check and update ALL affected Phase 3 outputs (see `POWER.md` → Output Structure) + +**DO NOT** ask next question until all affected files are updated. + +--- + +## Output + +**File**: `.kiro/specs/[feature-name]/clarification.md` + +> **Dependencies**: See `POWER.md` → File Dependencies for required template and helper files. + +--- + +## Pre-Check (GATE CHECK) + +**MUST pass this check before starting**: + +- [ ] **Phase 3 completed?** Verify `requirements.md` exists with user stories and use cases +- [ ] **Ambiguities identified?** List requirements with `[NEEDS CLARIFICATION]` markers +- [ ] **Stakeholder available?** User can answer clarification questions + +**If ANY check fails**: STOP. Return to Phase 3 or wait for stakeholder availability. + +--- + +## Validation Failure Check (PRIORITY) + +**CRITICAL**: Before starting clarification, check if `validation.md` exists. If it does, this is a **re-clarification** session triggered by validation failures. + +### Step 1: Check for Validation File + +Check if `validation.md` exists in the current spec folder. + +### Step 2: If Validation File Exists + +**You MUST:** + +1. **Load and analyze** `validation.md` +2. **Extract failed dimensions** - Identify dimensions with score < 80% or status ❌/⚠️ +3. **List specific issues** - Extract the "Negative Findings" from each failed dimension +4. **Prioritize clarification** - Focus questions on issues causing validation failures + +### Step 3: Display Validation Failure Summary + +```markdown +--- +## Re-Clarification Session (Post-Validation) + +I detected a previous validation report. Here are the **validation failures** that need clarification: + +### Failed Dimensions Summary + +| Dimension | Score | Status | Key Issues | +|-----------|-------|--------|------------| +| [Dimension] | [X]% | ❌/⚠️ | [Issue summary] | +| ... | ... | ... | ... | + +### Priority Clarification Areas + +Based on validation failures, I will focus clarification on: + +1. **[Issue Category]**: [Specific issue from validation] + - Related Requirements: [REQ-XXX, REQ-YYY] + - Validation Finding: "[Quote from negative findings]" + +2. **[Issue Category]**: [Specific issue from validation] + - Related Requirements: [REQ-XXX] + - Validation Finding: "[Quote from negative findings]" + +--- +Proceeding with targeted clarification questions... +``` + +### Validation-to-Clarification Mapping + +| Failed Dimension | Clarification Focus | +|------------------|---------------------| +| **Authenticity** | Verify user needs, confirm stakeholder requirements | +| **Completeness** | Fill missing specifications, clarify unclear parts | +| **Consistency** | Resolve conflicts, align terminology | +| **Feasibility** | Clarify scope, discuss constraints with stakeholders | +| **Verifiability** | Define acceptance criteria, quantify requirements | + +### Question Priority Order (Re-Clarification) + +When re-clarifying after validation failure: + +1. **First**: Questions directly addressing validation failures (highest priority) +2. **Second**: Questions about related requirements affected by failures +3. **Third**: New ambiguities discovered during validation +4. **Last**: Standard ambiguity taxonomy items + +--- + +## Ambiguity Taxonomy (MUST SCAN) + +Perform a structured ambiguity scan using this taxonomy: + +### 1. Functional Scope & Behavior + +| Check Point | Questions to Consider | +|-------------|----------------------| +| Core user goals | What defines success for the user? | +| Success criteria | How do we measure if the feature works? | +| Out-of-scope | What is explicitly NOT included? | +| User roles | Are all personas clearly differentiated? | + +### 2. Domain & Data Model + +| Check Point | Questions to Consider | +|-------------|----------------------| +| Entities & attributes | Are all data fields defined? | +| Identity & uniqueness | What makes each record unique? | +| Lifecycle/state | What states can entities transition through? | +| Data volume | What scale assumptions are we making? | + +### 3. Interaction & UX Flow + +| Check Point | Questions to Consider | +|-------------|----------------------| +| User journeys | Are critical paths fully documented? | +| Error states | What happens when things go wrong? | +| Empty states | What does the user see with no data? | +| Loading states | How is progress communicated? | + +### 4. Non-Functional Quality Attributes + +| Check Point | Questions to Consider | +|-------------|----------------------| +| Performance | Latency and throughput targets? | +| Scalability | Horizontal/vertical limits? | +| Reliability | Uptime and recovery requirements? | +| Security | Authentication and authorization rules? | +| Compliance | Regulatory constraints? | + +### 5. Integration & External Dependencies + +| Check Point | Questions to Consider | +|-------------|----------------------| +| External APIs | Which services? Failure modes? | +| Data formats | Import/export specifications? | +| Protocol versions | API versioning strategy? | + +### 6. Edge Cases & Failure Handling + +| Check Point | Questions to Consider | +|-------------|----------------------| +| Negative scenarios | What if user provides invalid input? | +| Rate limiting | How to handle abuse? | +| Concurrent edits | Conflict resolution strategy? | + +### 7. Terminology & Consistency + +| Check Point | Questions to Consider | +|-------------|----------------------| +| Glossary terms | Are key terms defined? | +| Synonyms | Are deprecated terms identified? | + +--- + +## Execution Flow + +### Step 1: Load and Analyze Specification + +Read `requirements.md` and scan for ambiguities using the taxonomy above. + +**Identify**: +- Vague terms: "user-friendly", "fast", "secure", "flexible" +- Missing details: "users can login" (which users? how?) +- Unclear scope: "manage products" (create/edit/delete/view?) +- Undefined conditions: "when needed", "if required" +- Placeholders: `[TBD]`, `[NEEDS CLARIFICATION]` + +### Step 2: Generate Prioritized Questions + +Create a prioritized queue of clarification questions: + +**Question Constraints**: +- **Answerable**: Multiple-choice (2-4 options) OR Short phrase (<=5 words) +- **Impactful**: Must materially impact architecture, data model, UX, or compliance +- **Balanced**: Cover different categories from the taxonomy +- **Non-trivial**: Exclude already-answered or obvious questions + +**Priority Order**: +1. Functional scope ambiguities (blocking) +2. Data model ambiguities (architectural impact) +3. Non-functional requirements (quality impact) +4. Edge cases (robustness impact) +5. Terminology (consistency impact) + +### Step 3: Sequential Questioning (ONE AT A TIME) + +**CRITICAL**: Present EXACTLY ONE question at a time. Wait for answer before next question. + +#### Rule: One Question Per Response + +✅ **CORRECT**: +``` +What specific user role will be using this login feature? + +Why I'm asking: Different user types (admin, customer, guest) have different authentication requirements. +``` + +❌ **VIOLATION**: +``` +What user roles will use this? What are the security requirements? Do you need password reset? +``` + +#### Pre-Send Check (BEFORE each question) +- [ ] Am I asking only ONE question? +- [ ] Is this the highest priority unanswered question? +- [ ] Have I explained why I'm asking this? + +#### Multiple-Choice Question Format + +```markdown +**Question [N/Total]**: [Category] + +[Complete question text] + +**Recommended**: Option [X] - [Brief reason for recommendation] + +**Options**: + +> **A** - [Option A description] + +> **B** - [Option B description] + +> **C** - [Option C description] + +> **Other** - Provide your own answer (<=5 words) + +--- +Reply with option letter (e.g., "A"), or "yes" to accept recommendation, or enter your custom answer. +``` + +#### Short-Answer Question Format + +```markdown +**Question [N/Total]**: [Category] + +[Complete question text] + +**Suggested Answer**: [Your suggestion] - [Brief reason] + +--- +Enter your answer (<=5 words), or "yes" to accept suggestion. +``` + +### Step 4: Record Answers (MANDATORY) + +**CRITICAL**: You MUST create and maintain a clarification log file. This is NON-NEGOTIABLE. + +#### 4.1 Create Clarification Log (After First Answer) + +**IMMEDIATELY after the FIRST question is answered**, create: + +``` +.kiro/specs/[feature-name]/clarification.md +``` + +#### 4.2 Update After EACH Answer (IMMEDIATE) + +**CRITICAL**: After EACH question is answered, you MUST **IMMEDIATELY** perform ALL of the following before asking the next question: + +1. **Record to clarification log** (`clarification.md`): + - Append the Q&A record + - Update the Summary table + +2. **Update ALL affected Phase 3 outputs** (see `POWER.md` → Output Structure): + - Apply clarification to corresponding sections + - **Remove** `[NEEDS CLARIFICATION]` markers with resolved content + - **Add cross-reference** to clarification log + +3. **Verify both files saved** before proceeding to next question + +**DO NOT batch updates. Each answer triggers immediate updates to BOTH files.** + +### Step 5: Stop Conditions + +Stop asking questions when ANY of these apply: +- All critical ambiguities resolved +- User signals completion ("done", "enough", "no more") +- Remaining ambiguities are non-blocking (can defer to implementation) + +### Step 6: Per-Answer Validation + +After EACH answer update, verify: +- [ ] Q&A recorded in `clarification.md` +- [ ] ALL affected Phase 3 outputs updated +- [ ] `[NEEDS CLARIFICATION]` markers removed +- [ ] No contradictory statements introduced +- [ ] Terminology consistent across all files + +### Step 7: Completion Report + +**BEFORE reporting completion**, verify: +1. `clarification.md` has been created and saved +2. `requirements.md` has been updated +3. All questions and answers are recorded + +**Output completion report**: + +```markdown +## Clarification Complete + +### Files Updated + +| File | Path | Status | +|------|------|--------| +| Clarification Log | `.kiro/specs/[feature-name]/clarification.md` | CREATED | +| Analysis | `.kiro/specs/[feature-name]/requirements.md` | UPDATED | + +### Session Summary + +**Questions asked**: [N] +**Session date**: YYYY-MM-DD + +### Questions & Answers + +| # | Category | Question | Choice | +|---|----------|----------|--------| +| 1 | [Category] | [Brief question] | [Choice] | +| 2 | [Category] | [Brief question] | [Choice] | + +### Coverage Summary + +| Category | Status | +|----------|--------| +| Functional Scope | Resolved / Clear / Deferred | +| Domain & Data | Resolved / Clear / Deferred | +| Interaction & UX | Resolved / Clear / Deferred | +| Non-Functional | Resolved / Clear / Deferred | +| Integration | Resolved / Clear / Deferred | +| Edge Cases | Resolved / Clear / Deferred | +| Terminology | Resolved / Clear / Deferred | + +**Status Legend**: +- **Resolved**: Was ambiguous, now clarified +- **Clear**: Already sufficient in analysis +- **Deferred**: Non-blocking, can resolve during implementation + +### Next Steps Available + +Based on the clarification results, you can choose one of the following: + +| Option | Command | When to Choose | +|--------|---------|----------------| +| **A** | **Clarify** (Continue) | Deferred items need resolution, or new ambiguities found | +| **B** | **Analyze** (Re-analyze) | Significant changes require updating analysis document | +| **C** | **Validate** (Proceed) | All critical ambiguities resolved, ready for validation | + +### Recommendation + +[Based on coverage summary, recommend Option A/B/C with reason] + +--- +**Reply with A, B, or C to proceed, or describe what you'd like to do next.** +``` + +--- + +## Behavior Rules + +- **No ambiguities found**: "No critical ambiguities detected. Recommend proceeding to Phase 5: Validate." +- **Analysis file missing**: "Please complete Phase 3: Analyze first." +- **Respect user signals**: Stop immediately if user says "done" or "enough" +- **Avoid speculation**: Don't ask about tech stack unless it blocks functional clarity + +--- + +## Exit Criteria (NON-NEGOTIABLE) + +| Criteria | Standard | Verification | Status | +|----------|----------|--------------|--------| +| Clarification Log | `clarification.md` created | File exists | [ ] | +| All Q&A Recorded | Complete details for each question | Review log | [ ] | +| Analysis Updated | Clarifications applied to `requirements.md` | Cross-reference | [ ] | +| No Contradictions | Consistent statements | Review both files | [ ] | +| Critical Ambiguities | All critical ambiguities resolved | Review coverage | [ ] | + +--- + +## Next Step (MUST PROMPT USER) + +**CRITICAL**: After EVERY clarification session, you MUST present the following options to the user: + +```markdown +--- +## Clarification Session Complete + +**What would you like to do next?** + +| Option | Action | Description | +|--------|--------|-------------| +| **A** | **Clarify** | Continue clarification - resolve deferred items or new ambiguities | +| **B** | **Analyze** | Return to Analysis - update requirements.md with clarification results | +| **C** | **Validate** | Proceed to Validation - verify requirements through 5 dimensions | + +**Recommendation**: [Your recommendation based on session results] + +--- +Reply with **A**, **B**, or **C**, or describe what you'd like to do. +``` + +### When to Recommend Each Option + +| Recommend | Condition | +|-----------|-----------| +| **A (Clarify)** | >2 items deferred, or user mentioned new unclear areas | +| **B (Analyze)** | Major scope changes, new user stories needed, or analysis outdated | +| **C (Validate)** | All critical ambiguities resolved, coverage summary shows mostly "Resolved" or "Clear" | + +### Option Flows + +```mermaid +stateDiagram-v2 + [*] --> Clarify: Start + + Clarify --> OptionPrompt: Session Complete + + state OptionPrompt { + [*] --> ShowOptions + ShowOptions --> WaitUserChoice + } + + OptionPrompt --> Clarify: User chooses A + OptionPrompt --> Analyze: User chooses B + OptionPrompt --> Validate: User chooses C + + Analyze --> Clarify: May need more clarification + Validate --> [*]: Requirements validated + + note right of OptionPrompt: MUST show options\nafter EVERY session +``` diff --git a/requirements-analyst/steering/phase5-requirements-validation.md b/requirements-analyst/steering/phase5-requirements-validation.md new file mode 100644 index 0000000..fea3439 --- /dev/null +++ b/requirements-analyst/steering/phase5-requirements-validation.md @@ -0,0 +1,711 @@ +--- +inclusion: agent +--- + +# Phase 5: Requirements Validation + +**Phase Objective**: Validate requirements through 5 critical dimensions to ensure they are ready for implementation. +**Time Allocation**: 15% of total effort +**Your Role**: Professional Requirements Analyst + +--- + +## Quick Reference + +| Validation Dimension | Focus | Key Question | +|---------------------|-------|--------------| +| **Authenticity** | Real need | Is this a genuine user/business need? | +| **Completeness** | Coverage | Are all aspects fully specified? | +| **Consistency** | Coherence | Are requirements conflict-free? | +| **Feasibility** | Achievability | Is it technically and economically viable? | +| **Verifiability** | Testability | Can we objectively verify it's met? | + +--- + +## Output + +**File**: `.kiro/specs/[feature-name]/validation.md` + +> **Dependencies**: See `POWER.md` → File Dependencies for required template and helper files. + +--- + +## The 5 Validation Dimensions (CORE FRAMEWORK) + +```mermaid +graph TB + subgraph ValidationFramework["Requirements Validation Framework"] + direction TB + V1[/"🎯 Authenticity
                真实性"/] + V2[/"📋 Completeness
                完整性"/] + V3[/"🔗 Consistency
                一致性"/] + V4[/"⚖️ Feasibility
                可行性"/] + V5[/"✅ Verifiability
                可验证性"/] + end + + REQ[Requirements] --> V1 + V1 --> V2 + V2 --> V3 + V3 --> V4 + V4 --> V5 + V5 --> VALID[Validated Requirements] + + style V1 fill:#e1f5fe,stroke:#01579b + style V2 fill:#e1f5fe,stroke:#01579b + style V3 fill:#e1f5fe,stroke:#01579b + style V4 fill:#fff3e0,stroke:#e65100 + style V5 fill:#e8f5e9,stroke:#1b5e20 +``` + +--- + +## MANDATORY: Multi-Role Validation + +Requirements MUST be validated from 5 role perspectives (see `helper-multi-role-validation.md`): +- **Product Manager (PM)**: Business value, user need, strategic alignment +- **Requirements Analyst (RA)**: Completeness, clarity, traceability +- **Software Architect (SA)**: Technical feasibility, architecture impact, NFRs +- **Software Engineer (SE)**: Implementation clarity, effort estimation, error handling +- **Test Engineer (TE)**: Testability, acceptance criteria, test coverage + +--- + +## Pre-Check (GATE CHECK) + +**MUST pass this check before starting**: + +- [ ] **Phase 4 completed?** Verify `clarification.md` exists with resolved ambiguities +- [ ] **Requirements documented?** All requirements in `requirements.md` are clarified +- [ ] **Stakeholders available?** Reviewers from different roles identified + +**If ANY check fails**: STOP. Return to Phase 4. + +--- + +## Dimension 1: Authenticity Validation (真实性验证) + +### Purpose + +Verify that requirements represent **genuine user needs** and **real business problems**, not assumptions or "nice-to-haves". + +### Validation Criteria + +| Criterion | Question | Evidence Required | +|-----------|----------|-------------------| +| **User Origin** | Did this come from actual users? | User interviews, feedback logs | +| **Problem Evidence** | Is there proof the problem exists? | Support tickets, user complaints, analytics | +| **Business Alignment** | Does it support business goals? | Business case, strategic plan link | +| **Stakeholder Confirmation** | Have stakeholders validated this need? | Sign-off, meeting minutes | +| **Usage Frequency** | How often will this be used? | Usage projections, market data | + +### Authenticity Checklist + +```markdown +## Authenticity Validation Checklist + +### Source Verification +- [ ] Requirement traced to specific user/stakeholder request +- [ ] Original request documented (interview, ticket, email) +- [ ] Not based solely on assumptions or competitor features + +### Problem Validation +- [ ] Problem statement clearly articulated +- [ ] Evidence of problem exists (metrics, complaints, observations) +- [ ] Impact of NOT solving this problem quantified + +### Stakeholder Validation +- [ ] Business sponsor confirmed the need +- [ ] End users confirmed this solves their problem +- [ ] No stakeholder objections recorded + +### Business Value +- [ ] Clear business benefit articulated +- [ ] ROI or value proposition defined +- [ ] Aligned with product strategy/roadmap +``` + +### Red Flags (Authenticity Issues) + +| Red Flag | Description | Action | +|----------|-------------|--------| +| 🚩 "Users might want..." | Assumption without evidence | Conduct user research | +| 🚩 "Competitor has it" | Feature copying without validation | Validate with YOUR users | +| 🚩 No stakeholder source | Origin unclear | Trace back to source | +| 🚩 "Future-proofing" | Speculative requirement | Defer or validate need | + +--- + +## Dimension 2: Completeness Validation (完整性验证) + +### Purpose + +Ensure requirements are **fully specified** with no missing information, gaps, or TBDs. + +### Completeness Model + +```mermaid +graph TB + subgraph Completeness["Completeness Dimensions"] + direction LR + C1[Functional
                Coverage] + C2[Data
                Coverage] + C3[Flow
                Coverage] + C4[State
                Coverage] + C5[Error
                Coverage] + C6[NFR
                Coverage] + end + + style C1 fill:#e1f5fe + style C2 fill:#e1f5fe + style C3 fill:#e1f5fe + style C4 fill:#fff3e0 + style C5 fill:#ffebee + style C6 fill:#f3e5f5 +``` + +### Completeness Checklist + +```markdown +## Completeness Validation Checklist + +### Functional Coverage +- [ ] All user roles/personas covered +- [ ] All CRUD operations specified (if applicable) +- [ ] All business rules documented +- [ ] All decision points have defined outcomes + +### Data Coverage +- [ ] All data entities defined +- [ ] All attributes specified with types +- [ ] All relationships documented +- [ ] Data validation rules complete +- [ ] Data lifecycle (create, update, archive, delete) defined + +### Flow Coverage +- [ ] Main success scenarios documented +- [ ] Alternative flows identified +- [ ] Entry and exit points clear +- [ ] Handoffs between actors/systems defined + +### State Coverage +- [ ] All possible states identified +- [ ] State transitions defined +- [ ] Transition triggers specified +- [ ] Invalid state transitions documented + +### Error Coverage +- [ ] Error conditions identified +- [ ] Error messages specified +- [ ] Recovery procedures defined +- [ ] Error escalation paths documented + +### Non-Functional Coverage +- [ ] Performance requirements quantified +- [ ] Security requirements specified +- [ ] Scalability requirements defined +- [ ] Availability requirements documented +- [ ] Compliance requirements listed +``` + +### Completeness Metrics + +| Category | Total Items | Specified | Complete (%) | Target | +|----------|-------------|-----------|--------------|--------| +| Functional | [N] | [N] | [%] | ≥95% | +| Data | [N] | [N] | [%] | ≥95% | +| Flows | [N] | [N] | [%] | ≥90% | +| States | [N] | [N] | [%] | ≥90% | +| Errors | [N] | [N] | [%] | ≥85% | +| NFRs | [N] | [N] | [%] | ≥90% | + +--- + +## Dimension 3: Consistency Validation (一致性验证) + +### Purpose + +Ensure requirements are **internally coherent** with no conflicts, contradictions, or ambiguous overlaps. + +### Consistency Types + +| Type | Description | Example | +|------|-------------|---------| +| **Internal** | No conflicts within same requirement | Field is both "required" and "optional" | +| **Inter-requirement** | No conflicts between requirements | REQ-1 says A, REQ-2 says NOT A | +| **Terminology** | Same term means same thing everywhere | "User" vs "Customer" vs "Client" | +| **Data** | Data definitions consistent | Field length differs in different places | +| **Temporal** | No timeline conflicts | Deadline A before deadline B, but B is prerequisite | + +### Consistency Checklist + +```markdown +## Consistency Validation Checklist + +### Terminology Consistency +- [ ] Glossary defined and maintained +- [ ] Same concepts use same terms +- [ ] No synonyms used interchangeably +- [ ] Acronyms expanded on first use + +### Data Consistency +- [ ] Field names consistent across requirements +- [ ] Data types consistent for same fields +- [ ] Validation rules consistent +- [ ] Format specifications consistent (dates, numbers, etc.) + +### Logic Consistency +- [ ] No contradictory business rules +- [ ] No conflicting conditions +- [ ] Priority order logical (no circular dependencies) +- [ ] Precedence rules clear when conflicts possible + +### Reference Consistency +- [ ] Cross-references valid and up-to-date +- [ ] No orphan requirements (unreferenced) +- [ ] No broken links to design/test documents +- [ ] Version references consistent +``` + +### Conflict Detection Matrix + +| Req A | Req B | Conflict Type | Resolution | +|-------|-------|---------------|------------| +| REQ-001 | REQ-005 | [Type] | [How resolved] | +| REQ-003 | REQ-007 | [Type] | [How resolved] | + +--- + +## Dimension 4: Feasibility Validation (可行性验证) + +### Purpose + +Validate that requirements are **achievable** from technical, economic, operational, and schedule perspectives. + +### Feasibility Dimensions + +```mermaid +graph TB + subgraph FeasibilityTypes["Comprehensive Feasibility Assessment"] + direction TB + TF["🔧 Technical Feasibility
                技术可行性"] + EF["💰 Economic Feasibility
                经济可行性"] + OF["⚙️ Operational Feasibility
                运营可行性"] + SF["📅 Schedule Feasibility
                时间可行性"] + LF["⚖️ Legal/Compliance
                合规可行性"] + end + + style TF fill:#e1f5fe,stroke:#01579b + style EF fill:#e8f5e9,stroke:#1b5e20 + style OF fill:#fff3e0,stroke:#e65100 + style SF fill:#f3e5f5,stroke:#4a148c + style LF fill:#ffebee,stroke:#b71c1c +``` + +### 4.1 Technical Feasibility (技术可行性) + +| Assessment Area | Questions | Rating | +|-----------------|-----------|--------| +| **Technology Maturity** | Is the required technology proven? | High/Medium/Low | +| **Team Capability** | Does team have required skills? | High/Medium/Low | +| **Architecture Fit** | Compatible with existing architecture? | High/Medium/Low | +| **Integration Complexity** | Can we integrate with required systems? | High/Medium/Low | +| **Performance Achievability** | Can we meet performance requirements? | High/Medium/Low | +| **Security Implementation** | Can we implement security requirements? | High/Medium/Low | + +### 4.2 Economic Feasibility (经济可行性) + +```markdown +## Economic Feasibility Analysis + +### Development Costs +| Cost Category | Estimate | Confidence | +|---------------|----------|------------| +| Development effort | [Person-months] | High/Medium/Low | +| Infrastructure | [Cost] | High/Medium/Low | +| Third-party licenses | [Cost] | High/Medium/Low | +| External services | [Cost] | High/Medium/Low | +| **Total Development** | **[Sum]** | | + +### Operational Costs (Annual) +| Cost Category | Estimate | Confidence | +|---------------|----------|------------| +| Hosting/Infrastructure | [Cost] | High/Medium/Low | +| Maintenance | [Cost] | High/Medium/Low | +| Support | [Cost] | High/Medium/Low | +| Third-party fees | [Cost] | High/Medium/Low | +| **Total Operational** | **[Sum]** | | + +### Benefit Analysis +| Benefit Category | Estimate | Timeframe | +|------------------|----------|-----------| +| Revenue increase | [Amount] | [Period] | +| Cost reduction | [Amount] | [Period] | +| Efficiency gain | [Amount] | [Period] | +| Risk mitigation | [Value] | [Period] | +| **Total Benefit** | **[Sum]** | | + +### ROI Calculation +- **Total Investment**: [Development + Year 1 Operational] +- **Annual Benefit**: [Total Benefit] +- **Payback Period**: [Months/Years] +- **3-Year ROI**: [Percentage] + +### Economic Decision +- [ ] ✅ Economically viable (ROI meets threshold) +- [ ] ⚠️ Marginal (requires further analysis) +- [ ] ❌ Not viable (costs exceed benefits) +``` + +### 4.3 Operational Feasibility (运营可行性) + +| Assessment Area | Questions | Status | +|-----------------|-----------|--------| +| **Process Impact** | How will this change existing processes? | [Assessment] | +| **Training Required** | What training is needed? | [Hours/Cost] | +| **Change Management** | How disruptive is this change? | High/Medium/Low | +| **Support Capability** | Can support team handle this? | Yes/Needs Scaling | +| **Data Migration** | Is data migration required? | [Scope/Risk] | + +### 4.4 Schedule Feasibility (时间可行性) + +| Milestone | Required Date | Achievable Date | Gap | Risk | +|-----------|---------------|-----------------|-----|------| +| Design Complete | [Date] | [Date] | [Days] | High/Medium/Low | +| Development Complete | [Date] | [Date] | [Days] | High/Medium/Low | +| Testing Complete | [Date] | [Date] | [Days] | High/Medium/Low | +| Release | [Date] | [Date] | [Days] | High/Medium/Low | + +### 4.5 Legal/Compliance Feasibility (合规可行性) + +| Requirement | Regulation | Compliance Status | Gap | +|-------------|------------|-------------------|-----| +| Data Privacy | GDPR/CCPA | Compliant/Gap | [Description] | +| Accessibility | WCAG 2.1 | Compliant/Gap | [Description] | +| Industry Specific | [Regulation] | Compliant/Gap | [Description] | + +### Feasibility Summary + +| Dimension | Rating | Risk Level | Blocking Issues | +|-----------|--------|------------|-----------------| +| Technical | High/Medium/Low | High/Medium/Low | [Count] | +| Economic | Viable/Marginal/Not Viable | High/Medium/Low | [Count] | +| Operational | High/Medium/Low | High/Medium/Low | [Count] | +| Schedule | Achievable/At Risk/Not Achievable | High/Medium/Low | [Count] | +| Legal/Compliance | Compliant/Gaps/Non-compliant | High/Medium/Low | [Count] | + +--- + +## Dimension 5: Verifiability Validation (可验证性验证) + +### Purpose + +Ensure every requirement can be **objectively verified** through testing, measurement, or inspection. + +### Verifiability Criteria + +| Criterion | Description | Example | +|-----------|-------------|---------| +| **Measurable** | Has quantifiable target | "Response time < 2 seconds" | +| **Observable** | Can see/detect outcome | "Button changes to green" | +| **Testable** | Can create test case | Clear pass/fail criteria | +| **Demonstrable** | Can show to stakeholder | Working prototype possible | + +### 5.1 Vague Terms Check (MANDATORY) + +**Scan ALL requirements** for ambiguous terms that prevent objective verification. + +| Category | Vague Terms to Detect | Quantified Alternative | +|----------|----------------------|------------------------| +| **Performance** | fast, quick, responsive, efficient | "< 2s response time", "95th percentile < 500ms" | +| **Usability** | user-friendly, easy, intuitive, simple | "Task completion rate > 90%", "< 3 clicks" | +| **Quality** | reliable, stable, robust, secure, safe | "99.9% uptime", "OWASP Top 10 compliant" | +| **Flexibility** | flexible, configurable, extensible | "Supports N configuration options" | +| **Scale** | scalable, many, few, large, small | "10,000 concurrent users", "1TB storage" | + +**Action Required**: For each vague term found, provide quantified replacement recommendation. + +### 5.2 Non-Quantified Standards Check (MANDATORY) + +**Scan ALL requirements** for standards lacking measurable metrics. + +| Standard Type | Non-Quantified Example | Quantified Example | +|---------------|------------------------|-------------------| +| **Time** | "fast loading", "quick response" | "Page load < 3s on 4G", "API response < 200ms" | +| **Capacity** | "support many users", "handle large data" | "10,000 concurrent users", "100GB dataset" | +| **Availability** | "high availability", "always available" | "99.9% uptime", "RTO < 1 hour" | +| **Quality** | "low error rate", "high accuracy" | "Error rate < 0.1%", "Accuracy > 95%" | +| **Performance** | "good throughput", "low latency" | "1000 TPS", "P99 latency < 100ms" | + +**Action Required**: For each non-quantified standard, specify measurable metric with threshold. + +### Verifiability Checklist + +```markdown +## Verifiability Validation Checklist + +### Quantification +- [ ] Performance requirements have numeric targets +- [ ] Capacity requirements have specific limits +- [ ] Quality requirements have measurable thresholds +- [ ] No vague terms like "fast", "user-friendly", "secure" + +### Test Design +- [ ] Each requirement has at least one test case design +- [ ] Acceptance criteria in Given-When-Then format +- [ ] Edge cases identified with test scenarios +- [ ] Negative test cases designed + +### Verification Method +- [ ] Verification method specified for each requirement + - [ ] Test (automated/manual) + - [ ] Inspection (code review, document review) + - [ ] Analysis (calculation, simulation) + - [ ] Demonstration (prototype, live demo) + +### Acceptance Criteria +- [ ] Every requirement has acceptance criteria +- [ ] Criteria are specific and unambiguous +- [ ] Criteria are achievable (not impossible to meet) +- [ ] Criteria are independent (not relying on uncontrolled factors) +``` + +### GWT Acceptance Criteria Format + +```gherkin +## Requirement: [REQ-ID] [Requirement Name] + +### AC-1: [Scenario Name] +Given [precondition/context] + And [additional precondition] +When [action/trigger] +Then [expected outcome] + And [additional outcome with measurable criteria] + +### AC-2: [Error Scenario] +Given [precondition] +When [error condition] +Then [error handling behavior] + And [user notification with specific message] +``` + +### Verification Matrix + +| Req ID | Verification Method | Test Cases | Acceptance Criteria | Status | +|--------|---------------------|------------|---------------------|--------| +| REQ-001 | Test | TC-001~003 | AC-001~003 | ✅ Verifiable | +| REQ-002 | Demonstration | Demo-001 | AC-004~005 | ✅ Verifiable | +| REQ-003 | Inspection | Review-001 | AC-006 | ⚠️ Needs refinement | + +--- + +## Validation Process Flow + +```mermaid +stateDiagram-v2 + [*] --> LoadRequirements: Start Validation + + LoadRequirements --> AuthenticityCheck: Load from requirements.md + + state AuthenticityCheck { + [*] --> VerifySource + VerifySource --> ValidateProblem + ValidateProblem --> ConfirmStakeholder + ConfirmStakeholder --> [*] + } + + AuthenticityCheck --> CompletenessCheck: Pass + + state CompletenessCheck { + [*] --> CheckFunctional + CheckFunctional --> CheckData + CheckData --> CheckFlows + CheckFlows --> CheckNFRs + CheckNFRs --> [*] + } + + CompletenessCheck --> ConsistencyCheck: Pass + + state ConsistencyCheck { + [*] --> CheckTerminology + CheckTerminology --> CheckLogic + CheckLogic --> DetectConflicts + DetectConflicts --> [*] + } + + ConsistencyCheck --> FeasibilityCheck: Pass + + state FeasibilityCheck { + [*] --> TechnicalAssessment + TechnicalAssessment --> EconomicAssessment + EconomicAssessment --> OperationalAssessment + OperationalAssessment --> ScheduleAssessment + ScheduleAssessment --> [*] + } + + FeasibilityCheck --> VerifiabilityCheck: Pass + + state VerifiabilityCheck { + [*] --> CheckMeasurability + CheckMeasurability --> DesignTests + DesignTests --> WriteGWT + WriteGWT --> [*] + } + + VerifiabilityCheck --> ValidationComplete: All Pass + ValidationComplete --> [*]: Generate Report + + AuthenticityCheck --> IssueResolution: Fail + CompletenessCheck --> IssueResolution: Fail + ConsistencyCheck --> IssueResolution: Fail + FeasibilityCheck --> IssueResolution: Fail + VerifiabilityCheck --> IssueResolution: Fail + + IssueResolution --> AuthenticityCheck: Resolved +``` + +--- + +## Validation Report Output + +### Report Structure Overview + +The validation report includes: + +1. **Executive Summary** - Overall validation status +2. **Dimension Summary Table** - Quick overview of all 5 dimensions +3. **Validation Radar Chart** - Visual representation of scores (radar chart + progress bars) +4. **Detailed Score Justification** - For each dimension: + - Score calculation formula + - Positive findings (why score is this high) + - Negative findings (why score is not higher) + - Verdict (2-3 sentence explanation) +5. **Multi-Role Validation** - Sign-off matrix from 5 role perspectives +6. **Traceability Matrix** - Requirements to test case mapping +7. **Outstanding Issues** - Unresolved items with severity and owner +8. **Sign-Off** - Stakeholder approvals + +### Score Justification Requirements + +**CRITICAL**: Every dimension score MUST include: + +| Requirement | Description | +|-------------|-------------| +| **Score Calculation** | Formula showing how percentage was derived | +| **Positive Findings** | Evidence table explaining why score is this high | +| **Negative Findings** | Issues table explaining why score is not higher | +| **Verdict** | 2-3 sentences summarizing the score justification | + +### Radar Chart Requirements + +The radar chart section MUST include: +- Mermaid `radar-beta` radar chart with 80% threshold curve +- Progress bar visualization table +- Analysis summary (average, highest, lowest, balance) +- Key insight (1-2 sentences) + +--- + +## Exit Criteria (NON-NEGOTIABLE) + +| Criterion | Standard | Verification | Status | +|----------|----------|--------------|--------| +| **Authenticity** | All P0/P1 requirements have documented origin | Source traced | [ ] | +| **Completeness** | ≥95% functional, ≥90% NFR coverage | Checklist complete | [ ] | +| **Consistency** | Zero unresolved conflicts | Conflict matrix clear | [ ] | +| **Feasibility** | All dimensions assessed, no blockers | Assessment complete | [ ] | +| **Verifiability** | 100% P0 requirements have GWT | Test design exists | [ ] | +| **Multi-Role Review** | 5 role perspectives applied | Checklist complete | [ ] | +| **Sign-Off** | Key stakeholders approved | Signatures obtained | [ ] | + +**CRITICAL**: NEVER mark validation complete if critical issues remain unresolved. + +--- + +## Next Step (MUST PROMPT USER) + +**CRITICAL**: After EVERY validation session, you MUST present the following options to the user: + +```markdown +--- +## Validation Session Complete + +### Validation Result Summary + +| Dimension | Score | Status | Issues | +|-----------|-------|--------|--------| +| Authenticity | [X]% | ✅/⚠️/❌ | [Count] | +| Completeness | [X]% | ✅/⚠️/❌ | [Count] | +| Consistency | [X]% | ✅/⚠️/❌ | [Count] | +| Feasibility | [X]% | ✅/⚠️/❌ | [Count] | +| Verifiability | [X]% | ✅/⚠️/❌ | [Count] | + +**Overall Status**: [PASS / FAIL] + +--- + +**What would you like to do next?** + +| Option | Action | Description | +|--------|--------|-------------| +| **A** | **Specify** | Proceed to Specification - write PRD, API spec, BDD, RTM | +| **B** | **Validate** | Continue Validation - address remaining issues or re-validate | +| **C** | **Clarify** | Return to Clarification - resolve ambiguities causing validation failures | +| **D** | **Analyze** | Return to Analysis - update requirements based on validation findings | + +**Recommendation**: [Your recommendation based on validation results] + +**Reason**: [Why this recommendation - reference specific failed dimensions/issues] + +--- +Reply with **A**, **B**, **C**, or **D**, or describe what you'd like to do. +``` + +### When to Recommend Each Option + +| Recommend | Condition | Typical Failed Dimensions | +|-----------|-----------|---------------------------| +| **A (Specify)** | All 5 dimensions ≥80%, no critical issues | None | +| **B (Validate)** | Minor issues remain, need to verify fixes | Any with minor issues | +| **C (Clarify)** | Ambiguities, unclear requirements, stakeholder input needed | Authenticity, Completeness (unclear parts) | +| **D (Analyze)** | Major gaps in requirements, need restructuring or new requirements | Completeness (missing), Consistency, Feasibility | + +### Validation Failure Routing Guide + +| Failed Dimension | Primary Issue | Recommended Action | +|------------------|---------------|-------------------| +| **Authenticity** | Unverified user needs | **C (Clarify)** - Need stakeholder confirmation | +| **Completeness** | Missing requirements | **D (Analyze)** - Need to add/expand requirements | +| **Completeness** | Unclear specifications | **C (Clarify)** - Need to resolve ambiguities | +| **Consistency** | Conflicting requirements | **D (Analyze)** - Need to restructure/resolve conflicts | +| **Feasibility** | Technical blockers | **D (Analyze)** - Need to redesign approach | +| **Feasibility** | Resource/schedule issues | **C (Clarify)** - Need stakeholder input on scope | +| **Verifiability** | Missing acceptance criteria | **C (Clarify)** - Need to define test criteria | + +### Option Flows + +```mermaid +stateDiagram-v2 + [*] --> Validate: Start + + Validate --> OptionPrompt: Session Complete + + state OptionPrompt { + [*] --> EvaluateResults + EvaluateResults --> ShowOptions + ShowOptions --> WaitUserChoice + } + + OptionPrompt --> Specify: A (All Pass) + OptionPrompt --> Validate: B (Minor Issues) + OptionPrompt --> Clarify: C (Ambiguities) + OptionPrompt --> Analyze: D (Major Gaps) + + Clarify --> Validate: After clarification + Analyze --> Clarify: After analysis update + Analyze --> Validate: Direct re-validation + Specify --> [*]: Requirements specified + + note right of OptionPrompt: MUST show options\nafter EVERY session + note left of Analyze: Return here for:\n- Missing requirements\n- Conflicts\n- Feasibility issues + note left of Clarify: Return here for:\n- Ambiguities\n- Stakeholder input\n- Acceptance criteria +``` diff --git a/requirements-analyst/steering/phase6-requirements-specification.md b/requirements-analyst/steering/phase6-requirements-specification.md new file mode 100644 index 0000000..8610d5e --- /dev/null +++ b/requirements-analyst/steering/phase6-requirements-specification.md @@ -0,0 +1,370 @@ +--- +inclusion: agent +--- + +# Phase 6: Requirements Specification + +**Phase Objective**: Formalize validated requirements into unified documentation, establish requirements baseline. +**Time Allocation**: 10% of total effort +**Your Role**: Professional Requirements Analyst + +--- + +## Quick Reference + +| Deliverable | Format | Purpose | Mandatory? | +|-------------|--------|---------|------------| +| PRD Document | Markdown/PDF | Complete product requirements | ✅ Yes | +| API Specification | OpenAPI YAML | API contract definition | If API-heavy | +| RTM | Markdown | Requirements traceability matrix | ✅ Yes | +| Requirements Baseline | Version controlled | Change management | ✅ Yes | + +**Baseline Establishment Process**: +1. Requirements Freeze → 2. Formal Review → 3. Stakeholder Approval → 4. Version Release → 5. Change Control + +--- + +## Output + +**Primary Output**: `.kiro/specs/[feature-name]/prd.md` (Product Requirements Document) + +**Additional Deliverables**: +- `.kiro/specs/[feature-name]/api.yaml` - OpenAPI specification (if applicable) +- `.kiro/specs/[feature-name]/rtm.md` - Requirements Traceability Matrix + +> **Dependencies**: See `POWER.md` → File Dependencies for required template and helper files. + +--- + +## Pre-Check (GATE CHECK) + +**MUST satisfy these conditions before starting**: + +| Check Item | Requirement | Status | +|-----------|-------------|--------| +| Phase 5 Complete | ALL Phase 5 validation criteria satisfied | [ ] | +| All Requirements Validated | Validated and approved requirements | [ ] | +| Stakeholder Alignment | Consensus on requirements | [ ] | + +**If check fails**: STOP. Return to Phase 5 and complete validation. + +--- + +## Custom Template Support (MUST ASK FIRST) + +**CRITICAL**: Before generating any specification documents, you MUST ask the user about custom templates. + +### Template Inquiry (MANDATORY) + +```markdown +--- +## Specification Template Selection + +Before I generate the specification documents, I need to know your template preferences. + +**Do you want to use a custom specification template?** + +| Option | Description | +|--------|-------------| +| **A** | **Use Default Templates** - Use the built-in PRD and API templates | +| **B** | **Use Custom Template** - Provide your own specification template | +| **C** | **Use Both** - Start with custom template, supplement with default sections | + +--- +Reply with **A**, **B**, or **C**. + +If you choose **B** or **C**, please provide: +- Template file path (e.g., `/path/to/template.md`) +- Or template name if stored in `.kiro/templates/` directory +``` + +### Custom Template Handling + +#### If User Chooses B or C: + +1. **Request Template Location**: +```markdown +Please provide the custom template: + +**Option 1**: File path +> Example: `/Users/you/templates/prd-template.md` +> Example: `./templates/my-spec-template.md` + +**Option 2**: Template name (if in `.kiro/templates/`) +> Example: `company-prd` (will look for `.kiro/templates/company-prd.md`) + +**Option 3**: Paste template content directly +> You can paste your template content here if it's short. +``` + +2. **Validate Template**: + - Check if file exists + - Read and parse template structure + - Identify placeholders (e.g., `[Product Name]`, `{{feature}}`, `$VARIABLE`) + - Report template structure to user + +3. **Apply Custom Template**: +```markdown +### Template Analysis + +I've analyzed your custom template. Here's what I found: + +| Aspect | Finding | +|--------|---------| +| **Template Path** | [Path] | +| **Sections Found** | [List of sections] | +| **Placeholders** | [List of variables to fill] | +| **Compatible With** | PRD / API / BDD / Other | + +**Missing Sections** (compared to standard): +- [Section 1] - Recommend adding for completeness +- [Section 2] - Optional but valuable + +Shall I proceed with this template? (Yes/No) +``` + +### Template Storage Locations + +| Priority | Location | Description | +|----------|----------|-------------| +| 1 | User-provided path | Explicit file path from user | +| 2 | `.kiro/templates/` | Project-specific templates | +| 3 | `~/.kiro/templates/` | User-global templates | +| 4 | Built-in templates | Default templates in this document | + +### Custom Template Placeholders + +Support these placeholder formats: + +| Format | Example | Description | +|--------|---------|-------------| +| `[Brackets]` | `[Product Name]` | Simple placeholder | +| `{{Mustache}}` | `{{feature_name}}` | Mustache-style | +| `$VARIABLE` | `$PRODUCT_NAME` | Shell-style | +| `<%=ERB%>` | `<%=product.name%>` | ERB-style | + +--- + +## Your Tasks (NON-NEGOTIABLE) + +1. **PRD Document**: Write complete Product Requirements Document +2. **API Specification**: Define API design document (if applicable) +3. **RTM**: Create Requirements Traceability Matrix linking requirements to design, code, and tests +4. **Requirements Baseline**: Establish formal requirements baseline with version control + +## What You MUST NEVER Do + +- ❌ NEVER use non-standard formats - MUST follow industry standards +- ❌ NEVER omit version control - MUST establish baseline +- ❌ NEVER ignore change management processes - MUST define change procedures +- ❌ NEVER over-pursue document perfection while ignoring actual value + +--- + +## Method 1: PRD Document + +### Purpose + +Create a complete Product Requirements Document that serves as the authoritative source for product definition. + +### PRD Structure Overview + +| Section | Content | +|---------|---------| +| Document Information | Version, owner, status | +| Executive Summary | 2-3 paragraph overview | +| Product Overview | Vision, objectives, target users, scope | +| Functional Requirements | Features, user stories, acceptance criteria, business rules | +| Non-Functional Requirements | Performance, security, reliability, usability | +| User Experience | Flows, wireframes, navigation | +| Technical Specifications | Architecture, integrations, data model | +| Release Plan | MVP, versions, roadmap | +| Dependencies and Risks | Dependencies, risk matrix | +| Appendices | Glossary, references, version history | +| Approvals | Stakeholder sign-off | + +### When to Use PRD + +- New product development +- Major feature releases +- Stakeholder alignment needed +- Formal documentation required + +--- + +## Method 2: API Specification (OpenAPI) + +### Purpose + +Define API contracts using OpenAPI 3.0 specification for development and documentation. + +### OpenAPI Structure Overview + +| Section | Content | +|---------|---------| +| `info` | API name, version, description, contact | +| `servers` | Production and staging URLs | +| `paths` | Endpoints with operations (GET, POST, PUT, DELETE) | +| `components/schemas` | Data models and request/response objects | +| `components/responses` | Reusable response definitions | +| `components/securitySchemes` | Authentication methods | +| `security` | Global security requirements | + +### When to Use OpenAPI + +- API-first development +- Microservices architecture +- Third-party integrations +- API documentation generation + +--- + +## Method 3: Requirements Traceability Matrix (RTM) + +### Purpose + +Create a comprehensive traceability matrix that links requirements to design, implementation, and test artifacts throughout the project lifecycle. + +### RTM Structure Overview + +| Section | Content | +|---------|---------| +| Forward Traceability | Requirements → Design → Code → Tests | +| Backward Traceability | Implementation → Requirements | +| Test Traceability | Test Cases → Requirements Coverage | +| Coverage Summary | Progress metrics and gap analysis | +| Change Impact | Impact analysis for requirement changes | +| Verification Status | Sign-off and approval tracking | + +### Key Traceability Links + +| Link Type | From | To | Purpose | +|-----------|------|-----|---------| +| **Derives** | Business Req | Functional Req | Decomposition tracking | +| **Implements** | Requirement | Code Location | Implementation tracking | +| **Verifies** | Test Case | Requirement | Test coverage tracking | +| **Depends** | Requirement | Requirement | Dependency management | + +### Coverage Metrics + +Track these metrics for each requirement: + +| Status | Definition | +|--------|------------| +| Designed | Has design reference | +| Implemented | Has code reference | +| Tested | Has test case(s) | +| Verified | Stakeholder approved | + +### When to Use RTM + +- Complex projects with many requirements +- Regulatory/compliance requirements +- Multi-team development +- Long-term maintenance planning +- Audit and verification needs + +--- + +## Method 4: Requirements Baseline Management + +### Version Numbering + +**Semantic Versioning**: MAJOR.MINOR.PATCH + +| Component | When to Increment | Example | +|-----------|-------------------|---------| +| **MAJOR** | Incompatible changes, major scope changes | 1.0.0 → 2.0.0 | +| **MINOR** | New features, backward compatible | 1.0.0 → 1.1.0 | +| **PATCH** | Bug fixes, clarifications | 1.0.0 → 1.0.1 | + +### Baseline Record Template + +```markdown +## Requirements Baseline Record + +### Baseline Information +| Field | Value | +|-------|-------| +| **Baseline Version** | v1.0.0 | +| **Baseline Date** | [Date] | +| **Approved By** | [Names] | +| **Status** | Active | + +### Included Requirements +| Req ID Range | Count | Category | +|--------------|-------|----------| +| REQ-001 ~ REQ-050 | 50 | Functional | +| NFR-001 ~ NFR-015 | 15 | Non-Functional | +| **Total** | **65** | | + +### Change Control Process +1. **Change Request**: Submit via [system/form] +2. **Impact Analysis**: Technical and schedule assessment +3. **CCB Review**: Change Control Board approval +4. **Implementation**: Approved changes implemented +5. **Documentation**: Requirements updated, new baseline + +### Change Request Template +| Field | Value | +|-------|-------| +| **CR ID** | CR-XXX | +| **Requester** | [Name] | +| **Date** | [Date] | +| **Requirements Affected** | [List] | +| **Change Description** | [Description] | +| **Justification** | [Why needed] | +| **Impact Assessment** | [Schedule, cost, risk] | +| **Decision** | Approved / Rejected / Deferred | +| **Approved By** | [Names] | + +### Version History +| Version | Date | Author | Changes | Approved By | +|---------|------|--------|---------|-------------| +| 1.0.0 | [Date] | [Name] | Initial baseline | [Names] | +| 1.0.1 | [Date] | [Name] | [Changes] | [Names] | +| 1.1.0 | [Date] | [Name] | [Changes] | [Names] | +``` + +--- + +## Complete Process Deliverables Checklist + +After completing all 6 phases, verify: + +- [ ] ✅ Stakeholder list and interview records +- [ ] ✅ User personas and journey maps +- [ ] ✅ Requirements value sorting matrix (MoSCoW, RICE) +- [ ] ✅ User story maps and use case diagrams +- [ ] ✅ Priority ranking and release plans +- [ ] ✅ Validation report +- [ ] ✅ PRD document +- [ ] ✅ API specification (if applicable) +- [ ] ✅ Requirements Traceability Matrix (RTM) +- [ ] ✅ Requirements baseline with version control + +--- + +## Exit Criteria (NON-NEGOTIABLE) + +| Criteria | Standard | Verification | Status | +|----------|----------|--------------|--------| +| PRD Document | Complete and reviewed | Checklist verified | [ ] | +| API Specification | OpenAPI format (if applicable) | Schema validated | [ ] | +| RTM | All requirements traced | Coverage > 80% | [ ] | +| Requirements Baseline | Version established | Git tagged | [ ] | +| Version Control | Under management | Repository confirmed | [ ] | +| Stakeholder Sign-off | Formal approval | Signatures obtained | [ ] | + +--- + +## Congratulations! + +You have completed all 6 phases of requirements engineering. + +**Next Steps**: Proceed to design phase with: +- Approved PRD as input +- API specifications for development contracts +- RTM for ongoing traceability and change impact analysis + +**Remember**: Requirements specification is not the end, but the starting point of continuous evolution. Establish good change management mechanisms to ensure requirements documentation always reflects the latest understanding. diff --git a/requirements-analyst/steering/template-analysis.md b/requirements-analyst/steering/template-analysis.md new file mode 100644 index 0000000..f3209df --- /dev/null +++ b/requirements-analyst/steering/template-analysis.md @@ -0,0 +1,489 @@ +--- +inclusion: agent +--- + +# Analysis Output Template + +**Output Files**: +- `.kiro/specs/[feature-name]/requirements.md` - This template +- `.kiro/specs/[feature-name]/data-model.md` - See `template-data-model.md` + +**Standards**: Must follow `helper-diagram-standards.md` + +--- + +## File Template + +```markdown +# Analysis: [Feature Name] + +**Created**: [Date] +**Status**: In Progress | Completed + +--- + +## 1. User Personas + +| Persona | Description | Key Goals | +|---------|-------------|-----------| +| [Persona 1] | [Brief description] | [Primary goals] | +| [Persona 2] | [Brief description] | [Primary goals] | + +--- + +## 2. Core User Activity Flow + +### Activity Diagram + +\`\`\`mermaid +stateDiagram-v2 + [*] --> Activity1: Start + + Activity1 --> Decision1 + state Decision1 <> + Decision1 --> Activity2: [Condition A] + Decision1 --> Activity3: [Condition B] + + state ParallelProcessing { + direction LR + [*] --> Task1 + [*] --> Task2 + Task1 --> [*] + Task2 --> [*] + } + + Activity2 --> ParallelProcessing + Activity3 --> Activity4 + ParallelProcessing --> Activity5 + + Activity4 --> Activity5 + Activity5 --> [*]: End +\`\`\` + +### Activity Details + +| Activity | Description | Input | Output | Participants | +|----------|-------------|-------|--------|--------------| +| **Activity 1** | [Description] | [Input] | [Output] | [Who] | +| **Activity 2** | [Description] | [Input] | [Output] | [Who] | + +--- + +## 3. User Story Map + +### Release Planning + +| Activity | MVP | v1.1 | v2.0 | +|----------|-----|------|------| +| **[Activity 1]** | US-001, US-002 | US-003 | US-004 | +| **[Activity 2]** | US-005 | US-006, US-007 | - | + +--- + +## 4. User Stories + +### Activity 1: [Activity Name] + +#### US-001: [Story Title] + +**Priority**: P0 | P1 | P2 +**Persona**: [Which persona] +**Release**: MVP | v1.1 | v2.0 + +**Story**: +> As a [role], +> I want [feature/capability], +> So that [business value/benefit]. + +**Acceptance Criteria**: + +\`\`\`gherkin +Scenario: [Scenario name] + Given [precondition] + When [action] + Then [expected result] +\`\`\` + +**INVEST Check**: +- [ ] **I**ndependent +- [ ] **N**egotiable +- [ ] **V**aluable +- [ ] **E**stimable +- [ ] **S**mall +- [ ] **T**estable + +--- + +## 5. Use Case Diagram + +\`\`\`mermaid +graph TB + subgraph SystemBoundary["System Boundary"] + direction TB + UC1((UC-001
                Use Case 1)) + UC2((UC-002
                Use Case 2)) + UC3((UC-003
                Use Case 3)) + UC4((UC-004
                Use Case 4)) + + UC1 -->|<>| UC2 + UC3 -.->|<>| UC1 + end + + Actor1[/"👤 Actor 1"\] + Actor2[/"👤 Actor 2"\] + External[/"🔌 External System"\] + + Actor1 --> UC1 + Actor1 --> UC3 + Actor2 --> UC2 + UC4 --> External + + style UC1 fill:#e1f5fe,stroke:#01579b + style UC2 fill:#e1f5fe,stroke:#01579b + style UC3 fill:#fff3e0,stroke:#e65100 + style UC4 fill:#e1f5fe,stroke:#01579b +\`\`\` + +### Use Case List + +| UC ID | Name | Primary Actor | Priority | Description | +|-------|------|---------------|----------|-------------| +| **UC-001** | [Name] | [Actor] | P0 | [Brief description] | +| **UC-002** | [Name] | [Actor] | P0 | [Brief description] | + +--- + +## 6. Use Case Details + +### UC-001: [Use Case Name] + +| Field | Value | +|-------|-------| +| **Use Case ID** | UC-001 | +| **Name** | [Descriptive name] | +| **Primary Actor** | [Who initiates] | +| **Secondary Actors** | [Other participants] | +| **Priority** | P0 / P1 / P2 | + +#### Main Flow Sequence Diagram + +\`\`\`mermaid +sequenceDiagram + autonumber + + actor User as 👤 User + participant UI as 🖥️ Interface + participant System as ⚙️ System + participant Agent as 🤖 Agent + participant DB as 🗄️ Database + + User->>UI: 1. Initiate Request + activate UI + UI->>System: 2. Forward Request + activate System + + par Parallel Processing + System->>Agent: 3a. Analyze Request + activate Agent + Agent-->>System: 3a. Analysis Result + deactivate Agent + and + System->>DB: 3b. Query Data + activate DB + DB-->>System: 3b. Return Data + deactivate DB + end + + alt Success + System-->>UI: 4. Success Response + UI-->>User: 5. Display Result + else Failure + System-->>UI: 4. Error Response + UI-->>User: 5. Display Error + end + + deactivate System + deactivate UI +\`\`\` + +#### Preconditions +1. [Condition that must be true before starting] + +#### Postconditions (Success) +1. [State after successful completion] + +#### Alternative Flows + +**A1: [Alternative scenario name]** +- **Trigger**: [When this alternative applies] +- **Description**: [What happens] + +#### Exception Flows + +**E1: [Error scenario name]** +- **Trigger**: [What causes this exception] +- **System Response**: "[Error message]" +- **Recovery**: [How to recover] + +--- + +## 7. Success Criteria + +### Success Criteria Summary + +| SC ID | Requirement | Category | Metric | Target | Verification | +|-------|-------------|----------|--------|--------|--------------| +| **SC-001** | US-001 | Functional | [Metric] | [Target] | [Method] | +| **SC-002** | US-001 | Performance | [Metric] | [Target] | [Method] | +| **SC-003** | US-002 | Usability | [Metric] | [Target] | [Method] | +| **SC-004** | REQ-001 | Business | [Metric] | [Target] | [Method] | + +### SC-001: [Criterion Name] + +| Field | Value | +|-------|-------| +| **Requirement** | US-001 / REQ-XXX | +| **Category** | Functional / Performance / Usability / Business / Quality | +| **Metric** | [What to measure] | +| **Target** | [Quantified goal] | +| **Baseline** | [Current state, if applicable] | +| **Measurement Method** | [How to measure] | +| **Verification Point** | [When to verify: Development / Testing / Post-launch] | + +**Definition of Success**: +> [Clear statement describing what success looks like for this criterion] + +**Definition of Failure**: +> [Clear statement describing what constitutes failure] + +### Success Criteria Traceability + +\`\`\`mermaid +graph LR + subgraph Requirements + REQ[REQ-001] + US1[US-001] + US2[US-002] + end + + subgraph SuccessCriteria[Success Criteria] + SC1[SC-001
                Functional] + SC2[SC-002
                Performance] + SC3[SC-003
                Usability] + SC4[SC-004
                Business] + end + + subgraph Verification + TC[Test Cases] + KPI[KPIs] + MON[Monitoring] + end + + US1 --> SC1 + US1 --> SC2 + US2 --> SC3 + REQ --> SC4 + + SC1 --> TC + SC2 --> MON + SC3 --> TC + SC4 --> KPI + + style SC1 fill:#e8f5e9,stroke:#1b5e20 + style SC2 fill:#e8f5e9,stroke:#1b5e20 + style SC3 fill:#e8f5e9,stroke:#1b5e20 + style SC4 fill:#e8f5e9,stroke:#1b5e20 +\`\`\` + +--- + +## 8. Dependency Analysis + +### Dependency Graph + +\`\`\`mermaid +graph TD + REQ001[REQ-001
                Foundation] + REQ002[REQ-002
                Depends on 001] + REQ003[REQ-003
                Depends on 001] + REQ004[REQ-004
                Depends on 002,003] + EXT[External API] + + REQ001 --> REQ002 + REQ001 --> REQ003 + REQ002 --> REQ004 + REQ003 --> REQ004 + EXT -.-> REQ003 + + style REQ001 fill:#e1f5fe,stroke:#01579b + style REQ004 fill:#e8f5e9,stroke:#1b5e20 + style EXT fill:#fff3e0,stroke:#e65100 +\`\`\` + +### Dependency Matrix + +| Req ID | Depends On | Type | Impact if Delayed | +|--------|------------|------|-------------------| +| **REQ-002** | REQ-001 | Mandatory | Blocks feature | +| **REQ-003** | REQ-001, External API | Mandatory + External | High risk | +| **REQ-004** | REQ-002, REQ-003 | Mandatory | Blocks release | + +### Critical Path + +| Step | Req ID | Requirement | Depends On | Risk | +|------|--------|-------------|------------|------| +| 1 | REQ-001 | [Requirement name/description] | - | Entry point | +| 2 | REQ-002 | [Requirement name/description] | REQ-001 | [Risk note] | +| 3 | REQ-004 | [Requirement name/description] | REQ-002, REQ-003 | Blocks release | + +**Path Summary**: `REQ-001` → `REQ-002` → `REQ-004` +**Total Dependencies**: 3 requirements in sequence +**Bottleneck**: [Identify the highest-risk requirement in the path] + +--- + +## 9. Feasibility Assessment + +| Requirement | Technical Feasibility | Risk Level | Notes | +|-------------|----------------------|------------|-------| +| **REQ-001** | High | Low | Standard implementation | +| **REQ-002** | Medium | Medium | Requires new integration | +| **REQ-003** | Low | High | External dependency | + +--- + +## 10. Non-Functional Requirements (NFR) + +### NFR Summary + +| Category | Count | Priority Distribution | +|----------|-------|----------------------| +| Performance | [N] | P0: [n], P1: [n], P2: [n] | +| Security | [N] | P0: [n], P1: [n], P2: [n] | +| Reliability | [N] | P0: [n], P1: [n], P2: [n] | +| Usability | [N] | P0: [n], P1: [n], P2: [n] | +| Scalability | [N] | P0: [n], P1: [n], P2: [n] | +| Maintainability | [N] | P0: [n], P1: [n], P2: [n] | +| Compatibility | [N] | P0: [n], P1: [n], P2: [n] | + +### Performance Requirements + +| NFR ID | Requirement | Metric | Target | Related FR | +|--------|-------------|--------|--------|------------| +| NFR-P01 | [Requirement] | [Metric] | [Target] | US-XXX | +| NFR-P02 | [Requirement] | [Metric] | [Target] | UC-XXX | + +### Security Requirements + +| NFR ID | Requirement | Metric | Target | Related FR | +|--------|-------------|--------|--------|------------| +| NFR-S01 | [Requirement] | [Metric] | [Target] | US-XXX | +| NFR-S02 | [Requirement] | [Metric] | [Target] | UC-XXX | + +### Reliability Requirements + +| NFR ID | Requirement | Metric | Target | Related FR | +|--------|-------------|--------|--------|------------| +| NFR-R01 | [Requirement] | [Metric] | [Target] | US-XXX | + +### Usability Requirements + +| NFR ID | Requirement | Metric | Target | Related FR | +|--------|-------------|--------|--------|------------| +| NFR-U01 | [Requirement] | [Metric] | [Target] | US-XXX | + +### Scalability Requirements + +| NFR ID | Requirement | Metric | Target | Related FR | +|--------|-------------|--------|--------|------------| +| NFR-SC01 | [Requirement] | [Metric] | [Target] | US-XXX | + +### Maintainability Requirements + +| NFR ID | Requirement | Metric | Target | Related FR | +|--------|-------------|--------|--------|------------| +| NFR-M01 | [Requirement] | [Metric] | [Target] | US-XXX | + +### Compatibility Requirements + +| NFR ID | Requirement | Metric | Target | Related FR | +|--------|-------------|--------|--------|------------| +| NFR-C01 | [Requirement] | [Metric] | [Target] | US-XXX | + +--- + +## 11. Analysis Update Log (If Iterating) + +> **Note**: Complete this section ONLY if `clarification.md` or `validation.md` already exist. + +### Applied from clarification.md + +| Q# | Clarification Summary | Applied To | Section Updated | +|----|----------------------|------------|-----------------| +| Q1 | [Brief summary of clarification] | US-XXX | User Stories | +| Q2 | [Brief summary of clarification] | UC-XXX | Use Cases | + +### Applied from validation.md + +| Issue ID | Validation Finding | Applied To | Section Updated | +|----------|-------------------|------------|-----------------| +| V-001 | [Brief summary of finding] | SC-XXX | Success Criteria | +| V-002 | [Brief summary of finding] | REQ-XXX | Dependency Analysis | + +### Iteration History + +| Version | Date | Trigger | Changes Made | +|---------|------|---------|--------------| +| v1.0 | [Date] | Initial analysis | Created | +| v1.1 | [Date] | Post-clarification | Updated per Q1-Q3 | +| v1.2 | [Date] | Post-validation | Addressed V-001, V-002 | + +--- + +## 12. Analysis Summary + +**User Roles Identified**: +- [Role 1] +- [Role 2] +- [Role 3] + +**Core Activities**: +- [Activity 1] +- [Activity 2] +- [Activity 3] + +**Key Findings**: +- **Finding 1**: [Description] +- **Finding 2**: [Description] + +**Risks Identified**: +- **Risk 1**: [Description and mitigation] +- **Risk 2**: [Description and mitigation] + +--- + +## 13. Related Artifacts + +### Data Model + +> **See**: `data-model.md` for complete data structure definitions + +| Entity | Description | Status | +|--------|-------------|--------| +| [Entity 1] | [Brief description] | Defined | +| [Entity 2] | [Brief description] | Defined | + +**Data Model Contains**: +- Entity definitions with attributes +- Entity relationships (ER diagram) +- State diagrams for entity lifecycles +- Validation rules and constraints +- Data dictionary + +--- + +## 14. Next Steps + +- [ ] Proceed to Phase 4: Clarify (Requirements Clarification) +- [ ] OR if iterating: Return to Phase 4/5 with updated analysis +``` diff --git a/requirements-analyst/steering/template-clarification.md b/requirements-analyst/steering/template-clarification.md new file mode 100644 index 0000000..d85fddb --- /dev/null +++ b/requirements-analyst/steering/template-clarification.md @@ -0,0 +1,186 @@ +--- +inclusion: agent +--- + +# Clarification Output Template + +**Output File**: `.kiro/specs/[feature-name]/clarification.md` + +**Standards**: Must follow Ambiguity Taxonomy from `phase4-requirements-clarification.md` + +--- + +## File Template + +```markdown +# Clarification Log: [Feature Name] + +**Feature**: [feature-name] +**Session Date**: YYYY-MM-DD +**Total Questions**: [N] +**Status**: In Progress | Completed + +--- + +## Q1: [Question Title] + +**Category**: Functional Scope / Domain & Data / Interaction & UX / Non-Functional / Integration / Edge Cases / Terminology + +**Question**: [Complete question text that was asked] + +**Options Presented**: +- **A**: [Option A - full description] +- **B**: [Option B - full description] +- **C**: [Option C - full description] +- **Other**: Custom answer allowed + +**Recommended**: Option [X] - [Reason for this recommendation] + +**User's Choice**: [The option letter user selected, or their custom answer] + +**Resolution**: [How this clarification was applied to the analysis document] + +**Applied To**: [Section in requirements.md that was updated] + +--- + +## Q2: [Question Title] + +**Category**: [Category] + +**Question**: [Question text] + +**Options Presented**: +- **A**: [Option A] +- **B**: [Option B] +- **C**: [Option C] +- **Other**: Custom answer allowed + +**Recommended**: Option [X] - [Reason] + +**User's Choice**: [Choice] + +**Resolution**: [How applied] + +**Applied To**: [Section updated] + +--- + +## Summary + +| # | Question | Category | Choice | Applied To | +|---|----------|----------|--------|------------| +| 1 | [Brief question summary] | [Category] | [A/B/C/Custom] | [Section in requirements.md] | +| 2 | [Brief question summary] | [Category] | [A/B/C/Custom] | [Section in requirements.md] | +| 3 | [Brief question summary] | [Category] | [A/B/C/Custom] | [Section in requirements.md] | + +--- + +## Coverage Summary + +| Category | Status | Notes | +|----------|--------|-------| +| **Functional Scope** | Resolved / Clear / Deferred | [Brief note] | +| **Domain & Data** | Resolved / Clear / Deferred | [Brief note] | +| **Interaction & UX** | Resolved / Clear / Deferred | [Brief note] | +| **Non-Functional** | Resolved / Clear / Deferred | [Brief note] | +| **Integration** | Resolved / Clear / Deferred | [Brief note] | +| **Edge Cases** | Resolved / Clear / Deferred | [Brief note] | +| **Terminology** | Resolved / Clear / Deferred | [Brief note] | + +**Status Legend**: +- **Resolved**: Was ambiguous, now clarified through Q&A +- **Clear**: Already sufficient in analysis document +- **Deferred**: Non-blocking, can resolve during implementation + +--- + +## Impact on Analysis Document + +### Sections Modified + +| Section | Change Description | +|---------|-------------------| +| [Section 1] | [Brief description of change] | +| [Section 2] | [Brief description of change] | + +### User Stories Updated + +| Story ID | Original | Updated | +|----------|----------|---------| +| US-XXX | [Original text] | [Updated based on clarification] | + +### Success Criteria Updated + +| SC ID | Original | Updated | +|-------|----------|---------| +| SC-XXX | [Original] | [Updated based on clarification] | + +### New Requirements Added + +| Req ID | Description | Source | +|--------|-------------|--------| +| REQ-XXX | [New requirement added based on clarification] | Q[N] | + +--- + +## Deferred Items + +Items that were identified but deferred for later resolution: + +| Item | Category | Reason for Deferral | When to Resolve | +|------|----------|---------------------|-----------------| +| [Item 1] | [Category] | [Why deferred] | [Implementation / Design phase] | +| [Item 2] | [Category] | [Why deferred] | [Implementation / Design phase] | + +--- + +## Assumptions Documented + +| ID | Assumption | Related Req | Risk if Wrong | Validated | +|----|------------|-------------|---------------|-----------| +| ASM-001 | [Assumption made during clarification] | REQ-XXX | [Risk] | Yes/No | + +--- + +## Out of Scope (Confirmed) + +| Item | Reason | Future Consideration | +|------|--------|---------------------| +| [Item] | [Why out of scope] | v2.0 / Never | + +--- + +## Session Notes + +[Any additional notes about the clarification session, observations, or recommendations for future phases] + +--- + +## Cross-References + +- **Analysis Document**: [requirements.md](./requirements.md) - Updated with clarifications +- **Previous Phase**: [sort.md](./sort.md) - Value sorting reference +- **Next Phase**: [validation.md](./validation.md) - To be created + +--- + +## Next Steps Available + +**What would you like to do next?** + +| Option | Action | When to Choose | +|--------|--------|----------------| +| **A** | **Clarify** (Continue) | Deferred items need resolution, or new ambiguities found | +| **B** | **Analyze** (Re-analyze) | Significant changes require updating analysis document | +| **C** | **Validate** (Proceed) | All critical ambiguities resolved, ready for validation | + +### Recommendation + +[Based on Coverage Summary above, recommend Option A/B/C] + +**Reason**: [Explain why this option is recommended] + +--- +**Reply with A, B, or C to proceed.** +``` diff --git a/requirements-analyst/steering/template-data-model.md b/requirements-analyst/steering/template-data-model.md new file mode 100644 index 0000000..bc8828b --- /dev/null +++ b/requirements-analyst/steering/template-data-model.md @@ -0,0 +1,304 @@ +--- +inclusion: agent +--- + +# Data Model Template + +**Output File**: `.kiro/specs/[feature-name]/data-model.md` + +**Standards**: Must follow `helper-diagram-standards.md` + +--- + +## File Template + +```markdown +# Data Model: [Feature Name] + +**Created**: [Date] +**Last Updated**: [Date] +**Status**: Draft | Review | Approved + +--- + +## 1. Data Model Overview + +### 1.1 Entity Relationship Diagram + +```mermaid +erDiagram + ENTITY_A ||--o{ ENTITY_B : "has" + ENTITY_A { + string id PK + string name + datetime created_at + } + ENTITY_B ||--|{ ENTITY_C : "contains" + ENTITY_B { + string id PK + string entity_a_id FK + string status + datetime updated_at + } + ENTITY_C { + string id PK + string entity_b_id FK + decimal amount + string type + } +``` + +### 1.2 Entity Summary + +| Entity | Description | Key Attributes | Relationships | +|--------|-------------|----------------|---------------| +| **Entity A** | [Description] | id, name | Has many Entity B | +| **Entity B** | [Description] | id, status | Belongs to Entity A, Has many Entity C | +| **Entity C** | [Description] | id, amount, type | Belongs to Entity B | + +--- + +## 2. Entity Definitions + +### 2.1 [Entity Name] + +#### Basic Information + +| Property | Value | +|----------|-------| +| **Entity ID** | ENT-001 | +| **Name** | [Entity Name] | +| **Description** | [What this entity represents] | +| **Bounded Context** | [Domain context this entity belongs to] | +| **Aggregate Root** | Yes / No | + +#### Attributes + +| Attribute | Type | Required | Unique | Default | Description | Constraints | +|-----------|------|----------|--------|---------|-------------|-------------| +| `id` | string | Yes | Yes | UUID | Primary identifier | UUID v4 format | +| `name` | string | Yes | No | - | Display name | 1-100 characters | +| `email` | string | Yes | Yes | - | Email address | Valid email format | +| `status` | enum | Yes | No | `active` | Current status | [active, inactive, suspended] | +| `created_at` | datetime | Yes | No | NOW() | Creation timestamp | ISO 8601 | +| `updated_at` | datetime | Yes | No | NOW() | Last update timestamp | ISO 8601 | +| `metadata` | json | No | No | {} | Additional data | Valid JSON object | + +#### Business Rules + +| Rule ID | Rule | Validation | +|---------|------|------------| +| BR-001 | [Rule description] | [How to validate] | +| BR-002 | [Rule description] | [How to validate] | + +#### Indexes + +| Index Name | Columns | Type | Purpose | +|------------|---------|------|---------| +| `idx_entity_name` | name | B-tree | Name search optimization | +| `idx_entity_status` | status | B-tree | Status filtering | +| `idx_entity_created` | created_at | B-tree | Time-based queries | + +--- + +## 3. Relationships + +### 3.1 Relationship Matrix + +| From Entity | Relationship | To Entity | Cardinality | Description | +|-------------|--------------|-----------|-------------|-------------| +| Entity A | has | Entity B | 1:N | One A has many B | +| Entity B | contains | Entity C | 1:N | One B contains many C | +| Entity A | references | Entity D | N:M | Many-to-many via junction | + +### 3.2 Relationship Details + +#### [Relationship Name] + +| Property | Value | +|----------|-------| +| **From** | Entity A | +| **To** | Entity B | +| **Cardinality** | One-to-Many (1:N) | +| **Navigability** | Bidirectional / Unidirectional | +| **Cascade Delete** | Yes / No | +| **Foreign Key** | `entity_b.entity_a_id` | + +**Business Rule**: [Rule governing this relationship] + +--- + +## 4. State Diagrams + +### 4.1 [Entity Name] Lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Draft: Create + + Draft --> Pending: Submit + Draft --> Cancelled: Cancel + + Pending --> Approved: Approve + Pending --> Rejected: Reject + Pending --> Draft: Return for Edit + + Approved --> Active: Activate + Approved --> Cancelled: Cancel + + Active --> Suspended: Suspend + Active --> Completed: Complete + Active --> Cancelled: Cancel + + Suspended --> Active: Reactivate + Suspended --> Cancelled: Cancel + + Rejected --> Draft: Revise + Rejected --> [*]: Archive + + Completed --> [*]: Archive + Cancelled --> [*]: Archive +``` + +### 4.2 State Definitions + +| State | Description | Entry Actions | Exit Actions | Allowed Transitions | +|-------|-------------|---------------|--------------|---------------------| +| **Draft** | Initial creation state | Initialize defaults | Validate required fields | Submit, Cancel | +| **Pending** | Awaiting approval | Notify approvers | - | Approve, Reject, Return | +| **Approved** | Approved but not active | Log approval | - | Activate, Cancel | +| **Active** | Currently in use | Start monitoring | Stop monitoring | Suspend, Complete, Cancel | +| **Suspended** | Temporarily disabled | Log suspension | - | Reactivate, Cancel | +| **Completed** | Successfully finished | Calculate metrics | Archive data | - | +| **Rejected** | Not approved | Notify creator | - | Revise, Archive | +| **Cancelled** | Terminated | Log cancellation | Release resources | - | + +### 4.3 State Transition Rules + +| From State | To State | Trigger | Guard Condition | Action | +|------------|----------|---------|-----------------|--------| +| Draft | Pending | Submit | All required fields filled | Send notification | +| Pending | Approved | Approve | Approver has permission | Log approval | +| Active | Suspended | Suspend | Valid reason provided | Pause operations | + +--- + +## 5. Data Constraints + +### 5.1 Validation Rules + +| Constraint ID | Entity | Field | Rule | Error Message | +|---------------|--------|-------|------|---------------| +| VAL-001 | User | email | Must be valid email format | "Invalid email format" | +| VAL-002 | Order | amount | Must be > 0 | "Amount must be positive" | +| VAL-003 | Product | price | Must be >= 0 | "Price cannot be negative" | + +### 5.2 Referential Integrity + +| Constraint | Parent | Child | On Delete | On Update | +|------------|--------|-------|-----------|-----------| +| FK_entity_b_a | Entity A | Entity B | CASCADE / RESTRICT / SET NULL | CASCADE | +| FK_entity_c_b | Entity B | Entity C | CASCADE / RESTRICT / SET NULL | CASCADE | + +### 5.3 Uniqueness Constraints + +| Constraint | Entity | Fields | Scope | Description | +|------------|--------|--------|-------|-------------| +| UQ_user_email | User | email | Global | Email must be unique across all users | +| UQ_order_ref | Order | reference, tenant_id | Per Tenant | Order reference unique within tenant | + +--- + +## 6. Data Volume Estimates + +### 6.1 Growth Projections + +| Entity | Initial Count | Monthly Growth | 1-Year Projection | Storage (per record) | +|--------|---------------|----------------|-------------------|---------------------| +| User | 1,000 | +500/month | 7,000 | ~2 KB | +| Order | 5,000 | +2,000/month | 29,000 | ~5 KB | +| OrderItem | 15,000 | +6,000/month | 87,000 | ~1 KB | + +### 6.2 Performance Considerations + +| Query Pattern | Frequency | Expected Latency | Index Strategy | +|---------------|-----------|------------------|----------------| +| User lookup by email | High | < 10ms | Unique index on email | +| Orders by date range | Medium | < 100ms | Composite index on (user_id, created_at) | +| Full-text search | Low | < 500ms | Full-text index | + +--- + +## 7. Data Dictionary + +### 7.1 Standard Field Types + +| Type Name | Base Type | Format | Example | +|-----------|-----------|--------|---------| +| `id` | string | UUID v4 | `550e8400-e29b-41d4-a716-446655440000` | +| `email` | string | RFC 5322 | `user@example.com` | +| `phone` | string | E.164 | `+1234567890` | +| `currency` | decimal | 2 decimals | `99.99` | +| `percentage` | decimal | 4 decimals | `0.1525` (15.25%) | +| `datetime` | string | ISO 8601 | `2024-01-15T10:30:00Z` | +| `date` | string | ISO 8601 | `2024-01-15` | + +### 7.2 Enumeration Types + +#### [Enum Name] + +| Value | Label | Description | +|-------|-------|-------------| +| `active` | Active | Entity is currently active | +| `inactive` | Inactive | Entity is disabled | +| `suspended` | Suspended | Entity is temporarily suspended | + +--- + +## 8. Domain Glossary + +| Term | Definition | Synonyms | Related Entities | +|------|------------|----------|------------------| +| **[Term 1]** | [Definition] | [Synonyms to avoid] | Entity A, Entity B | +| **[Term 2]** | [Definition] | [Synonyms to avoid] | Entity C | + +--- + +## 9. Data Model Traceability + +### 9.1 Requirements Mapping + +| Entity | Source Requirements | User Stories | +|--------|---------------------|--------------| +| Entity A | REQ-001, REQ-002 | US-001, US-003 | +| Entity B | REQ-003, REQ-005 | US-002, US-004 | + +### 9.2 Change History + +| Version | Date | Author | Changes | +|---------|------|--------|---------| +| 1.0 | [Date] | [Author] | Initial data model | +| 1.1 | [Date] | [Author] | Added Entity C, updated relationships | + +--- + +## 10. Notes and Decisions + +### 10.1 Design Decisions + +| Decision ID | Decision | Rationale | Alternatives Considered | +|-------------|----------|-----------|------------------------| +| DD-001 | [Decision] | [Why this choice] | [Other options] | + +### 10.2 Open Questions + +| Question ID | Question | Impact | Status | +|-------------|----------|--------|--------| +| Q-001 | [Question] | [Impact if unresolved] | Open / Resolved | + +### 10.3 Assumptions + +| Assumption ID | Assumption | Risk if Invalid | +|---------------|------------|-----------------| +| A-001 | [Assumption] | [Risk] | +``` diff --git a/requirements-analyst/steering/template-discovery.md b/requirements-analyst/steering/template-discovery.md new file mode 100644 index 0000000..c694d51 --- /dev/null +++ b/requirements-analyst/steering/template-discovery.md @@ -0,0 +1,123 @@ +--- +inclusion: agent +--- + +# Discovery Output Template + +**Output File**: `.kiro/specs/[feature-name]/discovery.md` + +--- + +## File Template + +```markdown +# Discovery: [Feature Name] + +**Created**: [Date] +**Status**: In Progress | Completed + +--- + +## 1. Project Overview + +**Project Name**: [Name] +**Business Context**: [Brief description] +**Project Goals**: [What success looks like] + +--- + +## 2. Stakeholders + +### Power-Interest Matrix + +\`\`\`mermaid +quadrantChart + title Stakeholder Analysis + x-axis Low Interest --> High Interest + y-axis Low Power --> High Power + quadrant-1 Manage Closely + quadrant-2 Keep Satisfied + quadrant-3 Monitor + quadrant-4 Keep Informed + Stakeholder1: [0.8, 0.9] + Stakeholder2: [0.6, 0.4] +\`\`\` + +### Stakeholder List + +| Name/Role | Power | Interest | Strategy | Contact | +|-----------|-------|----------|----------|---------| +| [Name] | High/Medium/Low | High/Medium/Low | [Strategy] | [Contact] | + +--- + +## 3. User Personas + +### Persona 1: [Name] + +| Attribute | Description | +|-----------|-------------| +| **Role** | [Job title/role] | +| **Goals** | [Primary goals] | +| **Pain Points** | [Key frustrations] | +| **Tech Proficiency** | Novice/Intermediate/Expert | + +**Quote**: "[Representative quote]" + +--- + +## 4. User Journey Map + +\`\`\`mermaid +journey + title [User Journey Name] + section Discovery + Task 1: 5: User + Task 2: 3: User + section Usage + Task 3: 4: User, System + Task 4: 2: User + section Completion + Task 5: 5: User +\`\`\` + +### Journey Details + +| Stage | Actions | Thoughts | Pain Points | Opportunities | +|-------|---------|----------|-------------|---------------| +| [Stage] | [Actions] | [Thoughts] | [Pain] | [Opportunity] | + +--- + +## 5. Competitive Analysis + +| Feature | Our Product | Competitor A | Competitor B | +|---------|-------------|--------------|--------------| +| [Feature 1] | ❓ Planned | ✅ Yes | ❌ No | +| [Feature 2] | ❓ Planned | ✅ Yes | ✅ Yes | + +### Differentiation Opportunities +1. [Opportunity 1] +2. [Opportunity 2] + +--- + +## 6. Raw Requirements List + +| ID | Requirement | Source | Priority | Notes | +|----|-------------|--------|----------|-------| +| REQ-001 | [Description] | [Stakeholder] | High/Medium/Low | [Notes] | + +--- + +## 7. Key Pain Points + +1. **[Pain Point 1]**: [Description and impact] +2. **[Pain Point 2]**: [Description and impact] + +--- + +## Next Steps + +- [ ] Proceed to Phase 2: Sort (Value Sorting) +``` diff --git a/requirements-analyst/steering/template-openapi.md b/requirements-analyst/steering/template-openapi.md new file mode 100644 index 0000000..dd040d5 --- /dev/null +++ b/requirements-analyst/steering/template-openapi.md @@ -0,0 +1,194 @@ +# OpenAPI Specification Template + +**Purpose**: API contract definition for development and documentation +**Output File**: `.kiro/specs/[feature-name]/api.yaml` + +--- + +## Template + +```yaml +openapi: 3.0.0 +info: + title: [API Name] + version: 1.0.0 + description: | + [API description] + contact: + name: [Team Name] + email: [Email] + +servers: + - url: https://api.example.com/v1 + description: Production + - url: https://api-staging.example.com/v1 + description: Staging + +paths: + /users: + get: + summary: List users + description: Returns a list of users + operationId: listUsers + tags: + - Users + parameters: + - name: page + in: query + schema: + type: integer + default: 1 + - name: limit + in: query + schema: + type: integer + default: 20 + maximum: 100 + responses: + '200': + description: Successful response + content: + application/json: + schema: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/User' + pagination: + $ref: '#/components/schemas/Pagination' + '401': + $ref: '#/components/responses/Unauthorized' + '500': + $ref: '#/components/responses/InternalError' + + post: + summary: Create user + description: Creates a new user + operationId: createUser + tags: + - Users + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateUserRequest' + responses: + '201': + description: User created + content: + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + $ref: '#/components/responses/BadRequest' + '409': + description: User already exists + +components: + schemas: + User: + type: object + required: + - id + - email + properties: + id: + type: string + format: uuid + email: + type: string + format: email + name: + type: string + createdAt: + type: string + format: date-time + + CreateUserRequest: + type: object + required: + - email + - password + properties: + email: + type: string + format: email + password: + type: string + minLength: 8 + name: + type: string + + Pagination: + type: object + properties: + page: + type: integer + limit: + type: integer + total: + type: integer + + Error: + type: object + properties: + code: + type: string + message: + type: string + + responses: + Unauthorized: + description: Authentication required + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + BadRequest: + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + InternalError: + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT + +security: + - bearerAuth: [] +``` + +--- + +## OpenAPI Structure Reference + +| Section | Content | +|---------|---------| +| `info` | API name, version, description, contact | +| `servers` | Production and staging URLs | +| `paths` | Endpoints with operations (GET, POST, PUT, DELETE) | +| `components/schemas` | Data models and request/response objects | +| `components/responses` | Reusable response definitions | +| `components/securitySchemes` | Authentication methods | +| `security` | Global security requirements | + +--- + +## When to Use OpenAPI + +- API-first development +- Microservices architecture +- Third-party integrations +- API documentation generation diff --git a/requirements-analyst/steering/template-prd.md b/requirements-analyst/steering/template-prd.md new file mode 100644 index 0000000..bfd7b20 --- /dev/null +++ b/requirements-analyst/steering/template-prd.md @@ -0,0 +1,889 @@ +--- +inclusion: agent +--- + +# PRD (Product Requirements Document) Template + +**Purpose**: Comprehensive product requirements document consolidating all analysis, clarification, and validation results. + +**Output File**: `.kiro/specs/[feature-name]/prd.md` + +**Source Documents**: +- `discovery.md` - Stakeholder and context information +- `sort.md` - Priority and release planning +- `requirements.md` - User stories, use cases, domain model +- `clarification.md` - Clarification decisions +- `validation.md` - Validation results + +--- + +## File Template + +```markdown +# Product Requirements Document (PRD) + +# [Product/Feature Name] + +--- + +## Document Information + +| Field | Value | +|-------|-------| +| **Product Name** | [Name] | +| **Version** | v1.0.0 | +| **Creation Date** | [Date] | +| **Last Updated** | [Date] | +| **Owner** | [Name] | +| **Status** | Draft / In Review / Approved | +| **Baseline** | [Baseline version if established] | + +### Document History + +| Version | Date | Author | Changes | Approved By | +|---------|------|--------|---------|-------------| +| 0.1 | [Date] | [Name] | Initial draft | - | +| 1.0 | [Date] | [Name] | Baseline release | [Names] | + +### Related Documents + +| Document | Location | Description | +|----------|----------|-------------| +| Discovery | `.kiro/specs/[name]/discovery.md` | Stakeholder analysis | +| Analysis | `.kiro/specs/[name]/requirements.md` | Detailed requirements | +| Clarification | `.kiro/specs/[name]/clarification.md` | Decision log | +| Validation | `.kiro/specs/[name]/validation.md` | Validation report | +| API Spec | `.kiro/specs/[name]/api.yaml` | API contract | +| RTM | `.kiro/specs/[name]/rtm.md` | Traceability matrix | + +--- + +## 1. Executive Summary + +### 1.1 Overview + +[2-3 paragraphs summarizing: What is this product? What problem does it solve? Who is it for? What are the key benefits?] + +### 1.2 Key Highlights + +| Aspect | Summary | +|--------|---------| +| **Target Users** | [Primary user personas] | +| **Core Value** | [Primary value proposition] | +| **MVP Scope** | [Key features in MVP] | +| **Timeline** | [Target release date] | +| **Success Metric** | [Primary KPI] | + +### 1.3 Validation Status + +| Dimension | Score | Status | +|-----------|-------|--------| +| Authenticity | [X]% | ✅/⚠️/❌ | +| Completeness | [X]% | ✅/⚠️/❌ | +| Consistency | [X]% | ✅/⚠️/❌ | +| Feasibility | [X]% | ✅/⚠️/❌ | +| Verifiability | [X]% | ✅/⚠️/❌ | + +--- + +## 2. Product Overview + +### 2.1 Product Vision + +[What is the long-term vision for this product? Where do we want to be in 2-3 years?] + +### 2.2 Problem Statement + +| Aspect | Description | +|--------|-------------| +| **Current State** | [How things work today] | +| **Pain Points** | [What problems users face] | +| **Impact** | [Business/user impact of these problems] | +| **Evidence** | [Data/research supporting this problem exists] | + +### 2.3 Product Objectives + +| ID | Objective | Success Metric | Target | Measurement Method | +|----|-----------|----------------|--------|-------------------| +| OBJ-001 | [Objective 1] | [Metric] | [Target Value] | [How measured] | +| OBJ-002 | [Objective 2] | [Metric] | [Target Value] | [How measured] | +| OBJ-003 | [Objective 3] | [Metric] | [Target Value] | [How measured] | + +### 2.4 Scope Definition + +#### In Scope + +| ID | Feature/Capability | Release | Priority | +|----|-------------------|---------|----------| +| S-001 | [Feature 1] | MVP | P0 | +| S-002 | [Feature 2] | MVP | P0 | +| S-003 | [Feature 3] | v1.1 | P1 | + +#### Out of Scope + +| Item | Reason | Future Consideration | +|------|--------|---------------------| +| [Excluded item 1] | [Why excluded] | v2.0 / Never | +| [Excluded item 2] | [Why excluded] | v2.0 / Never | + +#### Assumptions + +| ID | Assumption | Impact if Wrong | Validation Status | +|----|------------|-----------------|-------------------| +| A-001 | [Assumption] | [Impact] | Validated / Pending | +| A-002 | [Assumption] | [Impact] | Validated / Pending | + +#### Constraints + +| ID | Constraint | Type | Impact | +|----|-----------|------|--------| +| C-001 | [Constraint] | Technical / Business / Regulatory | [Impact] | +| C-002 | [Constraint] | Technical / Business / Regulatory | [Impact] | + +--- + +## 3. User Analysis + +### 3.1 User Personas + +#### Persona 1: [Persona Name] + +| Attribute | Description | +|-----------|-------------| +| **Role** | [Job title/role] | +| **Demographics** | [Age, tech-savviness, etc.] | +| **Goals** | [What they want to achieve] | +| **Pain Points** | [Current frustrations] | +| **Behaviors** | [How they work today] | +| **Success Criteria** | [What makes them successful] | + +**Quote**: "[Representative quote from user research]" + +#### Persona 2: [Persona Name] + +| Attribute | Description | +|-----------|-------------| +| **Role** | [Job title/role] | +| **Demographics** | [Age, tech-savviness, etc.] | +| **Goals** | [What they want to achieve] | +| **Pain Points** | [Current frustrations] | +| **Behaviors** | [How they work today] | +| **Success Criteria** | [What makes them successful] | + +### 3.2 User Journey Map + +\`\`\`mermaid +journey + title [Persona Name] - [Journey Name] + section Awareness + Discovers need: 3: User + Researches options: 2: User + section Consideration + Evaluates product: 4: User + Tries demo: 5: User, System + section Adoption + Signs up: 5: User, System + Completes onboarding: 4: User, System + section Usage + Performs core task: 5: User, System + Achieves goal: 5: User +\`\`\` + +### 3.3 Core User Activity Flow + +\`\`\`mermaid +stateDiagram-v2 + [*] --> Activity1: Start + + Activity1 --> Decision1 + state Decision1 <> + Decision1 --> Activity2: [Condition A] + Decision1 --> Activity3: [Condition B] + + Activity2 --> Activity4 + Activity3 --> Activity4 + Activity4 --> [*]: End +\`\`\` + +| Activity | Description | Actor | Input | Output | +|----------|-------------|-------|-------|--------| +| Activity 1 | [Description] | [Who] | [Input] | [Output] | +| Activity 2 | [Description] | [Who] | [Input] | [Output] | +| Activity 3 | [Description] | [Who] | [Input] | [Output] | +| Activity 4 | [Description] | [Who] | [Input] | [Output] | + +--- + +## 4. Functional Requirements + +### 4.1 Requirements Summary + +| Req ID | Requirement | Priority | Release | Status | +|--------|-------------|----------|---------|--------| +| REQ-001 | [Brief description] | P0 | MVP | Validated | +| REQ-002 | [Brief description] | P0 | MVP | Validated | +| REQ-003 | [Brief description] | P1 | v1.1 | Validated | + +### 4.2 User Story Map + +| Activity | MVP (P0) | v1.1 (P1) | v2.0 (P2) | +|----------|----------|-----------|-----------| +| **[Activity 1]** | US-001, US-002 | US-010 | US-020 | +| **[Activity 2]** | US-003, US-004 | US-011 | - | +| **[Activity 3]** | US-005 | US-012, US-013 | US-021 | + +### 4.3 Feature: [Feature 1 Name] + +#### 4.3.1 Overview + +[Description of the feature, its purpose, and value] + +#### 4.3.2 User Stories + +##### US-001: [Story Title] + +| Attribute | Value | +|-----------|-------| +| **Priority** | P0 | +| **Persona** | [Which persona] | +| **Release** | MVP | +| **Effort** | [Story points or T-shirt size] | + +**Story**: +> As a [role], +> I want [feature/capability], +> So that [business value/benefit]. + +**Acceptance Criteria**: + +\`\`\`gherkin +Scenario: [Happy path scenario] + Given [precondition] + And [additional precondition] + When [action] + Then [expected result] + And [additional verification] + +Scenario: [Error scenario] + Given [precondition] + When [error condition] + Then [error handling] + And [user notification] + +Scenario: [Edge case] + Given [edge condition] + When [action] + Then [expected behavior] +\`\`\` + +**INVEST Validation**: +- [x] **I**ndependent - Can be developed separately +- [x] **N**egotiable - Details can be discussed +- [x] **V**aluable - Delivers user/business value +- [x] **E**stimable - Team can estimate effort +- [x] **S**mall - Fits in one sprint +- [x] **T**estable - Clear test criteria + +##### US-002: [Story Title] + +[Same structure as above...] + +#### 4.3.3 Business Rules + +| Rule ID | Rule Description | Source | Exception | +|---------|------------------|--------|-----------| +| BR-001 | [Business rule description] | [Stakeholder/Policy] | [When not applicable] | +| BR-002 | [Business rule description] | [Stakeholder/Policy] | [When not applicable] | + +#### 4.3.4 Data Requirements + +| Field | Type | Required | Validation Rules | Default | Description | +|-------|------|----------|-----------------|---------|-------------| +| [field_name] | String(100) | Yes | Not empty, alphanumeric | - | [Description] | +| [field_name] | Integer | Yes | > 0, <= 1000 | 1 | [Description] | +| [field_name] | DateTime | No | Future date only | Now | [Description] | +| [field_name] | Enum | Yes | [Value1, Value2, Value3] | Value1 | [Description] | + +### 4.4 Feature: [Feature 2 Name] + +[Same structure as Feature 1...] + +--- + +## 5. Use Cases + +### 5.1 Use Case Diagram + +\`\`\`mermaid +graph TB + subgraph SystemBoundary["[System Name]"] + direction TB + UC1((UC-001
                Use Case 1)) + UC2((UC-002
                Use Case 2)) + UC3((UC-003
                Use Case 3)) + + UC1 -->|<>| UC2 + UC3 -.->|<>| UC1 + end + + Actor1[/"👤 Actor 1"\] + Actor2[/"👤 Actor 2"\] + External[/"🔌 External System"\] + + Actor1 --> UC1 + Actor1 --> UC3 + Actor2 --> UC2 + UC2 --> External + + style UC1 fill:#e1f5fe,stroke:#01579b + style UC2 fill:#e1f5fe,stroke:#01579b + style UC3 fill:#fff3e0,stroke:#e65100 +\`\`\` + +### 5.2 Use Case Summary + +| UC ID | Name | Primary Actor | Priority | Related Stories | +|-------|------|---------------|----------|-----------------| +| UC-001 | [Name] | [Actor] | P0 | US-001, US-002 | +| UC-002 | [Name] | [Actor] | P0 | US-003 | +| UC-003 | [Name] | [Actor] | P1 | US-010 | + +### 5.3 UC-001: [Use Case Name] + +| Attribute | Value | +|-----------|-------| +| **Use Case ID** | UC-001 | +| **Name** | [Descriptive name] | +| **Primary Actor** | [Who initiates] | +| **Secondary Actors** | [Other participants] | +| **Priority** | P0 | +| **Trigger** | [What starts this use case] | + +#### Preconditions +1. [Condition that must be true before starting] +2. [Another precondition] + +#### Postconditions (Success) +1. [State after successful completion] +2. [Another postcondition] + +#### Main Flow + +\`\`\`mermaid +sequenceDiagram + autonumber + + actor User as 👤 User + participant UI as 🖥️ Interface + participant System as ⚙️ System + participant DB as 🗄️ Database + + User->>UI: 1. [Action] + activate UI + UI->>System: 2. [Request] + activate System + System->>DB: 3. [Query] + activate DB + DB-->>System: 4. [Response] + deactivate DB + System-->>UI: 5. [Result] + deactivate System + UI-->>User: 6. [Display] + deactivate UI +\`\`\` + +| Step | Actor | Action | System Response | +|------|-------|--------|-----------------| +| 1 | User | [Action description] | - | +| 2 | System | - | [Response description] | +| 3 | User | [Action description] | - | +| 4 | System | - | [Response description] | + +#### Alternative Flows + +**A1: [Alternative scenario name]** + +| Attribute | Description | +|-----------|-------------| +| **Branch Point** | Step [N] | +| **Trigger** | [When this alternative applies] | +| **Flow** | [Steps in alternative flow] | +| **Rejoin** | Step [N] / End | + +#### Exception Flows + +**E1: [Error scenario name]** + +| Attribute | Description | +|-----------|-------------| +| **Trigger Point** | Step [N] | +| **Condition** | [What causes this exception] | +| **Error Message** | "[Exact error message]" | +| **System Response** | [What system does] | +| **User Recovery** | [How user can recover] | + +--- + +## 6. Domain Model + +### 6.1 Entity Relationship Diagram + +\`\`\`mermaid +erDiagram + USER ||--o{ ORDER : places + USER { + string id PK + string email UK + string name + datetime created_at + } + ORDER ||--|{ ORDER_ITEM : contains + ORDER { + string id PK + string user_id FK + string status + decimal total + datetime created_at + } + ORDER_ITEM { + string id PK + string order_id FK + string product_id FK + int quantity + decimal price + } + PRODUCT ||--o{ ORDER_ITEM : "ordered in" + PRODUCT { + string id PK + string name + decimal price + int stock + } +\`\`\` + +### 6.2 Entity Definitions + +#### Entity: [Entity Name] + +| Attribute | Type | Constraints | Description | +|-----------|------|-------------|-------------| +| id | UUID | PK, Not Null | Unique identifier | +| [attribute] | [Type] | [Constraints] | [Description] | +| created_at | DateTime | Not Null, Default: NOW | Creation timestamp | +| updated_at | DateTime | Not Null | Last update timestamp | + +**Business Rules**: +- [Rule 1 for this entity] +- [Rule 2 for this entity] + +### 6.3 State Diagrams + +#### [Entity Name] States + +\`\`\`mermaid +stateDiagram-v2 + [*] --> Draft: Create + + Draft --> Pending: Submit + Draft --> Cancelled: Cancel + + Pending --> Approved: Approve + Pending --> Rejected: Reject + Pending --> Draft: Return for Edit + + Approved --> Completed: Complete + Approved --> Cancelled: Cancel + + Rejected --> Draft: Revise + Rejected --> [*]: Abandon + + Completed --> [*] + Cancelled --> [*] +\`\`\` + +| State | Description | Allowed Transitions | Who Can Transition | +|-------|-------------|--------------------|--------------------| +| Draft | Initial state | Submit, Cancel | Owner | +| Pending | Awaiting approval | Approve, Reject, Return | Approver | +| Approved | Ready for processing | Complete, Cancel | System, Admin | +| Completed | Successfully finished | - | - | +| Rejected | Not approved | Revise, Abandon | Owner | +| Cancelled | Terminated | - | - | + +--- + +## 7. Non-Functional Requirements + +### 7.1 Performance Requirements + +| ID | Requirement | Metric | Target | Measurement | +|----|-------------|--------|--------|-------------| +| NFR-P001 | Page Load Time | Time to interactive | < 3 seconds | Lighthouse | +| NFR-P002 | API Response Time | 95th percentile latency | < 500ms | APM monitoring | +| NFR-P003 | Throughput | Requests per second | > 1000 RPS | Load testing | +| NFR-P004 | Concurrent Users | Simultaneous sessions | 10,000 | Load testing | +| NFR-P005 | Database Query | Average query time | < 100ms | Query profiler | + +### 7.2 Scalability Requirements + +| ID | Requirement | Current | Target | Growth Strategy | +|----|-------------|---------|--------|-----------------| +| NFR-S001 | Data Volume | [Current] | [Target] | [Strategy] | +| NFR-S002 | User Base | [Current] | [Target] | [Strategy] | +| NFR-S003 | Transaction Volume | [Current] | [Target] | [Strategy] | + +### 7.3 Availability & Reliability + +| ID | Requirement | Target | Measurement | +|----|-------------|--------|-------------| +| NFR-A001 | Uptime | 99.9% (< 8.76 hours/year downtime) | Monitoring | +| NFR-A002 | RTO (Recovery Time Objective) | < 1 hour | DR testing | +| NFR-A003 | RPO (Recovery Point Objective) | < 15 minutes | Backup verification | +| NFR-A004 | MTBF (Mean Time Between Failures) | > 720 hours | Incident tracking | +| NFR-A005 | MTTR (Mean Time To Recovery) | < 30 minutes | Incident tracking | + +### 7.4 Security Requirements + +| ID | Category | Requirement | Standard | +|----|----------|-------------|----------| +| NFR-SEC001 | Authentication | Multi-factor authentication for admin | NIST 800-63B | +| NFR-SEC002 | Authorization | Role-based access control (RBAC) | - | +| NFR-SEC003 | Data Encryption | TLS 1.3 for transit, AES-256 at rest | - | +| NFR-SEC004 | Password Policy | Min 12 chars, complexity requirements | NIST guidelines | +| NFR-SEC005 | Session Management | 30-minute timeout, secure cookies | OWASP | +| NFR-SEC006 | Audit Logging | All sensitive operations logged | SOC 2 | +| NFR-SEC007 | Vulnerability Scanning | No critical/high vulnerabilities | OWASP Top 10 | + +### 7.5 Usability Requirements + +| ID | Requirement | Target | Measurement | +|----|-------------|--------|-------------| +| NFR-U001 | Accessibility | WCAG 2.1 Level AA | Accessibility audit | +| NFR-U002 | Task Completion | > 90% success rate | Usability testing | +| NFR-U003 | Error Rate | < 5% user errors | Analytics | +| NFR-U004 | Learnability | Complete core task in < 5 minutes | Usability testing | +| NFR-U005 | Browser Support | Chrome, Firefox, Safari, Edge (latest 2 versions) | Testing matrix | +| NFR-U006 | Mobile Support | Responsive, iOS 14+, Android 10+ | Device testing | + +### 7.6 Compliance Requirements + +| ID | Regulation | Requirement | Status | +|----|------------|-------------|--------| +| NFR-C001 | GDPR | Data privacy, consent, right to deletion | [Status] | +| NFR-C002 | CCPA | California consumer privacy rights | [Status] | +| NFR-C003 | SOC 2 | Security controls audit | [Status] | +| NFR-C004 | [Industry Specific] | [Requirement] | [Status] | + +--- + +## 8. Interface Specifications + +### 8.1 User Interface + +#### Screen Inventory + +| Screen ID | Screen Name | Purpose | Priority | +|-----------|-------------|---------|----------| +| SCR-001 | [Screen Name] | [Purpose] | P0 | +| SCR-002 | [Screen Name] | [Purpose] | P0 | +| SCR-003 | [Screen Name] | [Purpose] | P1 | + +#### Wireframes / Mockups + +[Link to design files: Figma / Sketch / Adobe XD] + +| Screen | Wireframe | Mockup | Status | +|--------|-----------|--------|--------| +| SCR-001 | [Link] | [Link] | Approved | +| SCR-002 | [Link] | [Link] | In Review | + +#### Navigation Structure + +\`\`\` +├── Home +├── Dashboard +│ ├── Overview +│ ├── Analytics +│ └── Reports +├── [Feature Area] +│ ├── List View +│ ├── Detail View +│ └── Create/Edit +├── Settings +│ ├── Profile +│ ├── Preferences +│ └── Security +└── Help +\`\`\` + +### 8.2 API Interfaces + +| Endpoint | Method | Purpose | Auth Required | +|----------|--------|---------|---------------| +| /api/v1/[resource] | GET | List resources | Yes | +| /api/v1/[resource] | POST | Create resource | Yes | +| /api/v1/[resource]/{id} | GET | Get resource | Yes | +| /api/v1/[resource]/{id} | PUT | Update resource | Yes | +| /api/v1/[resource]/{id} | DELETE | Delete resource | Yes | + +> **Full API Specification**: See `api.yaml` (OpenAPI 3.0 format) + +### 8.3 External System Integrations + +| System | Integration Type | Direction | Purpose | Status | +|--------|-----------------|-----------|---------|--------| +| [System 1] | REST API | Outbound | [Purpose] | [Status] | +| [System 2] | Webhook | Inbound | [Purpose] | [Status] | +| [System 3] | Message Queue | Bidirectional | [Purpose] | [Status] | + +--- + +## 9. Error Handling + +### 9.1 Error Categories + +| Category | Code Range | Description | User Action | +|----------|------------|-------------|-------------| +| Validation | 400-499 | Invalid user input | Correct input and retry | +| Authentication | 401 | Not authenticated | Login required | +| Authorization | 403 | Not authorized | Contact admin | +| Not Found | 404 | Resource doesn't exist | Check URL/ID | +| Business Rule | 409, 422 | Business logic violation | Follow guidance | +| System | 500-599 | Internal error | Retry later, contact support | + +### 9.2 Error Message Specifications + +| Error Code | Condition | User Message | Technical Log | +|------------|-----------|--------------|---------------| +| ERR-001 | [Condition] | "[User-friendly message]" | [Technical details to log] | +| ERR-002 | [Condition] | "[User-friendly message]" | [Technical details to log] | +| ERR-003 | [Condition] | "[User-friendly message]" | [Technical details to log] | + +### 9.3 Recovery Procedures + +| Scenario | Detection | Auto-Recovery | Manual Recovery | +|----------|-----------|---------------|-----------------| +| [Scenario 1] | [How detected] | [Auto steps] | [Manual steps] | +| [Scenario 2] | [How detected] | [Auto steps] | [Manual steps] | + +--- + +## 10. Clarification Decisions + +> **Source**: `clarification.md` + +### 10.1 Clarification Log + +| Q# | Category | Question | Decision | Impact | Date | +|----|----------|----------|----------|--------|------| +| Q1 | [Category] | [Question asked] | [Decision made] | [What changed] | [Date] | +| Q2 | [Category] | [Question asked] | [Decision made] | [What changed] | [Date] | +| Q3 | [Category] | [Question asked] | [Decision made] | [What changed] | [Date] | + +### 10.2 Key Decisions Summary + +| Decision ID | Topic | Decision | Rationale | Stakeholder | +|-------------|-------|----------|-----------|-------------| +| DEC-001 | [Topic] | [What was decided] | [Why] | [Who approved] | +| DEC-002 | [Topic] | [What was decided] | [Why] | [Who approved] | + +--- + +## 11. Dependencies & Risks + +### 11.1 Dependency Graph + +\`\`\`mermaid +graph TD + REQ001[REQ-001
                Foundation] + REQ002[REQ-002] + REQ003[REQ-003] + REQ004[REQ-004
                Release Blocker] + EXT[External API] + + REQ001 --> REQ002 + REQ001 --> REQ003 + REQ002 --> REQ004 + REQ003 --> REQ004 + EXT -.-> REQ003 + + style REQ001 fill:#e1f5fe,stroke:#01579b + style REQ004 fill:#ffebee,stroke:#b71c1c + style EXT fill:#fff3e0,stroke:#e65100 +\`\`\` + +### 11.2 Critical Path + +| Step | Req ID | Requirement | Depends On | Duration | Risk | +|------|--------|-------------|------------|----------|------| +| 1 | REQ-001 | [Description] | - | [Estimate] | Entry point | +| 2 | REQ-002 | [Description] | REQ-001 | [Estimate] | [Risk] | +| 3 | REQ-003 | [Description] | REQ-001, External | [Estimate] | High - external | +| 4 | REQ-004 | [Description] | REQ-002, REQ-003 | [Estimate] | **Blocks release** | + +### 11.3 External Dependencies + +| ID | Dependency | Type | Owner | Status | Mitigation | +|----|------------|------|-------|--------|------------| +| DEP-001 | [Dependency] | Internal/External | [Team] | [Status] | [Mitigation plan] | +| DEP-002 | [Dependency] | Internal/External | [Team] | [Status] | [Mitigation plan] | + +### 11.4 Risk Register + +| Risk ID | Risk | Probability | Impact | Score | Mitigation | Owner | +|---------|------|-------------|--------|-------|------------|-------| +| RISK-001 | [Risk description] | H/M/L | H/M/L | [P×I] | [Strategy] | [Name] | +| RISK-002 | [Risk description] | H/M/L | H/M/L | [P×I] | [Strategy] | [Name] | +| RISK-003 | [Risk description] | H/M/L | H/M/L | [P×I] | [Strategy] | [Name] | + +--- + +## 12. Release Plan + +### 12.1 Release Overview + +| Release | Theme | Target Date | Status | +|---------|-------|-------------|--------| +| MVP (v1.0) | Core functionality | [Date] | [Status] | +| v1.1 | Enhanced usability | [Date] | Planned | +| v2.0 | Advanced features | [Date] | Planned | + +### 12.2 MVP (v1.0) Scope + +**Theme**: [MVP Theme] + +**Goal**: [What MVP proves/achieves] + +| Priority | Req ID | Requirement | Status | +|----------|--------|-------------|--------| +| P0 | REQ-001 | [Description] | [Status] | +| P0 | REQ-002 | [Description] | [Status] | +| P0 | REQ-003 | [Description] | [Status] | + +**Success Criteria**: +- [ ] [Criterion 1] +- [ ] [Criterion 2] +- [ ] [Criterion 3] + +**Explicitly Excluded from MVP**: +- [Feature] - Deferred to v1.1 +- [Feature] - Deferred to v2.0 + +### 12.3 v1.1 Scope + +**Theme**: [v1.1 Theme] + +| Priority | Req ID | Requirement | +|----------|--------|-------------| +| P1 | REQ-010 | [Description] | +| P1 | REQ-011 | [Description] | + +### 12.4 Roadmap + +\`\`\`mermaid +gantt + title Release Roadmap + dateFormat YYYY-MM-DD + section Releases + MVP (v1.0) Core CRUD :milestone, m1, 2025-03-31, 0d + v1.1 UX Polish :milestone, m2, 2025-06-30, 0d + v2.0 Scale & Performance :milestone, m3, 2025-12-31, 0d + v3.0 AI Features :milestone, m4, 2026-06-30, 0d + section Development + MVP Development :2025-01-01, 2025-03-31 + v1.1 Development :2025-04-01, 2025-06-30 + v2.0 Development :2025-07-01, 2025-12-31 + v3.0 Development :2026-01-01, 2026-06-30 +\`\`\` + +--- + +## 13. Success Criteria & KPIs + +### 13.1 Success Metrics + +| ID | Category | Metric | Baseline | Target | Measurement | +|----|----------|--------|----------|--------|-------------| +| KPI-001 | Business | [Metric] | [Current] | [Target] | [How measured] | +| KPI-002 | User | [Metric] | [Current] | [Target] | [How measured] | +| KPI-003 | Technical | [Metric] | [Current] | [Target] | [How measured] | +| KPI-004 | Quality | [Metric] | [Current] | [Target] | [How measured] | + +### 13.2 Acceptance Criteria Summary + +| Req ID | Criteria Count | Happy Path | Error Cases | Edge Cases | Status | +|--------|----------------|------------|-------------|------------|--------| +| REQ-001 | [N] | ✅ | ✅ | ✅ | Complete | +| REQ-002 | [N] | ✅ | ✅ | ⚠️ | In Progress | + +### 13.3 Definition of Done + +- [ ] All acceptance criteria pass +- [ ] Code reviewed and merged +- [ ] Unit tests written (coverage > 80%) +- [ ] Integration tests pass +- [ ] Performance benchmarks met +- [ ] Security scan passed +- [ ] Documentation updated +- [ ] Deployed to staging +- [ ] QA sign-off obtained + +--- + +## 14. Glossary + +| Term | Definition | Context | +|------|------------|---------| +| [Term 1] | [Definition] | [Where used] | +| [Term 2] | [Definition] | [Where used] | +| [Term 3] | [Definition] | [Where used] | + +--- + +## 15. Appendices + +### Appendix A: Reference Documents + +| Document | Location | Description | +|----------|----------|-------------| +| User Research | [Link] | Interview transcripts and surveys | +| Competitive Analysis | [Link] | Market research | +| Technical Spike | [Link] | Proof of concept results | + +### Appendix B: Open Questions + +| ID | Question | Owner | Due Date | Status | +|----|----------|-------|----------|--------| +| OQ-001 | [Question] | [Name] | [Date] | Open/Resolved | +| OQ-002 | [Question] | [Name] | [Date] | Open/Resolved | + +### Appendix C: Change Log + +| Date | Section | Change | Author | Reason | +|------|---------|--------|--------|--------| +| [Date] | [Section] | [What changed] | [Name] | [Why] | + +--- + +## Approvals + +### Stakeholder Sign-Off + +| Role | Name | Decision | Date | Comments | +|------|------|----------|------|----------| +| Product Owner | [Name] | Approved / Rejected | [Date] | [Comments] | +| Technical Lead | [Name] | Approved / Conditional | [Date] | [Conditions] | +| UX Lead | [Name] | Approved / Rejected | [Date] | [Comments] | +| QA Lead | [Name] | Approved / Rejected | [Date] | [Comments] | +| Business Stakeholder | [Name] | Approved / Rejected | [Date] | [Comments] | + +### Approval History + +| Version | Date | Approvers | Notes | +|---------|------|-----------|-------| +| v1.0 | [Date] | [Names] | Initial baseline | + +--- + +**Document End** +``` diff --git a/requirements-analyst/steering/template-rtm.md b/requirements-analyst/steering/template-rtm.md new file mode 100644 index 0000000..867dfbf --- /dev/null +++ b/requirements-analyst/steering/template-rtm.md @@ -0,0 +1,181 @@ +# Requirements Traceability Matrix (RTM) Template + +**Purpose**: Track requirements through design, implementation, and testing phases +**Output File**: `.kiro/specs/[feature-name]/rtm.md` + +--- + +## 1. Document Information + +| Field | Value | +|-------|-------| +| **Project** | [Project Name] | +| **Version** | v1.0.0 | +| **Last Updated** | [Date] | +| **Owner** | [Name] | +| **Status** | Draft / Under Review / Approved | + +--- + +## 2. Traceability Matrix + +### 2.1 Forward Traceability (Requirements → Implementation) + +| Req ID | Requirement | Priority | Design Ref | Code Ref | Test Case | Status | +|--------|-------------|----------|------------|----------|-----------|--------| +| REQ-001 | [Brief description] | Must | DES-001 | `src/module/file.ts:L50` | TC-001, TC-002 | Implemented | +| REQ-002 | [Brief description] | Must | DES-002 | `src/auth/login.ts:L120` | TC-003 | In Progress | +| REQ-003 | [Brief description] | Should | DES-003 | - | TC-004 | Not Started | +| NFR-001 | [Brief description] | Must | DES-004 | `src/utils/cache.ts` | TC-005 | Implemented | + +### 2.2 Backward Traceability (Implementation → Requirements) + +| Component | Code Location | Implements | Test Coverage | +|-----------|---------------|------------|---------------| +| UserService | `src/services/user.ts` | REQ-001, REQ-002 | TC-001~TC-003 | +| AuthModule | `src/auth/` | REQ-004, NFR-002 | TC-010~TC-015 | +| API Gateway | `src/api/gateway.ts` | REQ-005, NFR-001 | TC-020~TC-025 | + +### 2.3 Test Traceability + +| Test Case ID | Test Name | Requirements Covered | Type | Status | +|--------------|-----------|---------------------|------|--------| +| TC-001 | User registration success | REQ-001 | Functional | Pass | +| TC-002 | User registration validation | REQ-001 | Functional | Pass | +| TC-003 | Login authentication | REQ-002, NFR-002 | Security | Pass | +| TC-004 | Response time under load | NFR-001 | Performance | Pending | + +--- + +## 3. Coverage Summary + +### 3.1 Requirements Coverage + +| Category | Total | Designed | Implemented | Tested | Verified | +|----------|-------|----------|-------------|--------|----------| +| Functional (REQ) | 25 | 25 (100%) | 20 (80%) | 18 (72%) | 15 (60%) | +| Non-Functional (NFR) | 10 | 10 (100%) | 8 (80%) | 6 (60%) | 5 (50%) | +| **Total** | **35** | **35 (100%)** | **28 (80%)** | **24 (69%)** | **20 (57%)** | + +### 3.2 Coverage Visualization + +``` +Requirements Coverage Progress +============================================================ +Design: [####################] 100% (35/35) +Implementation:[################----] 80% (28/35) +Testing: [##############------] 69% (24/35) +Verification: [###########---------] 57% (20/35) +============================================================ +``` + +### 3.3 Gap Analysis + +| Gap Type | Count | Requirements | Action Required | +|----------|-------|--------------|-----------------| +| No Design | 0 | - | - | +| No Implementation | 7 | REQ-021~REQ-025, NFR-009, NFR-010 | Sprint 3 planned | +| No Test Cases | 11 | [List] | Test plan update needed | +| Test Failures | 2 | REQ-015, NFR-007 | Bug fix in progress | + +--- + +## 4. Traceability Links + +### 4.1 Link Types + +| Link Type | From | To | Description | +|-----------|------|-----|-------------| +| **Derives** | Business Req | Functional Req | Business requirement decomposed | +| **Implements** | Requirement | Code | Code implements requirement | +| **Verifies** | Test Case | Requirement | Test verifies requirement | +| **Depends** | Requirement | Requirement | Dependency relationship | + +### 4.2 Dependency Chain + +| Req ID | Requirement | Depends On | Depended By | +|--------|-------------|------------|-------------| +| REQ-001 | User Registration | - | REQ-002, REQ-003 | +| REQ-002 | Email Verification | REQ-001 | REQ-004 | +| REQ-003 | Profile Setup | REQ-001 | REQ-005 | +| REQ-004 | Account Activation | REQ-002 | REQ-006 | + +--- + +## 5. Change Impact Analysis + +### 5.1 Impact Matrix Template + +When a requirement changes, use this matrix to assess impact: + +| If Changed | Affects Design | Affects Code | Affects Tests | Risk Level | +|------------|---------------|--------------|---------------|------------| +| REQ-001 | DES-001, DES-002 | 5 files | 8 test cases | High | +| REQ-002 | DES-002 | 2 files | 3 test cases | Medium | +| NFR-001 | DES-004 | 3 files | 5 test cases | High | + +### 5.2 Change Log + +| Date | Req ID | Change Type | Description | Impact | Updated By | +|------|--------|-------------|-------------|--------|------------| +| [Date] | REQ-005 | Modified | Updated acceptance criteria | Low | [Name] | +| [Date] | REQ-012 | Added | New requirement from clarification | Medium | [Name] | +| [Date] | REQ-008 | Deleted | Descoped to v2.0 | Low | [Name] | + +--- + +## 6. Verification Status + +### 6.1 Verification Matrix + +| Req ID | Requirement | Verification Method | Verified By | Date | Result | +|--------|-------------|--------------------:|-------------|------|--------| +| REQ-001 | User Registration | Test + Demo | QA Team | [Date] | Pass | +| REQ-002 | Email Verification | Test | QA Team | [Date] | Pass | +| NFR-001 | Response < 200ms | Performance Test | DevOps | [Date] | Pass | +| NFR-002 | 99.9% Uptime | Monitoring | SRE | [Date] | Pending | + +### 6.2 Sign-off Status + +| Stakeholder | Role | Requirements Verified | Sign-off Date | Status | +|-------------|------|----------------------|---------------|--------| +| [Name] | Product Owner | All Functional | [Date] | Approved | +| [Name] | Tech Lead | All Technical | [Date] | Approved | +| [Name] | QA Lead | All Test Coverage | [Date] | Pending | +| [Name] | Security | NFR-002~NFR-005 | [Date] | Approved | + +--- + +## 7. RTM Maintenance + +### 7.1 Update Triggers + +| Event | Required Action | +|-------|-----------------| +| New requirement added | Add row to forward traceability | +| Requirement modified | Update all linked items, log change | +| Code committed | Update Code Ref column | +| Test case added/updated | Update Test Case column | +| Verification completed | Update status and sign-off | + +### 7.2 Review Schedule + +| Review Type | Frequency | Participants | Purpose | +|-------------|-----------|--------------|---------| +| Coverage Review | Weekly | Dev + QA | Track implementation progress | +| Gap Analysis | Bi-weekly | PM + Tech Lead | Identify missing coverage | +| Full RTM Review | Per Release | All Stakeholders | Release readiness | + +--- + +## Appendix: Status Definitions + +| Status | Definition | +|--------|------------| +| **Not Started** | Work has not begun | +| **In Progress** | Currently being worked on | +| **Implemented** | Code complete, awaiting test | +| **Tested** | Test cases executed | +| **Verified** | Stakeholder verified and approved | +| **Blocked** | Cannot proceed due to dependency | +| **Deferred** | Moved to future release | diff --git a/requirements-analyst/steering/template-sort.md b/requirements-analyst/steering/template-sort.md new file mode 100644 index 0000000..f107a4b --- /dev/null +++ b/requirements-analyst/steering/template-sort.md @@ -0,0 +1,132 @@ +--- +inclusion: agent +--- + +# Value Sorting Output Template + +**Output File**: `.kiro/specs/[feature-name]/sort.md` + +--- + +## File Template + +```markdown +# Value Sorting: [Feature Name] + +**Created**: [Date] +**Status**: In Progress | Completed + +--- + +## 1. MoSCoW Classification + +### Summary + +| Category | Count | Percentage | Status | +|----------|-------|------------|--------| +| MUST | X | X% | ✅ ≤30% | +| SHOULD | X | X% | - | +| COULD | X | X% | - | +| WON'T | X | X% | - | + +### MUST Have (≤30%) + +| Req ID | Requirement | Justification | +|--------|-------------|---------------| +| REQ-001 | [Description] | [Why MUST] | + +### SHOULD Have + +| Req ID | Requirement | Impact if Deferred | +|--------|-------------|-------------------| +| REQ-002 | [Description] | [Impact] | + +### COULD Have + +| Req ID | Requirement | Value Add | +|--------|-------------|-----------| +| REQ-003 | [Description] | [Benefit] | + +### WON'T Have (This Release) + +| Req ID | Requirement | Reason | +|--------|-------------|--------| +| REQ-004 | [Description] | [Why not now] | + +--- + +## 2. RICE Scoring + +| Req ID | Reach | Impact | Confidence | Effort | Score | Rank | +|--------|-------|--------|------------|--------|-------|------| +| REQ-001 | [num] | [0.25-3] | [%] | [months] | [calc] | 1 | + +**Formula**: Score = (Reach × Impact × Confidence) / Effort + +--- + +## 3. Value-Cost Matrix + +\`\`\`mermaid +quadrantChart + title Value-Cost Analysis + x-axis Low Cost --> High Cost + y-axis Low Value --> High Value + quadrant-1 P0: Quick Win + quadrant-2 P1: Strategic + quadrant-3 P2: Fill-in + quadrant-4 P3: Avoid + REQ001: [0.2, 0.9] + REQ002: [0.8, 0.8] + REQ003: [0.3, 0.3] +\`\`\` + +| Priority | Requirements | Action | +|----------|--------------|--------| +| P0 (Quick Win) | REQ-001 | Do First | +| P1 (Strategic) | REQ-002 | Plan Carefully | +| P2 (Fill-in) | REQ-003 | If Time Permits | +| P3 (Avoid) | REQ-004 | Deprioritize | + +--- + +## 4. Release Plan + +### MVP (v1.0) + +**Target**: [Date] +**Theme**: Core functionality + +| Req ID | Requirement | Priority | +|--------|-------------|----------| +| REQ-001 | [Description] | MUST | + +### Version 1.1 + +**Target**: [Date] +**Theme**: Enhanced usability + +| Req ID | Requirement | Priority | +|--------|-------------|----------| +| REQ-002 | [Description] | SHOULD | + +### Roadmap + +\`\`\`mermaid +gantt + title Release Roadmap + dateFormat YYYY-MM-DD + section MVP + Core Features :a1, 2024-01-01, 60d + section v1.1 + Enhancements :a2, after a1, 30d + section v2.0 + Advanced Features :a3, after a2, 45d +\`\`\` + +--- + +## Next Steps + +- [ ] Proceed to Phase 3: Analyze (Requirements Analysis) +``` diff --git a/requirements-analyst/steering/template-validation.md b/requirements-analyst/steering/template-validation.md new file mode 100644 index 0000000..06b2784 --- /dev/null +++ b/requirements-analyst/steering/template-validation.md @@ -0,0 +1,477 @@ +--- +inclusion: agent +--- + +# Validation Output Template + +**Output File**: `.kiro/specs/[feature-name]/validation.md` + +**Standards**: Must validate 5 dimensions from `phase5-requirements-validation.md` + +--- + +## File Template + +```markdown +# Validation Report: [Feature Name] + +**Feature**: [feature-name] +**Date**: YYYY-MM-DD +**Validator**: [Name] +**Status**: In Progress | Completed + +--- + +## Executive Summary + +[2-3 sentences summarizing validation outcome] + +**Overall Status**: ✅ Validated / ⚠️ Conditional / ❌ Failed + +--- + +## 1. Validation Dimension Summary + +| Dimension | Status | Score | Critical Issues | Notes | +|-----------|--------|-------|-----------------|-------| +| **Authenticity** | ✅/⚠️/❌ | [%] | [Count] | [Brief note] | +| **Completeness** | ✅/⚠️/❌ | [%] | [Count] | [Brief note] | +| **Consistency** | ✅/⚠️/❌ | [%] | [Count] | [Brief note] | +| **Feasibility** | ✅/⚠️/❌ | [Rating] | [Count] | [Brief note] | +| **Verifiability** | ✅/⚠️/❌ | [%] | [Count] | [Brief note] | + +--- + +## 1.1 Validation Radar Chart + +\`\`\`mermaid +%%{init: {'radar': {'max': 100, 'graticule': 'polygon', 'ticks': 5}}}%% +radar-beta + title "Requirements Validation Score" + axis auth["Authenticity"], comp["Completeness"], cons["Consistency"], feas["Feasibility"], veri["Verifiability"] + curve score["Score"]{auth: 85, comp: 92, cons: 95, feas: 78, veri: 88} + curve threshold["Threshold (80%)"]{auth: 80, comp: 80, cons: 80, feas: 80, veri: 80} +\`\`\` + +> **Note**: 80% threshold line represents minimum acceptable score. Dimensions below require attention. + +### Score Progress Bars + +| Dimension | Score | Visual | Status | +|-----------|-------|--------|--------| +| **Authenticity** | [X]% | ████████░░ | ✅/⚠️/❌ | +| **Completeness** | [X]% | █████████░ | ✅/⚠️/❌ | +| **Consistency** | [X]% | █████████▌ | ✅/⚠️/❌ | +| **Feasibility** | [X]% | ███████▌░░ | ✅/⚠️/❌ | +| **Verifiability** | [X]% | ████████▌░ | ✅/⚠️/❌ | + +**Visual Legend**: +- █ = 10% (each block represents 10%) +- ░ = remaining to 100% +- Threshold: 80% (████████░░) + +### Score Analysis Summary + +| Metric | Value | +|--------|-------| +| **Average Score** | [X]% | +| **Highest Dimension** | [Dimension] ([X]%) | +| **Lowest Dimension** | [Dimension] ([X]%) | +| **Dimensions Above Threshold (≥80%)** | [N]/5 | +| **Overall Balance** | Good / Moderate / Poor | + +### Key Insight + +> [2-3 sentences highlighting the most important observations from the validation scores. Identify strengths, weaknesses, and recommended focus areas. Example: "The validation shows strong specification quality (Consistency 95%, Completeness 92%) but Feasibility at 78% indicates schedule or resource constraints that need attention before proceeding. Recommend conducting a deeper feasibility review with technical leads."] + +--- + +## 2. Authenticity Validation (真实性) + +### Authenticity Score: [X]% - [Status] + +### Score Calculation + +- Total requirements evaluated: [N] +- Requirements with verified origin: [N] +- Requirements with stakeholder confirmation: [N] +- **Formula**: (Verified + Confirmed) / (Total × 2) × 100 = [X]% + +### Source Verification (Positive Findings) + +| Req ID | Origin | Evidence | Stakeholder Confirmed | Confidence | +|--------|--------|----------|----------------------|------------| +| REQ-001 | User Interview #12 | Interview transcript, 2024-XX-XX | ✅ Yes | High | +| REQ-002 | Support Ticket #456 | Ticket link, 50+ similar reports | ✅ Yes | High | + +### Red Flags Identified (Negative Findings) + +| Req ID | Red Flag | Impact | Action Required | +|--------|----------|--------|-----------------| +| REQ-003 | No user evidence, assumption-based | May build unwanted feature | Conduct user research | +| REQ-004 | Competitor feature copy | May not fit our users | Validate with target users | + +### Authenticity Verdict + +> [2-3 sentences explaining why this score is appropriate. Reference specific evidence above. Example: "Score of 85% reflects that 17 of 20 requirements have verified user origins. The 3 unverified requirements (REQ-003, REQ-004, REQ-012) are all P2 priority and can proceed with documented assumptions, but user validation is recommended before v2.0."] + +--- + +## 3. Completeness Validation (完整性) + +### Completeness Score: [X]% - [Status] + +### Score Calculation + +| Category | Total Items | Specified | Weight | Weighted Score | Target | Status | +|----------|-------------|-----------|--------|----------------|--------|--------| +| Functional | [N] | [N] | 30% | [%] | ≥95% | ✅/❌ | +| Data | [N] | [N] | 20% | [%] | ≥95% | ✅/❌ | +| Flows | [N] | [N] | 20% | [%] | ≥90% | ✅/❌ | +| States | [N] | [N] | 10% | [%] | ≥90% | ✅/❌ | +| Errors | [N] | [N] | 10% | [%] | ≥85% | ✅/❌ | +| NFRs | [N] | [N] | 10% | [%] | ≥90% | ✅/❌ | +| **Total** | | | 100% | **[X]%** | | | + +### Complete Areas (Positive Findings) + +- **Functional**: All [N] user stories have acceptance criteria, CRUD operations fully specified +- **Data**: All [N] entities have complete attribute definitions with types and constraints +- **Flows**: Main success scenarios and [N] alternative flows documented with clear triggers + +### Gaps Identified (Negative Findings) + +| Gap ID | Category | Missing Item | Impact | Severity | Action | +|--------|----------|--------------|--------|----------|--------| +| GAP-001 | Error | Error handling for API timeout | Users see blank screen | Major | Define timeout handling flow | +| GAP-002 | State | State transition "Pending" → "Cancelled" | Orphan records possible | Medium | Add state machine documentation | +| GAP-003 | NFR | Specific latency target for search | Cannot verify performance | Medium | Define: "Search results < 500ms" | + +### Completeness Verdict + +> [2-3 sentences explaining the score, highlighting critical gaps. Example: "Score of 91% indicates strong functional coverage but gaps in error handling (GAP-001) and NFR quantification (GAP-003). The error handling gap is Major severity as it affects user experience directly. Recommend addressing GAP-001 before development begins."] + +--- + +## 4. Consistency Validation (一致性) + +### Consistency Score: [X]% - [Status] + +### Score Calculation + +- Total consistency checks performed: [N] +- Checks passed: [N] +- Conflicts detected: [N] +- Conflicts resolved: [N] +- **Formula**: (Checks Passed + Resolved) / Total Checks × 100 = [X]% + +### Consistent Areas (Positive Findings) + +| Area | Items Checked | Status | Notes | +|------|---------------|--------|-------| +| Terminology | [N] terms | ✅ Consistent | Glossary maintained, no synonyms | +| Data Types | [N] fields | ✅ Consistent | All fields have matching types | +| Business Rules | [N] rules | ✅ Consistent | No contradictory rules found | + +### Terminology Check + +| Term | Definition | Used Consistently | Issues | +|------|------------|-------------------|--------| +| [Term 1] | [Definition] | ✅ Yes | None | +| [Term 2] | [Definition] | ⚠️ Partial | [Issue] | + +### Conflicts Detected (Negative Findings) + +| Conflict ID | Type | Req A | Req B | Description | Resolution Status | +|-------------|------|-------|-------|-------------|-------------------| +| CON-001 | Logic | REQ-001 | REQ-005 | REQ-001: "auto-approve < $100", REQ-005: "all orders need approval" | ✅ Resolved: REQ-005 updated | +| CON-002 | Terminology | REQ-002 | REQ-008 | "Customer" vs "Client" used interchangeably | ✅ Resolved: Standardized | +| CON-003 | Data | REQ-003 | REQ-010 | Email max length: 100 vs 255 chars | ⚠️ Pending | + +### Consistency Verdict + +> [2-3 sentences explaining the score. Example: "Score of 95% reflects 19 of 20 consistency checks passed. One data type conflict (CON-003) remains unresolved but is low risk as it only affects validation messages. The terminology conflict (CON-002) was critical and has been resolved by standardizing on 'Customer' throughout all documents."] + +--- + +## 5. Feasibility Validation (可行性) + +### Overall Feasibility Score: [Rating] - [Status] + +### Score Calculation (Composite Rating) + +| Sub-Dimension | Rating | Weight | Weighted Score | Key Factor | +|---------------|--------|--------|----------------|------------| +| Technical | High/Med/Low | 30% | [Score] | [Key factor] | +| Economic | Viable/Marginal/Not | 25% | [Score] | ROI: [X]% | +| Operational | High/Med/Low | 20% | [Score] | [Key factor] | +| Schedule | Achievable/Risk/Not | 15% | [Score] | Gap: [N] days | +| Compliance | Compliant/Gap/Non | 10% | [Score] | [Key factor] | +| **Overall** | | 100% | **[Rating]** | | + +--- + +### 5.1 Technical Feasibility - [Rating] + +| Area | Rating | Evidence | +|------|--------|----------| +| Technology Maturity | High/Medium/Low | [Specific evidence: e.g., "React 18 - widely adopted, team has 2 years experience"] | +| Team Capability | High/Medium/Low | [e.g., "Need 1 additional ML engineer for recommendation feature"] | +| Architecture Fit | High/Medium/Low | [e.g., "Microservices pattern aligns with existing architecture"] | +| Integration Complexity | High/Medium/Low | [e.g., "Payment gateway API has known rate limiting issues"] | + +**Technical Verdict**: ✅ Feasible / ⚠️ Risks / ❌ Not Feasible + +**Justification**: [Why this rating? e.g., "Rated High because core technologies are proven and team is experienced. Integration risk is mitigated by existing API wrapper library."] + +--- + +### 5.2 Economic Feasibility - [Rating] + +| Metric | Value | Benchmark | Assessment | +|--------|-------|-----------|------------| +| Development Cost | [Amount] | Budget: [Amount] | ✅/⚠️/❌ [Within/Over] budget | +| Annual Operational Cost | [Amount] | Industry avg: [Amount] | ✅/⚠️/❌ [Below/Above] average | +| Expected Annual Benefit | [Amount] | Required: [Amount] | ✅/⚠️/❌ [Exceeds/Meets/Below] threshold | +| **3-Year ROI** | **[%]** | Threshold: [%] | ✅/⚠️/❌ | +| **Payback Period** | **[Months]** | Threshold: [Months] | ✅/⚠️/❌ | + +**Economic Verdict**: ✅ Viable / ⚠️ Marginal / ❌ Not Viable + +**Justification**: [Why this rating? e.g., "ROI of 450% exceeds 100% threshold. Payback of 8 months is well within 18-month target. Development cost is 25% under budget."] + +--- + +### 5.3 Operational Feasibility - [Rating] + +| Area | Assessment | Risk | Evidence | +|------|------------|------|----------| +| Process Impact | [Description] | High/Medium/Low | [e.g., "Replaces manual approval workflow"] | +| Training Required | [Hours/Cost] | High/Medium/Low | [e.g., "16 hours per support staff, $5000 total"] | +| Change Management | [Complexity] | High/Medium/Low | [e.g., "Phased rollout over 3 departments"] | + +**Operational Verdict**: ✅ Feasible / ⚠️ Risks / ❌ Not Feasible + +**Justification**: [Why this rating? e.g., "Rated Medium due to training needs. Support team can scale, but 2-week onboarding period required."] + +--- + +### 5.4 Schedule Feasibility - [Rating] + +| Milestone | Required | Achievable | Gap | Risk | Mitigation | +|-----------|----------|------------|-----|------|------------| +| Design | [Date] | [Date] | [Days] | High/Medium/Low | [Mitigation if gap exists] | +| Development | [Date] | [Date] | [Days] | High/Medium/Low | [Mitigation if gap exists] | +| Release | [Date] | [Date] | [Days] | High/Medium/Low | [Mitigation if gap exists] | + +**Schedule Verdict**: ✅ Achievable / ⚠️ At Risk / ❌ Not Achievable + +**Justification**: [Why this rating? e.g., "2-week buffer exists before hard deadline. Parallel workstreams reduce critical path risk."] + +--- + +### 5.5 Compliance Feasibility - [Rating] + +| Regulation | Status | Gap | Impact | Action | +|------------|--------|-----|--------|--------| +| GDPR | Compliant/Gap | [Description] | [Impact if non-compliant] | [Action] | +| WCAG 2.1 | Compliant/Gap | [Description] | [Impact if non-compliant] | [Action] | +| [Industry Specific] | Compliant/Gap | [Description] | [Impact if non-compliant] | [Action] | + +**Compliance Verdict**: ✅ Compliant / ⚠️ Gaps Exist / ❌ Non-compliant + +**Justification**: [Why this rating? e.g., "GDPR compliant with existing data handling. Accessibility audit required before launch - scheduled for Week 6."] + +--- + +### Feasibility Verdict + +> [3-4 sentences summarizing overall feasibility. Example: "Overall feasibility rated HIGH based on strong technical foundation (mature stack, experienced team) and excellent economic outlook (450% ROI, 8-month payback). Schedule risk is mitigated by 2-week buffer. One compliance gap (accessibility audit) is non-blocking but must be addressed before public launch. No blocking issues identified."] + +--- + +## 6. Verifiability Validation (可验证性) + +### Verifiability Score: [X]% - [Status] + +### Score Calculation + +| Category | Total | Verifiable | Weight | Weighted Score | +|----------|-------|------------|--------|----------------| +| Quantified targets | [N] | [N] | 25% | [%] | +| No vague terms | [N] | [N] | 20% | [%] | +| Test cases designed | [N] | [N] | 25% | [%] | +| GWT criteria written | [N] | [N] | 20% | [%] | +| Verification method assigned | [N] | [N] | 10% | [%] | +| **Total** | | | 100% | **[X]%** | + +--- + +### 6.1 Vague Terms Check + +Scan all requirements for ambiguous/vague terms that prevent objective verification. + +| Vague Term | Found In | Count | Replacement Recommendation | +|------------|----------|-------|---------------------------| +| "fast" | REQ-004, REQ-012 | 2 | "Response time < 2s" | +| "user-friendly" | REQ-006 | 1 | "Task completion rate > 90%" | +| "secure" | REQ-008 | 1 | "OWASP Top 10 compliant" | +| "flexible" | REQ-015 | 1 | "Supports 3 configuration options" | +| "easy to use" | REQ-018 | 1 | "Complete task in < 3 clicks" | +| "high performance" | REQ-021 | 1 | "Handle 1000 concurrent users" | +| "reliable" | - | 0 | - | +| "scalable" | - | 0 | - | + +**Common Vague Terms to Scan**: +- Performance: fast, quick, responsive, efficient, high-performance +- Usability: user-friendly, easy, intuitive, simple, convenient +- Quality: reliable, stable, robust, secure, safe +- Flexibility: flexible, configurable, customizable, extensible +- Scale: scalable, many, few, large, small + +**Vague Terms Summary**: [N] vague terms found in [M] requirements + +--- + +### 6.2 Non-Quantified Standards Check + +Identify standards and criteria that lack measurable metrics. + +| Req ID | Non-Quantified Statement | Issue | Quantified Recommendation | +|--------|--------------------------|-------|--------------------------| +| REQ-004 | "System should respond quickly" | No time metric | "Response time < 500ms for 95th percentile" | +| REQ-009 | "Support many users" | No number | "Support 10,000 concurrent users" | +| REQ-011 | "High availability" | No percentage | "99.9% uptime (< 8.76 hours downtime/year)" | +| REQ-014 | "Low error rate" | No threshold | "Error rate < 0.1%" | +| REQ-017 | "Fast loading" | No time metric | "Page load < 3s on 4G network" | + +**Standards Requiring Quantification**: +- Time: response time, loading time, processing time, timeout +- Capacity: concurrent users, transactions per second, storage size +- Availability: uptime percentage, recovery time, failover time +- Quality: error rate, success rate, accuracy rate +- Performance: throughput, latency, bandwidth + +**Non-Quantified Summary**: [N] standards lack metrics in [M] requirements + +--- + +### Verifiable Requirements (Positive Findings) + +| Req ID | Verification Method | Test Cases | GWT Scenarios | Status | Why Verifiable | +|--------|---------------------|------------|---------------|--------|----------------| +| REQ-001 | Automated Test | TC-001~003 | 3 scenarios | ✅ Complete | Quantified: "Response < 2s" | +| REQ-002 | Performance Test | PT-001 | 2 scenarios | ✅ Complete | Measurable: "99.9% uptime" | +| REQ-003 | Manual Demo | Demo-001 | 1 scenario | ✅ Complete | Observable: "Button turns green" | + +### Non-Verifiable Requirements (Negative Findings) + +| Req ID | Issue | Why Not Verifiable | Impact | Recommendation | +|--------|-------|-------------------|--------|----------------| +| REQ-004 | Vague target | "System should be fast" - no metric | Cannot verify performance | Specify: "Response < 2s for 95th percentile" | +| REQ-005 | No test design | Complex integration scenario | Cannot prove completion | Design integration test with mock services | +| REQ-006 | Subjective criteria | "User-friendly interface" | Different interpretations | Define: "Task completion rate > 90%" | + +--- + +### GWT Coverage Matrix + +| Req ID | Happy Path | Error Scenarios | Edge Cases | Status | +|--------|------------|-----------------|------------|--------| +| REQ-001 | ✅ | ✅ (3) | ✅ (2) | ✅ Complete | +| REQ-002 | ✅ | ✅ (2) | ❌ Missing | ⚠️ Incomplete | +| REQ-003 | ✅ | ❌ Missing | ❌ Missing | ⚠️ Incomplete | + +### Sample GWT Scenarios + +\`\`\`gherkin +## REQ-001: [Requirement Name] + +### AC-001: Happy Path +Given [precondition] +When [action] +Then [expected result] + And [measurable outcome] + +### AC-002: Error Handling +Given [precondition] +When [error condition] +Then [error response] + And [user notification] +\`\`\` + +### Verifiability Verdict + +> [2-3 sentences explaining the score. Example: "Score of 88% reflects strong test coverage for P0 requirements but 3 requirements (REQ-004, REQ-005, REQ-006) need refinement. REQ-004's vague performance target is critical - must be quantified before development. REQ-005 and REQ-006 are P2 and can be refined during implementation planning."] + +--- + +## 7. Multi-Role Validation + +### Role Sign-Off Matrix + +| Req ID | PM | RA | SA | SE | TE | Overall | +|--------|----|----|----|----|-----|---------| +| REQ-001 | ✅ | ✅ | ⚠️ | ✅ | ✅ | ⚠️ | +| REQ-002 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | + +**Legend**: ✅ Pass | ⚠️ Issues | ❌ Fail + +### Role-Specific Concerns + +| Role | Req ID | Concern | Resolution | +|------|--------|---------|------------| +| SA | REQ-001 | Architecture impact | [Resolution] | + +--- + +## 8. Traceability Matrix + +| Req ID | Business Goal | User Story | Use Case | Test Case | Status | +|--------|---------------|------------|----------|-----------|--------| +| REQ-001 | BG-001 | US-001 | UC-001 | TC-001~005 | ✅ | +| REQ-002 | BG-001 | US-002 | UC-002 | TC-006~010 | ✅ | + +**Traceability Coverage**: [X]% fully traced + +--- + +## 9. Outstanding Issues + +| ID | Dimension | Severity | Description | Owner | Due | Status | +|----|-----------|----------|-------------|-------|-----|--------| +| V-001 | Authenticity | Critical | [Desc] | [Name] | [Date] | Open | +| V-002 | Completeness | Major | [Desc] | [Name] | [Date] | Open | +| V-003 | Feasibility | Major | [Desc] | [Name] | [Date] | Resolved | + +--- + +## 10. Sign-Off + +| Role | Name | Decision | Date | Comments | +|------|------|----------|------|----------| +| Product Owner | [Name] | Approved/Rejected | [Date] | [Comments] | +| Technical Lead | [Name] | Approved/Conditional/Rejected | [Date] | [Conditions] | +| QA Lead | [Name] | Approved/Rejected | [Date] | [Comments] | + +--- + +## Next Steps Available + +**What would you like to do next?** + +| Option | Action | When to Choose | +|--------|--------|----------------| +| **A** | **Specify** (Proceed) | All 5 dimensions pass, no critical issues, sign-off obtained | +| **B** | **Validate** (Continue) | Critical/major issues remain, feasibility concerns need resolution | +| **C** | **Clarify** (Return) | New ambiguities discovered, authenticity gaps need stakeholder input | + +### Recommendation + +[Based on Validation Dimension Summary above, recommend Option A/B/C] + +**Reason**: [Explain why this option is recommended based on validation results] + +--- +**Reply with A, B, or C to proceed.** +``` From c20af7e2f26bcf10c5ca012a5a12c1fc258f3d9d Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Thu, 22 Jan 2026 06:29:24 +0000 Subject: [PATCH 14/18] Add legacy-app-modernization-analyzer power --- legacy-app-modernization-analyzer | 1 + 1 file changed, 1 insertion(+) create mode 160000 legacy-app-modernization-analyzer diff --git a/legacy-app-modernization-analyzer b/legacy-app-modernization-analyzer new file mode 160000 index 0000000..ef48038 --- /dev/null +++ b/legacy-app-modernization-analyzer @@ -0,0 +1 @@ +Subproject commit ef48038f5b4c7bb8ee4f33985d678243097310f8 From 373d07635f517d1359c58c099222bb5e8dbedf07 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Fri, 23 Jan 2026 09:38:07 +0000 Subject: [PATCH 15/18] feat: Enhanced pathway scoring framework and cost visualization - Add weighted Recommendation Score (6 factors) replacing simple approachability - Introduce visual dot indicator matrix for pathway scoring - Replace xychart-beta with Gantt chart for 3-Year cost visualization - Add optional detailed pricing simulation (1,000 vCPU, HK region) - Fix Gantt chart syntax: use explicit positions instead of 'after' keyword - Clarify UTC timezone for report timestamps - Convert from submodule to regular files --- legacy-app-modernization-analyzer | 1 - legacy-app-modernization-analyzer/POWER.md | 138 ++++ legacy-app-modernization-analyzer/README.md | 134 ++++ legacy-app-modernization-analyzer/mcp.json | 11 + .../steering/aws-target-services.md | 135 ++++ .../steering/dotnet-to-aws.md | 270 +++++++ .../steering/evaluation-framework.md | 168 +++++ .../steering/j2ee-to-springboot-reactive.md | 348 +++++++++ .../steering/report-structure.md | 670 ++++++++++++++++++ .../steering/weblogic-to-springboot.md | 330 +++++++++ .../steering/websphere-to-springboot.md | 284 ++++++++ 11 files changed, 2488 insertions(+), 1 deletion(-) delete mode 160000 legacy-app-modernization-analyzer create mode 100644 legacy-app-modernization-analyzer/POWER.md create mode 100644 legacy-app-modernization-analyzer/README.md create mode 100644 legacy-app-modernization-analyzer/mcp.json create mode 100644 legacy-app-modernization-analyzer/steering/aws-target-services.md create mode 100644 legacy-app-modernization-analyzer/steering/dotnet-to-aws.md create mode 100644 legacy-app-modernization-analyzer/steering/evaluation-framework.md create mode 100644 legacy-app-modernization-analyzer/steering/j2ee-to-springboot-reactive.md create mode 100644 legacy-app-modernization-analyzer/steering/report-structure.md create mode 100644 legacy-app-modernization-analyzer/steering/weblogic-to-springboot.md create mode 100644 legacy-app-modernization-analyzer/steering/websphere-to-springboot.md diff --git a/legacy-app-modernization-analyzer b/legacy-app-modernization-analyzer deleted file mode 160000 index ef48038..0000000 --- a/legacy-app-modernization-analyzer +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ef48038f5b4c7bb8ee4f33985d678243097310f8 diff --git a/legacy-app-modernization-analyzer/POWER.md b/legacy-app-modernization-analyzer/POWER.md new file mode 100644 index 0000000..d675035 --- /dev/null +++ b/legacy-app-modernization-analyzer/POWER.md @@ -0,0 +1,138 @@ +--- +name: "legacy-app-modernization-analyzer" +displayName: "Legacy App Modernization Analyzer" +description: "Analyzes legacy enterprise codebases (.NET, WebSphere, WebLogic) and generates comprehensive AWS modernization feasibility reports with visual architecture diagrams, dependency analysis, and migration pathways" +keywords: [".NET", "WebSphere", "WebLogic", "Spring Boot", "modernization", "migration", "legacy", "AWS", "containerization", "microservices", "J2EE", "Jakarta", "reactive"] +version: "2.0.0" +--- + +# Legacy App Modernization Analyzer + +## Overview + +This power provides elite-level enterprise architecture analysis for legacy application modernization projects. It supports multiple source platforms and generates comprehensive feasibility reports with visual diagrams, following a rigorous evaluation framework and migration strategy bank. + +## Supported Modernization Paths + +| Source Platform | Target Platform | Steering File | +|-----------------|-----------------|---------------| +| .NET Framework 4.x | .NET 8 + AWS | `steering/dotnet-to-aws.md` | +| IBM WebSphere | Spring Boot Reactive + AWS | `steering/websphere-to-springboot.md` | +| Oracle WebLogic | Spring Boot Reactive + AWS | `steering/weblogic-to-springboot.md` | + +## Workflow + +### Step 1: Platform Detection + +Scan the codebase to identify the source platform: + +**Detect .NET:** +- Look for: `.sln`, `.csproj`, `.vbproj`, `web.config`, `packages.config`, `appsettings.json` +- If found → Load `steering/dotnet-to-aws.md` + +**Detect WebSphere:** +- Look for: `ibm-web-bnd.xml`, `ibm-web-ext.xml`, `ibm-application-bnd.xml`, `ibm-ejb-jar-bnd.xml` +- JAR dependencies: `com.ibm.websphere.*`, `com.ibm.ws.*`, `com.ibm.mq.*` +- If found → Load `steering/websphere-to-springboot.md` + +**Detect WebLogic:** +- Look for: `weblogic.xml`, `weblogic-application.xml`, `weblogic-ejb-jar.xml` +- JAR dependencies: `weblogic.*`, `oracle.weblogic.*`, `com.bea.*` +- If found → Load `steering/weblogic-to-springboot.md` + +### Step 2: Load Common Framework + +ALWAYS load these steering files for any analysis: +- `steering/common/evaluation-framework.md` - Universal evaluation areas +- `steering/common/report-structure.md` - **AUTHORITATIVE** report format standards +- `steering/common/aws-target-services.md` - AWS service mappings + +### Step 3: Execute Platform-Specific Analysis + +Follow the loaded platform steering file for: +- Technology-specific detection patterns +- Migration strategy bank +- Code transformation examples +- Platform-specific risks and mitigations + +## Analysis Methodology + +### Exhaustive Analysis Mode + +Generate the most detailed, comprehensive report possible. Assume the user demands extreme depth - this is $1M/project consulting-grade work. + +### Incremental Codebase Scanning + +To avoid context overflow when analyzing large codebases: + +**Phase 1: Discovery (Lightweight)** +- First, scan ONLY for solution/project files +- Build a project inventory WITHOUT reading full file contents +- Identify the solution structure and project count + +**Phase 2: Targeted Analysis (Per-Project)** +- Analyze ONE project at a time +- In the first pass, gather a map of all files to understand scope +- Read only files relevant to the current analysis step +- Summarize findings before moving to the next project + +**Phase 3: Selective Deep Dives** +- Only read full file contents when specifically needed +- Use grep/search tools to FIND patterns first +- Avoid reading entire directories into context + +**Memory Management Rules:** +- Summarize findings after each major component +- Do NOT load all source files simultaneously +- Process large codebases in batches of 5-10 files +- Prioritize: config files → project files → key source → supporting files + +### Database Detection + +Scan the codebase to identify database technology: +- SQL Server indicators: connection strings, `SqlConnection`, `SqlCommand` +- Oracle indicators: `Oracle.DataAccess`, `Oracle.ManagedDataAccess` +- DB2 indicators: `IBM.Data.DB2` +- If commercial database detected, prominently recommend Aurora PostgreSQL for cost optimization + +### Proprietary Dependency Analysis + +For EVERY proprietary/commercial library found: +- Detailed compatibility assessment table +- Code migration examples (before/after) +- Specific mitigation options with effort levels + +## Bundled MCP Server + +This power includes the `fetch` MCP server (configured in `mcp-config.json`) to query package registry APIs for license verification. + +**Note**: Ensure `uvx` is installed (via `uv` Python package manager). See [uv installation guide](https://docs.astral.sh/uv/getting-started/installation/). + +## Prerequisites + +- Access to codebase (local or repository) +- Familiarity with source platform (.NET, WebSphere, or WebLogic) +- Understanding of modernization goals (cloud-native, containerization, etc.) +- Awareness of proprietary/commercial library dependencies + +## Trigger Phrases + +This power activates when users mention: +- "analyze this codebase" +- "modernization assessment" +- "migration feasibility" +- "legacy application" +- "AWS migration" +- "containerize app" +- "modernize to Spring Boot" +- "modernize to .NET 8" +- ".NET modernization" +- "WebSphere migration" +- "WebLogic migration" +- "J2EE modernization" + +## Output + +Generate report in `yymmddhhmm_MODERNIZATION_REPORT.md` following the structure defined in `steering/common/report-structure.md`. As for yymmddhhmm, it is the current time's year for yy, month for mm, day for dd, hour for hh and minutes for mm (UTC Timezone). + +**CRITICAL:** The `steering/common/report-structure.md` file is the SINGLE SOURCE OF TRUTH for all report formatting, section structure, visualization standards, and quality requirements. Do NOT deviate from it. diff --git a/legacy-app-modernization-analyzer/README.md b/legacy-app-modernization-analyzer/README.md new file mode 100644 index 0000000..644fd46 --- /dev/null +++ b/legacy-app-modernization-analyzer/README.md @@ -0,0 +1,134 @@ +# Legacy App Modernization Analyzer + +A Kiro Power that provides enterprise-grade legacy codebase modernization analysis. Generates comprehensive AWS migration feasibility reports with visual architecture diagrams, proprietary dependency analysis, and strategic migration pathways. + +## Supported Modernization Paths + +| Source Platform | Target Platform | Description | Status | +|-----------------|-----------------|-------------|--------| +| .NET Framework 4.x | .NET 8 + AWS | Windows-based .NET apps to cross-platform cloud-native | ✅ Stable | +| IBM WebSphere | Spring Boot Reactive + AWS | J2EE/Jakarta EE to reactive microservices | 🧪 BETA | +| Oracle WebLogic | Spring Boot Reactive + AWS | J2EE/Jakarta EE to reactive microservices | 🧪 BETA | + +> **Note**: WebSphere and WebLogic modernization paths are in BETA. While functional, these paths may have limited coverage for some proprietary APIs and edge cases. + +## Features + +- **Auto-Detection**: Automatically identifies source platform from codebase indicators +- **Platform-Specific Analysis**: Dedicated migration strategies for each source platform +- **Comprehensive Evaluation**: 18+ modernization areas assessed +- **Visual Architecture Diagrams**: Mermaid.js diagrams with component-level color coding +- **Package License Verification**: Queries NuGet/Maven APIs for license validation +- **Proprietary Dependency Analysis**: Impact assessment with code migration examples +- **Database Migration**: SQL Server/Oracle/DB2 → Aurora PostgreSQL recommendations +- **Strategic Alignment**: AWS 7 Rs and Gartner TIME framework classification +- **Risk Assessment**: "Impact If Not Modernized" for every finding with probability ratings +- **3 Migration Pathways**: Ranked by weighted Recommendation Score with visual dot indicators +- **Cost-Benefit Analysis**: Qualitative assessments by default (Low/Medium/High/Very High), with optional detailed pricing simulation available on request + +## Platform Detection + +The analyzer automatically detects your source platform: + +### .NET Detection +- Files: `.sln`, `.csproj`, `.vbproj`, `web.config`, `packages.config`, `appsettings.json` + +### WebSphere Detection +- Files: `ibm-web-bnd.xml`, `ibm-web-ext.xml`, `ibm-application-bnd.xml`, `ibm-ejb-jar-bnd.xml` +- Dependencies: `com.ibm.websphere.*`, `com.ibm.ws.*`, `com.ibm.mq.*` + +### WebLogic Detection +- Files: `weblogic.xml`, `weblogic-application.xml`, `weblogic-ejb-jar.xml` +- Dependencies: `weblogic.*`, `oracle.weblogic.*`, `com.bea.*` + +## Prerequisites + +- Kiro IDE +- `uvx` installed (for fetch MCP server) + - Install: `pip install uv` or see [uv installation guide](https://docs.astral.sh/uv/getting-started/installation/) + +## Usage + +Activate by mentioning: +- "analyze this codebase" +- "modernization assessment" +- "migration feasibility" +- "legacy application" +- "AWS migration" +- "containerize app" +- "modernize to Spring Boot" +- "modernize to .NET 8" +- ".NET modernization" +- "WebSphere migration" +- "WebLogic migration" +- "J2EE modernization" + +### Example + +``` +User: analyze this codebase and generate a modernization report +``` + +The power will: +1. Detect source platform (.NET, WebSphere, or WebLogic) +2. Load platform-specific steering file +3. Load common framework files (evaluation, report structure, AWS services) +4. Scan codebase incrementally (context-aware for large projects) +5. Detect database technology +6. Verify package licenses via registry APIs +7. Generate `yymmddhhmm_MODERNIZATION_REPORT.md` (timestamped: YY=year, MM=month, DD=day, HH=hour, MM=minutes) + +## Output + +Report structure is defined by `steering/report-structure.md` (single source of truth): + +1. **Professional Advisory Notice** - Consultation disclaimer +2. **Executive Summary** - Strategic verdict, feasibility score, risk of inaction +3. **Visual Architecture** - Current and target state diagrams (color-coded) +4. **Critical Findings Matrix** - 10+ findings with priorities +5. **Proprietary Dependency Analysis** - License verification, migration examples +6. **Database Analysis** - Detection and migration opportunity +7. **Recommended Pathways** - 3 pathways with: + - Weighted Recommendation Scores (6 factors: Long-term Value, Implementation Risk, Cost Efficiency, Time to Value, Team Readiness, Business Continuity) + - Visual dot indicator scoring matrix (●●●●●●●●●○ format) + - Quadrant chart for effort vs value positioning + - Pros/cons tables and risk assessments +8. **Next Steps** - Recommended pathway implementation roadmap +9. **Cost-Benefit Analysis** - Pathway comparison (qualitative) +10. **Solution Structure Summary** - Projects and complexity +11. **Conclusion** - Assessment and success factors + +## Project Structure + +``` +legacy-app-modernization-analyzer/ +├── POWER.md # Main power definition +├── mcp.json # MCP server configuration (fetch) +├── README.md # This file +└── steering/ + ├── evaluation-framework.md # Universal evaluation areas + ├── report-structure.md # Report format standards (AUTHORITATIVE) + ├── aws-target-services.md # AWS service mappings + ├── j2ee-to-springboot-reactive.md # J2EE migration patterns + ├── dotnet-to-aws.md # .NET → .NET 8 + AWS + ├── websphere-to-springboot.md # WebSphere → Spring Boot + └── weblogic-to-springboot.md # WebLogic → Spring Boot +``` + +## Version History + +### v2.0.0 - Legacy App Modernization Analyzer +- Multi-platform support: .NET, WebSphere, WebLogic +- Platform auto-detection +- Spring Boot Reactive target for Java platforms +- Consolidated steering files with authoritative report structure +- Expanded database support (SQL Server, Oracle, DB2) + +### v1.x - .NET Modernization Analyzer +- Original .NET Framework → .NET 8 analyzer +- NuGet license verification +- Architecture diagram color coding + +## License + +Apache 2.0 diff --git a/legacy-app-modernization-analyzer/mcp.json b/legacy-app-modernization-analyzer/mcp.json new file mode 100644 index 0000000..f68b9f0 --- /dev/null +++ b/legacy-app-modernization-analyzer/mcp.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "fetch": { + "command": "uvx", + "args": ["mcp-server-fetch"], + "env": {}, + "disabled": false, + "autoApprove": ["fetch"] + } + } +} diff --git a/legacy-app-modernization-analyzer/steering/aws-target-services.md b/legacy-app-modernization-analyzer/steering/aws-target-services.md new file mode 100644 index 0000000..47ead05 --- /dev/null +++ b/legacy-app-modernization-analyzer/steering/aws-target-services.md @@ -0,0 +1,135 @@ +--- +inclusion: always +--- + +# AWS Target Services for Modernization + +This guide maps common legacy components to AWS-native services. + +## Compute Services + +| Legacy Component | AWS Service | Notes | +|------------------|-------------|-------| +| Application Server (WebLogic, WebSphere, IIS) | Amazon ECS / EKS | Container orchestration | +| Virtual Machines | Amazon EC2 / Fargate | Serverless containers preferred | +| Batch Processing | AWS Batch / Step Functions | Managed batch workloads | +| Scheduled Jobs | Amazon EventBridge / Lambda | Serverless scheduling | + +### Container Recommendations + +- **ECS Fargate**: Simplified container deployment, no server management +- **EKS**: Kubernetes-based orchestration for complex workloads +- **Graviton Processors**: Up to 40% cost savings with ARM64 + +## Database Services + +| Legacy Database | AWS Service | Migration Path | +|-----------------|-------------|----------------| +| SQL Server | Amazon RDS SQL Server | Lift-and-shift | +| SQL Server | Aurora PostgreSQL | Cost optimization (no licensing) | +| Oracle | Amazon RDS Oracle | Lift-and-shift | +| Oracle | Aurora PostgreSQL | Cost optimization | +| DB2 | Amazon RDS | Via DMS migration | +| MySQL | Amazon RDS MySQL / Aurora MySQL | Direct migration | + +### Database Migration Tools + +- **AWS Schema Conversion Tool (SCT)**: Schema and stored procedure conversion +- **AWS Database Migration Service (DMS)**: Data migration with minimal downtime +- **pgLoader**: Open-source alternative for PostgreSQL migration + +### Cost Optimization + +Database licensing is often the largest cost component: +- SQL Server licensing: Very High ongoing cost +- Oracle licensing: Very High ongoing cost +- Aurora PostgreSQL: No licensing fees, High savings potential + +## Messaging Services + +| Legacy Messaging | AWS Service | Use Case | +|------------------|-------------|----------| +| MSMQ | Amazon SQS | Point-to-point queuing | +| WebSphere MQ | Amazon SQS / Amazon MQ | Enterprise messaging | +| WebLogic JMS | Amazon SQS / MSK | JMS replacement | +| RabbitMQ | Amazon MQ | Managed RabbitMQ | +| Kafka | Amazon MSK | Managed Kafka | +| Pub/Sub | Amazon SNS | Fan-out messaging | +| Event-Driven | Amazon EventBridge | Event bus | + +## Security Services + +| Legacy Security | AWS Service | Notes | +|-----------------|-------------|-------| +| Windows Auth | Amazon Cognito | OAuth 2.0/OIDC | +| LDAP | Amazon Cognito / Directory Service | Identity management | +| Custom Auth | Amazon Cognito | User pools | +| Secrets Storage | AWS Secrets Manager | Credential management | +| Certificate Management | AWS Certificate Manager | SSL/TLS certificates | + +## Configuration & Storage + +| Legacy Component | AWS Service | Notes | +|------------------|-------------|-------| +| Config Files | AWS Systems Manager Parameter Store | Centralized config | +| File Storage | Amazon S3 | Object storage | +| Session State | Amazon ElastiCache / DynamoDB | Distributed sessions | +| Caching | Amazon ElastiCache | Redis/Memcached | + +## Observability + +| Legacy Monitoring | AWS Service | Notes | +|-------------------|-------------|-------| +| Application Logs | Amazon CloudWatch Logs | Centralized logging | +| Metrics | Amazon CloudWatch Metrics | Application metrics | +| Tracing | AWS X-Ray | Distributed tracing | +| APM | CloudWatch Application Insights | Application monitoring | + +## Networking + +| Legacy Component | AWS Service | Notes | +|------------------|-------------|-------| +| Load Balancer | Application Load Balancer (ALB) | Layer 7 load balancing | +| DNS | Amazon Route 53 | DNS management | +| CDN | Amazon CloudFront | Content delivery | +| VPN | AWS VPN / Direct Connect | Hybrid connectivity | + +## AWS Well-Architected Alignment + +### Operational Excellence +- Infrastructure as Code (CloudFormation, CDK) +- Automated deployment pipelines (CodePipeline) +- Observability (CloudWatch, X-Ray) + +### Security +- Secrets management (Secrets Manager) +- IAM roles for service authentication +- Encryption in transit and at rest +- VPC isolation and security groups + +### Reliability +- Multi-AZ deployment +- Auto-scaling +- Circuit breakers (with application code) +- Graceful degradation patterns + +### Performance Efficiency +- Graviton processors for cost-optimized performance +- Right-sizing based on workload +- Caching strategies + +### Cost Optimization +- Graviton instances (up to 40% savings) +- Spot instances for non-critical workloads +- Reserved capacity for predictable workloads +- License elimination (Aurora PostgreSQL vs SQL Server) + +## Recommended Migration Tools + +| Tool | Purpose | +|------|---------| +| AWS Application Discovery Service | Discover on-premises applications | +| AWS Migration Hub | Track migration progress | +| AWS App2Container | Containerize .NET and Java apps | +| AWS Transform | .NET modernization assistance | +| Kiro | AI-powered migration assistance | diff --git a/legacy-app-modernization-analyzer/steering/dotnet-to-aws.md b/legacy-app-modernization-analyzer/steering/dotnet-to-aws.md new file mode 100644 index 0000000..4b692b4 --- /dev/null +++ b/legacy-app-modernization-analyzer/steering/dotnet-to-aws.md @@ -0,0 +1,270 @@ +--- +inclusion: manual +--- + +# .NET Framework to .NET 8 + AWS Modernization + +## Platform Detection + +### .NET-Specific Files to Detect + +- `.sln` - Solution files +- `.csproj` / `.vbproj` - Project files +- `web.config` / `app.config` - Configuration files +- `packages.config` - Legacy NuGet packages +- `appsettings.json` - Modern configuration +- `Global.asax` - ASP.NET application file + +### .NET-Specific Dependencies + +- `System.Web.*` - ASP.NET Web Forms +- `System.Data.SqlClient` / `Microsoft.Data.SqlClient` - SQL Server +- `System.ServiceModel.*` - WCF +- `EntityFramework` / `Microsoft.EntityFrameworkCore` - ORM + +### Target Framework Detection + +Extract from `.csproj` files: +- `net48` - .NET Framework 4.8 +- `net6.0` - .NET 6 +- `net8.0` - .NET 8 + +## Migration Strategy Bank + +### API & Library Modernization + +| Current | Target | Notes | +|---------|--------|-------| +| EF6 | EF Core 8 | Modern ORM with better performance | +| Web Forms | ASP.NET Core MVC/Razor | Modern web framework | +| WCF | gRPC or REST APIs | Cloud-native communication | +| ADO.NET | Dapper or EF Core | Simplified data access | +| ASP.NET MVC 5 | ASP.NET Core MVC | Cross-platform MVC | +| Web API 2 | ASP.NET Core Web API | Modern REST APIs | + +### Architecture Transformation + +| Current | Target | Notes | +|---------|--------|-------| +| Monolith | Microservices | Containerized, independently deployable | +| IIS-hosted | Docker/ECS/EKS | Linux containers on AWS | +| Traditional MVC | API + SPA | Modern frontend separation | +| x86 | ARM (Graviton) | Cost optimization | +| Windows Server | Linux | Cost savings, better container support | + +### Database Modernization + +| Current | Target | Notes | +|---------|--------|-------| +| SQL Server | Aurora PostgreSQL | Cost optimization (no licensing) | +| SQL Server | Amazon RDS SQL Server | Managed service | +| LINQ to SQL | EF Core | Modern data access | +| Stored Procedures | Application code | Better testability | + +### Messaging & Integration + +| Current | Target | Notes | +|---------|--------|-------| +| MSMQ | Amazon SQS/SNS | Cloud-native messaging | +| Azure Service Bus | Amazon SQS/EventBridge | AWS event-driven | +| NServiceBus | MassTransit | Modern service bus | +| SignalR | SignalR on AWS | Real-time communication | + +### Security Modernization + +| Current | Target | Notes | +|---------|--------|-------| +| Windows Auth | AWS Cognito | OAuth 2.0/OIDC | +| ASP.NET Membership | ASP.NET Core Identity | Modern identity | +| Forms Auth | JWT/OAuth2 | Token-based auth | +| Machine Keys | AWS KMS | Key management | + +### Cloud-Native Patterns + +| Current | Target | Notes | +|---------|--------|-------| +| web.config | AWS Parameter Store | Centralized config | +| File storage | Amazon S3 | Scalable object storage | +| Session State | ElastiCache/DynamoDB | Distributed sessions | +| Logging | AWS CloudWatch | Centralized logging | +| Caching | ElastiCache | Distributed caching | + +## .NET-Specific Evaluation Areas + +### Platform & Framework Assessment + +- **Target Framework Version**: v4.x vs .NET Core/5+/6+/8 +- **Windows-Only Dependencies**: Identify Windows-specific APIs +- **32-bit vs 64-bit**: Architecture compatibility +- **Framework EOL Status**: Support lifecycle assessment + +### ASP.NET Web Forms Assessment + +If Web Forms detected: +- Count of `.aspx` pages +- ViewState usage complexity +- Code-behind patterns +- User controls and custom controls +- Master pages structure + +Migration options: +1. **Incremental**: Add ASP.NET Core alongside Web Forms +2. **Rewrite**: Full rewrite to Blazor or React +3. **Strangler Fig**: Gradually replace pages + +### WCF Assessment + +If WCF detected: +- Service contracts (`[ServiceContract]`) +- Data contracts (`[DataContract]`) +- Binding configurations +- Security modes (Transport, Message) +- Duplex/callback patterns + +Migration options: +1. **gRPC**: For internal service communication +2. **REST API**: For external/public APIs +3. **CoreWCF**: For minimal changes (limited) + +### Entity Framework Assessment + +If EF6 detected: +- DbContext implementations +- Code-First vs Database-First +- Migration history +- Lazy loading usage +- Complex relationships + +Migration to EF Core: +- Breaking changes in EF Core +- Removed features (lazy loading proxy differences) +- New features (split queries, compiled queries) + +## NuGet License Verification + +For each NuGet package, verify license via NuGet.org API: + +1. Query: `https://api.nuget.org/v3/registration5-gz-semver2/{package-id}/index.json` +2. Extract `catalogEntry` URL +3. Fetch catalog entry and extract `licenseExpression` (SPDX identifier) + +Include verification note in report: +> 📋 **License Verification**: All NuGet package licenses were verified by querying the NuGet.org Catalog API. + +## SQL Server to PostgreSQL Migration + +### T-SQL to PostgreSQL Conversion + +| T-SQL | PostgreSQL | Notes | +|-------|------------|-------| +| `GETDATE()` | `NOW()` or `CURRENT_TIMESTAMP` | | +| `ISNULL(a, b)` | `COALESCE(a, b)` | | +| `CONVERT(type, value)` | `CAST(value AS type)` | | +| `TOP n` | `LIMIT n` | Move to end of query | +| `DATEADD(day, n, date)` | `date + INTERVAL 'n days'` | | +| `DATEDIFF(day, a, b)` | `DATE_PART('day', b - a)` | | +| `nvarchar(max)` | `TEXT` | | +| `uniqueidentifier` | `UUID` | | +| `datetime2` | `TIMESTAMP` | | +| `money` | `DECIMAL(19,4)` | | + +### Migration Tools + +- **AWS Schema Conversion Tool (SCT)**: Schema and stored procedure conversion +- **AWS Database Migration Service (DMS)**: Data migration +- **pgLoader**: Open-source data migration + +## Recommended Tools + +Prioritize AWS Transform tools in this order: + +| Tool | Purpose | Priority | +|------|---------|----------| +| AWS Transform for Windows Full Stack | End-to-end .NET modernization including framework upgrade + database migration | 1st - Use when both app and DB migration needed | +| AWS Transform for .NET | .NET Framework to .NET Core/8 porting, EF6 → EF Core migration | 2nd - Use for application-only migration | +| AWS Schema Conversion Tool (SCT) | Database schema conversion analysis (SQL Server → PostgreSQL) | 3rd - Use for database-only scenarios | +| AWS Database Migration Service (DMS) | Data migration with minimal downtime | 3rd - Use with SCT for database migration | +| AWS App2Container | Containerization of existing .NET applications | 4th - Use for lift-and-shift containerization | +| Kiro | AI-assisted code migration and refactoring | Supplementary - Use throughout all phases | + +**Tool Selection Guidance:** +- For full modernization (.NET upgrade + SQL Server → Aurora PostgreSQL): Use **AWS Transform for Windows Full Stack** +- For .NET framework upgrade only (keeping SQL Server): Use **AWS Transform for .NET** +- For database migration only (keeping .NET Framework): Use **SCT + DMS** +- For containerization without code changes: Use **AWS App2Container** + +## Code Migration Examples + +### web.config to appsettings.json + +**Before (web.config):** +```xml + + + + + + +``` + +**After (appsettings.json):** +```json +{ + "ConnectionStrings": { + "DefaultConnection": "Host=myserver;Database=mydb;Username=user;Password=pass;" + }, + "ApiKey": "secret123" +} +``` + +### ASP.NET MVC to ASP.NET Core + +**Before (ASP.NET MVC 5):** +```csharp +public class HomeController : Controller +{ + public ActionResult Index() + { + return View(); + } +} +``` + +**After (ASP.NET Core):** +```csharp +public class HomeController : Controller +{ + private readonly ILogger _logger; + + public HomeController(ILogger logger) + { + _logger = logger; + } + + public IActionResult Index() + { + return View(); + } +} +``` + +### EF6 to EF Core + +**Before (EF6):** +```csharp +public class MyDbContext : DbContext +{ + public MyDbContext() : base("DefaultConnection") { } + public DbSet Customers { get; set; } +} +``` + +**After (EF Core):** +```csharp +public class MyDbContext : DbContext +{ + public MyDbContext(DbContextOptions options) : base(options) { } + public DbSet Customers { get; set; } +} +``` diff --git a/legacy-app-modernization-analyzer/steering/evaluation-framework.md b/legacy-app-modernization-analyzer/steering/evaluation-framework.md new file mode 100644 index 0000000..9814522 --- /dev/null +++ b/legacy-app-modernization-analyzer/steering/evaluation-framework.md @@ -0,0 +1,168 @@ +--- +inclusion: always +--- + +# Common Modernization Evaluation Framework + +This framework applies to ALL modernization analyses regardless of source platform (.NET, WebSphere, WebLogic). + +## Universal Evaluation Areas + +### 1. Architecture Assessment + +Evaluate the current architecture for modernization readiness: + +- **Monolithic vs Modular**: Identify if application is monolithic or has modular components +- **Layering Patterns**: Assess Domain/Data/Web/Infrastructure separation +- **Coupling Analysis**: Measure inter-component dependencies +- **Layering Violations**: Identify cross-layer dependencies that violate architecture +- **Service Boundaries**: Identify potential microservice decomposition points + +### 2. Code Quality + +Assess codebase maintainability: + +- **Cyclomatic Complexity**: Measure method/class complexity +- **Maintainability Index**: Overall code maintainability score +- **Code Duplication**: Identify duplicated code blocks +- **Technical Debt**: Estimate accumulated technical debt +- **Code Coverage**: Existing test coverage percentage + +### 3. DevOps Readiness + +Evaluate CI/CD and deployment maturity: + +- **CI/CD Pipeline**: Existing automation for build/test/deploy +- **Container Readiness**: Dockerfile or containerization present +- **Infrastructure as Code**: CloudFormation, CDK, Terraform usage +- **Environment Parity**: Dev/staging/prod consistency +- **Deployment Frequency**: Current release cadence + +### 4. Security Patterns + +Assess security implementation: + +- **Authentication Mechanisms**: Current auth patterns (LDAP, OAuth, custom) +- **Authorization Patterns**: Role-based access control implementation +- **Secrets Management**: How credentials are stored and accessed +- **Transport Security**: TLS/SSL configuration +- **Security Vulnerabilities**: Known CVEs in dependencies + +### 5. Observability + +Evaluate monitoring and logging: + +- **Logging Patterns**: Structured vs unstructured logging +- **Log Aggregation**: Centralized logging solution +- **Metrics Collection**: Application and infrastructure metrics +- **Distributed Tracing**: Request tracing across services +- **Alerting**: Monitoring and alerting configuration + +### 6. Database Layer + +Assess data access patterns: + +- **ORM Usage**: Entity Framework, Hibernate, JPA, etc. +- **Connection Patterns**: Connection pooling, transaction management +- **Stored Procedure Complexity**: Count and complexity of stored procedures +- **Database-Specific Features**: Vendor-specific SQL features in use +- **Data Model Complexity**: Relationship complexity, normalization level + +### 7. Testing Maturity + +Evaluate test coverage and quality: + +- **Unit Test Coverage**: Percentage of code covered by unit tests +- **Integration Tests**: Presence of integration test suites +- **End-to-End Tests**: Automated E2E testing +- **Performance Tests**: Load and stress testing capability +- **Test Automation**: CI integration of test suites + +### 8. Documentation Quality + +Assess existing documentation: + +- **Architecture Diagrams**: Current state documentation +- **API Documentation**: OpenAPI/Swagger or equivalent +- **Runbooks**: Operational documentation +- **Code Comments**: Inline documentation quality +- **README Files**: Project documentation completeness + +## Risk of Inaction Framework + +For EVERY finding, articulate the business impact if not modernized: + +| Risk Category | Questions to Answer | +|---------------|---------------------| +| Security | What vulnerabilities will emerge? What compliance risks exist? | +| Performance | How will performance degrade over time? | +| Support Lifecycle | When do frameworks/libraries reach EOL? | +| Competitive Disadvantage | How does technical debt impact time-to-market? | +| Cost Implications | What are the ongoing maintenance costs? | +| Talent Acquisition | How hard is it to hire developers for legacy tech? | +| Scalability | Can the system handle future growth? | + +## Strategic Alignment Frameworks + +### AWS 7 Rs of Migration + +Classify each modernization pathway: + +| Strategy | Description | When to Use | +|----------|-------------|-------------| +| **Rehost** | Lift-and-shift to cloud | Quick migration, minimal changes | +| **Replatform** | Lift-tinker-and-shift | Minor optimizations during migration | +| **Refactor** | Re-architect for cloud-native | Significant modernization needed | +| **Repurchase** | Move to SaaS | Replace with commercial solution | +| **Retire** | Decommission | Application no longer needed | +| **Retain** | Keep as-is | Not ready for migration | +| **Relocate** | Hypervisor-level migration | VMware to AWS migration | + +### Gartner TIME Framework + +Classify applications for portfolio decisions: + +| Classification | Description | Action | +|----------------|-------------|--------| +| **Tolerate** | Keep running with minimal investment | Maintain only | +| **Invest** | Modernize and enhance | Active development | +| **Migrate** | Move to new platform | Platform change | +| **Eliminate** | Decommission or replace | Remove from portfolio | + +## Cost-Benefit Analysis Framework + +### Infrastructure Cost Comparison + +Use qualitative levels (Low/Medium/High/Very High) for: + +- Current infrastructure costs +- Modernized infrastructure costs +- Licensing costs (current vs target) +- Operational overhead +- Savings potential + +### ROI Assessment + +Evaluate return on investment: + +- Investment level required +- Expected returns (cost savings, efficiency gains) +- Time to value realization +- Risk-adjusted returns + +## Report Quality Standards + +### Visualization Requirements + +- Use Mermaid.js for ALL diagrams +- NEVER use ASCII art +- Include architecture diagrams (current and target state) +- Include dependency graphs +- Include migration roadmap visualizations + +### Evidence-Based Analysis + +- Reference actual files, packages, and patterns found +- Provide specific metrics (file counts, LOC, dependency counts) +- Include code examples for migration patterns +- Back all claims with codebase evidence diff --git a/legacy-app-modernization-analyzer/steering/j2ee-to-springboot-reactive.md b/legacy-app-modernization-analyzer/steering/j2ee-to-springboot-reactive.md new file mode 100644 index 0000000..99e0167 --- /dev/null +++ b/legacy-app-modernization-analyzer/steering/j2ee-to-springboot-reactive.md @@ -0,0 +1,348 @@ +--- +inclusion: fileMatch +fileMatchPattern: "**/websphere-to-springboot.md,**/weblogic-to-springboot.md" +--- + +# J2EE to Spring Boot Reactive Migration - Common Patterns + +This steering file contains common migration patterns shared between WebSphere and WebLogic to Spring Boot Reactive migrations. + +## Target Architecture + +All J2EE migrations target: +- Spring Boot 3.x with Java 17+ +- Fully reactive architecture (WebFlux, R2DBC, Reactor) +- AWS container-based deployments (ECS/EKS) +- Graviton processor optimization +- AWS Java Runtime (Corretto) + +## Common Migration Strategy Bank + +### Application Server → Spring Boot + +| J2EE Component | Spring Boot Equivalent | +|----------------|------------------------| +| EJB Stateless Session Beans | Spring `@Service` with reactive return types (Mono/Flux) | +| EJB Stateful Session Beans | Spring service + Redis/DynamoDB for state | +| EJB Message-Driven Beans | Reactor Kafka / AWS SQS listeners | +| J2EE Security | Spring Security Reactive | +| J2EE Timer Service | Spring `@Scheduled` | +| JNDI DataSource | Spring `DataSource` bean / R2DBC | +| JMS | Amazon SQS / MSK (Kafka) | +| Work Manager / Async Beans | Reactor Schedulers | +| Application Server Clustering | ECS/EKS + ALB | +| Server Diagnostics | Spring Boot Actuator + CloudWatch | + +### Data Access Migration + +| J2EE JPA | Spring Data | +|----------|-------------| +| JPA with Hibernate/TopLink/EclipseLink | Spring Data R2DBC (reactive) | +| `persistence.xml` | `application.yml` R2DBC config | +| EntityManager | R2DatabaseClient | +| JPQL queries | Native SQL / query methods | +| JTA transactions | R2DBC reactive transactions | + +### Messaging Migration + +| J2EE JMS | AWS Messaging | +|----------|---------------| +| JMS Connection Factory | Kafka/SQS connection config | +| JMS Queues | Kafka topics / SQS queues | +| JMS Topics | Kafka topics / SNS topics | +| JMS MessageListener | Reactor Kafka / SQS async | +| XA Transactions | Saga pattern / Outbox pattern | + +### Security Migration + +| J2EE Security | Spring Security Reactive | +|---------------|--------------------------| +| User Registry (LDAP) | ReactiveAuthenticationManager | +| Security Tokens | JWT / OAuth2 | +| Security Roles | Spring authorities | +| `@RolesAllowed` | `@PreAuthorize` | +| Credential Vault | AWS Secrets Manager | + +## Common Implementation Phases + +### Phase 0: Dependency Analysis + +1. Scan for J2EE imports (`javax.ejb`, `javax.servlet`, `javax.persistence`, `javax.jms`) +2. Identify application server-specific imports +3. Analyze deployment descriptors +4. Calculate dependency density scores +5. Generate migration complexity report + +### Phase 1: Project Structure Migration + +1. Update to Spring Boot 3.x parent +2. Remove ALL J2EE and application server dependencies +3. Add Spring Boot reactive starters: + - `spring-boot-starter-webflux` (NOT `spring-boot-starter-web`) + - `spring-boot-starter-data-r2dbc` + - `spring-boot-starter-rsocket` +4. Configure multi-architecture Docker build (x86_64 + ARM64) + +### Phase 2: Configuration Migration + +1. Remove `web.xml` entirely +2. Migrate deployment descriptors to `application.yml` +3. Replace JNDI lookups with Spring DI +4. Configure R2DBC data sources + +### Phase 3: EJB Migration + +1. Convert Stateless Session Beans to `@Service` +2. Convert Stateful Session Beans to services + Redis +3. Migrate MDBs to reactive message listeners +4. Replace `@EJB` with constructor injection + +### Phase 4: Data Access Migration + +1. Remove `persistence.xml` +2. Configure Spring Data R2DBC +3. Convert JPA entities to R2DBC entities +4. Rewrite JPQL to native SQL + +### Phase 5: Web Services Migration + +1. Convert JAX-RS to Spring WebFlux +2. Replace servlet filters with WebFilter +3. Eliminate HttpServletRequest/Response usage + +### Phase 6: Messaging Migration + +1. Replace JMS with Kafka/SQS +2. Convert JMS producers to reactive publishers +3. Migrate MDBs to reactive consumers + +### Phase 7: Security Migration + +1. Replace J2EE security with Spring Security Reactive +2. Migrate user registries to Cognito/LDAP +3. Replace security tokens with JWT/OAuth2 + +### Phase 8: Container Optimization + +1. Create multi-arch Dockerfile (x86_64 + ARM64) +2. Configure for AWS Java Runtime (Corretto) +3. Optimize for Graviton processors + +## J2EE to Jakarta EE Namespace Change + +All J2EE migrations must handle the namespace change: +- `javax.*` packages → `jakarta.*` packages +- Spring Boot 3.x uses Jakarta EE 9+ +- Requires dependency updates across the board + +## Common Code Migration Examples + +### EJB to Spring Service + +**Before (J2EE EJB):** +```java +@Stateless +public class OrderServiceBean implements OrderService { + @Resource + private SessionContext ctx; + + @EJB + private InventoryService inventory; + + @TransactionAttribute(TransactionAttributeType.REQUIRED) + public Order createOrder(OrderRequest request) { + // blocking implementation + } +} +``` + +**After (Spring Boot Reactive):** +```java +@Service +public class OrderService { + private final InventoryService inventory; + + public OrderService(InventoryService inventory) { + this.inventory = inventory; + } + + @Transactional + public Mono createOrder(OrderRequest request) { + return inventory.checkStock(request.getItems()) + .flatMap(available -> saveOrder(request)); + } +} +``` + +### JMS MDB to Reactive Kafka + +**Before (J2EE MDB):** +```java +@MessageDriven(activationConfig = { + @ActivationConfigProperty(propertyName = "destinationType", + propertyValue = "javax.jms.Queue"), + @ActivationConfigProperty(propertyName = "destination", + propertyValue = "jms/OrderQueue") +}) +public class OrderMessageBean implements MessageListener { + public void onMessage(Message message) { + // blocking processing + } +} +``` + +**After (Reactor Kafka):** +```java +@Component +public class OrderMessageConsumer { + @Bean + public Consumer>> orderConsumer() { + return records -> records + .flatMap(record -> processOrder(record.value()) + .doOnSuccess(v -> record.receiverOffset().acknowledge())) + .subscribe(); + } +} +``` + +### JAX-RS to WebFlux + +**Before (JAX-RS):** +```java +@Path("/orders") +public class OrderResource { + @GET + @Path("/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response getOrder(@PathParam("id") String id) { + Order order = orderService.findById(id); + return Response.ok(order).build(); + } +} +``` + +**After (Spring WebFlux):** +```java +@RestController +@RequestMapping("/orders") +public class OrderController { + private final OrderService orderService; + + @GetMapping("/{id}") + public Mono getOrder(@PathVariable String id) { + return orderService.findById(id); + } +} +``` + +### JPA to R2DBC + +**Before (JPA):** +```java +@Entity +@Table(name = "orders") +public class Order { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @OneToMany(mappedBy = "order", fetch = FetchType.LAZY) + private List items; +} + +public interface OrderRepository extends JpaRepository { + List findByCustomerId(Long customerId); +} +``` + +**After (R2DBC):** +```java +@Table("orders") +public class Order { + @Id + private Long id; + // Note: No relationship annotations in R2DBC +} + +public interface OrderRepository extends ReactiveCrudRepository { + Flux findByCustomerId(Long customerId); +} +``` + +## AWS Target Services + +| Component | AWS Service | +|-----------|-------------| +| Container Orchestration | Amazon ECS / EKS | +| Database | Amazon Aurora PostgreSQL (R2DBC) | +| Messaging | Amazon SQS / MSK (Kafka) | +| Identity | Amazon Cognito | +| Caching | Amazon ElastiCache (Redis) | +| Secrets | AWS Secrets Manager | +| Configuration | AWS Parameter Store | +| Logging | Amazon CloudWatch Logs | +| Tracing | AWS X-Ray | +| Load Balancing | Application Load Balancer | + +## Validation Criteria + +All J2EE to Spring Boot reactive migrations must meet: + +1. Zero J2EE/Jakarta/Application Server dependencies in final build +2. Application starts with embedded Netty (not servlet container) +3. All EJBs converted to Spring reactive services +4. All data access migrated to R2DBC +5. Messaging works with Kafka/SQS +6. Security implemented with Spring Security Reactive +7. Container runs on both x86_64 and ARM64 (Graviton) +8. All tests pass with WebTestClient and StepVerifier + +## Risk Mitigation Patterns + +### Stateful Session Bean State Management + +**Risk**: Loss of conversational state +**Mitigation**: External session storage with Redis +```java +@Service +public class SessionStateService { + private final ReactiveRedisTemplate redisTemplate; + + public Mono getState(String sessionId) { + return redisTemplate.opsForValue().get(sessionId); + } + + public Mono saveState(String sessionId, SessionState state) { + return redisTemplate.opsForValue().set(sessionId, state, Duration.ofMinutes(30)); + } +} +``` + +### XA Transaction Replacement + +**Risk**: Loss of distributed transaction support +**Mitigation**: Saga pattern with outbox +```java +@Service +public class OrderSagaService { + public Mono createOrderSaga(OrderRequest request) { + return orderRepository.save(order) + .flatMap(saved -> outboxRepository.save(new OutboxEvent(saved))) + .flatMap(event -> inventoryService.reserve(request.getItems()) + .onErrorResume(e -> compensate(order))); + } +} +``` + +### Lazy Loading Replacement + +**Risk**: N+1 query problems without lazy loading +**Mitigation**: Explicit reactive data fetching +```java +public Mono getOrderWithItems(Long orderId) { + return Mono.zip( + orderRepository.findById(orderId), + orderItemRepository.findByOrderId(orderId).collectList() + ).map(tuple -> new OrderWithItems(tuple.getT1(), tuple.getT2())); +} +``` diff --git a/legacy-app-modernization-analyzer/steering/report-structure.md b/legacy-app-modernization-analyzer/steering/report-structure.md new file mode 100644 index 0000000..498681e --- /dev/null +++ b/legacy-app-modernization-analyzer/steering/report-structure.md @@ -0,0 +1,670 @@ +--- +inclusion: always +--- + +# Modernization Report Structure + +This defines the standard report structure for ALL modernization analyses (.NET, WebLogic, WebSphere). + +## CRITICAL RULES - READ FIRST + +**This file is the SINGLE SOURCE OF TRUTH for report formatting. Follow these rules exactly:** + +1. **NO dollar amounts by default** - Use qualitative levels (Low/Medium/High/Very High) for cost estimates +2. **NO time estimates** - No hours, days, weeks, or months anywhere in the report +3. **NO real dates** - Gantt charts use generic weeks (Week 1, Week 2, etc.) +4. **NO file counts or line counts** - Solution Structure is simple +5. **NO Appendix section** - Report ends with Conclusion +6. **Professional Advisory Notice goes at TOP** - Before Executive Summary, not at the end +7. **Cost-Benefit Analysis compares PATHWAYS** - Current vs Pathway 1 vs Pathway 2 vs Pathway 3 (NOT by component like Database/Compute/Storage) +8. **Legends REQUIRED** - Every architecture diagram must have a color legend after it +9. **Gantt chart for 3-Year costs** - Use Mermaid Gantt as stacked horizontal bars (NOT line chart, NOT pie chart) +10. **NO "Quick Wins" section** - Implementation timeline is based on recommended pathway phases only +11. **Pathway Theme required** - Each pathway needs a 3-5 sentence theme paragraph +12. **Pros and Cons required** - Each pathway needs a pros/cons table +13. **Parallel tasks in Gantt** - Show concurrent tasks and dependencies clearly +14. **ABSOLUTELY NO ASCII ART** - ALL diagrams MUST use Mermaid.js syntax ONLY +15. **Visual dot indicators for scoring** - Use ●●●●●●●●●○ (9) format in Pathway Scoring Matrix +16. **OPTIONAL detailed pricing** - User can request 1,000 vCPU assumption with real AWS HK region pricing (see Section 9 Appendix) + +--- + +## VISUALIZATION REQUIREMENTS - MERMAID ONLY + +**⛔ ASCII ART IS STRICTLY FORBIDDEN ⛔** + +ALL diagrams in this report MUST be Mermaid.js diagrams. ASCII art diagrams are NOT ACCEPTABLE and will cause the report to FAIL quality checks. + +### FORBIDDEN - DO NOT USE: +``` +❌ ASCII art boxes: ++------------------+ +| Component | ++------------------+ + | + v ++------------------+ +| Another | ++------------------+ + +❌ ASCII arrows: -->, ===>, |---> +❌ ASCII boxes: [____], +----+, | | +❌ Text-based flow diagrams +❌ Any diagram made with +, -, |, or > characters +``` + +### REQUIRED - USE ONLY MERMAID: +```mermaid +graph TD + A[Component] --> B[Another] +``` + +**RULE: If you find yourself typing `+`, `-`, `|`, or `>` characters to draw boxes or arrows, STOP IMMEDIATELY and use Mermaid.js instead.** + +--- + +## Report Sections + +### 1. Professional Advisory Notice (TOP OF REPORT) + +MUST include this EXACT notice at the VERY TOP of the report, before Executive Summary: + +> 📋 **Professional Advisory Notice**: This report provides a high-level technical analysis based on automated codebase scanning and should be interpreted in consultation with AWS Modernization Specialists or authorized AWS Modernization Partners. The findings and recommendations herein are intended to inform strategic planning discussions and should not be acted upon directly without professional guidance. Implementation effectiveness is influenced by numerous factors that cannot be extracted from the codebase alone, including organizational readiness, team dynamics, business constraints, regulatory requirements, and market conditions. We recommend engaging with qualified modernization experts to develop a comprehensive implementation strategy tailored to your specific organizational context. + +--- + +### 2. Executive Summary + +MUST include: + +- **Strategic Verdict Table**: + | Dimension | Assessment | + |-----------|------------| + | Overall Modernization Feasibility | ✅/⚠️/❌ **RATING (X/10)** | + | 7 Rs Classification | **Classification** (with brief description) | + | Gartner TIME Model | **Classification** | + | Recommended Target | Target platform description | + | Risk Level | **LEVEL** - Brief description | + +- **Modernization Areas Summary Table** (high-level by area): + | Area | Status | Complexity | Key Action | + |------|--------|------------|------------| + | Platform & Framework | ⚠️/✅/🔴 Needs Work/Good/Critical | Low/Medium/High | Brief action | + | Architecture | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + | Dependencies | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + | Code Quality | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + | Data Layer | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + | Database | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + | Authentication | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + | Infrastructure | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + | DevOps | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + | Cloud Integration | ⚠️/✅/🔴 | Low/Medium/High | Brief action | + +- **Positive Indicators** (bullet list of what's already good) +- **Critical Blockers** (bullet list of what must change) + +- **Risk of Inaction Table** (MUST include Impact rating AND Probability): + | Risk Category | Impact | Probability | Business Consequence | + |---------------|--------|-------------|---------------------| + | Risk name | 🔴 High / 🟠 Medium / 🟡 Low | High/Medium/Low/Certain | Detailed consequence description | + +### 3. Visual Architecture State + +MUST include Mermaid.js diagrams with color coding: + +#### Current Architecture (Color-Coded by Modernization Risk) + +Show all layers with technologies, color-coded by risk: +- Use `style NodeName fill:#ff6b6b` for 🔴 Critical blockers (must modernize) +- Use `style NodeName fill:#ffa94d` for 🟠 Concerns (should modernize) +- Use `style NodeName fill:#69db7c` for 🟢 Already modern (no changes needed) + +Include a legend after the diagram: +``` +**Legend:** +- 🔴 Red: Critical blockers, must modernize +- 🟠 Orange: Concerns, should modernize +- 🟢 Green: Already modern, no changes needed +``` + +#### Target Architecture + +Show modernized stack with color coding: +- Use `style NodeName fill:#69db7c` for 🟢 Modernized components +- Use `style NodeName fill:#74c0fc` for 🔵 AWS managed services + +Include a legend after the diagram: +``` +**Legend:** +- 🟢 Green: Modernized components +- 🔵 Blue: AWS managed services +``` + +#### Project Dependency Graph + +Show project dependencies with color coding based on migration status. + +### 4. Critical Findings Matrix + +| # | Issue | Evaluation Area | Impact | Impact If Not Modernized | Priority | +|---|-------|-----------------|--------|--------------------------|----------| +| 1 | Issue description | Area | 🔴 High / 🟠 Medium / 🟡 Low | Detailed consequence | P0/P1/P2/P3 | + +Priority levels: +- P0: Critical blocker - must fix before migration +- P1: High priority - address in first phase +- P2: Medium priority - address in subsequent phases +- P3: Low priority - nice to have + +MUST include 10+ findings. + +### 5. Proprietary Dependency Analysis + +Include license verification note: +> 📋 **License Verification**: Package licenses were verified via [NuGet.org/Maven Central/etc.] package metadata. All identified packages use permissive open-source licenses compatible with commercial use. + +**Summary Table**: +| Library | Version | License | [.NET Core/8 / Java 17] Status | AWS/Linux Impact | Mitigation Strategy | +|---------|---------|---------|-------------------------------|------------------|---------------------| + +For EACH significant proprietary library requiring migration, provide: +- **Detailed Analysis** section with: + - Current usage description + - Migration complexity assessment (Low/Medium/High) + - Breaking changes to address (if applicable) + - Code migration examples (before/after) + - Mitigation options table: + | Option | Effort | Recommendation | + |--------|--------|----------------| + +### 6. Database Analysis & Migration Opportunity + +**Database Detection Summary**: +| Aspect | Finding | +|--------|---------| +| Database Technology | **Database name** (Edition, Version if known) | +| Connection String Location | Config file locations | +| Data Access Pattern | ORM / Raw SQL / Stored Procedures | +| Stored Procedures | Count (None detected = ✅) | +| Database-Specific Features | List of vendor-specific features | +| Provider | Provider name | + +**Migration Section** (e.g., SQL Server → Aurora PostgreSQL): +- Why This Matters (bullet points on cost/benefits) +- Migration Complexity Assessment table: + | Component | Complexity | Notes | + |-----------|------------|-------| +- Code Migration Examples (before/after for connection strings, EF config, etc.) +- Data Type Mapping Reference table +- Recommended Migration Tools +- Impact If Not Migrated + +### 7. Recommended Pathways + +Generate exactly 3 distinct pathways. + +#### Pathway Recommendation Scoring Framework + +Each pathway is evaluated using a weighted scoring system across 6 key factors. The **Recommendation Score** is a weighted average that balances all factors for decision-making. + +**Scoring Factors & Weights:** + +| Factor | Weight | Description | +|--------|--------|-------------| +| Long-term Value | 25% | Cost savings, performance gains, future-proofing potential | +| Implementation Risk | 20% | Technical complexity, failure probability, rollback difficulty | +| Cost Efficiency | 20% | Infrastructure savings, licensing elimination, operational overhead reduction | +| Time to Value | 15% | How quickly benefits are realized after migration | +| Team Readiness | 10% | Skills availability, training requirements, learning curve | +| Business Continuity | 10% | Disruption to operations during migration, parallel running capability | + +**Pathway Scoring Matrix:** + +Use visual dot indicators to show scores. Format: `●●●●●●●●●○ (9)` where filled dots = score, empty dots = remaining to 10. + +| Factor (Weight) | Pathway 1: Full Modernization | Pathway 2: Lift & Optimize | Pathway 3: Containerize Only | +|-----------------|-------------------------------|---------------------------|------------------------------| +| Long-term Value (25%) | ●●●●●●●●●○ (9) | ●●●●●●○○○○ (6) | ●●●○○○○○○○ (3) | +| Implementation Risk (20%) | ●●●●●●○○○○ (6) | ●●●●●●●○○○ (7) | ●●●●●●●●●○ (9) | +| Cost Efficiency (20%) | ●●●●●●●●●○ (9) | ●●●●●○○○○○ (5) | ●●●○○○○○○○ (3) | +| Time to Value (15%) | ●●●●●○○○○○ (5) | ●●●●●●●○○○ (7) | ●●●●●●●●●○ (9) | +| Team Readiness (10%) | ●●●●●●○○○○ (6) | ●●●●●●●○○○ (7) | ●●●●●●●●●○ (9) | +| Business Continuity (10%) | ●●●●●●●○○○ (7) | ●●●●●●●●○○ (8) | ●●●●●●●●●○ (9) | +| **Recommendation Score** | **7.4/10** | **6.4/10** | **5.4/10** | + +> 📋 **Scoring Note**: Higher scores are better for all factors. Implementation Risk is scored inversely (10 = lowest risk, 1 = highest risk). The Recommendation Score is calculated as the weighted average of all factors. Pathway 1 excels in long-term value and cost efficiency but requires more effort. Pathway 3 scores high on ease factors but low on value factors. + +**Pathway Comparison Matrix** (Mermaid quadrantChart): +```mermaid +quadrantChart + title Modernization Pathway Comparison + x-axis Low Effort --> High Effort + y-axis Low Value --> High Value + quadrant-1 Strategic Wins + quadrant-2 Quick Wins + quadrant-3 Low Priority + quadrant-4 Major Projects + "Pathway 1: Name": [x, y] + "Pathway 2: Name": [x, y] + "Pathway 3: Name": [x, y] +``` + +--- + +For each pathway: + +**Pathway N: [Name] (Recommendation Score: X.X/10)** - ✅ RECOMMENDED / ❌ NOT RECOMMENDED + +- **7 Rs Classification:** Classification (with brief description) +- **Gartner TIME:** Classification + +**Pathway Theme:** +A paragraph (3-5 sentences) describing the overall philosophy and approach of this pathway. Explain what makes this pathway unique, who it's best suited for, and the key trade-offs involved. This should help stakeholders quickly understand the essence of the pathway without reading all the details. + +**Strategy Overview:** +Brief description of the approach. + +**Migration Roadmap** (Mermaid flowchart with phases): +```mermaid +flowchart LR + subgraph Phase1["Phase 1: Name"] + A1[Task 1] + A2[Task 2] + end + + subgraph Phase2["Phase 2: Name"] + B1[Task 1] + end + + Phase1 --> Phase2 + + style Phase1 fill:#color + style Phase2 fill:#color +``` + +**Effort Breakdown** (NO time estimates, use relative sequencing): +| Phase | Complexity | Relative Sequence | Key Deliverables | +|-------|------------|-------------------|------------------| +| Phase 1: Name | Low/Medium/High | First | Deliverables | +| Phase 2: Name | Low/Medium/High | Second | Deliverables | + +**Pros and Cons:** + +| Pros | Cons | +|------|------| +| ✅ Benefit 1 | ❌ Drawback 1 | +| ✅ Benefit 2 | ❌ Drawback 2 | +| ✅ Benefit 3 | ❌ Drawback 3 | + +**Risk Assessment:** +- Technical Risk: Level (description) +- Business Risk: Level (description) +- Rollback Capability: Level (description) + +**When to Choose This Path:** +- Bullet points on when this pathway is appropriate + +--- + +### 8. Next Steps: Recommended Pathway Implementation + +This section details the implementation plan for the **recommended pathway** identified in Section 7. Do NOT include a separate "Quick Wins" section - all implementation details should be based on the recommended pathway phases. + +#### Implementation Roadmap + +> ⚠️ **Timeline Disclaimer**: The timeline shown in this roadmap is for **indicative conceptual visualization only** and does not represent a precise estimation. Actual timelines can vary significantly based on factors including modernization team experience, project priorities, resource allocation, organizational change management processes, testing requirements, and third-party dependencies. + +Use generic week numbers (Week 1, Week 2, etc.) - NO real dates. The Gantt chart MUST show: +- Tasks from the recommended pathway phases +- Parallel execution where tasks can run concurrently +- Dependencies between tasks (stacked/sequential where required) +- Clear visualization of which tasks block others + +**CRITICAL: Use explicit start/end positions, NOT `after` syntax.** The `after` keyword does not render correctly with `dateFormat X`. Always use `:taskId, startWeek, endWeek` format. + +```mermaid +gantt + title Recommended Pathway Implementation (Indicative Timeline) + dateFormat X + axisFormat Week %s + + section Phase 1: [Name] + Task 1 (Foundation) :a1, 0, 2 + Task 2 (Can run parallel) :a2, 0, 2 + Task 3 (Depends on Task 1) :a3, 2, 3 + + section Phase 2: [Name] + Task 4 (Depends on Phase 1) :b1, 3, 6 + Task 5 (Parallel with Task 4) :b2, 3, 5 + Task 6 (Depends on Task 4) :b3, 6, 8 + + section Phase 3: [Name] + Task 7 (Depends on Phase 2) :c1, 8, 10 + Task 8 (Parallel with Task 7) :c2, 8, 11 +``` + +**Gantt Chart Syntax Rules:** +- Format: `:taskId, startWeek, endWeek` (e.g., `:a1, 0, 2` means Week 0 to Week 2) +- Parallel tasks: Same start week (e.g., `:a1, 0, 2` and `:a2, 0, 2`) +- Sequential tasks: Next task starts where previous ends (e.g., `:a3, 2, 3` follows `:a1, 0, 2`) +- **DO NOT use `after` keyword** - it doesn't render correctly with numeric date format + +**Key:** Tasks with the same start week run in parallel. Sequential dependencies are shown by starting a task at the end week of its predecessor. + +#### Phase Breakdown + +Detail each phase from the recommended pathway: + +| Phase | Key Activities | Complexity | Dependencies | Key Deliverables | +|-------|---------------|------------|--------------|------------------| +| Phase 1: [Name] | Activity list | Low/Medium/High | Prerequisites | Deliverables | +| Phase 2: [Name] | Activity list | Low/Medium/High | Phase 1 completion | Deliverables | +| Phase 3: [Name] | Activity list | Low/Medium/High | Phase 2 completion | Deliverables | + +NO effort estimates in hours/days/weeks. + +#### Immediate Actions + +| Action | Owner | Complexity | Impact | +|--------|-------|------------|--------| +| Action description | Team/Role | Low/Medium/High | Impact description | + +#### Decision Points & Dependencies + +Mermaid flowchart showing decision flow and dependencies for the recommended pathway. + +#### Recommended Tool Support + +Prioritize AWS Transform tools in this order: + +| Tool | Purpose | Phase | +|------|---------|-------| +| AWS Transform for Windows Full Stack | End-to-end .NET modernization (framework upgrade + database migration) | All phases | +| AWS Transform for .NET | .NET Framework to .NET Core/8 porting, EF6 → EF Core migration | Phase 1-2 | +| AWS Schema Conversion Tool (SCT) | Database schema conversion analysis | Phase 2 | +| AWS Database Migration Service (DMS) | Data migration with minimal downtime | Phase 3-4 | +| AWS App2Container | Containerization of existing applications | Phase 4 | +| Kiro | AI-assisted code migration and refactoring | All phases | + +Note: For .NET modernization, prefer AWS Transform for Windows Full Stack when both application and database migration are needed. Use individual tools (SCT, DMS, App2Container) only for specific scenarios or when Transform doesn't cover the use case. + +### 9. Cost-Benefit Analysis + +**CRITICAL: This section compares costs BY PATHWAY (Current vs Pathway 1 vs Pathway 2 vs Pathway 3), NOT by component (Database/Compute/Storage). Do NOT create charts showing cost by component.** + +#### 3-Year Cost Comparison (Qualitative) + +Use qualitative levels (Low/Medium/High/Very High) - NO dollar amounts by default: + +| Cost Factor | Current | Pathway 1 | Pathway 2 | Pathway 3 | +|-------------|---------|-----------|-----------|-----------| +| Compute | Baseline | Low | Medium | High | +| Database | Baseline | Low | High | High | +| Licensing | High | None | Medium | High | +| Migration Effort | N/A | High | Medium | Low | +| Operational Overhead | High | Low | Medium | High | +| **Overall Recurring** | Baseline | **60-70% savings** | **30-40% savings** | **~0% savings** | + +#### 3-Year Cost Visualization + +Use a Mermaid Gantt chart to create stacked horizontal bars showing relative year-by-year costs: + +```mermaid +gantt + title 3-Year Relative Cost Comparison (Baseline = 100) + dateFormat X + axisFormat %s + todayMarker off + + section Current (300) + Year 1 - 100 :active, 0, 100 + Year 2 - 100 :crit, 100, 200 + Year 3 - 100 :200, 300 + + section Pathway 1 (~100) + Year 1 - 45 :active, 0, 45 + Year 2 - 25 :crit, 45, 70 + Year 3 - 25 :70, 95 + + section Pathway 2 (~180) + Year 1 - 70 :active, 0, 70 + Year 2 - 55 :crit, 70, 125 + Year 3 - 55 :125, 180 + + section Pathway 3 (~305) + Year 1 - 105 :active, 0, 105 + Year 2 - 100 :crit, 105, 205 + Year 3 - 100 :205, 305 +``` + +**Legend:** 🔵 Year 1 (active = blue) | 🔴 Year 2 (crit = red) | 🩵 Year 3 (no status = teal/cyan) — X-axis: Relative cost units (Current annual = 100). Bar length represents cumulative 3-year cost. + +**Gantt Chart Color Reference:** +- `active` = blue +- `crit` = red +- (no status) = teal/cyan + +#### Key Cost Drivers + +| Driver | Impact | Pathway 1 | Pathway 2 | Pathway 3 | +|--------|--------|-----------|-----------|-----------| +| Database Licensing | Very High | ✅ Eliminated | ❌ Retained | ❌ Retained | +| OS Licensing | High | ✅ Eliminated | ✅ Eliminated | ❌ Retained | +| Graviton ARM64 | Medium | ✅ 20% savings | ❌ Not available | ❌ Not available | +| Serverless DB | Medium | ✅ Auto-scaling | ❌ Not used | ❌ Not used | + +#### ROI Summary + +| Metric | Pathway 1 | Pathway 2 | Pathway 3 | +|--------|-----------|-----------|-----------| +| Investment Level | High | Medium | Low | +| Returns Potential | Very High | Medium | None | +| Payback Period | Short-term (months) | Short-term (months) | N/A | +| Risk-Adjusted Value | High | Medium | Low | + +**Key Value Drivers:** +- Pathway 1: Maximum savings from eliminating all licensing costs + Graviton compute +- Pathway 2: Moderate savings from OS license elimination only +- Pathway 3: No recurring savings; only operational benefits + +#### Cost Optimization Opportunities + +| Optimization | Potential Additional Savings | +|--------------|------------------------------| +| Compute Savings Plans (1-year) | Up to 17% | +| Compute Savings Plans (3-year) | Up to 52% | +| Reserved Capacity | Up to 35% on databases | +| Spot Instances | Up to 70% on eligible tasks | +| Right-sizing | 10-30% typical | + +--- + +### OPTIONAL: Detailed Cost Simulation (1,000 vCPU Assumption) + +> 📋 **User Request Required**: This section is ONLY included if the user explicitly requests detailed cost calculations. Ask: *"Would you like me to include a detailed cost simulation based on 1,000 vCPUs with real AWS Hong Kong region pricing?"* + +If requested, include the following detailed analysis: + +#### Baseline Assumption + +> 📋 **Baseline Assumption**: This analysis assumes a production workload of **1,000 vCPUs** running continuously (24/7/365) in **Asia Pacific (Hong Kong)** region. All prices are based on on-demand pricing as of January 2025. Actual costs may vary based on Reserved Instance commitments, Savings Plans, and usage patterns. + +#### Pricing Reference Sources + +| Service | Pricing Source | +|---------|---------------| +| ECS Fargate | [AWS Fargate Pricing](https://aws.amazon.com/fargate/pricing/) | +| RDS SQL Server | [AWS RDS SQL Server Pricing](https://aws.amazon.com/rds/sqlserver/pricing/) | +| Aurora PostgreSQL | [AWS Aurora Pricing](https://aws.amazon.com/rds/aurora/pricing/) | + +#### Compute Pricing Breakdown (per vCPU-hour, HK Region) + +| Platform | vCPU/hour | Memory/GB/hour | OS License/vCPU/hour | Total/vCPU/hour (with 2GB RAM) | +|----------|-----------|----------------|---------------------|-------------------------------| +| Fargate Linux/x86 | $0.0XXX | $0.00XXX | — | **$0.0XXX** | +| Fargate Linux/ARM (Graviton) | $0.0XXX | $0.00XXX | — | **$0.0XXX** | +| Fargate Windows/x86 | $0.0XXX | $0.0XXX | $0.0XX | **$0.1XXX** | + +#### Database Pricing Breakdown (HK Region) + +| Database | Instance/Capacity | Hourly Cost | Monthly Cost (730 hrs) | Notes | +|----------|-------------------|-------------|------------------------|-------| +| RDS SQL Server Standard (Multi-AZ) | db.m5.2xlarge | ~$X.XX/hr | ~$X,XXX | License included | +| Aurora PostgreSQL Serverless v2 | Per ACU | $0.XX/ACU-hour | $XX.XX/ACU | 1 ACU ≈ 2GB RAM | + +> 📋 **Database Sizing Rationale**: For a typical web application, database compute is commonly 5-10% of application tier capacity. For 1,000 app vCPUs, 2 × db.m5.2xlarge (16 vCPU total) or 16 ACU Aurora is reasonable. + +#### Detailed Cost Model per Pathway + +**Current State:** +| Cost Component | Calculation | Monthly Cost | Annual Cost | +|----------------|-------------|--------------|-------------| +| Fargate Windows Compute | 1,000 vCPU × $X.XX/hr × 730 hrs | $XX,XXX | $XXX,XXX | +| Fargate Windows Memory | 2,000 GB × $X.XX/hr × 730 hrs | $XX,XXX | $XXX,XXX | +| Windows OS License | 1,000 vCPU × $X.XX/hr × 730 hrs | $XX,XXX | $XXX,XXX | +| RDS SQL Server (Multi-AZ) | 2 × db.m5.2xlarge × $X.XX/hr × 730 hrs | $X,XXX | $XXX,XXX | +| **Total Current State** | | **$XXX,XXX** | **$X,XXX,XXX** | + +**Pathway 1 (Full Modernization):** +| Cost Component | Calculation | Monthly Cost | Annual Cost | +|----------------|-------------|--------------|-------------| +| Fargate Graviton Compute | 1,000 vCPU × $X.XX/hr × 730 hrs | $XX,XXX | $XXX,XXX | +| Fargate Graviton Memory | 2,000 GB × $X.XX/hr × 730 hrs | $X,XXX | $XX,XXX | +| Aurora PostgreSQL Serverless v2 | 16 ACU × $X.XX/hr × 730 hrs | $X,XXX | $XX,XXX | +| **Total Pathway 1 Recurring** | | **$XX,XXX** | **$XXX,XXX** | + +**One-Time Migration Costs:** + +| Migration Component | Internal Team | Professional Services | Tooling/Infra | Total | +|--------------------|---------------|----------------------|---------------|-------| +| Framework Migration | $XX,XXX | $XX,XXX | $XX,XXX | $XXX,XXX | +| Database Migration | $XX,XXX | $XX,XXX | $X,XXX | $XX,XXX | +| Testing & Validation | $XX,XXX | $XX,XXX | $XX,XXX | $XX,XXX | +| Training | $X,XXX | $XX,XXX | — | $XX,XXX | +| **Total One-Time** | **$XX,XXX** | **$XXX,XXX** | **$XX,XXX** | **$XXX,XXX** | + +#### 3-Year TCO Comparison (Detailed) + +| Pathway | Year 1 | Year 2 | Year 3 | 3-Year Total | vs Current | +|---------|--------|--------|--------|--------------|------------| +| **Current** | $X.XXM | $X.XXM | $X.XXM | **$X.XXM** | — | +| **Pathway 1** | $X.XXM | $X.XXM | $X.XXM | **$X.XXM** | **-XX%** | +| **Pathway 2** | $X.XXM | $X.XXM | $X.XXM | **$X.XXM** | **-XX%** | +| **Pathway 3** | $X.XXM | $X.XXM | $X.XXM | **$X.XXM** | **-X%** | + +#### ROI Analysis (Detailed) + +| Metric | Pathway 1 | Pathway 2 | Pathway 3 | +|--------|-----------|-----------|-----------| +| One-Time Investment | $XXX,XXX | $XXX,XXX | $XX,XXX | +| Annual Savings | $X,XXX,XXX | $XXX,XXX | $0 | +| Payback Period | **~X.X months** | **~X.X months** | N/A | +| 3-Year Net Savings | **$X,XXX,XXX** | **$X,XXX,XXX** | **-$XX,XXX** | +| 3-Year ROI | **X,XXX%** | **X,XXX%** | **-100%** | + +> 📋 **Sources**: Pricing data sourced from AWS official pricing pages (January 2025). See linked URLs for current rates. + +--- + +### 10. Solution Structure Summary + +Simple table showing projects and migration complexity - NO file counts or line counts: + +| Project | Current Framework | Target Framework | Migration Complexity | +|---------|------------------|------------------|---------------------| +| Project.Name | Current version | Target version | Low/Medium/High/None | + +### 11. Conclusion + +Brief summary including: +- Overall assessment statement with feasibility score +- Recommended pathway with key benefits +- Key success factors (bullet list) + +--- + +*Report generated by [Platform] Modernization Analyzer Power* +*Analysis Date: [Date]* + +## Visualization Standards + +### Mermaid Diagram Types to Use + +1. **Architecture Diagrams**: `graph TB` or `graph LR` with color-coded styles +2. **Dependency Graphs**: `graph TD` with color-coded styles +3. **Flowcharts**: `flowchart LR` or `flowchart TB` with subgraphs for phases +4. **Quadrant Charts**: `quadrantChart` for pathway comparison +5. **Gantt Charts**: `gantt` for both implementation timelines (dateFormat X, axisFormat Week %s) AND 3-year cost visualization (as horizontal stacked bars) + +### Color Coding Standards + +Architecture diagrams: +- `fill:#ff6b6b` - Red: Critical blockers +- `fill:#ffa94d` - Orange: Concerns +- `fill:#69db7c` - Green: Modern/good +- `fill:#74c0fc` - Blue: AWS managed services +- `fill:#ffd43b` - Yellow: In progress/transitional + +### Diagram Best Practices + +- Use clear, descriptive labels +- Include legends for color coding +- Show clear boundaries between components +- Annotate with technology decisions +- Keep diagrams readable (not too complex) + +## Quality Checklist + +Before completing the report, verify: + +**VISUALIZATION (CRITICAL):** +- [ ] ⛔ NO ASCII ART ANYWHERE - All diagrams use Mermaid.js ONLY (no +, -, |, > box drawings) +- [ ] At least 6 different Mermaid diagram types included +- [ ] Current Architecture diagram has color coding with legend +- [ ] Target Architecture diagram has color coding with legend + +**STRUCTURE:** +- [ ] Professional Advisory Notice at TOP of report (before Executive Summary) +- [ ] Executive Summary includes feasibility score (X/10), 7Rs, Gartner TIME +- [ ] Risk of Inaction has Impact rating (High/Medium/Low) AND Probability columns +- [ ] All proprietary dependencies analyzed with migration examples +- [ ] Database technology detected and documented +- [ ] Critical Findings Matrix has 10+ findings + +**PATHWAYS:** +- [ ] Exactly 3 pathways with full detail +- [ ] Pathway Scoring Matrix uses visual dot indicators: ●●●●●●●●●○ (9) format +- [ ] Scoring Note explains the weighted average calculation +- [ ] Each pathway has a "Recommendation Score" (weighted average, X.X/10) +- [ ] Each pathway has a "Pathway Theme" paragraph (3-5 sentences) +- [ ] Each pathway has a "Pros and Cons" table +- [ ] Pathway with highest Recommendation Score is marked ✅ RECOMMENDED + +**NEXT STEPS:** +- [ ] NO "Quick Wins" section - implementation is based on recommended pathway only +- [ ] Next Steps section focuses on recommended pathway implementation +- [ ] Implementation Roadmap Gantt shows parallel tasks and dependencies +- [ ] Gantt chart has timeline disclaimer +- [ ] Gantt chart uses generic weeks (no real dates) + +**COST-BENEFIT:** +- [ ] 3-Year Cost Comparison table uses qualitative levels (Low/Medium/High) by default +- [ ] 3-Year Cost Visualization uses Mermaid GANTT chart as stacked horizontal bars with RELATIVE units +- [ ] Gantt chart legend explains colors: 🔵 Year 1 (active) | 🔴 Year 2 (crit) | 🩵 Year 3 (no status) +- [ ] Key Cost Drivers table shows which costs are eliminated/retained per pathway +- [ ] ROI Summary uses qualitative assessments (High/Medium/Low, Short-term/Long-term) +- [ ] Cost Optimization Opportunities table included +- [ ] OPTIONAL: If user requests detailed pricing, include 1,000 vCPU simulation with HK region pricing + +**FORBIDDEN:** +- [ ] NO dollar amounts in default Cost-Benefit section (use qualitative levels) +- [ ] NO effort estimates in hours/days/weeks +- [ ] NO file counts or line counts +- [ ] NO Appendix section (except optional detailed pricing if requested) +- [ ] NO ASCII art diagrams +- [ ] NO line charts or pie charts for cost visualization (use Gantt as horizontal bars) +- [ ] NO radar charts (use visual dot matrix instead) + +**FINAL:** +- [ ] Solution Structure Summary is simple (no file/line counts) +- [ ] Conclusion section present diff --git a/legacy-app-modernization-analyzer/steering/weblogic-to-springboot.md b/legacy-app-modernization-analyzer/steering/weblogic-to-springboot.md new file mode 100644 index 0000000..aaf311d --- /dev/null +++ b/legacy-app-modernization-analyzer/steering/weblogic-to-springboot.md @@ -0,0 +1,330 @@ +--- +inclusion: manual +--- + +# Oracle WebLogic to Spring Boot Reactive Migration + +## Objective + +Migrate Oracle WebLogic Server-based J2EE applications to Spring Boot 3.x with Java 17 using a fully reactive architecture, targeting AWS container-based deployments optimized for Graviton processors. + +## Platform Detection + +### WebLogic-Specific Files + +- `weblogic.xml` - Web application descriptor +- `weblogic-application.xml` - Application descriptor +- `weblogic-ejb-jar.xml` - EJB descriptor +- `weblogic-cmp-rdbms-jar.xml` - CMP mappings +- `weblogic-ra.xml` - Resource adapter +- `plan.xml` - Deployment plan + +### WebLogic-Specific Dependencies + +Scan for these package imports: +- `weblogic.*` - WebLogic APIs +- `oracle.weblogic.*` - Oracle WebLogic +- `com.bea.*` - BEA (legacy WebLogic) +- `oracle.toplink.*` - Oracle TopLink ORM + +### WebLogic-Specific Code Patterns + +- `weblogic.jndi.*` - JNDI extensions +- `weblogic.security.*` - Security APIs +- `weblogic.work.*` - Work Manager +- `weblogic.transaction.*` - Transaction APIs +- `weblogic.rmi.*` - RMI with T3 protocol +- `weblogic.jms.*` - JMS extensions + +## Migration Strategy Bank + +### Application Server → Spring Boot + +| WebLogic Component | Spring Boot Equivalent | +|--------------------|------------------------| +| EJB Stateless Session Beans | Spring `@Service` with reactive return types | +| EJB Stateful Session Beans | Spring service + Redis for state | +| EJB Message-Driven Beans | Reactor Kafka / AWS SQS listeners | +| WebLogic Security | Spring Security Reactive | +| WebLogic Timer Service | Spring `@Scheduled` | +| JNDI DataSource | Spring `DataSource` bean / R2DBC | +| WebLogic JMS | Amazon SQS / MSK (Kafka) | +| CommonJ Work Manager | Reactor Schedulers | +| WebLogic Clustering | ECS/EKS + ALB | +| WLDF (Diagnostics) | Spring Boot Actuator + CloudWatch | + +### Configuration Migration + +| WebLogic | Spring Boot | +|----------|-------------| +| `weblogic.xml` | `application.yml` | +| `weblogic-application.xml` | Spring configuration | +| `weblogic-ejb-jar.xml` | `@Transactional` + Spring Security | +| JNDI resources | Spring beans / AWS SDK | +| `plan.xml` | Spring profiles | + +### Data Access Migration + +| WebLogic JPA | Spring Data | +|--------------|-------------| +| JPA with TopLink/Hibernate | Spring Data R2DBC (reactive) | +| `persistence.xml` | `application.yml` R2DBC config | +| EntityManager | R2DatabaseClient | +| JPQL queries | Native SQL / query methods | +| JTA transactions | R2DBC reactive transactions | + +### Messaging Migration + +| WebLogic JMS | AWS Messaging | +|--------------|---------------| +| JMS Connection Factory | Kafka/SQS connection config | +| Distributed Destinations | Kafka partitions / SQS queues | +| Store-and-Forward (SAF) | Kafka durability / SQS DLQ | +| T3 Protocol | Standard Kafka/HTTP protocols | +| XA Transactions | Saga pattern / Outbox pattern | + +### Security Migration + +| WebLogic Security | Spring Security Reactive | +|-------------------|--------------------------| +| Security Realm | ReactiveAuthenticationManager | +| Authentication Providers | Spring Security providers | +| Authorization Providers | Spring authorities | +| `@RolesAllowed` | `@PreAuthorize` | +| Credential Mapping | AWS Secrets Manager | +| SSL Configuration | Netty SSL / ALB TLS | + +## WebLogic-Specific Risks + +### Proprietary API Dependencies + +| Risk | Mitigation | +|------|------------| +| T3/T3S Protocol | Replace with REST/gRPC/RSocket | +| CommonJ Work Manager | Replace with Reactor Schedulers | +| WebLogic Timer Service | Replace with Spring scheduling | +| WebLogic Security APIs | Replace with Spring Security + Cognito | +| WebLogic JMS Extensions | Replace with Kafka/SQS | +| Oracle TopLink | Replace with Spring Data R2DBC | +| WLDF | Replace with Actuator + CloudWatch | + +### J2EE to Jakarta EE + +- `javax.*` packages → `jakarta.*` packages +- Requires dependency updates across the board +- Spring Boot 3.x uses Jakarta EE 9+ + +## Implementation Phases + +### Phase 0: Dependency Analysis + +1. Scan for J2EE imports (`javax.ejb`, `javax.servlet`, `javax.persistence`, `javax.jms`) +2. Identify WebLogic-specific imports (`weblogic.*`, `oracle.weblogic.*`) +3. Analyze deployment descriptors +4. Identify T3 protocol usage +5. Calculate dependency density scores +6. Generate migration complexity report + +### Phase 1: Project Structure Migration + +1. Update to Spring Boot 3.x parent +2. Remove ALL J2EE and WebLogic dependencies +3. Remove `weblogic-client.jar`, `wlthint3client.jar` +4. Add Spring Boot reactive starters +5. Configure multi-architecture Docker build + +### Phase 2: Configuration Migration + +1. Remove `web.xml` +2. Migrate WebLogic deployment descriptors to `application.yml` +3. Replace JNDI lookups with Spring DI +4. Configure R2DBC data sources +5. Migrate `plan.xml` to Spring profiles + +### Phase 3: EJB Migration + +1. Convert Stateless Session Beans to `@Service` +2. Convert Stateful Session Beans to services + Redis +3. Migrate MDBs to reactive message listeners +4. Replace `@EJB` with constructor injection +5. Eliminate T3 protocol for remote EJB calls + +### Phase 4: Data Access Migration + +1. Remove `persistence.xml` +2. Configure Spring Data R2DBC +3. Convert JPA/TopLink entities to R2DBC entities +4. Rewrite JPQL to native SQL + +### Phase 5: Web Services Migration + +1. Convert JAX-RS (Jersey) to Spring WebFlux +2. Replace servlet filters with WebFilter +3. Eliminate HttpServletRequest/Response usage + +### Phase 6: Messaging Migration + +1. Replace WebLogic JMS with Kafka/SQS +2. Eliminate T3 protocol for JMS thin clients +3. Convert JMS producers to reactive publishers +4. Migrate MDBs to reactive consumers +5. Replace SAF with Kafka durability + +### Phase 7: Security Migration + +1. Replace WebLogic security realm with Spring Security Reactive +2. Migrate authentication providers to Cognito/LDAP +3. Replace credential mapping with Secrets Manager + +### Phase 8: Container Optimization + +1. Create multi-arch Dockerfile (x86_64 + ARM64) +2. Configure for AWS Java Runtime (Corretto) +3. Optimize for Graviton processors + +## Code Migration Examples + +### EJB to Spring Service + +**Before (WebLogic EJB):** +```java +@Stateless +@TransactionAttribute(TransactionAttributeType.REQUIRED) +public class OrderServiceBean implements OrderService { + @Resource + private SessionContext ctx; + + @EJB + private InventoryService inventory; + + public Order createOrder(OrderRequest request) { + // blocking implementation with T3 remote calls + } +} +``` + +**After (Spring Boot Reactive):** +```java +@Service +public class OrderService { + private final InventoryService inventory; + + public OrderService(InventoryService inventory) { + this.inventory = inventory; + } + + @Transactional + public Mono createOrder(OrderRequest request) { + return inventory.checkStock(request.getItems()) + .flatMap(available -> saveOrder(request)); + } +} +``` + +### WebLogic JMS to Reactive Kafka + +**Before (WebLogic JMS MDB):** +```java +@MessageDriven(activationConfig = { + @ActivationConfigProperty(propertyName = "destinationType", + propertyValue = "javax.jms.Queue"), + @ActivationConfigProperty(propertyName = "destination", + propertyValue = "jms/OrderQueue") +}) +public class OrderMessageBean implements MessageListener { + public void onMessage(Message message) { + // blocking processing + } +} +``` + +**After (Reactor Kafka):** +```java +@Component +public class OrderMessageConsumer { + @Bean + public Consumer>> orderConsumer() { + return records -> records + .flatMap(record -> processOrder(record.value()) + .doOnSuccess(v -> record.receiverOffset().acknowledge())) + .subscribe(); + } +} +``` + +### Work Manager to Reactor Scheduler + +**Before (WebLogic Work Manager):** +```java +@Resource +private WorkManager workManager; + +public void processAsync(Work work) { + workManager.schedule(work); +} +``` + +**After (Reactor Scheduler):** +```java +public Mono processAsync(Runnable task) { + return Mono.fromRunnable(task) + .subscribeOn(Schedulers.boundedElastic()) + .then(); +} +``` + +## AWS Target Architecture + +```mermaid +graph TB + subgraph "Current State - WebLogic" + WL[WebLogic Server] + DB1[(Oracle DB)] + JMS1[WebLogic JMS] + T3[T3 Protocol] + end + + subgraph "Target State - AWS" + ECS[Amazon ECS/EKS] + SB[Spring Boot Reactive] + RDS[(Amazon Aurora PostgreSQL)] + MSK[Amazon MSK/SQS] + COG[Amazon Cognito] + REDIS[Amazon ElastiCache] + end + + WL --> ECS + DB1 --> RDS + JMS1 --> MSK + T3 -.->|Eliminated| ECS +``` + +## Oracle-Specific Migrations + +### Oracle Database Options + +| Current | Target | Notes | +|---------|--------|-------| +| Oracle Database | Amazon RDS Oracle | Lift-and-shift | +| Oracle Database | Aurora PostgreSQL | Cost optimization (no licensing) | +| Oracle Coherence | Amazon ElastiCache | Distributed caching | +| Oracle AQ | Amazon SQS/SNS | Message queuing | + +### Oracle License Considerations + +- Oracle Database licensing on AWS can be expensive +- Consider Aurora PostgreSQL for significant cost savings +- Use AWS SCT for schema conversion +- Use AWS DMS for data migration + +## Validation Criteria + +1. Zero J2EE/Jakarta/WebLogic dependencies in final build +2. Zero T3 protocol usage +3. Application starts with embedded Netty (not servlet container) +4. All EJBs converted to Spring reactive services +5. All data access migrated to R2DBC +6. Messaging works with Kafka/SQS +7. Security implemented with Spring Security Reactive +8. Container runs on both x86_64 and ARM64 (Graviton) +9. All tests pass with WebTestClient and StepVerifier diff --git a/legacy-app-modernization-analyzer/steering/websphere-to-springboot.md b/legacy-app-modernization-analyzer/steering/websphere-to-springboot.md new file mode 100644 index 0000000..83df581 --- /dev/null +++ b/legacy-app-modernization-analyzer/steering/websphere-to-springboot.md @@ -0,0 +1,284 @@ +--- +inclusion: manual +--- + +# IBM WebSphere to Spring Boot Reactive Migration + +## Objective + +Migrate IBM WebSphere Application Server-based J2EE applications to Spring Boot 3.x with Java 17 using a fully reactive architecture, targeting AWS container-based deployments optimized for Graviton processors. + +## Platform Detection + +### WebSphere-Specific Files + +- `ibm-web-ext.xml` - Web module extensions +- `ibm-web-bnd.xml` - Web module bindings +- `ibm-application-ext.xml` - Application extensions +- `ibm-application-bnd.xml` - Application bindings +- `ibm-ejb-jar-ext.xml` - EJB extensions +- `ibm-ejb-jar-bnd.xml` - EJB bindings +- `was.policy` - Security policy (WebSphere traditional) +- `server.xml` - Liberty server configuration + +### WebSphere-Specific Dependencies + +Scan for these package imports: +- `com.ibm.websphere.*` - WebSphere APIs +- `com.ibm.ws.*` - WebSphere services +- `com.ibm.ejs.*` - EJB services +- `com.ibm.wsspi.*` - WebSphere SPI +- `com.ibm.mq.*` - WebSphere MQ native API + +### WebSphere-Specific Code Patterns + +- `com.ibm.websphere.security.*` - Security APIs +- `com.ibm.websphere.asynchbeans.*` - Async Beans +- `com.ibm.websphere.scheduler.*` - Scheduler Service +- JNDI lookups with WebSphere namespace +- IIOP/RMI-IIOP protocol usage + +## Migration Strategy Bank + +### Application Server → Spring Boot + +| WebSphere Component | Spring Boot Equivalent | +|---------------------|------------------------| +| EJB Stateless Session Beans | Spring `@Service` with reactive return types | +| EJB Stateful Session Beans | Spring service + Redis for state | +| EJB Message-Driven Beans | Reactor Kafka / AWS SQS listeners | +| WebSphere Security | Spring Security Reactive | +| WebSphere Scheduler | Spring `@Scheduled` | +| JNDI DataSource | Spring `DataSource` bean / R2DBC | +| WebSphere MQ | Amazon SQS / MSK (Kafka) | +| WebSphere Async Beans | Reactor Schedulers | +| DynaCache | Spring Cache + Redis | +| WebSphere PMI | Spring Boot Actuator + CloudWatch | + +### Configuration Migration + +| WebSphere | Spring Boot | +|-----------|-------------| +| `ibm-web-ext.xml` | `application.yml` | +| `ibm-web-bnd.xml` | Spring Security config | +| JNDI resources | Spring beans / AWS SDK | +| `was.policy` | Spring Security policies | +| `server.xml` (Liberty) | `application.yml` | + +### Data Access Migration + +| WebSphere JPA | Spring Data | +|---------------|-------------| +| JPA with OpenJPA/EclipseLink | Spring Data R2DBC (reactive) | +| `persistence.xml` | `application.yml` R2DBC config | +| EntityManager | R2DatabaseClient | +| JPQL queries | Native SQL / query methods | +| JTA transactions | R2DBC reactive transactions | + +### Messaging Migration + +| WebSphere MQ | AWS Messaging | +|--------------|---------------| +| MQ Connection Factory | Kafka/SQS connection config | +| MQ Queues | Kafka topics / SQS queues | +| MQ Topics | Kafka topics / SNS topics | +| JMS MessageListener | Reactor Kafka / SQS async | +| XA Transactions | Saga pattern / Outbox pattern | + +### Security Migration + +| WebSphere Security | Spring Security Reactive | +|--------------------|--------------------------| +| User Registry (LDAP) | ReactiveAuthenticationManager | +| LTPA Tokens | JWT / OAuth2 | +| Security Roles | Spring authorities | +| `@RolesAllowed` | `@PreAuthorize` | +| Credential Vault | AWS Secrets Manager | + +## WebSphere-Specific Risks + +### Proprietary API Dependencies + +| Risk | Mitigation | +|------|------------| +| WebSphere Async Beans | Replace with Reactor Schedulers | +| WebSphere Scheduler | Replace with Spring scheduling | +| WebSphere Security APIs | Replace with Spring Security + Cognito | +| IIOP Protocol | Replace with REST/gRPC/RSocket | +| WebSphere MQ Native API | Replace with Kafka/SQS | +| DynaCache | Replace with Redis reactive | + +### J2EE to Jakarta EE + +- `javax.*` packages → `jakarta.*` packages +- Requires dependency updates across the board +- Spring Boot 3.x uses Jakarta EE 9+ + +## Implementation Phases + +### Phase 0: Dependency Analysis + +1. Scan for J2EE imports (`javax.ejb`, `javax.servlet`, `javax.persistence`, `javax.jms`) +2. Identify WebSphere-specific imports (`com.ibm.websphere.*`, `com.ibm.ws.*`) +3. Analyze deployment descriptors +4. Calculate dependency density scores +5. Generate migration complexity report + +### Phase 1: Project Structure Migration + +1. Update to Spring Boot 3.x parent +2. Remove ALL J2EE and WebSphere dependencies +3. Add Spring Boot reactive starters +4. Configure multi-architecture Docker build + +### Phase 2: Configuration Migration + +1. Remove `web.xml` +2. Migrate IBM deployment descriptors to `application.yml` +3. Replace JNDI lookups with Spring DI +4. Configure R2DBC data sources + +### Phase 3: EJB Migration + +1. Convert Stateless Session Beans to `@Service` +2. Convert Stateful Session Beans to services + Redis +3. Migrate MDBs to reactive message listeners +4. Replace `@EJB` with constructor injection + +### Phase 4: Data Access Migration + +1. Remove `persistence.xml` +2. Configure Spring Data R2DBC +3. Convert JPA entities to R2DBC entities +4. Rewrite JPQL to native SQL + +### Phase 5: Web Services Migration + +1. Convert JAX-RS to Spring WebFlux +2. Replace servlet filters with WebFilter +3. Eliminate HttpServletRequest/Response usage + +### Phase 6: Messaging Migration + +1. Replace WebSphere MQ with Kafka/SQS +2. Convert JMS producers to reactive publishers +3. Migrate MDBs to reactive consumers + +### Phase 7: Security Migration + +1. Replace WebSphere security with Spring Security Reactive +2. Migrate user registries to Cognito/LDAP +3. Replace LTPA with JWT/OAuth2 + +### Phase 8: Container Optimization + +1. Create multi-arch Dockerfile (x86_64 + ARM64) +2. Configure for AWS Java Runtime (Corretto) +3. Optimize for Graviton processors + +## Code Migration Examples + +### EJB to Spring Service + +**Before (WebSphere EJB):** +```java +@Stateless +public class OrderServiceBean implements OrderService { + @Resource + private SessionContext ctx; + + @EJB + private InventoryService inventory; + + @TransactionAttribute(TransactionAttributeType.REQUIRED) + public Order createOrder(OrderRequest request) { + // blocking implementation + } +} +``` + +**After (Spring Boot Reactive):** +```java +@Service +public class OrderService { + private final InventoryService inventory; + + public OrderService(InventoryService inventory) { + this.inventory = inventory; + } + + @Transactional + public Mono createOrder(OrderRequest request) { + return inventory.checkStock(request.getItems()) + .flatMap(available -> saveOrder(request)); + } +} +``` + +### JMS to Reactive Kafka + +**Before (WebSphere MQ MDB):** +```java +@MessageDriven(activationConfig = { + @ActivationConfigProperty(propertyName = "destinationType", + propertyValue = "javax.jms.Queue"), + @ActivationConfigProperty(propertyName = "destination", + propertyValue = "jms/OrderQueue") +}) +public class OrderMessageBean implements MessageListener { + public void onMessage(Message message) { + // blocking processing + } +} +``` + +**After (Reactor Kafka):** +```java +@Component +public class OrderMessageConsumer { + @Bean + public Consumer>> orderConsumer() { + return records -> records + .flatMap(record -> processOrder(record.value()) + .doOnSuccess(v -> record.receiverOffset().acknowledge())) + .subscribe(); + } +} +``` + +## AWS Target Architecture + +```mermaid +graph TB + subgraph "Current State - WebSphere" + WAS[WebSphere Application Server] + DB1[(DB2/Oracle)] + MQ1[WebSphere MQ] + LDAP1[LDAP Registry] + end + + subgraph "Target State - AWS" + ECS[Amazon ECS/EKS] + SB[Spring Boot Reactive] + RDS[(Amazon Aurora PostgreSQL)] + SQS[Amazon SQS/MSK] + COG[Amazon Cognito] + REDIS[Amazon ElastiCache] + end + + WAS --> ECS + DB1 --> RDS + MQ1 --> SQS + LDAP1 --> COG +``` + +## Validation Criteria + +1. Zero J2EE/Jakarta/WebSphere dependencies in final build +2. Application starts with embedded Netty (not servlet container) +3. All EJBs converted to Spring reactive services +4. All data access migrated to R2DBC +5. Messaging works with Kafka/SQS +6. Security implemented with Spring Security Reactive +7. Container runs on both x86_64 and ARM64 (Graviton) +8. All tests pass with WebTestClient and StepVerifier From 97c4e7dce0b44f08eb7280083647ed17f92c2561 Mon Sep 17 00:00:00 2001 From: David Lau Date: Wed, 11 Feb 2026 06:49:35 +0000 Subject: [PATCH 16/18] feat: Update legacy-app-modernization-analyzer - AD/SSO blocker, decision tree, hybrid sidecar pattern, Gantt fixes --- legacy-app-modernization-analyzer/README.md | 19 +- .../steering/dotnet-to-aws.md | 315 ++++++++++++++++++ .../steering/evaluation-framework.md | 68 ++++ .../steering/report-structure.md | 148 +++++++- .../steering/weblogic-to-springboot.md | 42 +++ .../steering/websphere-to-springboot.md | 42 +++ 6 files changed, 615 insertions(+), 19 deletions(-) diff --git a/legacy-app-modernization-analyzer/README.md b/legacy-app-modernization-analyzer/README.md index 644fd46..d6fc952 100644 --- a/legacy-app-modernization-analyzer/README.md +++ b/legacy-app-modernization-analyzer/README.md @@ -20,11 +20,15 @@ A Kiro Power that provides enterprise-grade legacy codebase modernization analys - **Visual Architecture Diagrams**: Mermaid.js diagrams with component-level color coding - **Package License Verification**: Queries NuGet/Maven APIs for license validation - **Proprietary Dependency Analysis**: Impact assessment with code migration examples +- **Active Directory / Windows SSO Detection**: Identifies AD authentication scenarios (Windows SSO vs Forms Auth) as critical migration blockers with scenario-specific modernization approaches - **Database Migration**: SQL Server/Oracle/DB2 → Aurora PostgreSQL recommendations - **Strategic Alignment**: AWS 7 Rs and Gartner TIME framework classification - **Risk Assessment**: "Impact If Not Modernized" for every finding with probability ratings - **3 Migration Pathways**: Ranked by weighted Recommendation Score with visual dot indicators +- **Dual Timeline Comparison**: Traditional vs Agentic AI-Accelerated timelines showing the value of AWS Transform + Kiro - **Cost-Benefit Analysis**: Qualitative assessments by default (Low/Medium/High/Very High), with optional detailed pricing simulation available on request +- **Modernization Decision Tree (.NET)**: Visual Mermaid flowchart walking through feasibility checks, platform selection, and architecture decisions with a findings map showing exactly which codebase attributes drove the recommendation +- **Hybrid Modernization Pattern**: Automatically detects un-modernizable dependencies (e.g., Crystal Reports, COM components, deprecated J2EE libraries) and recommends a Legacy Component Isolation architecture with EC2 sidecar + API wrappers alongside the modernized stack ## Platform Detection @@ -32,6 +36,7 @@ The analyzer automatically detects your source platform: ### .NET Detection - Files: `.sln`, `.csproj`, `.vbproj`, `web.config`, `packages.config`, `appsettings.json` +- AD/SSO indicators: ``, `WindowsIdentity`, `Membership.ValidateUser()`, `System.DirectoryServices` ### WebSphere Detection - Files: `ibm-web-bnd.xml`, `ibm-web-ext.xml`, `ibm-application-bnd.xml`, `ibm-ejb-jar-bnd.xml` @@ -88,15 +93,19 @@ Report structure is defined by `steering/report-structure.md` (single source of 4. **Critical Findings Matrix** - 10+ findings with priorities 5. **Proprietary Dependency Analysis** - License verification, migration examples 6. **Database Analysis** - Detection and migration opportunity -7. **Recommended Pathways** - 3 pathways with: +7. **Decision Tree Findings Map** (.NET) - Node-by-node walkthrough showing scanned attributes, findings, and the recommended target platform/architecture path +8. **Recommended Pathways** - 3 pathways with: - Weighted Recommendation Scores (6 factors: Long-term Value, Implementation Risk, Cost Efficiency, Time to Value, Team Readiness, Business Continuity) - Visual dot indicator scoring matrix (●●●●●●●●●○ format) - Quadrant chart for effort vs value positioning - Pros/cons tables and risk assessments -8. **Next Steps** - Recommended pathway implementation roadmap -9. **Cost-Benefit Analysis** - Pathway comparison (qualitative) -10. **Solution Structure Summary** - Projects and complexity -11. **Conclusion** - Assessment and success factors +9. **Next Steps** - Recommended pathway implementation roadmap with: + - Dual timeline comparison (Traditional vs Agentic AI-Accelerated) + - Tool automation impact analysis (AWS Transform, Kiro, SCT, DMS) + - Timeline reduction metrics (typically 70-80% faster with GenAI tools) +10. **Cost-Benefit Analysis** - Pathway comparison (qualitative) +11. **Solution Structure Summary** - Projects and complexity +12. **Conclusion** - Assessment and success factors ## Project Structure diff --git a/legacy-app-modernization-analyzer/steering/dotnet-to-aws.md b/legacy-app-modernization-analyzer/steering/dotnet-to-aws.md index 4b692b4..e4641d5 100644 --- a/legacy-app-modernization-analyzer/steering/dotnet-to-aws.md +++ b/legacy-app-modernization-analyzer/steering/dotnet-to-aws.md @@ -21,6 +21,17 @@ inclusion: manual - `System.Data.SqlClient` / `Microsoft.Data.SqlClient` - SQL Server - `System.ServiceModel.*` - WCF - `EntityFramework` / `Microsoft.EntityFrameworkCore` - ORM +- `System.DirectoryServices` / `System.DirectoryServices.AccountManagement` - Active Directory (⛔ Critical Blocker) + +### Active Directory / SSO Detection + +Scan `web.config` for authentication mode: +- `` → Windows SSO scenario (Critical Blocker - Complete Rewrite) +- `` with `ValidateUser` or `PrincipalContext` in code → Forms Auth against AD (Remote Auth approach) + +Scan source code for: +- `User.IsInRole()`, `WindowsIdentity`, `WindowsPrincipal` → Windows SSO +- `Membership.ValidateUser()`, `PrincipalContext`, `FormsAuthentication.SetAuthCookie()` → Forms Auth against AD ### Target Framework Detection @@ -29,6 +40,216 @@ Extract from `.csproj` files: - `net6.0` - .NET 6 - `net8.0` - .NET 8 +## .NET Modernization Decision Tree + +The following decision tree defines the base logic for determining the modernization approach. When generating the report, walk through each decision node and map the actual findings from the codebase scan to show readers exactly which attributes were extracted and how they led to the recommended approach. + +```mermaid +flowchart TD + %% Nodes + Start([Start: .NET Framework 4.8 App]) + + %% Phase 1: Feasibility Check + CheckTech{Uses Unsupported Tech?
                (AppDomains, Remoting, CAS,
                WF, COM+, WebForms, WCF-Server)} + Redesign[Must Redesign/Replace
                Unsupported Components] + StayFramework1[Stay on .NET Framework
                (Legacy Mode)] + + CheckPlatform{Tied to Platform?
                (SharePoint, BizTalk, etc.)} + MigratePlatform[Migrate Platform First] + StayFramework2[Stay on .NET Framework
                (Platform Constraint)] + + CheckLibs{Critical 3rd-Party Libs
                Lack Modern .NET Version?} + ReplaceLibs[Replace/Port Libraries] + StayFramework3[Stay on .NET Framework
                (Dependency Hell)] + + CheckOS{Target OS Supported
                by .NET 8?} + UpgradeOS[Upgrade OS] + StayFramework4[Stay on .NET Framework
                (OS Constraint)] + + %% Phase 2: Platform Selection + MoveModern([Move to Modern .NET / .NET 8]) + + CheckWinFeat{Needs Windows-Only Features?
                (WPF/WinForms, GDI+, Registry,
                Win-Specific P/Invoke)} + TargetWinX86[Target: Windows x86/x64
                (No Graviton)] + + CheckWinDeps{Has Windows-Only Native Deps?
                (COM, win-x64 DLLs)} + TargetLinuxCap([Linux Capable]) + + %% Phase 3: Architecture Selection + CheckArmSupport{All Libs/Agents Support
                linux-arm64?} + TargetLinuxX86[Target: Linux x86-64
                (Step 1)] + + CheckWorkload{CPU-Bound / High Scale?
                (Crypto, API, Batch)} + TargetGraviton[Target: AWS Graviton / ARM64
                (Best Performance/Cost)] + TargetLinuxChoice[Choice: Linux x86 OR Graviton
                (Based on Ops Preference)] + + %% Edges / Logic Flow + Start --> CheckTech + CheckTech -- Yes --> Redesign + Redesign --> CheckTech + CheckTech -- Cannot Fix --> StayFramework1 + CheckTech -- No --> CheckPlatform + + CheckPlatform -- Yes --> MigratePlatform + MigratePlatform --> CheckPlatform + CheckPlatform -- Cannot Fix --> StayFramework2 + CheckPlatform -- No --> CheckLibs + + CheckLibs -- Yes --> ReplaceLibs + ReplaceLibs --> CheckLibs + CheckLibs -- Cannot Fix --> StayFramework3 + CheckLibs -- No --> CheckOS + + CheckOS -- No --> UpgradeOS + UpgradeOS --> CheckOS + CheckOS -- Cannot Upgrade --> StayFramework4 + CheckOS -- Yes --> MoveModern + + MoveModern --> CheckWinFeat + CheckWinFeat -- Yes --> TargetWinX86 + CheckWinFeat -- No --> CheckWinDeps + CheckWinDeps -- Yes --> TargetWinX86 + CheckWinDeps -- No --> TargetLinuxCap + + TargetLinuxCap --> CheckArmSupport + CheckArmSupport -- No --> TargetLinuxX86 + CheckArmSupport -- Yes --> CheckWorkload + CheckWorkload -- Yes --> TargetGraviton + CheckWorkload -- No --> TargetLinuxChoice + + %% Styling + classDef termination fill:#f9f9f9,stroke:#333,stroke-width:2px; + classDef decision fill:#e1f5fe,stroke:#01579b,stroke-width:2px; + classDef process fill:#fff9c4,stroke:#fbc02d,stroke-width:2px; + classDef success fill:#e8f5e9,stroke:#2e7d32,stroke-width:4px; + classDef failure fill:#ffebee,stroke:#c62828,stroke-width:2px; + + class Start,MoveModern,TargetLinuxCap termination; + class CheckTech,CheckPlatform,CheckLibs,CheckOS,CheckWinFeat,CheckWinDeps,CheckArmSupport,CheckWorkload decision; + class Redesign,MigratePlatform,ReplaceLibs,UpgradeOS process; + class TargetGraviton,TargetWinX86,TargetLinuxX86,TargetLinuxChoice success; + class StayFramework1,StayFramework2,StayFramework3,StayFramework4 failure; +``` + +### Decision Tree Mapping Instructions + +When generating the modernization report, include a **Decision Tree Findings Map** section that walks through each node and shows: + +| Decision Node | What We Scanned | What We Found | Result | +|---------------|-----------------|---------------|--------| +| Unsupported Tech? | `.csproj` refs, `Global.asax`, code patterns | _(e.g., "WebForms detected: 12 .aspx pages")_ | Yes/No | +| Tied to Platform? | Project refs, NuGet packages | _(e.g., "No SharePoint/BizTalk dependencies")_ | Yes/No | +| Critical Libs Missing? | `packages.config`, `.csproj` PackageReference | _(e.g., "All packages have .NET 8 versions")_ | Yes/No | +| Target OS Supported? | Runtime dependencies, P/Invoke calls | _(e.g., "No OS-specific constraints")_ | Yes/No | +| Windows-Only Features? | WPF/WinForms refs, GDI+, Registry calls | _(e.g., "No Windows-only UI frameworks")_ | Yes/No | +| Windows-Only Native Deps? | COM references, native DLL imports | _(e.g., "No COM interop detected")_ | Yes/No | +| ARM64 Support? | NuGet native packages, agent dependencies | _(e.g., "All deps support linux-arm64")_ | Yes/No | +| CPU-Bound / High Scale? | Application profile, workload patterns | _(e.g., "API-heavy, high request volume")_ | Yes/No | + +Highlight the path taken through the decision tree by marking the actual route with ✅ and dead-end branches with ❌. This gives readers full transparency into why a specific target platform and architecture was recommended. + +## .NET Modernization Decision Tree + +Use this decision tree as the base logic for the analysis. When generating the report, map actual findings from the codebase scan onto each decision node to show readers exactly which attributes were extracted and how they led to the recommended approach. + +```mermaid +flowchart TD + %% Nodes + Start([Start: .NET Framework 4.8 App]) + + %% Phase 1: Feasibility Check + CheckTech{Uses Unsupported Tech?
                (AppDomains, Remoting, CAS,
                WF, COM+, WebForms, WCF-Server)} + Redesign[Must Redesign/Replace
                Unsupported Components] + StayFramework1[Stay on .NET Framework
                (Legacy Mode)] + + CheckPlatform{Tied to Platform?
                (SharePoint, BizTalk, etc.)} + MigratePlatform[Migrate Platform First] + StayFramework2[Stay on .NET Framework
                (Platform Constraint)] + + CheckLibs{Critical 3rd-Party Libs
                Lack Modern .NET Version?} + ReplaceLibs[Replace/Port Libraries] + StayFramework3[Stay on .NET Framework
                (Dependency Hell)] + + CheckOS{Target OS Supported
                by .NET 8?} + UpgradeOS[Upgrade OS] + StayFramework4[Stay on .NET Framework
                (OS Constraint)] + + %% Phase 2: Platform Selection + MoveModern([Move to Modern .NET / .NET 8]) + + CheckWinFeat{Needs Windows-Only Features?
                (WPF/WinForms, GDI+, Registry,
                Win-Specific P/Invoke)} + TargetWinX86[Target: Windows x86/x64
                (No Graviton)] + + CheckWinDeps{Has Windows-Only Native Deps?
                (COM, win-x64 DLLs)} + TargetLinuxCap([Linux Capable]) + + %% Phase 3: Architecture Selection + CheckArmSupport{All Libs/Agents Support
                linux-arm64?} + TargetLinuxX86[Target: Linux x86-64
                (Step 1)] + + CheckWorkload{CPU-Bound / High Scale?
                (Crypto, API, Batch)} + TargetGraviton[Target: AWS Graviton / ARM64
                (Best Performance/Cost)] + TargetLinuxChoice[Choice: Linux x86 OR Graviton
                (Based on Ops Preference)] + + %% Edges / Logic Flow + Start --> CheckTech + CheckTech -- Yes --> Redesign + Redesign --> CheckTech + CheckTech -- Cannot Fix --> StayFramework1 + CheckTech -- No --> CheckPlatform + + CheckPlatform -- Yes --> MigratePlatform + MigratePlatform --> CheckPlatform + CheckPlatform -- Cannot Fix --> StayFramework2 + CheckPlatform -- No --> CheckLibs + + CheckLibs -- Yes --> ReplaceLibs + ReplaceLibs --> CheckLibs + CheckLibs -- Cannot Fix --> StayFramework3 + CheckLibs -- No --> CheckOS + + CheckOS -- No --> UpgradeOS + UpgradeOS --> CheckOS + CheckOS -- Cannot Upgrade --> StayFramework4 + CheckOS -- Yes --> MoveModern + + MoveModern --> CheckWinFeat + CheckWinFeat -- Yes --> TargetWinX86 + CheckWinFeat -- No --> CheckWinDeps + CheckWinDeps -- Yes --> TargetWinX86 + CheckWinDeps -- No --> TargetLinuxCap + + TargetLinuxCap --> CheckArmSupport + CheckArmSupport -- No --> TargetLinuxX86 + CheckArmSupport -- Yes --> CheckWorkload + CheckWorkload -- Yes --> TargetGraviton + CheckWorkload -- No --> TargetLinuxChoice + + %% Styling + classDef termination fill:#f9f9f9,stroke:#333,stroke-width:2px; + classDef decision fill:#e1f5fe,stroke:#01579b,stroke-width:2px; + classDef process fill:#fff9c4,stroke:#fbc02d,stroke-width:2px; + classDef success fill:#e8f5e9,stroke:#2e7d32,stroke-width:4px; + classDef failure fill:#ffebee,stroke:#c62828,stroke-width:2px; + + class Start,MoveModern,TargetLinuxCap termination; + class CheckTech,CheckPlatform,CheckLibs,CheckOS,CheckWinFeat,CheckWinDeps,CheckArmSupport,CheckWorkload decision; + class Redesign,MigratePlatform,ReplaceLibs,UpgradeOS process; + class TargetGraviton,TargetWinX86,TargetLinuxX86,TargetLinuxChoice success; + class StayFramework1,StayFramework2,StayFramework3,StayFramework4 failure; +``` + +### How to Use This Decision Tree in Reports + +When generating the modernization report, walk through each decision node and map the actual codebase findings: + +1. **At each decision node**, state what was scanned and what was found (or not found) +2. **Highlight the path taken** through the tree based on evidence +3. **For blocker nodes** (red), explain specifically what was detected and why it blocks +4. **For the final target node** (green), explain how the cumulative findings led to this recommendation + +This gives readers full traceability from codebase evidence → decision logic → recommended target platform. + ## Migration Strategy Bank ### API & Library Modernization @@ -79,6 +300,58 @@ Extract from `.csproj` files: | Forms Auth | JWT/OAuth2 | Token-based auth | | Machine Keys | AWS KMS | Key management | +### ⛔ Critical Blocker: Active Directory / Windows SSO Authentication + +This is a **critical modernization blocker** that MUST be detected and reported. Scan `web.config` and source code to determine which AD authentication scenario applies. + +#### Scenario 1: Windows SSO with Active Directory (Complete Rewrite Required) + +**Detection Indicators:** +- `` in `web.config` +- NO login screen (transparent SSO via browser/Kerberos) +- Code uses `User.IsInRole()` directly +- References to `WindowsIdentity`, `WindowsPrincipal` +- IIS Windows Authentication enabled + +**Modernization Approach — Complete Rewrite to Native Core:** + +| Action | Required | Notes | +|--------|----------|-------| +| Implement new middleware in `Program.cs` | ✅ Yes | New auth pipeline setup | +| Configure Windows Authentication packages / IIS settings | ✅ Yes | `Microsoft.AspNetCore.Authentication.Negotiate` | +| Write new LDAP / DirectoryServices code | ✅ Yes | Replace implicit Windows identity resolution | +| Refactor code using `HttpContext` | ✅ Yes | `System.Web.HttpContext` → `Microsoft.AspNetCore.Http.HttpContext` | +| Configure System.Web Adapters | ❌ No | Not applicable for native rewrite | +| Set up Data Protection / Ring Keys | ❌ No | Not required | + +**Risk if Not Modernized:** Windows SSO is tightly coupled to on-premises Active Directory and IIS. It cannot run on Linux containers or AWS ECS/EKS without a complete rewrite of the authentication layer. This blocks any containerization or cloud migration. + +#### Scenario 2: Forms Authentication against Active Directory (Remote Auth via System.Web Adapters) + +**Detection Indicators:** +- `` or `` in `web.config` +- YES login screen (custom login page) +- Code uses `Membership.ValidateUser()` or `PrincipalContext` +- References to `System.DirectoryServices`, `System.DirectoryServices.AccountManagement` +- `FormsAuthentication.SetAuthCookie()` usage + +**Modernization Approach — Remote Authentication using System.Web Adapters:** + +| Action | Required | Notes | +|--------|----------|-------| +| Implement new middleware in `Program.cs` | ✅ Yes | Configure remote auth middleware | +| Configure System.Web Adapters | ✅ Yes | Bridge between .NET Core and Framework app | +| Refactor code using `HttpContext` | ⚠️ Minimal | Less refactoring than full rewrite | +| Write new LDAP / DirectoryServices code | ❌ No | Leverages existing Framework app for AD validation | +| Set up Data Protection / Ring Keys | ❌ No | Not required | +| Configure Windows Auth packages / IIS settings | ❌ No | Not applicable for remote auth setup | + +**Risk if Not Modernized:** Forms Auth against AD is less tightly coupled than Windows SSO, but still relies on legacy `System.Web` membership providers. The System.Web Adapters approach allows incremental migration while keeping the existing AD integration intact during transition. + +#### Detection Priority + +When scanning a .NET codebase, check for AD/SSO indicators **early** in the analysis as this is a critical blocker that significantly impacts migration pathway selection, effort estimates, and timeline. + ### Cloud-Native Patterns | Current | Target | Notes | @@ -89,6 +362,48 @@ Extract from `.csproj` files: | Logging | AWS CloudWatch | Centralized logging | | Caching | ElastiCache | Distributed caching | +## Hybrid Modernization: EC2 Legacy Sidecar Pattern + +In some cases, certain libraries or components are tightly coupled to the original architecture and have no modern equivalent for the target platform. For .NET, this includes dependencies on Windows-specific system DLLs, .NET Framework-only libraries, or components like Crystal Reports that have no Linux-compatible version. + +When these un-modernizable components are identified, recommend a hybrid approach: + +### Pattern: Modernize + Legacy Sidecar + +1. Modernize everything possible to the target architecture (.NET 8 / Linux / containers) +2. Isolate the un-modernizable components into a dedicated EC2 instance running the original platform (e.g., Windows Server with .NET Framework / IIS) +3. Build API wrappers (REST or gRPC) around the legacy components on the EC2 instance +4. Have the modernized application interface with the legacy sidecar through these wrappers + +```mermaid +flowchart LR + subgraph Modern["Modernized Stack (ECS/EKS)"] + App[".NET 8 App
                (Linux Container)"] + end + subgraph Legacy["Legacy Sidecar (EC2)"] + Wrapper["API Wrapper
                (REST/gRPC)"] + Component["Un-modernizable
                Component
                (e.g., Crystal Reports,
                Windows DLLs)"] + Wrapper --> Component + end + App -- "API Call" --> Wrapper +``` + +### When to Recommend This Pattern + +- A critical library has no .NET 8 or Linux-compatible version +- A component depends on Windows-specific system APIs (GDI+, COM, Registry) that cannot be abstracted +- Rewriting the component is not feasible within the migration timeline +- The component is stable and rarely changes (low maintenance burden) + +### Report Guidance + +When this pattern applies, include it as an additional pathway or as a variant of the primary pathway, with: +- List of specific components that require the legacy sidecar +- Justification for why each component cannot be modernized +- API wrapper design recommendations +- Cost implications of maintaining the EC2 sidecar instance +- Long-term plan to eventually retire the sidecar (if feasible) + ## .NET-Specific Evaluation Areas ### Platform & Framework Assessment diff --git a/legacy-app-modernization-analyzer/steering/evaluation-framework.md b/legacy-app-modernization-analyzer/steering/evaluation-framework.md index 9814522..024b78a 100644 --- a/legacy-app-modernization-analyzer/steering/evaluation-framework.md +++ b/legacy-app-modernization-analyzer/steering/evaluation-framework.md @@ -166,3 +166,71 @@ Evaluate return on investment: - Provide specific metrics (file counts, LOC, dependency counts) - Include code examples for migration patterns - Back all claims with codebase evidence + +## Hybrid Modernization Pattern: Legacy Component Isolation + +In some cases, certain libraries or components are tightly coupled to the original architecture and have no modern equivalent for the target platform. When this is detected, recommend a **hybrid modernization** approach: modernize everything possible to the target architecture, and isolate the un-modernizable components on a dedicated EC2 instance with API wrappers. + +### When to Apply + +This pattern applies when the analysis finds dependencies that: +- Have no compatible version for the target platform/OS +- Are tightly coupled to the legacy runtime and cannot be replaced +- Would require prohibitive effort to rewrite from scratch + +### Platform-Specific Examples + +| Platform | Un-Modernizable Dependency Example | Why It Can't Modernize | +|----------|-------------------------------------|------------------------| +| .NET Framework | Crystal Reports | No Linux-compatible version; requires Windows + .NET Framework runtime | +| .NET Framework | Windows-only system DLLs, COM components | Tied to Windows OS; no cross-platform equivalent | +| .NET Framework | Legacy .NET Framework-only DLLs (no .NET 8 port) | Vendor abandoned or closed-source with no modern build | +| WebSphere / WebLogic | Deprecated J2EE libraries (e.g., JAX-RPC, Entity Beans) | Removed from Jakarta EE; no Spring Boot equivalent | +| WebSphere / WebLogic | Vendor-specific JEE extensions (e.g., IBM MQ JEE bindings, WebLogic T3 protocol) | Proprietary APIs with no open-source replacement | + +### Recommended Architecture + +``` +┌─────────────────────────────────────┐ +│ Modernized Application │ +│ (.NET 8 / Spring Boot on ECS/EKS) │ +│ │ +│ ┌─────────────────────────┐ │ +│ │ API Wrapper / Client │────────┼──── REST/gRPC ────┐ +│ └─────────────────────────┘ │ │ +└─────────────────────────────────────┘ │ + ▼ + ┌────────────────────────────┐ + │ Legacy Component Host │ + │ (EC2 - Windows/.NET Fwk │ + │ or EC2 - JEE App Server) │ + │ │ + │ ┌──────────────────────┐ │ + │ │ API Wrapper Service │ │ + │ │ (exposes REST/gRPC) │ │ + │ └──────┬───────────────┘ │ + │ │ │ + │ ┌──────▼───────────────┐ │ + │ │ Legacy Component │ │ + │ │ (Crystal Reports, │ │ + │ │ COM, JAX-RPC, etc) │ │ + │ └──────────────────────┘ │ + └────────────────────────────┘ +``` + +### Implementation Guidance + +1. **Identify** all un-modernizable components during the codebase scan +2. **Extract** these components into a standalone service with a clean API boundary +3. **Deploy** the legacy service on an EC2 instance running the required legacy runtime (Windows Server for .NET Framework, or a JEE app server for WebSphere/WebLogic components) +4. **Wrap** each legacy component with a REST or gRPC API so the modernized application can interface with it +5. **Modernize** everything else to the target architecture (ECS/EKS on Linux) + +### Report Guidance + +When this pattern is recommended, the report should: +- List each un-modernizable component with the specific reason it cannot be migrated +- Show the wrapper API design for each isolated component +- Include the EC2 legacy host in the target architecture diagram +- Factor the EC2 instance cost into the cost-benefit analysis +- Note this as a transitional architecture — the long-term goal is to eventually replace or retire the legacy components diff --git a/legacy-app-modernization-analyzer/steering/report-structure.md b/legacy-app-modernization-analyzer/steering/report-structure.md index 498681e..c9b4584 100644 --- a/legacy-app-modernization-analyzer/steering/report-structure.md +++ b/legacy-app-modernization-analyzer/steering/report-structure.md @@ -11,8 +11,8 @@ This defines the standard report structure for ALL modernization analyses (.NET, **This file is the SINGLE SOURCE OF TRUTH for report formatting. Follow these rules exactly:** 1. **NO dollar amounts by default** - Use qualitative levels (Low/Medium/High/Very High) for cost estimates -2. **NO time estimates** - No hours, days, weeks, or months anywhere in the report -3. **NO real dates** - Gantt charts use generic weeks (Week 1, Week 2, etc.) +2. **DUAL TIMELINE COMPARISON REQUIRED** - Always show Traditional vs Agentic AI-Accelerated timelines side-by-side to demonstrate the value of AWS Transform and Kiro +3. **NO real dates** - Gantt charts use generic weeks (Week 1, Week 2, etc.) with `axisFormat Week %S` (uppercase S) and `tickInterval 2` 4. **NO file counts or line counts** - Solution Structure is simple 5. **NO Appendix section** - Report ends with Conclusion 6. **Professional Advisory Notice goes at TOP** - Before Executive Summary, not at the end @@ -322,11 +322,14 @@ Use generic week numbers (Week 1, Week 2, etc.) - NO real dates. The Gantt chart **CRITICAL: Use explicit start/end positions, NOT `after` syntax.** The `after` keyword does not render correctly with `dateFormat X`. Always use `:taskId, startWeek, endWeek` format. +**CRITICAL: Use `axisFormat Week %S` (uppercase S), NOT `%s` (lowercase).** Lowercase `%s` causes axis label rendering issues. Always include `tickInterval 2` to prevent label crowding. + ```mermaid gantt title Recommended Pathway Implementation (Indicative Timeline) dateFormat X - axisFormat Week %s + axisFormat Week %S + tickInterval 2 section Phase 1: [Name] Task 1 (Foundation) :a1, 0, 2 @@ -344,6 +347,8 @@ gantt ``` **Gantt Chart Syntax Rules:** +- **MUST use `axisFormat Week %S`** (uppercase S) — lowercase `%s` causes overlapping/garbled axis labels +- **MUST include `tickInterval 2`** to prevent x-axis label crowding - Format: `:taskId, startWeek, endWeek` (e.g., `:a1, 0, 2` means Week 0 to Week 2) - Parallel tasks: Same start week (e.g., `:a1, 0, 2` and `:a2, 0, 2`) - Sequential tasks: Next task starts where previous ends (e.g., `:a3, 2, 3` follows `:a1, 0, 2`) @@ -373,18 +378,108 @@ NO effort estimates in hours/days/weeks. Mermaid flowchart showing decision flow and dependencies for the recommended pathway. -#### Recommended Tool Support +#### Timeline Comparison: Traditional vs Agentic AI-Accelerated + +**ALWAYS include both timelines to demonstrate the value of AWS Transform and Kiro:** + +##### Why Agentic AI Dramatically Reduces Timeline -Prioritize AWS Transform tools in this order: +| Task Category | Traditional Approach | With AWS Transform + Kiro | Acceleration Factor | +|---------------|---------------------|---------------------------|---------------------| +| Code Analysis | Manual review, days | Automated scanning, minutes | 100x+ | +| Framework Migration | Line-by-line rewrite, weeks | AWS Transform auto-conversion, hours | 50x+ | +| EF6 → EF Core | Manual refactoring, weeks | AWS Transform patterns, hours | 40x+ | +| Controller Migration | Manual per controller, days | Kiro batch migration, minutes | 100x+ | +| View Updates | Manual per view, days | Kiro pattern application, hours | 20x+ | +| Dockerfile Creation | Manual research + writing | Kiro generation, minutes | 50x+ | +| Test Generation | Manual writing, weeks | Kiro auto-generation, hours | 30x+ | -| Tool | Purpose | Phase | -|------|---------|-------| -| AWS Transform for Windows Full Stack | End-to-end .NET modernization (framework upgrade + database migration) | All phases | -| AWS Transform for .NET | .NET Framework to .NET Core/8 porting, EF6 → EF Core migration | Phase 1-2 | -| AWS Schema Conversion Tool (SCT) | Database schema conversion analysis | Phase 2 | -| AWS Database Migration Service (DMS) | Data migration with minimal downtime | Phase 3-4 | -| AWS App2Container | Containerization of existing applications | Phase 4 | -| Kiro | AI-assisted code migration and refactoring | All phases | +##### Dual Timeline Gantt Charts + +**Traditional Approach (Without GenAI Tools):** +```mermaid +gantt + title Traditional Migration Timeline + dateFormat X + axisFormat Week %S + tickInterval 2 + + section Analysis + Manual code review :a1, 0, 2 + Dependency analysis :a2, 2, 3 + + section Framework Migration + Create .NET 8 projects :b1, 3, 4 + Manual code conversion :b2, 4, 10 + EF6 to EF Core (manual) :b3, 10, 14 + + section Web Layer + Controller migration :c1, 14, 18 + View updates :c2, 18, 21 + Auth migration :c3, 21, 23 + + section Database + Schema conversion :d1, 14, 16 + Data migration :d2, 23, 25 + + section Testing & Deploy + Integration testing :e1, 25, 28 + Performance testing :e2, 28, 30 + Production cutover :e3, 30, 32 +``` + +**Agentic AI-Accelerated (With AWS Transform + Kiro):** +```mermaid +gantt + title Agentic AI-Accelerated Timeline + dateFormat X + axisFormat Week %S + tickInterval 1 + + section Phase 1: Foundation + AWS Transform analysis :a1, 0, 0.5 + Auto-scaffold .NET 8 :a2, 0, 0.5 + Domain + Data migration :a3, 0.5, 1 + + section Phase 2: Parallel Migration + EF Core (AWS Transform) :b1, 1, 2 + Controllers (Kiro) :b2, 1, 2 + Views (Kiro) :b3, 1, 2 + Aurora + SCT :b4, 1, 2 + + section Phase 3: Integration + Auth + DMS :c1, 2, 3 + Containerization (Kiro) :c2, 2, 3 + + section Phase 4: Validate + AI-assisted testing :d1, 3, 4 + Human review + fixes :d2, 4, 5 + Production cutover :d3, 5, 6 +``` + +##### Timeline Comparison Summary + +| Metric | Traditional | Agentic AI-Accelerated | Reduction | +|--------|-------------|------------------------|-----------| +| Total Duration | ~32 weeks | ~6 weeks | **81% faster** | +| Manual Coding Effort | Very High | Low (review-focused) | **~80% less** | +| Human Role | Write code | Review + validate | Shifted | +| Parallelization | Limited | Massive | Enabled by AI | +| Risk of Errors | Higher | Lower (consistent patterns) | Reduced | + +> 📋 **Key Insight**: AWS Transform automates 70-80% of code conversion. Kiro handles repetitive migrations in parallel. Human effort shifts from writing code to reviewing AI-generated output. The bottleneck becomes testing and validation, not coding. + +#### Recommended Tool Support (Automation Impact) + +| Tool | Purpose | Automation Level | Time Savings | +|------|---------|------------------|--------------| +| AWS Transform for Windows Full Stack | End-to-end .NET + DB migration | 70-80% automated | Weeks → Days | +| AWS Transform for .NET | Framework + EF migration | 60-70% automated | Weeks → Days | +| Kiro | Code migration, refactoring, test generation | 80-90% automated | Days → Hours | +| AWS Schema Conversion Tool | Schema analysis + conversion | 90% automated | Days → Hours | +| AWS Database Migration Service | Data migration | 95% automated | Days → Hours | + +> 📋 **Automation Reality**: With these tools, the migration work shifts from "writing code" to "reviewing and validating AI-generated code." A skilled team can review and approve changes much faster than writing from scratch. Note: For .NET modernization, prefer AWS Transform for Windows Full Stack when both application and database migration are needed. Use individual tools (SCT, DMS, App2Container) only for specific scenarios or when Transform doesn't cover the use case. @@ -409,6 +504,22 @@ Use qualitative levels (Low/Medium/High/Very High) - NO dollar amounts by defaul Use a Mermaid Gantt chart to create stacked horizontal bars showing relative year-by-year costs: +**CRITICAL: Bars must be stacked, NOT starting from zero.** Each bar's start position must equal the previous bar's end position within the same section. This creates a visual stacking effect where Year 2 begins where Year 1 ends, and Year 3 begins where Year 2 ends. + +✅ **CORRECT** (stacked — each bar starts where previous ends): +``` +Year 1 - 45 :active, 0, 45 +Year 2 - 25 :crit, 45, 70 +Year 3 - 25 :70, 95 +``` + +❌ **WRONG** (all bars start from 0 — not stacked): +``` +Year 1 - 45 :active, 0, 45 +Year 2 - 25 :crit, 0, 25 +Year 3 - 25 :0, 25 +``` + ```mermaid gantt title 3-Year Relative Cost Comparison (Baseline = 100) @@ -437,6 +548,8 @@ gantt Year 3 - 100 :205, 305 ``` +**CRITICAL for 3-Year Cost Chart:** This chart uses `axisFormat %s` (lowercase) because the x-axis represents cost units (0-300+), NOT weeks. Do NOT use `%S` (uppercase) here — it caps at 59 and wraps. The stacking is achieved by chaining bar positions: Year 2 starts where Year 1 ends, Year 3 starts where Year 2 ends. Each bar within a section MUST start from the end of the previous bar, NOT from 0. + **Legend:** 🔵 Year 1 (active = blue) | 🔴 Year 2 (crit = red) | 🩵 Year 3 (no status = teal/cyan) — X-axis: Relative cost units (Current annual = 100). Bar length represents cumulative 3-year cost. **Gantt Chart Color Reference:** @@ -594,7 +707,7 @@ Brief summary including: 2. **Dependency Graphs**: `graph TD` with color-coded styles 3. **Flowcharts**: `flowchart LR` or `flowchart TB` with subgraphs for phases 4. **Quadrant Charts**: `quadrantChart` for pathway comparison -5. **Gantt Charts**: `gantt` for both implementation timelines (dateFormat X, axisFormat Week %s) AND 3-year cost visualization (as horizontal stacked bars) +5. **Gantt Charts**: `gantt` for both implementation timelines (dateFormat X, axisFormat Week %S, tickInterval 2) AND 3-year cost visualization (as horizontal stacked bars). **MUST use uppercase %S, NOT lowercase %s.** ### Color Coding Standards @@ -647,6 +760,13 @@ Before completing the report, verify: - [ ] Gantt chart has timeline disclaimer - [ ] Gantt chart uses generic weeks (no real dates) +**TIMELINE COMPARISON:** +- [ ] BOTH Traditional and Agentic AI-Accelerated timelines shown +- [ ] Timeline comparison table with reduction percentages +- [ ] Tool automation levels documented with time savings +- [ ] Human role clearly defined as "review + validate" not "write" +- [ ] Acceleration factors table included + **COST-BENEFIT:** - [ ] 3-Year Cost Comparison table uses qualitative levels (Low/Medium/High) by default - [ ] 3-Year Cost Visualization uses Mermaid GANTT chart as stacked horizontal bars with RELATIVE units diff --git a/legacy-app-modernization-analyzer/steering/weblogic-to-springboot.md b/legacy-app-modernization-analyzer/steering/weblogic-to-springboot.md index aaf311d..11a70a1 100644 --- a/legacy-app-modernization-analyzer/steering/weblogic-to-springboot.md +++ b/legacy-app-modernization-analyzer/steering/weblogic-to-springboot.md @@ -94,6 +94,48 @@ Scan for these package imports: | Credential Mapping | AWS Secrets Manager | | SSL Configuration | Netty SSL / ALB TLS | +## Hybrid Modernization: EC2 Legacy Sidecar Pattern + +In some cases, certain libraries or components are tightly coupled to the original J2EE/WebLogic architecture and have no Spring Boot (non-JEE) compatible version. This includes deprecated JEE-specific libraries, proprietary WebLogic APIs with no open-source equivalent, or vendor-specific middleware that cannot be replaced. + +When these un-modernizable components are identified, recommend a hybrid approach: + +### Pattern: Modernize + Legacy Sidecar + +1. Modernize everything possible to Spring Boot Reactive / containers +2. Isolate the un-modernizable components into a dedicated EC2 instance running the original WebLogic runtime +3. Build API wrappers (REST or gRPC) around the legacy components on the EC2 instance +4. Have the modernized Spring Boot application interface with the legacy sidecar through these wrappers + +```mermaid +flowchart LR + subgraph Modern["Modernized Stack (ECS/EKS)"] + App["Spring Boot Reactive App
                (Linux Container)"] + end + subgraph Legacy["Legacy Sidecar (EC2)"] + Wrapper["API Wrapper
                (REST/gRPC)"] + Component["Un-modernizable
                Component
                (e.g., Proprietary JEE Libs,
                WebLogic-specific APIs)"] + Wrapper --> Component + end + App -- "API Call" --> Wrapper +``` + +### When to Recommend This Pattern + +- A critical library depends on JEE APIs that are deprecated or have no Spring Boot equivalent +- A component uses proprietary WebLogic APIs with no open-source alternative +- Rewriting the component is not feasible within the migration timeline +- The component is stable and rarely changes (low maintenance burden) + +### Report Guidance + +When this pattern applies, include it as an additional pathway or as a variant of the primary pathway, with: +- List of specific components that require the legacy sidecar +- Justification for why each component cannot be modernized +- API wrapper design recommendations +- Cost implications of maintaining the EC2 sidecar instance +- Long-term plan to eventually retire the sidecar (if feasible) + ## WebLogic-Specific Risks ### Proprietary API Dependencies diff --git a/legacy-app-modernization-analyzer/steering/websphere-to-springboot.md b/legacy-app-modernization-analyzer/steering/websphere-to-springboot.md index 83df581..cc43aca 100644 --- a/legacy-app-modernization-analyzer/steering/websphere-to-springboot.md +++ b/legacy-app-modernization-analyzer/steering/websphere-to-springboot.md @@ -95,6 +95,48 @@ Scan for these package imports: | `@RolesAllowed` | `@PreAuthorize` | | Credential Vault | AWS Secrets Manager | +## Hybrid Modernization: EC2 Legacy Sidecar Pattern + +In some cases, certain libraries or components are tightly coupled to the original J2EE/WebSphere architecture and have no Spring Boot (non-JEE) compatible version. This includes deprecated JEE-specific libraries, proprietary WebSphere APIs with no open-source equivalent, or vendor-specific middleware that cannot be replaced. + +When these un-modernizable components are identified, recommend a hybrid approach: + +### Pattern: Modernize + Legacy Sidecar + +1. Modernize everything possible to Spring Boot Reactive / containers +2. Isolate the un-modernizable components into a dedicated EC2 instance running the original WebSphere runtime +3. Build API wrappers (REST or gRPC) around the legacy components on the EC2 instance +4. Have the modernized Spring Boot application interface with the legacy sidecar through these wrappers + +```mermaid +flowchart LR + subgraph Modern["Modernized Stack (ECS/EKS)"] + App["Spring Boot Reactive App
                (Linux Container)"] + end + subgraph Legacy["Legacy Sidecar (EC2)"] + Wrapper["API Wrapper
                (REST/gRPC)"] + Component["Un-modernizable
                Component
                (e.g., Proprietary JEE Libs,
                WebSphere-specific APIs)"] + Wrapper --> Component + end + App -- "API Call" --> Wrapper +``` + +### When to Recommend This Pattern + +- A critical library depends on JEE APIs that are deprecated or have no Spring Boot equivalent +- A component uses proprietary WebSphere APIs with no open-source alternative +- Rewriting the component is not feasible within the migration timeline +- The component is stable and rarely changes (low maintenance burden) + +### Report Guidance + +When this pattern applies, include it as an additional pathway or as a variant of the primary pathway, with: +- List of specific components that require the legacy sidecar +- Justification for why each component cannot be modernized +- API wrapper design recommendations +- Cost implications of maintaining the EC2 sidecar instance +- Long-term plan to eventually retire the sidecar (if feasible) + ## WebSphere-Specific Risks ### Proprietary API Dependencies From 70a0d62ec20690f0f1a054fe0d306d3c41edc801 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 11 Mar 2026 08:36:12 +0000 Subject: [PATCH 17/18] feat: Add COBOL/Mainframe to Java Spring Boot modernization pathway with report quality rules --- legacy-app-modernization-analyzer/POWER.md | 31 +- legacy-app-modernization-analyzer/README.md | 30 +- .../steering/cobol-to-java.md | 1147 +++++++++++++++++ 3 files changed, 1192 insertions(+), 16 deletions(-) create mode 100644 legacy-app-modernization-analyzer/steering/cobol-to-java.md diff --git a/legacy-app-modernization-analyzer/POWER.md b/legacy-app-modernization-analyzer/POWER.md index d675035..0703130 100644 --- a/legacy-app-modernization-analyzer/POWER.md +++ b/legacy-app-modernization-analyzer/POWER.md @@ -1,8 +1,8 @@ --- name: "legacy-app-modernization-analyzer" displayName: "Legacy App Modernization Analyzer" -description: "Analyzes legacy enterprise codebases (.NET, WebSphere, WebLogic) and generates comprehensive AWS modernization feasibility reports with visual architecture diagrams, dependency analysis, and migration pathways" -keywords: [".NET", "WebSphere", "WebLogic", "Spring Boot", "modernization", "migration", "legacy", "AWS", "containerization", "microservices", "J2EE", "Jakarta", "reactive"] +description: "Analyzes legacy enterprise codebases (.NET, WebSphere, WebLogic, COBOL/Mainframe) and generates comprehensive AWS modernization feasibility reports with visual architecture diagrams, dependency analysis, and migration pathways" +keywords: [".NET", "WebSphere", "WebLogic", "COBOL", "Mainframe", "Spring Boot", "modernization", "migration", "legacy", "AWS", "containerization", "microservices", "J2EE", "Jakarta", "Java"] version: "2.0.0" --- @@ -16,9 +16,10 @@ This power provides elite-level enterprise architecture analysis for legacy appl | Source Platform | Target Platform | Steering File | |-----------------|-----------------|---------------| -| .NET Framework 4.x | .NET 8 + AWS | `steering/dotnet-to-aws.md` | -| IBM WebSphere | Spring Boot Reactive + AWS | `steering/websphere-to-springboot.md` | -| Oracle WebLogic | Spring Boot Reactive + AWS | `steering/weblogic-to-springboot.md` | +| .NET Framework | .NET 8 + AWS | `steering/dotnet-to-aws.md` | +| IBM WebSphere | Spring Boot + AWS | `steering/websphere-to-springboot.md` | +| Oracle WebLogic | Spring Boot + AWS | `steering/weblogic-to-springboot.md` | +| COBOL/Mainframe | Java Spring Boot + AWS | `steering/cobol-to-java.md` | ## Workflow @@ -40,12 +41,18 @@ Scan the codebase to identify the source platform: - JAR dependencies: `weblogic.*`, `oracle.weblogic.*`, `com.bea.*` - If found → Load `steering/weblogic-to-springboot.md` +**Detect COBOL/Mainframe:** +- Look for: `*.cbl`, `*.cob`, `*.cpy`, `*.CPY`, `*.bms`, `*.BMS`, `*.jcl`, `*.JCL`, `*.csd` +- Code patterns: `EXEC CICS`, `EXEC SQL`, `WORKING-STORAGE SECTION`, `PROCEDURE DIVISION` +- If found → Load `steering/cobol-to-java.md` +- **MANDATORY for COBOL:** Execute the Mechanical Data Inventory Extraction AND Mechanical Business Rule Extraction procedures defined in the steering file. The Business Logic Extraction section with all 10 categories MUST appear in the report. This is not optional — it is the most critical section for COBOL modernization. + ### Step 2: Load Common Framework ALWAYS load these steering files for any analysis: -- `steering/common/evaluation-framework.md` - Universal evaluation areas -- `steering/common/report-structure.md` - **AUTHORITATIVE** report format standards -- `steering/common/aws-target-services.md` - AWS service mappings +- `steering/evaluation-framework.md` - Universal evaluation areas +- `steering/report-structure.md` - **AUTHORITATIVE** report format standards +- `steering/aws-target-services.md` - AWS service mappings ### Step 3: Execute Platform-Specific Analysis @@ -130,9 +137,13 @@ This power activates when users mention: - "WebSphere migration" - "WebLogic migration" - "J2EE modernization" +- "COBOL modernization" +- "mainframe migration" +- "COBOL to Java" +- "mainframe to cloud" ## Output -Generate report in `yymmddhhmm_MODERNIZATION_REPORT.md` following the structure defined in `steering/common/report-structure.md`. As for yymmddhhmm, it is the current time's year for yy, month for mm, day for dd, hour for hh and minutes for mm (UTC Timezone). +Generate report in `yymmddhhmm_MODERNIZATION_REPORT.md` following the structure defined in `steering/report-structure.md`. As for yymmddhhmm, it is the current time's year for yy, month for mm, day for dd, hour for hh and minutes for mm (UTC Timezone). -**CRITICAL:** The `steering/common/report-structure.md` file is the SINGLE SOURCE OF TRUTH for all report formatting, section structure, visualization standards, and quality requirements. Do NOT deviate from it. +**CRITICAL:** The `steering/report-structure.md` file is the SINGLE SOURCE OF TRUTH for all report formatting, section structure, visualization standards, and quality requirements. Do NOT deviate from it. diff --git a/legacy-app-modernization-analyzer/README.md b/legacy-app-modernization-analyzer/README.md index d6fc952..7a5379d 100644 --- a/legacy-app-modernization-analyzer/README.md +++ b/legacy-app-modernization-analyzer/README.md @@ -6,11 +6,12 @@ A Kiro Power that provides enterprise-grade legacy codebase modernization analys | Source Platform | Target Platform | Description | Status | |-----------------|-----------------|-------------|--------| -| .NET Framework 4.x | .NET 8 + AWS | Windows-based .NET apps to cross-platform cloud-native | ✅ Stable | -| IBM WebSphere | Spring Boot Reactive + AWS | J2EE/Jakarta EE to reactive microservices | 🧪 BETA | -| Oracle WebLogic | Spring Boot Reactive + AWS | J2EE/Jakarta EE to reactive microservices | 🧪 BETA | +| .NET Framework | .NET 8 + AWS | Windows-based .NET apps to cross-platform cloud-native | ✅ Stable | +| IBM WebSphere | Spring Boot + AWS | J2EE/Jakarta EE to microservices | 🧪 BETA | +| Oracle WebLogic | Spring Boot + AWS | J2EE/Jakarta EE to microservices | 🧪 BETA | +| COBOL/Mainframe | Java Spring Boot + AWS | CICS online, batch, DB2, VSAM to containerized Java on Graviton | 🧪 BETA | -> **Note**: WebSphere and WebLogic modernization paths are in BETA. While functional, these paths may have limited coverage for some proprietary APIs and edge cases. +> **Note**: WebSphere, WebLogic, and COBOL modernization paths are in BETA. While functional, these paths may have limited coverage for some proprietary APIs and edge cases. ## Features @@ -21,6 +22,10 @@ A Kiro Power that provides enterprise-grade legacy codebase modernization analys - **Package License Verification**: Queries NuGet/Maven APIs for license validation - **Proprietary Dependency Analysis**: Impact assessment with code migration examples - **Active Directory / Windows SSO Detection**: Identifies AD authentication scenarios (Windows SSO vs Forms Auth) as critical migration blockers with scenario-specific modernization approaches +- **COBOL Modernization**: CICS online, batch processing, DB2, and VSAM migration patterns to Spring Boot with AWS Graviton targeting +- **COBOL Business Logic Extraction**: Exhaustive line-by-line extraction of business rules from COBOL PROCEDURE DIVISIONs, categorized into 10 rule types: input validation, calculation/processing, decision/routing, data access, inter-program communication, error handling, screen/interface, batch processing, security/authorization, and temporal/state management — each traced to specific paragraph names and code locations +- **COBOL Report Internal Consistency**: Built-in consistency rules ensuring summary-to-detail traceability, count verification across business rule categories, inventory completeness for VSAM files, DB2 tables, IMS databases, MQ queues, copybook mappings, and CICS transactions — with anti-pattern detection to prevent mismatched counts or phantom categories +- **COBOL-Specific Deep Evaluation**: Beyond standard framework areas — assesses reverse engineering readiness, platform-specific compiler behavior (rounding, EBCDIC collation, COMP/COMP-3 layout), undocumented business rules (tribal knowledge), regulatory compliance (SOX, PCI DSS, GDPR, HIPAA), performance/operational baselines, and coexistence/migration strategy with strangler fig architecture diagrams - **Database Migration**: SQL Server/Oracle/DB2 → Aurora PostgreSQL recommendations - **Strategic Alignment**: AWS 7 Rs and Gartner TIME framework classification - **Risk Assessment**: "Impact If Not Modernized" for every finding with probability ratings @@ -28,6 +33,7 @@ A Kiro Power that provides enterprise-grade legacy codebase modernization analys - **Dual Timeline Comparison**: Traditional vs Agentic AI-Accelerated timelines showing the value of AWS Transform + Kiro - **Cost-Benefit Analysis**: Qualitative assessments by default (Low/Medium/High/Very High), with optional detailed pricing simulation available on request - **Modernization Decision Tree (.NET)**: Visual Mermaid flowchart walking through feasibility checks, platform selection, and architecture decisions with a findings map showing exactly which codebase attributes drove the recommendation +- **Modernization Decision Tree (COBOL)**: Visual Mermaid flowchart evaluating CICS online, DB2, VSAM, batch jobs, and business logic complexity to determine the optimal migration path to Spring Boot 3.x + Java 17 on ECS Fargate/Graviton, with a findings map documenting what was scanned and discovered - **Hybrid Modernization Pattern**: Automatically detects un-modernizable dependencies (e.g., Crystal Reports, COM components, deprecated J2EE libraries) and recommends a Legacy Component Isolation architecture with EC2 sidecar + API wrappers alongside the modernized stack ## Platform Detection @@ -42,6 +48,11 @@ The analyzer automatically detects your source platform: - Files: `ibm-web-bnd.xml`, `ibm-web-ext.xml`, `ibm-application-bnd.xml`, `ibm-ejb-jar-bnd.xml` - Dependencies: `com.ibm.websphere.*`, `com.ibm.ws.*`, `com.ibm.mq.*` +### COBOL Mainframe Detection +- Files: COBOL source (`.cbl`), copybooks (`.cpy`), JCL (`.jcl`), BMS maps (`.bms`) +- Dependencies: CICS commands, DB2 SQL, VSAM file operations, MQ Series +- Indicators: `EXEC CICS`, `EXEC SQL`, `COPY` statements, `CALL`/`XCTL` program transfers + ### WebLogic Detection - Files: `weblogic.xml`, `weblogic-application.xml`, `weblogic-ejb-jar.xml` - Dependencies: `weblogic.*`, `oracle.weblogic.*`, `com.bea.*` @@ -67,6 +78,10 @@ Activate by mentioning: - "WebSphere migration" - "WebLogic migration" - "J2EE modernization" +- "COBOL modernization" +- "mainframe migration" +- "COBOL to Java" +- "mainframe to cloud" ### Example @@ -75,7 +90,7 @@ User: analyze this codebase and generate a modernization report ``` The power will: -1. Detect source platform (.NET, WebSphere, or WebLogic) +1. Detect source platform (.NET, WebSphere, WebLogic, or COBOL) 2. Load platform-specific steering file 3. Load common framework files (evaluation, report structure, AWS services) 4. Scan codebase incrementally (context-aware for large projects) @@ -93,7 +108,7 @@ Report structure is defined by `steering/report-structure.md` (single source of 4. **Critical Findings Matrix** - 10+ findings with priorities 5. **Proprietary Dependency Analysis** - License verification, migration examples 6. **Database Analysis** - Detection and migration opportunity -7. **Decision Tree Findings Map** (.NET) - Node-by-node walkthrough showing scanned attributes, findings, and the recommended target platform/architecture path +7. **Decision Tree Findings Map** (.NET / COBOL) - Node-by-node walkthrough showing scanned attributes, findings, and the recommended target platform/architecture path 8. **Recommended Pathways** - 3 pathways with: - Weighted Recommendation Scores (6 factors: Long-term Value, Implementation Risk, Cost Efficiency, Time to Value, Team Readiness, Business Continuity) - Visual dot indicator scoring matrix (●●●●●●●●●○ format) @@ -119,6 +134,8 @@ legacy-app-modernization-analyzer/ ├── report-structure.md # Report format standards (AUTHORITATIVE) ├── aws-target-services.md # AWS service mappings ├── j2ee-to-springboot-reactive.md # J2EE migration patterns + ├── cobol-to-java.md # COBOL → Java 17+ Spring Boot 3.x (includes mechanical data inventory + internal consistency rules) + ├── cobol-analysis-enhancements.md # COBOL analysis supplements (data extraction, business rules, cross-ref) ├── dotnet-to-aws.md # .NET → .NET 8 + AWS ├── websphere-to-springboot.md # WebSphere → Spring Boot └── weblogic-to-springboot.md # WebLogic → Spring Boot @@ -128,6 +145,7 @@ legacy-app-modernization-analyzer/ ### v2.0.0 - Legacy App Modernization Analyzer - Multi-platform support: .NET, WebSphere, WebLogic +- COBOL Mainframe to Java Spring Boot modernization path (BETA) - Platform auto-detection - Spring Boot Reactive target for Java platforms - Consolidated steering files with authoritative report structure diff --git a/legacy-app-modernization-analyzer/steering/cobol-to-java.md b/legacy-app-modernization-analyzer/steering/cobol-to-java.md new file mode 100644 index 0000000..b6ddd4b --- /dev/null +++ b/legacy-app-modernization-analyzer/steering/cobol-to-java.md @@ -0,0 +1,1147 @@ +--- +inclusion: manual +--- + +# COBOL Mainframe to Java Spring Boot Modernization + +## Objective + +Migrate IBM Mainframe COBOL applications (CICS online, batch, DB2, VSAM) to Java 17+ with Spring Boot 3.x, targeting AWS container-based deployments optimized for Graviton processors. + +## Platform Detection + +### COBOL/Mainframe-Specific Files + +- `*.cbl` / `*.cob` - COBOL source programs +- `*.cpy` / `*.CPY` - COBOL copybooks (shared data structures) +- `*.bms` / `*.BMS` - BMS map definitions (CICS screen layouts) +- `*.jcl` / `*.JCL` - Job Control Language (batch scheduling) +- `*.proc` - JCL procedures +- `*.sql` - DB2 SQL DDL and DML scripts +- `*.csd` - CICS resource definitions (CSD) + +### COBOL-Specific Code Patterns + +- `EXEC CICS` - CICS online transaction processing +- `EXEC SQL` - Embedded DB2 SQL +- `COPY` statements - Copybook inclusions +- `CALL` / `EXEC CICS XCTL` / `EXEC CICS LINK` - Inter-program communication +- `EXEC CICS READ` / `WRITE` / `REWRITE` / `DELETE` - VSAM file I/O +- `EXEC CICS SEND MAP` / `RECEIVE MAP` - BMS screen handling +- `EXEC CICS RETURN TRANSID` - Pseudo-conversational control +- `PERFORM` / `PERFORM UNTIL` / `PERFORM VARYING` - Control flow +- `EVALUATE` / `IF` / `WHEN` - Decision logic +- `STRING` / `UNSTRING` / `INSPECT` - String manipulation +- `SORT` / `MERGE` - Data sorting +- `REDEFINES` - Memory overlay / union types + +### COBOL Program Type Classification + +| Indicator | Program Type | Migration Target | +|-----------|-------------|-----------------| +| `EXEC CICS SEND MAP` + `RECEIVE MAP` | CICS Online (Screen) | Spring Boot REST Controller + Web UI | +| `EXEC CICS READ/WRITE` only | CICS Online (Data) | Spring Boot @Service + JPA Repository | +| `EXEC SQL` + no CICS | Batch DB2 | Spring Batch Job + JPA/JDBC | +| JCL with SORT/MERGE utilities | Batch File Processing | Spring Batch Job + FlatFileItemReader | +| `CALL` subroutines only | Utility/Library | Spring @Component / @Service | +| `EXEC CICS XCTL` routing | Menu/Navigation | Spring Boot Controller routing | + + +## COBOL Modernization Decision Tree + +```mermaid +flowchart TD + Start([Start: COBOL Mainframe Application]) + CheckCICS{Uses CICS Online?} + CheckDB2{Uses DB2 Database?} + CheckVSAM{Uses VSAM Files?} + CheckBatch{Has JCL Batch Jobs?} + CheckComplexity{Business Logic Complexity?} + CICSPath[CICS to Spring Boot REST APIs] + DB2Path[DB2 to Aurora PostgreSQL via SCT/DMS] + VSAMPath[VSAM to Aurora PostgreSQL Tables] + BatchPath[JCL/Batch to Spring Batch Jobs] + SimplePath[Simple Refactor: Direct Translation] + ComplexPath[Complex Refactor: Decompose to Microservices] + TargetArch([Target: Spring Boot 3.x + Java 17 on ECS Fargate / Graviton]) + + Start --> CheckCICS + CheckCICS -- Yes --> CICSPath + CheckCICS -- No --> CheckBatch + CheckBatch -- Yes --> BatchPath + CheckBatch -- No --> SimplePath + CICSPath --> CheckDB2 + BatchPath --> CheckDB2 + CheckDB2 -- Yes --> DB2Path + CheckDB2 -- No --> CheckVSAM + DB2Path --> CheckVSAM + CheckVSAM -- Yes --> VSAMPath + CheckVSAM -- No --> CheckComplexity + VSAMPath --> CheckComplexity + CheckComplexity -- High --> ComplexPath + CheckComplexity -- Low/Medium --> SimplePath + ComplexPath --> TargetArch + SimplePath --> TargetArch + + classDef decision fill:#e1f5fe,stroke:#01579b,stroke-width:2px; + classDef process fill:#fff9c4,stroke:#fbc02d,stroke-width:2px; + classDef success fill:#e8f5e9,stroke:#2e7d32,stroke-width:4px; + classDef termination fill:#f9f9f9,stroke:#333,stroke-width:2px; + class Start,TargetArch termination; + class CheckCICS,CheckDB2,CheckVSAM,CheckBatch,CheckComplexity decision; + class CICSPath,DB2Path,VSAMPath,BatchPath,SimplePath,ComplexPath process; +``` + +### Decision Tree Mapping Instructions + +When generating the modernization report, include a Decision Tree Findings Map: + +| Decision Node | What We Scanned | What We Found | Result | +|---------------|-----------------|---------------|--------| +| Uses CICS Online? | `EXEC CICS` commands in .cbl files | _(e.g., "15 CICS programs with SEND/RECEIVE MAP")_ | Yes/No | +| Uses DB2 Database? | `EXEC SQL` statements, SQL DDL files | _(e.g., "8 programs with embedded SQL, 12 tables")_ | Yes/No | +| Uses VSAM Files? | `EXEC CICS READ/WRITE`, VSAM DD statements | _(e.g., "5 VSAM KSDS files identified")_ | Yes/No | +| Has JCL Batch Jobs? | .jcl files, SORT/MERGE utilities | _(e.g., "20 JCL jobs with 45 steps")_ | Yes/No | +| Business Logic Complexity? | Cyclomatic complexity, inter-program calls | _(e.g., "High: 50+ programs, deep call chains")_ | Low/Medium/High | + + +## Migration Strategy Bank + +### Data Type Mapping: COBOL to Java + +| COBOL Type | PIC Clause | Java Type | Notes | +|------------|-----------|-----------|-------| +| Alphanumeric | `PIC X(n)` | `String` | Trim trailing spaces | +| Numeric Display (small) | `PIC 9(1-4)` | `int` | Or `short` for optimization | +| Numeric Display (medium) | `PIC 9(5-9)` | `int` | Standard integer | +| Numeric Display (large) | `PIC 9(10-18)` | `long` | Long integer | +| Signed Binary | `PIC S9(1-9) COMP` | `int` | Binary/COMP/COMP-4 | +| Signed Binary (large) | `PIC S9(10-18) COMP` | `long` | Binary/COMP/COMP-4 | +| Packed Decimal | `PIC S9(n)V9(m) COMP-3` | `BigDecimal` | Critical for financial data | +| Implied Decimal | `PIC 9(n)V9(m)` | `BigDecimal` | Explicit decimal in Java | +| Single Float | `COMP-1` | `float` | Rarely used in business | +| Double Float | `COMP-2` | `double` | Avoid for financial calcs | +| Condition Name | `88 level` | `enum` or `boolean` | Map to Java enums | +| Group Item | `01`/`05` levels | POJO/DTO class | Nested structure to class | +| REDEFINES | Memory overlay | Inheritance/Composition | Analyze actual usage | +| OCCURS | Array/table | `List` or `T[]` | With optional DEPENDING ON | + +### Program Structure Mapping + +| COBOL Construct | Java/Spring Boot Equivalent | +|----------------|---------------------------| +| COBOL Program (.cbl) | Java Class (`@Service` or `@Component`) | +| Paragraph | Java method (camelCase naming) | +| Section | Java class or package grouping | +| WORKING-STORAGE | Instance variables / local variables | +| LINKAGE SECTION | Method parameters / DTOs | +| Copybook (.cpy) | Shared Java class (POJO/DTO) in common package | +| PERFORM paragraph | Method invocation | +| PERFORM UNTIL | `while` / `do-while` loop | +| PERFORM VARYING | `for` loop | +| CALL program | Spring DI + method call on injected service | +| XCTL (transfer control) | Delegate to service, return result | +| EVALUATE / WHEN | `switch` expression (Java 17+) or `if-else` | +| STRING | `StringBuilder.append()` | +| UNSTRING | `String.split()` / regex | +| INSPECT TALLYING | String counting methods | +| INSPECT REPLACING | `String.replace()` / `String.replaceAll()` | +| SORT | `Collections.sort()` / `Stream.sorted()` / SQL `ORDER BY` | +| MOVE | Variable assignment | +| COMPUTE | Arithmetic expression | + + +### CICS to Spring Boot Web + +| CICS Construct | Spring Boot Equivalent | +|---------------|----------------------| +| CICS Transaction (TRANSID) | REST API endpoint (`@RestController`) | +| BMS Map (SEND MAP) | JSON response / HTML template | +| BMS Map (RECEIVE MAP) | `@RequestBody` / `@RequestParam` | +| EXEC CICS READ | JPA `findById()` / Spring Data query | +| EXEC CICS WRITE | JPA `save()` (insert) | +| EXEC CICS REWRITE | JPA `save()` (update) | +| EXEC CICS DELETE | JPA `deleteById()` | +| EXEC CICS STARTBR / READNEXT | JPA paginated query / `findAll(Pageable)` | +| EIBAID (PF keys) | HTTP methods (GET/POST/PUT/DELETE) or action params | +| COMMAREA | DTO / Spring Session / Redis | +| EXEC CICS RETURN TRANSID | Stateless REST (no pseudo-conversational needed) | +| EXEC CICS XCTL | Controller redirect / service delegation | +| EXEC CICS LINK | Service method call (synchronous) | +| RESP / RESP2 codes | Java exceptions + `@ExceptionHandler` | +| DFHCOMMAREA | Request/Response DTO | +| CICS Temporary Storage | Redis / ElastiCache | +| CICS Transient Data | Amazon SQS queue | + +### Data Access Migration + +| COBOL/Mainframe Data | Java/AWS Target | Migration Approach | +|---------------------|----------------|-------------------| +| VSAM KSDS | Aurora PostgreSQL table (PK) | Record layout to JPA @Entity; key to PK | +| VSAM ESDS | Aurora PostgreSQL table (auto-ID) | Sequential to auto-increment ID | +| VSAM RRDS | Aurora PostgreSQL table (int PK) | Relative record to integer PK | +| DB2 Tables | Aurora PostgreSQL | AWS SCT for schema, DMS for data | +| DB2 Stored Procedures | JPA Repository methods / native SQL | Rewrite in Java or PostgreSQL functions | +| DB2 SQLCA | Spring exception handling | Map SQLCODE to Java exceptions | +| Sequential Files | S3 objects / Spring Batch flat files | FlatFileItemReader/Writer | +| GDG (Generation Data Groups) | S3 versioned objects | S3 versioning or timestamped keys | +| EBCDIC encoding | UTF-8 | Charset conversion (CP037 to UTF-8) | + +### Batch Processing Migration + +| JCL/COBOL Batch | Spring Batch / AWS Equivalent | +|----------------|------------------------------| +| JCL Job | Spring Batch `Job` | +| JCL Job Step | Spring Batch `Step` | +| JCL COND parameter | Spring Batch flow decisions (`on()`/`to()`) | +| JCL DD statement | Spring resource config (`application.yml`) | +| JCL SORT utility | SQL `ORDER BY` / Java `Collections.sort()` | +| JCL IEBGENER (copy) | Spring Batch copy step / S3 copy | +| JCL IDCAMS (VSAM utility) | Database DDL / Flyway migrations | +| Checkpoint/Restart | Spring Batch chunk processing + restart | +| COBOL Report Writer | JasperReports / Apache POI | +| CA-7 / TWS Scheduling | AWS Step Functions / EventBridge Scheduler | +| ABEND handling | Spring Batch `SkipPolicy` / `RetryPolicy` | + +### Security Migration + +| Mainframe Security | Spring Boot / AWS Equivalent | +|-------------------|----------------------------| +| RACF | Spring Security + AWS Cognito | +| ACF2 | Spring Security + AWS Cognito | +| Top Secret | Spring Security + AWS Cognito | +| CICS Security (CESN) | Spring Security authentication | +| User ID / Password | Cognito User Pools / OAuth 2.0 | +| Security Groups/Roles | Spring `@PreAuthorize` / Cognito Groups | +| Resource-level security | Spring method security / IAM policies | +| Audit logging | CloudWatch Logs / CloudTrail | + + +## Hybrid Modernization: EC2 Legacy Sidecar Pattern + +In some cases, certain mainframe components cannot be directly migrated to Java. This includes proprietary middleware, hardware-specific interfaces, or third-party mainframe software with no Java equivalent. + +```mermaid +flowchart LR + subgraph Modern["Modernized Stack (ECS/EKS)"] + App["Spring Boot 3.x App
                (Java 17 on Linux Container)"] + end + subgraph Legacy["Legacy Sidecar (EC2 / M2 Replatform)"] + Wrapper["API Wrapper
                (REST/gRPC)"] + Component["Un-modernizable
                Component
                (e.g., Proprietary Middleware,
                Hardware Interfaces)"] + Wrapper --> Component + end + App -- "API Call" --> Wrapper +``` + +When this pattern applies, include in the report: +- List of specific components requiring the legacy sidecar +- Justification for why each component cannot be modernized +- API wrapper design recommendations +- Cost implications of maintaining the EC2/M2 sidecar +- Long-term plan to retire the sidecar + +## COBOL-Specific Risks + +### Proprietary Dependencies + +| Risk | Mitigation | +|------|------------| +| CICS pseudo-conversational model | Replace with stateless REST APIs | +| BMS screen maps | Replace with modern web UI or API-only | +| VSAM file access patterns | Migrate to relational database with JPA | +| DB2 embedded SQL (EXEC SQL) | Convert to Spring Data JPA / native PostgreSQL | +| JCL job scheduling dependencies | Map to Spring Batch + Step Functions | +| EBCDIC character encoding | Convert all data to UTF-8 during migration | +| Packed decimal (COMP-3) precision | Use `BigDecimal` exclusively for financial data | +| COBOL REDEFINES (memory overlays) | Redesign as Java inheritance/composition | +| Mainframe security (RACF/ACF2) | Replace with Spring Security + Cognito | +| Inter-program COMMAREA coupling | Redesign as service interfaces with DTOs | + +### Data Migration Risks + +| Risk | Impact | Mitigation | +|------|--------|------------| +| EBCDIC to UTF-8 data corruption | Data integrity loss | Use validated charset conversion with CP037 codepage | +| Packed decimal precision loss | Financial calculation errors | Map all COMP-3 to BigDecimal, never float/double | +| VSAM key structure mismatch | Query performance degradation | Analyze key patterns, create proper indexes | +| DB2-specific SQL syntax | Query failures on PostgreSQL | Use AWS SCT for automated conversion | +| Implicit decimal points (PIC V) | Calculation errors | Make all decimals explicit in Java | +| REDEFINES data interpretation | Data corruption | Analyze actual usage, create proper Java types | +| GDG versioning semantics | Data loss | Map to S3 versioning or timestamped naming | + + +## Implementation Phases + +### Phase 0: Discovery and Assessment +1. Inventory all COBOL programs, copybooks, JCL jobs, BMS maps +2. Classify programs by type (CICS online, batch, utility, subroutine) +3. Map inter-program dependencies (CALL, XCTL, LINK chains) +4. Identify VSAM files, DB2 tables, and data access patterns +5. Extract and document all business rules (see Business Logic Extraction Framework) +6. Calculate complexity metrics (LOC, cyclomatic complexity, dependency depth) +7. Identify dead code and unused programs for elimination + +### Phase 1: Foundation and Infrastructure +1. Set up Spring Boot 3.x project structure with Java 17 +2. Configure Aurora PostgreSQL database +3. Set up Spring Security with AWS Cognito +4. Create CI/CD pipeline (CodePipeline, CodeBuild) +5. Configure container infrastructure (ECS Fargate, Graviton) +6. Set up Spring Batch infrastructure for batch jobs +7. Create shared DTO/POJO classes from copybooks + +### Phase 2: Data Migration +1. Convert VSAM record layouts to JPA entity classes +2. Generate PostgreSQL schema from VSAM/DB2 structures +3. Use AWS SCT for DB2 to PostgreSQL schema conversion +4. Use AWS DMS for data migration with minimal downtime +5. Convert EBCDIC data to UTF-8 +6. Validate data integrity post-migration +7. Create Flyway migration scripts for schema versioning + +### Phase 3: CICS Online Program Migration +1. Convert BMS maps to REST API endpoint definitions +2. Migrate CICS transaction programs to Spring Boot controllers +3. Convert CICS file I/O to JPA repository operations +4. Replace COMMAREA with DTOs and service interfaces +5. Implement Spring Security for authentication/authorization +6. Replace pseudo-conversational model with stateless REST + +### Phase 4: Batch Job Migration +1. Convert JCL jobs to Spring Batch job definitions +2. Migrate batch COBOL programs to Spring Batch steps +3. Replace JCL SORT/MERGE with Java/SQL equivalents +4. Configure Spring Batch chunk processing for checkpoint/restart +5. Set up AWS Step Functions for job orchestration +6. Configure EventBridge for scheduling + +### Phase 5: Integration and Testing +1. Integration testing of all migrated services +2. Data validation (compare mainframe output vs Java output) +3. Performance testing and optimization +4. Security testing and penetration testing +5. User acceptance testing +6. Parallel run: mainframe and Java side-by-side + +### Phase 6: Cutover and Decommission +1. Production deployment to ECS Fargate +2. DNS/routing cutover +3. Monitor and stabilize +4. Decommission mainframe resources +5. Knowledge transfer and documentation + + +## Code Migration Examples + +### COBOL Copybook to Java Entity + +**Before (COBOL Copybook):** +```cobol + 01 SEC-USER-DATA. + 05 SEC-USR-ID PIC X(08). + 05 SEC-USR-FNAME PIC X(20). + 05 SEC-USR-LNAME PIC X(20). + 05 SEC-USR-PWD PIC X(08). + 05 SEC-USR-TYPE PIC X(01). + 05 SEC-USR-FILLER PIC X(23). +``` + +**After (Java JPA Entity):** +```java +@Entity +@Table(name = "sec_user") +public class SecUser { + @Id + @Column(name = "usr_id", length = 8) + private String userId; + + @Column(name = "usr_fname", length = 20) + private String firstName; + + @Column(name = "usr_lname", length = 20) + private String lastName; + + @Column(name = "usr_pwd", length = 8) + private String password; + + @Column(name = "usr_type", length = 1) + private String userType; +} +``` + +### CICS Transaction to REST Controller + +**Before (COBOL CICS Sign-on):** +```cobol + VALIDATE-USER. + EXEC CICS READ FILE('USRSEC') + INTO(SEC-USER-DATA) + RIDFLD(WS-USER-ID) + RESP(WS-RESP-CD) + END-EXEC. + IF WS-RESP-CD = DFHRESP(NORMAL) + IF SEC-USR-PWD = WS-PASSWORD + PERFORM ROUTE-USER + ELSE + MOVE 'Invalid password' TO WS-MESSAGE + END-IF + ELSE + MOVE 'User not found' TO WS-MESSAGE + END-IF. +``` + +**After (Spring Boot):** +```java +@RestController +@RequestMapping("/api/auth") +public class SignOnController { + private final AuthenticationService authService; + + public SignOnController(AuthenticationService authService) { + this.authService = authService; + } + + @PostMapping("/login") + public ResponseEntity login(@RequestBody LoginRequest request) { + return ResponseEntity.ok( + authService.authenticate(request.getUserId(), request.getPassword())); + } +} +``` + +### JCL Batch Job to Spring Batch + +**Before (JCL):** +```jcl +//DAILYRPT JOB (ACCT),'DAILY REPORT',CLASS=A +//STEP01 EXEC PGM=RPTPGM +//INPUT DD DSN=PROD.TRANS.DAILY,DISP=SHR +//OUTPUT DD DSN=PROD.REPORT.DAILY,DISP=(NEW,CATLG) +``` + +**After (Spring Batch):** +```java +@Configuration +public class DailyReportJobConfig { + @Bean + public Job dailyReportJob(JobRepository jobRepository, Step processStep) { + return new JobBuilder("dailyReportJob", jobRepository) + .start(processStep).build(); + } + + @Bean + public Step processStep(JobRepository repo, PlatformTransactionManager tx) { + return new StepBuilder("processTransactions", repo) + .chunk(100, tx) + .reader(transactionReader()) + .processor(reportProcessor()) + .writer(reportWriter()) + .build(); + } +} +``` + + +## AWS Target Architecture + +```mermaid +graph TB + subgraph "Current State: Mainframe" + MF[IBM Mainframe z/OS] + CICS[CICS Transaction Server] + COBOL[COBOL Programs] + DB2[(DB2 Database)] + VSAM[(VSAM Files)] + JCL[JCL Batch Jobs] + RACF[RACF Security] + BMS[BMS Screens] + end + + subgraph "Target State: AWS" + ECS[Amazon ECS Fargate / Graviton] + SB[Spring Boot 3.x / Java 17] + RDS[(Amazon Aurora PostgreSQL)] + BATCH[Spring Batch on ECS] + SF[AWS Step Functions] + COG[Amazon Cognito] + S3[(Amazon S3)] + SQS[Amazon SQS] + CW[Amazon CloudWatch] + ALB[Application Load Balancer] + end + + MF --> ECS + CICS --> SB + COBOL --> SB + DB2 --> RDS + VSAM --> RDS + JCL --> BATCH + JCL --> SF + RACF --> COG + BMS --> ALB + + style MF fill:#ff6b6b + style CICS fill:#ff6b6b + style COBOL fill:#ff6b6b + style DB2 fill:#ffa94d + style VSAM fill:#ffa94d + style JCL fill:#ff6b6b + style RACF fill:#ffa94d + style BMS fill:#ff6b6b + style ECS fill:#69db7c + style SB fill:#69db7c + style RDS fill:#74c0fc + style BATCH fill:#69db7c + style SF fill:#74c0fc + style COG fill:#74c0fc + style S3 fill:#74c0fc + style SQS fill:#74c0fc + style CW fill:#74c0fc + style ALB fill:#74c0fc +``` + +## Validation Criteria + +1. Zero COBOL/CICS/JCL dependencies in final Java build +2. All VSAM data migrated to Aurora PostgreSQL with integrity verified +3. All DB2 data migrated to Aurora PostgreSQL via SCT + DMS +4. All CICS transactions converted to REST API endpoints +5. All batch jobs converted to Spring Batch with Step Functions orchestration +6. Spring Security + Cognito replaces RACF/ACF2 authentication +7. All financial calculations use `BigDecimal` (never float/double) +8. All data converted from EBCDIC to UTF-8 +9. Container runs on both x86_64 and ARM64 (Graviton) +10. Comprehensive test coverage: unit, integration, regression, performance +11. Parallel run validation: mainframe output matches Java output + +## Recommended Tools + +| Tool | Purpose | Priority | +|------|---------|----------| +| AWS Transform for Mainframe | End-to-end COBOL to Java refactoring with AI agents | 1st | +| AWS Mainframe Modernization (Blu Age) | Automated COBOL to Java code transformation | 2nd | +| AWS Mainframe Modernization (Micro Focus / Rocket) | Replatform: run COBOL on AWS without rewriting | Alternative | +| AWS Schema Conversion Tool (SCT) | DB2 to PostgreSQL schema conversion | For DB migration | +| AWS Database Migration Service (DMS) | Data migration with minimal downtime | For DB migration | +| Kiro | AI-assisted code migration, refactoring, test generation | Throughout all phases | +| Spring Batch | Batch job framework replacing JCL/COBOL batch | Core framework | +| AWS Step Functions | Batch job orchestration replacing mainframe schedulers | Orchestration | +| Amazon EventBridge Scheduler | Cron-based job scheduling replacing CA-7/TWS | Scheduling | + +**Tool Selection Guidance:** +- For full AI-driven refactoring (COBOL to Java): Use AWS Transform for Mainframe +- For automated code transformation: Use AWS Mainframe Modernization (Blu Age) +- For replatforming without rewrite: Use AWS Mainframe Modernization (Micro Focus/Rocket) +- For database migration (DB2 to Aurora PostgreSQL): Use SCT + DMS +- For incremental migration with AI assistance: Use Kiro throughout + + +## COBOL-Specific Evaluation Areas (Beyond Standard Framework) + +The standard evaluation framework (evaluation-framework.md) covers universal areas. The following are COBOL/mainframe-specific evaluation areas that MUST be assessed in addition to provide modernization specialists with the evidence they need to plan effectively. + +### Reverse Engineering Readiness + +Successful COBOL modernization has two halves: reverse engineering (understanding what exists) and forward engineering (building the new system). Thorough reverse engineering is the foundation for a well-planned modernization. Assess: + +- Are all COBOL programs, copybooks, JCL jobs, and BMS maps inventoried? +- Are inter-program dependencies (CALL, XCTL, LINK chains) fully mapped? +- Are all implicit dependencies (copybooks, shared files, JCL orchestration) resolved? +- Is there a deterministic model of the application landscape? +- Has dead code been identified for elimination (typically 20-40% of codebase)? + +### Platform-Specific Compiler Behavior + +The same COBOL source code behaves differently depending on the compiler and runtime. These behaviors are NOT in the source code and must be documented for modernization specialists: + +| Behavior | Consideration | Specialist Guidance | +|----------|--------------|-------------------| +| Number rounding rules | Financial calculation accuracy depends on compiler-specific rounding | Document compiler-specific rounding; replicate in Java | +| EBCDIC collating sequence | Sort/comparison logic may produce different results in ASCII/UTF-8 | Test all comparison and sort logic explicitly | +| Memory layout (COMP, COMP-3) | Data interpretation depends on platform-specific storage format | Map all data types precisely to Java equivalents | +| Packed decimal handling | Precision in financial data requires exact mapping | Use BigDecimal exclusively; validate at boundary values | +| REDEFINES memory overlays | Multiple interpretations of same memory area | Analyze actual usage patterns; create proper Java types | + +### Undocumented Business Rules (Tribal Knowledge) + +Business logic embedded in COBOL programs is often the most valuable asset in the system. Modernization specialists need a clear picture of how well this logic is documented: + +- Are subject matter experts (SMEs) available who understand the business rules? +- Can business rules be extracted and validated before migration? +- Is there a business rule traceability matrix? +- What percentage of business logic is documented vs undocumented? +- Are there retired or soon-to-retire staff whose knowledge should be captured? + +### Regulatory Compliance Considerations + +Modernization specialists need to understand the compliance landscape to plan the migration approach: + +| Regulation | Consideration | What Specialists Need | +|------------|--------------|---------------------| +| SOX (Sarbanes-Oxley) | Audit trails, access controls, change management | Current audit logging patterns and how to preserve them | +| PCI DSS | Encryption, monitoring, vulnerability management | Payment data flows and current security controls | +| GDPR / Privacy | Data sovereignty, PII protection | PII field inventory and data residency requirements | +| HIPAA | PHI protection, access controls | PHI data flows and encryption requirements | +| Industry-specific | Banking (GLBA), Insurance, Government (FISMA) | Current compliance control mappings | + +### Performance and Operational Baseline + +Establishing the current performance baseline gives modernization specialists the targets they need to design the right architecture: + +| Metric | What to Capture | Why It Matters | +|--------|----------------|---------------| +| Transaction latency | Current response times for key transactions | Sets the performance target for the Java system | +| Transaction throughput | Peak and average TPS | Determines infrastructure sizing | +| Batch window | Current batch completion times and deadlines | Defines parallelization requirements for Spring Batch | +| Checkpoint/restart | Current restart granularity | Determines Spring Batch chunk sizing | +| Availability SLA | Current uptime requirements | Drives multi-AZ and DR architecture decisions | + +### Coexistence and Migration Strategy Considerations + +For large mainframe portfolios, modernization specialists will need to design a coexistence architecture. Provide evidence on: + +- Can the application be decomposed into independently migratable modules? +- What downstream systems consume mainframe data (file feeds, MQ, APIs)? +- What upstream systems feed data into the mainframe? +- What integration patterns exist (CICS Transaction Gateway, MQ, ESB, file transfers)? +- Is there a natural decomposition boundary for incremental migration? + +```mermaid +flowchart LR + subgraph Facade["API Gateway / Facade"] + Router[Request Router] + end + subgraph Legacy["Mainframe (Shrinking)"] + COBOL[COBOL Programs] + VSAM[(VSAM/DB2)] + end + subgraph Modern["AWS (Growing)"] + Java[Spring Boot Services] + Aurora[(Aurora PostgreSQL)] + end + subgraph Sync["Data Sync"] + CDC[CDC / DMS] + end + + Router -- "Legacy Routes" --> COBOL + Router -- "Migrated Routes" --> Java + VSAM <-- "Sync" --> CDC + CDC <-- "Sync" --> Aurora + + style Legacy fill:#ffa94d + style Modern fill:#69db7c + style Facade fill:#74c0fc + style Sync fill:#ffd43b +``` + + +### Mainframe Cost Baseline + +Establishing the current cost baseline enables modernization specialists to build accurate ROI models: + +| Cost Component | Description | Typical Impact | +|---------------|-------------|---------------| +| MIPS/MSU consumption | IBM processor-based licensing | Very High — escalates with workload growth | +| z/OS licensing | Operating system license fees | High — tied to MIPS | +| CICS licensing | Transaction server license | High — per-MIPS pricing | +| DB2 licensing | Database license fees | High — per-MIPS pricing | +| ISV software | Third-party tools (monitoring, middleware) | Medium to High — often MIPS-based | +| Hardware maintenance | IBM hardware support contracts | High — increases with age | +| Facility costs | Power, cooling, floor space | Medium — significant if last mainframe workload | +| DR costs | Secondary mainframe or DR contract | High — often 50-70% of primary cost | +| Staff costs | Specialized mainframe operators and programmers | High — premium salaries, shrinking talent pool | + +### Organizational Readiness Assessment + +Modernization specialists need to understand the team landscape to recommend the right approach and timeline: + +| Factor | Evidence to Capture | +|--------|-------------------| +| COBOL expertise | Number of COBOL-skilled staff, retirement timeline, knowledge documentation status | +| Java/Spring Boot skills | Current Java team size, training plans, hiring pipeline | +| Dual-skilled resources | Staff who understand both COBOL and Java (bridge resources) | +| Operations team | Current monitoring/ops practices, cloud-native readiness | +| Business stakeholder availability | SME availability for business rule validation and UAT | +| Executive sponsorship | Funding model, multi-year commitment, organizational priority | +| Change management | Existing change management processes and readiness | + +### Testing Strategy Considerations (COBOL-Specific) + +Modernization specialists need to understand the testing landscape to plan validation: + +| Test Type | Purpose | Approach | +|-----------|---------|----------| +| Output equivalence | Prove Java output matches mainframe | Automated field-by-field comparison | +| EBCDIC sort order | Validate comparison/sort logic | Test all >, <, >=, <= operations | +| Numeric boundary | Validate data type conversions | Test at PIC clause boundaries, signed/unsigned | +| Financial precision | Validate decimal/rounding accuracy | Compare every financial calculation to penny | +| Batch chain | Validate multi-step job sequences | End-to-end batch chain with restart scenarios | +| Performance/stress | Validate throughput under load | Production-equivalent volume testing | +| Parallel run | Final validation before cutover | Run both systems simultaneously, compare outputs | +| Test data capture | Enable all above testing | Capture production data and scenarios from day one | + + +## Business Logic Extraction Framework + +This section defines how to exhaustively extract, categorize, and document ALL business logic from COBOL programs. This is the most critical input to the modernization report — without a complete business logic inventory, modernization specialists cannot plan effectively. + +### Extraction Approach + +For EVERY COBOL program in scope, analyze the PROCEDURE DIVISION line by line and extract business rules into the categories below. Each rule must reference the specific paragraph name and code location where it is implemented. + +### Category 1: Input Validation Rules + +Extract ALL data validation logic — every field check, format validation, and required-field enforcement. + +| Rule ID | Field Name | Validation Type | Condition | Error Action | Source Location | +|---------|-----------|----------------|-----------|-------------|-----------------| +| VR-nnn | Field being validated | Required / Format / Range / Cross-field / Referential | Exact condition from code | Error message and recovery action | Paragraph name | + +Look for: required field checks (spaces, low-values, zeros), numeric range validation, format validation (date formats, alphanumeric patterns), cross-field validation, referential validation, length validation, character set validation, business constraint validation. + +### Category 2: Calculation and Processing Rules + +Extract ALL business calculations, formulas, data transformations, and processing logic. + +| Rule ID | Rule Description | Formula/Logic | Input Fields | Output Fields | Rounding/Precision | Source Location | +|---------|-----------------|---------------|-------------|--------------|-------------------|-----------------| +| PR-nnn | What the calculation does | Exact formula or COMPUTE statement | Fields used as input | Fields that receive results | Rounding rules if any | Paragraph name | + +Look for: arithmetic (COMPUTE, ADD, SUBTRACT, MULTIPLY, DIVIDE), rounding rules (ROUNDED keyword), accumulation logic, data transformation, date calculations, rate calculations, proration/allocation, currency formatting. + +### Category 3: Decision and Routing Rules + +Extract ALL conditional logic that determines program flow, user routing, or business outcomes. + +| Rule ID | Condition | True Action | False Action | Business Meaning | Source Location | +|---------|-----------|-------------|-------------|-----------------|-----------------| +| DR-nnn | Exact condition from EVALUATE/IF | Action when true | Action when false | Business interpretation | Paragraph name | + +Look for: EVALUATE statements (all WHEN clauses), IF/ELSE chains (every branch), 88-level condition name usage, EIBAID processing (every PF key), user type routing, status-based branching, threshold-based decisions, priority/precedence logic. + +### Category 4: Data Access Rules + +Extract ALL file/database access patterns, including keys, access modes, and business context. + +| Rule ID | Resource | Operation | Key/Criteria | Success Logic | Failure Logic | Business Purpose | Source Location | +|---------|----------|-----------|-------------|--------------|--------------|-----------------|-----------------| +| DA-nnn | File or table name | READ/WRITE/REWRITE/DELETE/STARTBR | Key field(s) | What happens on success | What happens on error | Why this access exists | Paragraph name | + +Look for: VSAM KSDS reads, browse operations (STARTBR/READNEXT/READPREV), writes, rewrites, deletes, DB2 SELECT/INSERT/UPDATE/DELETE, cursor processing, sequential file I/O, file status code handling. + +### Category 5: Inter-Program Communication Rules + +Extract ALL data passed between programs and the business rules governing that communication. + +| Rule ID | Source Program | Target Program | Transfer Method | Data Passed | Business Purpose | Conditions | Source Location | +|---------|---------------|---------------|----------------|------------|-----------------|-----------|-----------------| +| IC-nnn | Calling program | Called program | CALL/XCTL/LINK | COMMAREA fields or parameters | Why this transfer occurs | When this transfer happens | Paragraph name | + +Look for: COMMAREA field population/consumption, program routing logic, return code handling, session/context propagation, error propagation between programs. + + +### Category 6: Error Handling and Recovery Rules + +Extract ALL error conditions, error messages, and recovery procedures. + +| Rule ID | Error Condition | Error Source | User Message | Recovery Action | Severity | Source Location | +|---------|----------------|-------------|-------------|----------------|----------|-----------------| +| EH-nnn | What triggers the error | CICS RESP / FILE STATUS / business condition | Exact message text | What the program does to recover | Critical/Warning/Info | Paragraph name | + +Look for: CICS RESP/RESP2 handling, FILE STATUS handling, DB2 SQLCODE handling, business rule violations, resource unavailable errors, ABEND handling, error message literals, cursor positioning on error, error flag setting. + +### Category 7: Screen/Interface Rules (CICS Programs) + +Extract ALL screen interaction logic for BMS-based CICS programs. + +| Rule ID | Map/Field | Direction | Business Rule | Attribute Control | Source Location | +|---------|----------|-----------|--------------|-------------------|-----------------| +| SR-nnn | Map name and field name | Input/Output | What the field does and its constraints | Color, protection, cursor positioning | Paragraph name | + +Look for: initial screen display logic, field population logic, field attribute manipulation, cursor positioning, screen clearing, message area population, PF key labeling, screen flow sequences. + +### Category 8: Batch Processing Rules (Batch Programs) + +Extract ALL batch-specific business logic for JCL/batch COBOL programs. + +| Rule ID | Job/Step | Rule Description | Input | Output | Condition | Source Location | +|---------|---------|-----------------|-------|--------|-----------|-----------------| +| BR-nnn | JCL job and step name | What the batch rule does | Input files/parameters | Output files/reports | When this rule applies | Paragraph name | + +Look for: record selection criteria, sort/merge criteria, control break logic, report formatting rules, checkpoint/restart logic, file matching logic, accumulation/summarization, date-based processing, conditional step execution, return code propagation. + +### Category 9: Security and Authorization Rules + +Extract ALL security-related business logic. + +| Rule ID | Security Function | Mechanism | Condition | Action | Source Location | +|---------|------------------|-----------|-----------|--------|-----------------| +| SEC-nnn | What security function | How it is implemented | When it applies | What happens | Paragraph name | + +Look for: user authentication logic, user authorization logic, resource-level security, password validation rules, session management, audit trail generation, data masking/redaction, encryption/decryption. + +### Category 10: Temporal and State Management Rules + +Extract ALL time-based logic and state management patterns. + +| Rule ID | Rule Description | Time/State Element | Condition | Action | Source Location | +|---------|-----------------|-------------------|-----------|--------|-----------------| +| TM-nnn | What the rule does | Date field, status field, or state flag | When it triggers | What happens | Paragraph name | + +Look for: date-based business rules, status transitions, aging calculations, scheduling logic, pseudo-conversational state management, flag-based state tracking, counter-based logic. + +### Extraction Completeness Checklist + +For each COBOL program analyzed, verify: +- [ ] Every EVALUATE statement has ALL WHEN clauses documented +- [ ] Every IF/ELSE chain has ALL branches documented (including ELSE) +- [ ] Every 88-level condition name usage is documented with business meaning +- [ ] Every EXEC CICS command is documented with its business purpose +- [ ] Every EXEC SQL statement is documented with its business purpose +- [ ] Every PERFORM target paragraph has its business logic extracted +- [ ] Every file READ/WRITE/REWRITE/DELETE has success AND failure paths documented +- [ ] Every error message literal is captured exactly as coded +- [ ] Every COMMAREA field has its population and consumption logic documented +- [ ] Every CALL/XCTL/LINK has its conditions and data passing documented +- [ ] Every COMPUTE/ADD/SUBTRACT/MULTIPLY/DIVIDE has its formula documented +- [ ] Every MOVE that transforms data (not just copies) is documented +- [ ] Every STRING/UNSTRING operation is documented +- [ ] Every INSPECT operation is documented +- [ ] Dead code paths are identified and marked as candidates for elimination + + +### Business Logic Summary Table (Per Program) + +After extraction, produce a summary for each program: + +| Category | Rule Count | Critical | High | Medium | Low | +|----------|-----------|----------|------|--------|-----| +| Input Validation | [count] | [count] | [count] | [count] | [count] | +| Calculation/Processing | [count] | [count] | [count] | [count] | [count] | +| Decision/Routing | [count] | [count] | [count] | [count] | [count] | +| Data Access | [count] | [count] | [count] | [count] | [count] | +| Inter-Program Communication | [count] | [count] | [count] | [count] | [count] | +| Error Handling | [count] | [count] | [count] | [count] | [count] | +| Screen/Interface | [count] | [count] | [count] | [count] | [count] | +| Batch Processing | [count] | [count] | [count] | [count] | [count] | +| Security/Authorization | [count] | [count] | [count] | [count] | [count] | +| Temporal/State Management | [count] | [count] | [count] | [count] | [count] | +| **Total** | **[total]** | **[total]** | **[total]** | **[total]** | **[total]** | + +Criticality levels: +- Critical: Rule failure causes data corruption, financial loss, or security breach +- High: Rule failure causes incorrect business outcomes or user-facing errors +- Medium: Rule failure causes degraded functionality or workaround needed +- Low: Rule failure causes cosmetic issues or minor inconvenience + +### Business Logic Dependency Map + +After extracting all rules, produce a cross-program dependency map showing which business rules span multiple programs: + +```mermaid +graph TD + subgraph "Authentication Rules" + VR1[VR-001: User ID Validation] + VR2[VR-002: Password Validation] + DA1[DA-001: USRSEC File Read] + end + subgraph "Routing Rules" + DR1[DR-001: User Type Check] + IC1[IC-001: Admin Program Transfer] + IC2[IC-002: User Program Transfer] + end + subgraph "Session Rules" + IC3[IC-003: COMMAREA Population] + TM1[TM-001: Session State Setup] + end + + VR1 --> DA1 + VR2 --> DA1 + DA1 --> DR1 + DR1 --> IC1 + DR1 --> IC2 + IC1 --> IC3 + IC2 --> IC3 + IC3 --> TM1 +``` + +This diagram must be generated from actual extracted rules, showing the real dependency chain of business logic across the application. + +### Migration Impact Assessment Per Business Rule + +For each extracted business rule, assess migration impact to help modernization specialists prioritize: + +| Rule ID | Rule Description | Migration Complexity | Java Pattern | Specialist Attention | Notes | +|---------|-----------------|---------------------|-------------|---------------------|-------| +| VR-001 | User ID required | Low | Bean Validation `@NotBlank` | Standard | Direct mapping | +| PR-001 | Interest calculation | High | `BigDecimal` with specific rounding | Precision validation required | Must validate rounding behavior | +| DR-001 | User type routing | Medium | Spring Security roles | Role model design | May require role model redesign | +| DA-001 | VSAM key read | Medium | JPA `findById()` | Key structure review | Key structure may change | +| EH-001 | RESP code 13 handling | Low | `@ExceptionHandler` | Standard | Direct mapping | + +This table connects business logic extraction directly to migration planning, making it actionable for the modernization team. + +## Mechanical Data Inventory Extraction + +Use targeted regex searches across the entire codebase FIRST, then read specific files only for detail. Every inventory must be cross-referenced against at least two independent sources. + +### VSAM File Inventory (must match CSD + LISTCAT + program usage) + +**Source 1 — CSD file definitions:** `grepSearch: query="DEFINE FILE" includePattern="**/*.csd"` +**Source 2 — LISTCAT metadata:** `grepSearch: query="CLUSTER|KEYLEN|AVGLRECL|MAXLRECL|REC-TOTAL" includePattern="**/LISTCAT*"` +**Source 3 — AIX and PATH:** `grepSearch: query="^0AIX|^0PATH" includePattern="**/LISTCAT*"` +**Cross-reference:** `grepSearch: query="DATASET|FILE" includePattern="**/*.cbl"` + +Completeness check: DEFINE FILE count in CSD must match VSAM clusters in LISTCAT. Every CSD file must appear in at least one program. + +Output table (REQUIRED): CICS File | VSAM Dataset | Type | Key Len | Rec Len | Records | Programs | PostgreSQL Target + +### Batch Data File Inventory + +Scan data directories, cross-reference with JCL DD statements, match to copybook record layouts. + +Output table (REQUIRED): File Name | Format | Record Layout Copybook | Record Length | JCL Jobs | PostgreSQL Target + +### DB2 Table Inventory (must match DDL + DCL + program SQL) + +**Source 1 — DDL:** `grepSearch: query="CREATE TABLE" includePattern="**/*.ddl"` +**Source 2 — DCL:** `grepSearch: query="EXEC SQL DECLARE.*TABLE" includePattern="**/*.dcl"` +**Source 3 — Embedded SQL:** `grepSearch: query="EXEC SQL" includePattern="**/*.cbl"` +**Source 4 — SQL INCLUDE:** `grepSearch: query="EXEC SQL.*INCLUDE" includePattern="**/*.cbl"` + +Completeness check: Every DDL table must have a DCL. Every program SQL table must appear in DDL. Every DCL INCLUDE must resolve. + +Output table (REQUIRED): Table | Columns | Primary Key | Foreign Keys | DDL File | Programs | SQL Operations + +### IMS Database Inventory + +Search for: `*.dbd`, `*.psb`, `CBLTDLI|AIBTDLI` in .cbl files. + +### MQ Queue Inventory + +Search for: `MQGET|MQPUT|MQPUT1|MQOPEN|MQCLOSE` and queue name patterns in .cbl files. + +### Exhaustive Copybook Data Type Mapping + +Step 1: List ALL copybooks in every cpy directory. +Step 2: Read EVERY copybook — extract 01-level record, all fields with PIC clauses, all 88-levels, all REDEFINES. +Step 3: Map EVERY field using conversion table: + +| PIC Pattern | PostgreSQL | Java | Notes | +|-------------|-----------|------|-------| +| `X(n)` | VARCHAR(n) | String | | +| `9(1-4)` | SMALLINT | int | | +| `9(5-9)` | INTEGER | int | | +| `9(10-18)` | BIGINT | long | | +| `S9(n)V9(m)` | NUMERIC(n+m,m) | BigDecimal | Financial — CRITICAL | +| `S9(n) COMP` | INTEGER/BIGINT | int/long | Binary storage | +| `S9(n) COMP-3` | NUMERIC | BigDecimal | Packed decimal | +| `X(10)` with DATE in name | DATE | LocalDate | | +| `X(26)` with TS in name | TIMESTAMP | Instant | | + +Step 4: Cross-reference copybooks to programs via `grepSearch: query="COPY " includePattern="**/*.cbl"`. + +Completeness check: Every copybook must have a data type mapping table. Every COPY statement must resolve. + +Output (REQUIRED): One data type mapping table PER copybook showing every field. + +### CICS Transaction Inventory (must match CSD + menu copybooks + programs) + +**Source 1 — CSD transactions:** `grepSearch: query="DEFINE TRANSACTION" includePattern="**/*.csd"` +**Source 2 — CSD programs:** `grepSearch: query="DEFINE PROGRAM" includePattern="**/*.csd"` +**Source 3 — Menu copybooks:** `grepSearch: query="CDEMO-MENU-OPT|CDEMO-ADMIN-OPT" includePattern="**/*.cpy"` +**Source 4 — BMS mapsets:** `grepSearch: query="DEFINE MAPSET" includePattern="**/*.csd"` + +Output tables (REQUIRED): +1. Online Transactions: Trans ID | Program | Function | REST API Target +2. Regular User Menu Options: # | Option | Program | Access Level +3. Admin Menu Options: # | Option | Program +4. Batch Programs: Program | Function | Spring Batch Target +5. Sub-Application Programs: Program | Sub-App | Function + +## Mechanical Business Rule Extraction Procedures + +The Business Logic Extraction Framework (above) defines 10 categories. This section specifies HOW to mechanically find every rule using codebase-wide searches. Use these searches FIRST, then read surrounding context only where needed. + +### Procedure for Input Validation Rules + +1. Required fields: `grepSearch: query="= SPACES|= LOW-VALUES|= ZEROS" includePattern="**/*.cbl"` +2. Numeric validation: `grepSearch: query="IS NOT NUMERIC|IS NUMERIC" includePattern="**/*.cbl"` +3. Validation flags: `grepSearch: query="88.*FLG-.*VALUE" includePattern="**/*.cbl"` +4. Range/list validations: `grepSearch: query="VALUES.*THRU|88.*VALUES '" includePattern="**/*.cpy"` +5. EVALUATE TRUE blocks: `grepSearch: query="EVALUATE TRUE" includePattern="**/*.cbl"` — read 30-50 lines context +6. Error messages (confirms validations): `grepSearch: query="MOVE '.*' TO WS-MESSAGE|MOVE '.*' TO WS-RETURN-MSG" includePattern="**/*.cbl"` + +Completeness: validation rule count must be >= distinct error message count. + +### Procedure for Calculation/Processing Rules + +1. All arithmetic: `grepSearch: query="COMPUTE |ADD .* TO |SUBTRACT .* FROM |MULTIPLY .* BY |DIVIDE .* BY " includePattern="**/*.cbl"` +2. Financial fields (CRITICAL): `grepSearch: query="CURR-BAL|CREDIT-LIMIT|TRAN-AMT|INT-RATE|CAT-BAL|PAGE-TOTAL|GRAND-TOTAL" includePattern="**/*.cbl"` +3. FUNCTION calls: `grepSearch: query="FUNCTION " includePattern="**/*.cbl"` +4. String operations: `grepSearch: query="STRING |UNSTRING |INSPECT " includePattern="**/*.cbl"` +5. Report formatting: `grepSearch: query="PIC .*Z.*\\.|PIC \\+|PIC -" includePattern="**/*.cbl"` + +Completeness: every COMPUTE/ADD/SUBTRACT/MULTIPLY/DIVIDE must appear as a rule. + +### Procedure for Decision/Routing Rules + +1. XCTL transfers: `grepSearch: query="XCTL PROGRAM" includePattern="**/*.cbl"` +2. LINK calls: `grepSearch: query="EXEC CICS LINK" includePattern="**/*.cbl"` +3. PF key handling: `grepSearch: query="EIBAID|DFHENTER|DFHPF" includePattern="**/*.cbl"` +4. User type routing: `grepSearch: query="USRTYP-ADMIN|USRTYP-USER|USR-TYPE" includePattern="**/*.cbl"` +5. Menu option tables: `grepSearch: query="OPT-PGMNAME|OPT-NAME|OPT-COUNT" includePattern="**/*.cpy"` + +### Procedure for Data Access Rules + +1. All CICS file I/O: `grepSearch: query="EXEC CICS (READ|WRITE|REWRITE|DELETE|STARTBR|READNEXT|READPREV|ENDBR)" includePattern="**/*.cbl"` +2. All DB2 SQL: `grepSearch: query="EXEC SQL" includePattern="**/*.cbl"` +3. MQ operations: `grepSearch: query="CALL 'MQ" includePattern="**/*.cbl"` +4. TD/TS queues: `grepSearch: query="WRITEQ TD|READQ TD|WRITEQ TS|READQ TS" includePattern="**/*.cbl"` +5. Batch file I/O: `grepSearch: query="OPEN |CLOSE |READ |WRITE " includePattern="**/CB*.cbl"` + +### Procedure for Security Rules + +1. Password handling: `grepSearch: query="USR-PWD|PASSWORD|PASSWD" includePattern="**/*.cbl"` +2. User type checks: `grepSearch: query="USRTYP|USR-TYPE|USER-TYPE" includePattern="**/*.cbl"` +3. Session context: `grepSearch: query="CDEMO-USER-ID|CDEMO-FROM-PROGRAM|CDEMO-TO-PROGRAM" includePattern="**/*.cbl"` +4. CSD security: `grepSearch: query="RESSEC|CMDSEC" includePattern="**/*.csd"` + +### Procedure for Error Handling Rules + +1. CICS RESP: `grepSearch: query="RESP\\(|DFHRESP" includePattern="**/*.cbl"` +2. Error messages: `grepSearch: query="MOVE '.*' TO WS-MESSAGE|MOVE '.*' TO WS-RETURN-MSG|MOVE '.*' TO ERRMSGO" includePattern="**/*.cbl"` +3. 88-level messages: `grepSearch: query="88.*VALUE$" includePattern="**/*.cbl"` +4. ABEND handling: `grepSearch: query="HANDLE ABEND|ABEND-CODE" includePattern="**/*.cbl"` +5. DB2 SQLCODE: `grepSearch: query="SQLCODE|SQLCA" includePattern="**/*.cbl"` +6. MQ errors: `grepSearch: query="MQ-REASON-CODE|MQ-CONDITION-CODE|MQRC-" includePattern="**/*.cbl"` +7. Batch file status: `grepSearch: query="FILE-STATUS|STATUS = '00'|STATUS NOT" includePattern="**/*.cbl"` + +Completeness: every error message literal must appear as an EH rule. + +### Procedure for Batch Processing Rules + +1. JCL programs: `grepSearch: query="EXEC PGM=" includePattern="**/*.jcl"` +2. JCL datasets: `grepSearch: query="DD.*DSN=" includePattern="**/*.jcl"` +3. Sort/merge: `grepSearch: query="SORT|MERGE|DFSORT" includePattern="**/*.jcl"` + +### Expected Rule Counts (Quality Gate) + +For a typical COBOL/CICS application (~40 programs, ~30 copybooks, ~40 JCL jobs): + +| Category | Expected Minimum | If Below, Re-run Searches | +|----------|-----------------|--------------------------| +| Input Validation | 25-40 | Re-scan EVALUATE TRUE blocks and error messages | +| Calculation/Processing | 10-20 | Re-scan all COMPUTE/ADD/SUBTRACT and financial fields | +| Decision/Routing | 5-15 | Re-read all menu copybooks and XCTL calls | +| Data Access | 25-40 | Re-scan all VSAM files x all programs, all DB2 SQL | +| Security | 3-8 | Re-scan password handling and user type checks | +| Error Handling | 10-25 | Re-capture all error message literals | +| **Total** | **80-150** | If total < 80, extraction is incomplete | + +## Report Internal Consistency Rules + +When generating or editing a COBOL/Mainframe modernization report, every inventory and analysis section MUST be internally consistent, non-contradictory, complete, and explainable. A reader must be able to follow a clear rationale from any summary table to its corresponding detail section without encountering unexplained gaps or mismatched numbers. + +### General Business Logic Consistency Principles + +1. **Summary-to-Detail Traceability**: Every summary table row MUST have a corresponding detail subsection. Every number in a summary table MUST be verifiable by counting rows in the detail tables. +2. **No Phantom Categories**: If a summary table lists N categories, there MUST be exactly N detail subsections — no more, no fewer. +3. **No Phantom Counts**: If a summary table claims X rules/items in a category, the detail subsection MUST contain exactly X rows. +4. **Consistent Naming**: Category names in summary tables MUST match subsection headings exactly. Do not use "Financial Calculation Rules" in a detail heading if the summary table says "Calculation/Processing". +5. **Severity Breakdown Verification**: If a summary table has columns for severity levels (Critical/High/Medium/Low), each detail subsection heading MUST declare its breakdown (e.g., "4 Critical, 10 High, 8 Medium, 6 Low = 28 total") and the individual rule rows MUST include a Severity column so the counts are independently verifiable. +6. **Cross-Total Verification**: Row totals (Critical+High+Medium+Low) MUST equal the Rule Count column. Column totals MUST equal the Total row. The grand total MUST equal the sum of all category Rule Counts. +7. **Source Traceability**: Every rule, data access pattern, or inventory item MUST cite a specific source program, copybook, DDL file, or JCL job that can be found in the codebase. + +### Business Logic Summary & Key Business Rules Consistency + +#### Structure Requirements + +- The summary table MUST list ALL categories with columns: Category, Rule Count, Critical, High, Medium, Low. +- The "Key Business Rules Extracted" section MUST contain one subsection per category row. +- Each subsection MUST list exactly the number of rules claimed in the summary table for that category. +- Each rule row MUST have: Rule ID (unique, sequential within category), Severity, description columns, and Source (program name). +- The severity values in each row MUST match the counts declared in the subsection heading and the summary table. + +#### Methodology Note Requirements + +- A methodology note MUST explain what was scanned (source file types), what constitutes a "rule", and the total count. +- The total count in the methodology note MUST match the summary table grand total. +- Do NOT reference a different number than what the summary table shows. + +#### What Counts as a Business Rule + +Each rule must be a distinct, identifiable construct from the source code: +- **Input Validation**: An explicit check (IF/EVALUATE) that rejects or flags invalid input — one rule per distinct validation check. +- **Calculation/Processing**: An arithmetic operation (ADD, COMPUTE, SUBTRACT) or implied-decimal field definition requiring BigDecimal mapping — one rule per distinct calculation or critical field. +- **Decision/Routing**: An EVALUATE or IF that determines program flow (XCTL target, menu dispatch, processing branch) — one rule per distinct decision point. +- **Data Access**: A CICS READ/WRITE/REWRITE/DELETE/STARTBR/READNEXT/READPREV, EXEC SQL, or IMS DL/I call — one rule per distinct file+operation+program combination. +- **Inter-Program Communication**: An XCTL, MQ call (MQOPEN/MQGET/MQPUT/MQCLOSE), DL/I CALL, TD queue write, or external program CALL — one rule per distinct communication pattern. +- **Error Handling**: A DFHRESP/SQLCODE/MQRC check with a specific user-facing message or recovery action — one rule per distinct error condition handled. +- **Screen/Interface**: A BMS SEND/RECEIVE pattern, PF key handler, cursor positioning, or field attribute manipulation — one rule per distinct screen interaction pattern. +- **Batch Processing**: A batch job's primary processing logic (file scan, report generation, data extract, database load/unload) — one rule per distinct batch function. +- **Security/Authorization**: An authentication check, access control decision, or credential management operation — one rule per distinct security function. +- **Temporal/State Management**: A pseudo-conversational state check, change detection comparison, or pagination state tracking — one rule per distinct state management pattern. + +### Inventory Consistency Rules + +#### VSAM File Inventory + +- Every VSAM file referenced in CSD definitions or CICS programs MUST appear in the inventory table. +- Columns MUST include: CICS File name, VSAM Dataset name, Type (KSDS/AIX/PATH), Key Length, Record Length, Programs that access it, and PostgreSQL target table. +- The "Programs" column MUST list only programs where the file access is actually coded (EXEC CICS READ/WRITE with that file's DD name). +- AIX/PATH entries MUST reference their base cluster. + +#### DB2 Table Inventory + +- Every table referenced in DDL files or EXEC SQL statements MUST appear in the inventory. +- Columns MUST include: Table name, Column count, Primary Key, Foreign Keys, DDL File, Programs, SQL Operations. +- The "SQL Operations" column MUST list only operations actually found in the source (SELECT, INSERT, UPDATE, DELETE). +- The "Programs" column MUST match programs containing EXEC SQL statements referencing that table. + +#### IMS Database Inventory + +- Every DBD and PSB file in the codebase MUST appear in the inventory. +- Columns MUST include: DBD name, PSB name(s), Type (HIDAM/HDAM/etc.), Programs, Purpose. +- Programs listed MUST actually contain DL/I calls referencing those PSBs. + +#### MQ Queue Inventory + +- Every MQ queue referenced in MQOPEN/MQPUT/MQGET calls MUST appear in the inventory. +- Columns MUST include: Queue name/purpose, Direction (Input/Output), Programs, Purpose. +- Programs listed MUST contain the actual MQ API calls. + +#### Copybook Data Type Mapping + +- Every copybook used in COPY statements across the COBOL programs MUST be considered for inclusion. +- At minimum, copybooks defining record layouts for VSAM files, DB2 tables, and COMMAREA structures MUST be mapped. +- Columns MUST include: COBOL Field, PIC Clause, PostgreSQL type, Java type, Notes. +- Financial fields (PIC S9(n)V99) MUST be flagged as "Financial — CRITICAL" and mapped to BigDecimal. +- PII fields (SSN, DOB, phone, government ID) MUST be flagged as "PII" or "PII — encrypt". + +#### CICS Transaction Inventory + +- Every CICS transaction ID defined in CSD files or referenced in RETURN TRANSID statements MUST appear. +- Online transactions MUST include: Trans ID, Program, Function description, REST API Target. +- The REST API Target MUST follow consistent naming conventions (e.g., GET/POST/PUT/DELETE /api/resource). +- Sub-application transactions MUST be listed separately with their sub-app context. +- Menu option tables MUST match the copybook definitions (COMEN02Y, COADM02Y). + +### Report Anti-Patterns to Avoid + +1. **Never** list rules in a detail section under a heading labeled "(Critical)" if the section contains rules of mixed severity — use the full breakdown format instead. +2. **Never** use a category name in a detail heading that doesn't exist in the summary table. +3. **Never** claim a total of N rules in a methodology note while the summary table shows a different number. +4. **Never** list only a subset of categories from the summary table in the detail section without explaining why others are omitted. +5. **Never** list more or fewer rules in a detail subsection than the summary table claims for that category. + +## Cross-Reference Validation (Final Quality Gate) + +Before finalizing the report, run these validation checks: + +1. **Copybook-to-Program Matrix:** Every copybook must be referenced by at least one program. Unreferenced copybooks are dead code. +2. **File-to-Program Matrix:** Every VSAM file in CSD must be accessed by at least one program. Every DB2 table in DDL must be accessed. +3. **Transaction-to-Program Matrix:** Every CSD DEFINE TRANSACTION must map to a DEFINE PROGRAM. Every menu option program must exist. +4. **Data Type Mapping Completeness:** Every .cpy file must have a data type mapping table. Expect 80-120+ fields for a CardDemo-sized app. +5. **Business Rule Count Validation:** Verify against Expected Rule Counts table. If any category is below minimum, re-run searches. From 63123483624caa9a19fe858a7b6aacce41ba97ac Mon Sep 17 00:00:00 2001 From: Kiro Date: Thu, 21 May 2026 06:56:02 +0000 Subject: [PATCH 18/18] sync(aidlc): align with aidlc-workflows v0.1.8 Sync the aidlc power with the latest content from aidlc-workflows upstream (HEAD at commit 4d2830c, post-v0.1.8). All steering files have been brought up to date with the upstream rule details and the extensions framework has been added. Content updates (18 files): - core-workflow.md: add multi-IDE rule details path resolution and Extensions Loading section. Preserve power-specific frontmatter and Language Selection. Fix typos and audit.md wording. Flatten bare rule-file references (e.g. workspace-detection.md -> inception-workspace-detection.md) for power layout. - common-error-handling.md: rename Phase -> Stage throughout, fix Recovery Procedures section ordering, rename Code Generation Errors sub-sections to (Part 2: Code Generation). - common-workflow-changes.md: rename Phase -> Stage throughout, drop Units Planning / Code Planning from restart impact lists. - common-terminology.md: merge Code Planning + Code Generation into one stage with Part 1 / Part 2; collapse Design + Units Planning / Generation into Units Generation; refresh sub-step examples. - common-welcome-message.md: switch ASCII box drawings from double-line characters to plain ASCII for portability. - common-process-overview.md: update cross-references and stage names to match the merged Code Generation stage. - inception-requirements-analysis.md: add Step 5.1 Extension Opt-In Prompts and the gate before Step 7. - inception-workflow-planning.md: rename section 3.3 to Units Generation, drop UP/CP nodes from Mermaid, prune checklists. - inception-workspace-detection.md: add stale artifact detection branches for reverse engineering rerun. - inception-reverse-engineering.md: rewrite rerun behavior, fix step numbering to a contiguous 1-13 sequence. - inception-application-design.md: rename prerequisites, rewrite question section to be proactive, add consolidated design doc. - inception-units-generation.md: rename prerequisites, rewrite question section, label progress as Part 1 (Planning). - inception-user-stories.md: fix Step 14 -> Step 15 reference. - construction-build-and-test.md: standardize completion message into the three-section format, rename Phase -> Stage. - construction-code-generation.md: add Frontend Components steps, rename Step 9 to Code Generation Part 1 (Planning), add Automation Friendly Code Rules. - construction-functional-design.md: add Frontend Components question and frontend-components.md artifact. - construction-nfr-design.md: rewrite question section to be proactive across all categories. - construction-infrastructure-design.md: rewrite question section to be proactive across all categories. - common-ascii-diagram-standards.md: fix bare reference content-validation.md -> common-content-validation.md. New files (4): - extensions-security-baseline.md - extensions-security-baseline.opt-in.md - extensions-property-based-testing.md - extensions-property-based-testing.opt-in.md All references between steering files now use the flat -.md naming convention required by the power layout. Generated artifacts under aidlc-docs/ retain their original names. --- .../common-ascii-diagram-standards.md | 2 +- aidlc/steering/common-error-handling.md | 88 ++--- aidlc/steering/common-process-overview.md | 6 +- aidlc/steering/common-terminology.md | 28 +- aidlc/steering/common-welcome-message.md | 60 ++-- aidlc/steering/common-workflow-changes.md | 56 ++-- aidlc/steering/construction-build-and-test.md | 42 ++- .../steering/construction-code-generation.md | 12 +- .../construction-functional-design.md | 7 + .../construction-infrastructure-design.md | 29 +- aidlc/steering/construction-nfr-design.md | 25 +- aidlc/steering/core-workflow.md | 71 ++-- .../extensions-property-based-testing.md | 284 ++++++++++++++++ ...xtensions-property-based-testing.opt-in.md | 19 ++ .../steering/extensions-security-baseline.md | 307 ++++++++++++++++++ .../extensions-security-baseline.opt-in.md | 18 + .../steering/inception-application-design.md | 26 +- .../inception-requirements-analysis.md | 21 ++ .../steering/inception-reverse-engineering.md | 26 +- aidlc/steering/inception-units-generation.md | 43 +-- aidlc/steering/inception-user-stories.md | 2 +- aidlc/steering/inception-workflow-planning.md | 22 +- .../steering/inception-workspace-detection.md | 6 +- 23 files changed, 956 insertions(+), 244 deletions(-) create mode 100644 aidlc/steering/extensions-property-based-testing.md create mode 100644 aidlc/steering/extensions-property-based-testing.opt-in.md create mode 100644 aidlc/steering/extensions-security-baseline.md create mode 100644 aidlc/steering/extensions-security-baseline.opt-in.md diff --git a/aidlc/steering/common-ascii-diagram-standards.md b/aidlc/steering/common-ascii-diagram-standards.md index 498ab22..c5c1c35 100644 --- a/aidlc/steering/common-ascii-diagram-standards.md +++ b/aidlc/steering/common-ascii-diagram-standards.md @@ -112,5 +112,5 @@ Before creating diagrams: ## Alternative -For complex diagrams, use Mermaid (see `content-validation.md`) +For complex diagrams, use Mermaid (see `common-content-validation.md`) diff --git a/aidlc/steering/common-error-handling.md b/aidlc/steering/common-error-handling.md index 18d1890..6a26d25 100644 --- a/aidlc/steering/common-error-handling.md +++ b/aidlc/steering/common-error-handling.md @@ -16,12 +16,12 @@ - Invalid user input that cannot be processed - System errors preventing file operations -**High**: Phase cannot complete as planned +**High**: Stage cannot complete as planned - Incomplete answers to required questions - Contradictory user responses -- Missing dependencies from prior phases +- Missing dependencies from prior stages -**Medium**: Phase can continue with workarounds +**Medium**: Stage can continue with workarounds - Optional artifacts missing - Non-critical validation failures - Partial completion possible @@ -31,9 +31,9 @@ - Optional information missing - Non-blocking warnings -## Phase-Specific Error Handling +## Stage-Specific Error Handling -### Context Assessment Errors +### Workspace Detection Errors **Error**: Cannot read workspace files - **Cause**: Permission issues, missing directories @@ -45,12 +45,12 @@ - **Solution**: Ask user if they want to start fresh or attempt recovery - **Recovery**: Create backup, start new state file -**Error**: Cannot determine required phases +**Error**: Cannot determine required stages - **Cause**: Insufficient information from user - **Solution**: Ask clarifying questions about intent and scope - **Workaround**: Default to comprehensive execution plan -### Requirements Assessment Errors +### Requirements Analysis Errors **Error**: User provides contradictory requirements - **Cause**: Unclear understanding, changing needs @@ -67,11 +67,11 @@ - **Solution**: Highlight unanswered questions, provide examples - **Do Not Proceed**: Until all required questions are answered -### Story Development Errors +### User Stories Errors **Error**: Cannot map requirements to stories - **Cause**: Requirements too vague, missing functional details -- **Solution**: Return to Requirements Assessment for clarification +- **Solution**: Return to Requirements Analysis for clarification - **Workaround**: Create stories based on available information, mark as incomplete **Error**: User provides ambiguous story planning answers @@ -110,7 +110,7 @@ **Error**: Cannot generate design artifacts - **Cause**: Missing unit information, unclear requirements -- **Solution**: Return to Units Planning to clarify unit definition +- **Solution**: Return to Units Generation to clarify unit definition - **Workaround**: Generate partial design, mark gaps ### NFR Implementation Errors @@ -130,11 +130,11 @@ - **Solution**: Clearly mark as **HUMAN TASK**, provide instructions - **Wait**: For user confirmation before proceeding -### Code Planning Errors +### Code Generation Planning Errors **Error**: Code generation plan is incomplete - **Cause**: Missing design artifacts, unclear requirements -- **Solution**: Return to Design phase to complete artifacts +- **Solution**: Return to Design stage to complete artifacts - **Recovery**: Generate plan with available information, mark gaps **Error**: Unit dependencies not satisfied @@ -142,7 +142,7 @@ - **Solution**: Reorder generation sequence to respect dependencies - **Workaround**: Generate with stub dependencies, integrate later -### Code Generation Errors +### Code Generation Errors (Part 2: Code Generation) **Error**: Cannot generate code for a step - **Cause**: Insufficient design information, unclear requirements @@ -173,12 +173,12 @@ ## Recovery Procedures -### Partial Phase Completion +### Partial Stage Completion -**Scenario**: Phase was interrupted mid-execution +**Scenario**: Stage was interrupted mid-execution **Recovery Steps**: -1. Load the phase plan file +1. Load the stage plan file 2. Identify last completed step (last [x] checkbox) 3. Resume from next uncompleted step 4. Verify all prior steps are actually complete @@ -190,43 +190,43 @@ **Recovery Steps**: 1. Create backup: `aidlc-state.md.backup` -2. Ask user which phase they're actually on +2. Ask user which stage they're actually on 3. Regenerate state file from scratch -4. Mark completed phases based on existing artifacts -5. Resume from current phase +4. Mark completed stages based on existing artifacts +5. Resume from current stage ### Missing Artifacts -**Scenario**: Required artifacts from prior phase are missing +**Scenario**: Required artifacts from prior stage are missing **Recovery Steps**: 1. Identify which artifacts are missing 2. Determine if they can be regenerated -3. If yes: Return to that phase, regenerate artifacts +3. If yes: Return to that stage, regenerate artifacts 4. If no: Ask user to provide information manually 5. Document the gap in `audit.md` -### User Wants to Restart Phase +### User Wants to Restart Stage -**Scenario**: User is unhappy with phase results and wants to redo +**Scenario**: User is unhappy with stage results and wants to redo **Recovery Steps**: 1. Confirm user wants to restart (data will be lost) 2. Archive existing artifacts: `{artifact}.backup` -3. Reset phase status in `aidlc-state.md` -4. Clear phase checkboxes in plan files -5. Re-execute phase from beginning +3. Reset stage status in `aidlc-state.md` +4. Clear stage checkboxes in plan files +5. Re-execute stage from beginning -### User Wants to Skip Phase +### User Wants to Skip Stage -**Scenario**: User wants to skip a phase that was planned +**Scenario**: User wants to skip a stage that was planned **Recovery Steps**: 1. Confirm user understands implications 2. Document skip reason in `audit.md` -3. Mark phase as "SKIPPED" in `aidlc-state.md` -4. Proceed to next phase -5. Note: May cause issues in later phases if dependencies missing +3. Mark stage as "SKIPPED" in `aidlc-state.md` +4. Proceed to next stage +5. Note: May cause issues in later stages if dependencies missing ## Escalation Guidelines @@ -247,11 +247,20 @@ ### When to Suggest Starting Over **Consider Fresh Start If**: -- Multiple phases have errors +- Multiple stages have errors - State file is severely corrupted +- User requirements have changed significantly +- Architectural decision needs to be reversed - User cannot provide missing information - Artifacts are inconsistent across phases +**Before Starting Over**: +1. Archive all existing work +2. Document lessons learned +3. Identify what to preserve +4. Get user confirmation +5. Create new execution plan + ## Session Resumption Errors ### Missing Artifacts During Resumption @@ -324,23 +333,14 @@ 3. **Fail fast**: Stop immediately if critical artifacts are missing 4. **Communicate clearly**: Tell user exactly what's missing and why it's needed 5. **Offer options**: Regenerate, provide manually, or start fresh -6. **Document recovery**: Log all recovery actions in audit.md State file is severely corrupted -- User requirements have changed significantly -- Architectural decision needs to be reversed - -**Before Starting Over**: -1. Archive all existing work -2. Document lessons learned -3. Identify what to preserve -4. Get user confirmation -5. Create new execution plan +6. **Document recovery**: Log all recovery actions in audit.md ## Logging Requirements ### Error Logging Format ```markdown -## Error - [Phase Name] +## Error - [Stage Name] **Timestamp**: [ISO timestamp] **Error Type**: [Critical/High/Medium/Low] **Description**: [What went wrong] @@ -354,7 +354,7 @@ ### Recovery Logging Format ```markdown -## Recovery - [Phase Name] +## Recovery - [Stage Name] **Timestamp**: [ISO timestamp] **Issue**: [What needed recovery] **Recovery Steps**: [What was done] diff --git a/aidlc/steering/common-process-overview.md b/aidlc/steering/common-process-overview.md index a547a58..ce59583 100644 --- a/aidlc/steering/common-process-overview.md +++ b/aidlc/steering/common-process-overview.md @@ -2,14 +2,14 @@ **Purpose**: Technical reference for AI model and developers to understand complete workflow structure. -**Note**: Similar content exists in core-workflow.md (user welcome message) and README.md (documentation). This duplication is INTENTIONAL - each file serves a different purpose: +**Note**: Similar content exists in common-welcome-message.md (user welcome message) and README.md (documentation). This duplication is INTENTIONAL - each file serves a different purpose: - **This file**: Detailed technical reference with Mermaid diagram for AI model context loading -- **core-workflow.md**: User-facing welcome message with ASCII diagram +- **common-welcome-message.md**: User-facing welcome message with ASCII diagram - **README.md**: Human-readable documentation for repository ## The Three-Phase Lifecycle: • **INCEPTION PHASE**: Planning and architecture (Workspace Detection + conditional phases + Workflow Planning) -• **CONSTRUCTION PHASE**: Design, implementation, build and test (per-unit design + Code Planning/Generation + Build & Test) +• **CONSTRUCTION PHASE**: Design, implementation, build and test (per-unit design + Code Generation + Build & Test) • **OPERATIONS PHASE**: Placeholder for future deployment and monitoring workflows ## The Adaptive Workflow: diff --git a/aidlc/steering/common-terminology.md b/aidlc/steering/common-terminology.md index 5193a75..3c96836 100644 --- a/aidlc/steering/common-terminology.md +++ b/aidlc/steering/common-terminology.md @@ -10,13 +10,13 @@ - 🟡 **OPERATIONS PHASE** - Deployment & Monitoring (future expansion) **Stage**: An individual workflow activity within a phase -- Examples: Context Assessment stage, Requirements Assessment stage, Code Planning stage +- Examples: Context Assessment stage, Requirements Assessment stage, Code Generation stage - Each stage has specific prerequisites, steps, and outputs - Stages can be ALWAYS-EXECUTE or CONDITIONAL **Usage Examples**: - ✅ "The CONSTRUCTION phase contains 7 stages" -- ✅ "The Code Planning stage is always executed" +- ✅ "The Code Generation stage is always executed" - ✅ "We're in the INCEPTION phase, executing the Requirements Assessment stage" - ❌ "The Requirements Assessment phase" (should be "stage") - ❌ "The CONSTRUCTION stage" (should be "phase") @@ -35,7 +35,7 @@ - User Stories (CONDITIONAL) - Workflow Planning (ALWAYS) - Application Design (CONDITIONAL) -- Design - Units Planning/Generation (CONDITIONAL) +- Units Generation (CONDITIONAL) **Outputs**: Requirements, user stories, architectural decisions, unit definitions @@ -49,8 +49,7 @@ - NFR Requirements (CONDITIONAL, per-unit) - NFR Design (CONDITIONAL, per-unit) - Infrastructure Design (CONDITIONAL, per-unit) -- Code Planning (ALWAYS) -- Code Generation (ALWAYS) +- Code Generation (ALWAYS) — includes Part 1: Planning and Part 2: Generation - Build and Test (ALWAYS) **Outputs**: Design artifacts, NFR implementations, code, tests @@ -73,15 +72,14 @@ - **Workspace Detection**: Initial analysis of workspace state and project type - **Requirements Analysis**: Gathering requirements (depth varies based on complexity) - **Workflow Planning**: Creating execution plan for which phases to run -- **Code Planning**: Creating detailed implementation plans for code generation -- **Code Generation**: Generating actual code based on plans and prior artifacts +- **Code Generation**: Single stage with two parts — Part 1 (Planning) creates detailed implementation plans, Part 2 (Generation) generates actual code based on plans and prior artifacts - **Build and Test**: Building all units and executing comprehensive testing ### Conditional Stages - **Reverse Engineering**: Analyzing existing codebase (brownfield projects only) - **User Stories**: Creating user stories and personas (includes Story Planning and Story Generation) - **Application Design**: Designing application components, methods, business rules, and services -- **Design**: Designing system components (includes Units Planning, Units Generation, per-unit design) +- **Units Generation**: Decomposing the system into units of work (includes internal planning and generation sub-steps, plus per-unit design) - **Functional Design**: Technology-agnostic business logic design (per-unit) - **NFR Requirements**: Determining NFRs and selecting tech stack (per-unit) - **NFR Design**: Incorporating NFR patterns and logical components (per-unit) @@ -122,7 +120,7 @@ A reusable building block within a service or module. Components are classes, fu ### When to Use Each Term **Unit of Work**: -- During Units Planning and Units Generation phases +- During the Units Generation stage - When discussing system decomposition - In planning documents and discussions - Example: "How should we decompose this into units of work?" @@ -151,12 +149,12 @@ A reusable building block within a service or module. Components are classes, fu - **Planning**: Creating a plan with questions and checkboxes for execution - **Generation**: Executing the plan to create artifacts -Examples: -- Story Planning → Story Generation -- Units Planning → Units Generation -- Unit Design Planning → Unit Design Generation -- NFR Planning → NFR Generation -- Code Planning → Code Generation +Examples (these are internal sub-steps within a single stage, not separate stages): +- Story Planning → Story Generation (within User Stories stage) +- Units Planning → Units Generation (within Units Generation stage) +- Unit Design Planning → Unit Design Generation (within per-unit design) +- NFR Planning → NFR Generation (within NFR Requirements stage) +- Code Generation Part 1 (Planning) → Code Generation Part 2 (Generation) ### Depth Levels - **Minimal**: Quick, focused execution for simple changes diff --git a/aidlc/steering/common-welcome-message.md b/aidlc/steering/common-welcome-message.md index 8c775ef..c8ef7a7 100644 --- a/aidlc/steering/common-welcome-message.md +++ b/aidlc/steering/common-welcome-message.md @@ -24,40 +24,40 @@ AI-DLC is a structured yet flexible software development process that adapts to User Request | v - ╔═══════════════════════════════════════╗ - ║ INCEPTION PHASE ║ - ║ Planning & Application Design ║ - ╠═══════════════════════════════════════╣ - ║ • Workspace Detection (ALWAYS) ║ - ║ • Reverse Engineering (COND) ║ - ║ • Requirements Analysis (ALWAYS) ║ - ║ • User Stories (CONDITIONAL) ║ - ║ • Workflow Planning (ALWAYS) ║ - ║ • Application Design (CONDITIONAL) ║ - ║ • Units Generation (CONDITIONAL) ║ - ╚═══════════════════════════════════════╝ + +---------------------------------------+ + | INCEPTION PHASE | + | Planning & Application Design | + +---------------------------------------+ + | * Workspace Detection (ALWAYS) | + | * Reverse Engineering (COND) | + | * Requirements Analysis (ALWAYS) | + | * User Stories (CONDITIONAL) | + | * Workflow Planning (ALWAYS) | + | * Application Design (CONDITIONAL) | + | * Units Generation (CONDITIONAL) | + +---------------------------------------+ | v - ╔═══════════════════════════════════════╗ - ║ CONSTRUCTION PHASE ║ - ║ Design, Implementation & Test ║ - ╠═══════════════════════════════════════╣ - ║ • Per-Unit Loop (for each unit): ║ - ║ - Functional Design (COND) ║ - ║ - NFR Requirements Assess (COND) ║ - ║ - NFR Design (COND) ║ - ║ - Infrastructure Design (COND) ║ - ║ - Code Generation (ALWAYS) ║ - ║ • Build and Test (ALWAYS) ║ - ╚═══════════════════════════════════════╝ + +---------------------------------------+ + | CONSTRUCTION PHASE | + | Design, Implementation & Test | + +---------------------------------------+ + | * Per-Unit Loop (for each unit): | + | - Functional Design (COND) | + | - NFR Requirements Assess (COND) | + | - NFR Design (COND) | + | - Infrastructure Design (COND) | + | - Code Generation (ALWAYS) | + | * Build and Test (ALWAYS) | + +---------------------------------------+ | v - ╔═══════════════════════════════════════╗ - ║ OPERATIONS PHASE ║ - ║ Placeholder for Future ║ - ╠═══════════════════════════════════════╣ - ║ • Operations (PLACEHOLDER) ║ - ╚═══════════════════════════════════════╝ + +---------------------------------------+ + | OPERATIONS PHASE | + | Placeholder for Future | + +---------------------------------------+ + | * Operations (PLACEHOLDER) | + +---------------------------------------+ | v Complete diff --git a/aidlc/steering/common-workflow-changes.md b/aidlc/steering/common-workflow-changes.md index cc7d33f..ca235df 100644 --- a/aidlc/steering/common-workflow-changes.md +++ b/aidlc/steering/common-workflow-changes.md @@ -1,37 +1,37 @@ -# Mid-Workflow Changes and Phase Management +# Mid-Workflow Changes and Stage Management ## Overview -Users may request changes to the execution plan or phase execution during the workflow. This document provides guidance on handling these requests safely and effectively. +Users may request changes to the execution plan or stage execution during the workflow. This document provides guidance on handling these requests safely and effectively. --- ## Types of Mid-Workflow Changes -### 1. Adding a Skipped Phase +### 1. Adding a Skipped Stage -**Scenario**: User wants to add a phase that was originally skipped +**Scenario**: User wants to add a stage that was originally skipped **Example**: "Actually, I want to add user stories even though we skipped that stage" **Handling**: 1. **Confirm Request**: "You want to add User Stories stage. This will create user stories and personas. Confirm?" -2. **Check Dependencies**: Verify all prerequisite phases are complete -3. **Update Execution Plan**: Add phase to `execution-plan.md` with rationale -4. **Update State**: Mark phase as "PENDING" in `aidlc-state.md` -5. **Execute Phase**: Follow normal phase execution process +2. **Check Dependencies**: Verify all prerequisite stages are complete +3. **Update Execution Plan**: Add stage to `execution-plan.md` with rationale +4. **Update State**: Mark stage as "PENDING" in `aidlc-state.md` +5. **Execute Stage**: Follow normal stage execution process 6. **Log Change**: Document in `audit.md` with timestamp and reason **Considerations**: -- May need to update later phases that could benefit from new artifacts +- May need to update later stages that could benefit from new artifacts - Existing artifacts may need revision to incorporate new information - Timeline will be extended --- -### 2. Skipping a Planned Phase +### 2. Skipping a Planned Stage -**Scenario**: User wants to skip a phase that was planned to execute +**Scenario**: User wants to skip a stage that was planned to execute **Example**: "Let's skip the NFR Design stage for now" @@ -39,13 +39,13 @@ Users may request changes to the execution plan or phase execution during the wo 1. **Confirm Request**: "You want to skip NFR Design. This means no NFR patterns or logical components will be incorporated. Confirm?" 2. **Warn About Impact**: Explain what will be missing and potential consequences 3. **Get Explicit Confirmation**: User must explicitly confirm understanding of impact -4. **Update Execution Plan**: Mark phase as "SKIPPED" with reason -5. **Update State**: Mark phase as "SKIPPED" in `aidlc-state.md` -6. **Adjust Later Phases**: Note that later phases may need manual setup +4. **Update Execution Plan**: Mark stage as "SKIPPED" with reason +5. **Update State**: Mark stage as "SKIPPED" in `aidlc-state.md` +6. **Adjust Later Stages**: Note that later stages may need manual setup 7. **Log Change**: Document in `audit.md` with timestamp and reason **Considerations**: -- Later phases may fail or require manual intervention +- Later stages may fail or require manual intervention - User accepts responsibility for missing artifacts - Can be added back later if needed @@ -85,7 +85,7 @@ Users may request changes to the execution plan or phase execution during the wo **Handling**: 1. **Assess Impact**: Identify all stages that depend on the stage to be restarted -2. **Warn User**: "Restarting Application Design will require redoing: Units Planning, Units Generation, per-unit design (all units), Code Planning, Code Generation. Confirm?" +2. **Warn User**: "Restarting Application Design will require redoing: Units Generation, per-unit design (all units), Code Generation. Confirm?" 3. **Get Explicit Confirmation**: User must understand full impact 4. **If Confirmed**: - Archive all affected artifacts @@ -111,7 +111,7 @@ Users may request changes to the execution plan or phase execution during the wo **Handling**: 1. **Confirm Request**: "You want to change Requirements Analysis from Standard to Comprehensive depth. This will be more thorough but take longer. Confirm?" -2. **Update Execution Plan**: Change depth level in `workflow-planning.md` +2. **Update Execution Plan**: Change depth level in `aidlc-docs/inception/plans/execution-plan.md` 3. **Adjust Approach**: Follow comprehensive depth guidelines for the stage 4. **Update Estimates**: Inform user of new timeline estimate 5. **Log Change**: Document depth change and reason @@ -134,7 +134,7 @@ Users may request changes to the execution plan or phase execution during the wo 2. **Update Checkboxes**: Mark all completed steps with [x] 3. **Update State**: Ensure `aidlc-state.md` reflects current status 4. **Log Pause**: Document pause point in `audit.md` -5. **Provide Resume Instructions**: "When you return, I'll detect your existing project and offer to continue from: [current phase, current step]" +5. **Provide Resume Instructions**: "When you return, I'll detect your existing project and offer to continue from: [current stage, current step]" **On Resume**: 1. **Detect Existing Project**: Check for `aidlc-state.md` @@ -154,8 +154,8 @@ Users may request changes to the execution plan or phase execution during the wo **Handling**: 1. **Assess Current Progress**: Determine how far into workflow 2. **Explain Impact**: - - If before Units Planning: Minimal impact, just update decision - - If after Units Planning: Must redo Units Planning, Units Generation, all per-unit design + - If before Units Generation: Minimal impact, just update decision + - If after Units Generation: Must redo Units Generation, all per-unit design - If after Code Generation: Significant rework required 3. **Recommend Approach**: - Early in workflow: Restart from Application Design stage @@ -229,21 +229,21 @@ Users may request changes to the execution plan or phase execution during the wo ``` User requests change | - ├─ Is it current phase? - | ├─ Yes: Can modify or restart current phase + ├─ Is it current stage? + | ├─ Yes: Can modify or restart current stage | └─ No: Go to next question | - ├─ Is it a completed phase? - | ├─ Yes: Assess impact on dependent phases + ├─ Is it a completed stage? + | ├─ Yes: Assess impact on dependent stages | | ├─ Low impact: Modify and update dependents - | | └─ High impact: Recommend restart from that phase + | | └─ High impact: Recommend restart from that stage | └─ No: Go to next question | - ├─ Is it adding a skipped phase? + ├─ Is it adding a skipped stage? | ├─ Yes: Check prerequisites, add to plan, execute | └─ No: Go to next question | - ├─ Is it skipping a planned phase? + ├─ Is it skipping a planned stage? | ├─ Yes: Warn about impact, get confirmation, skip | └─ No: Go to next question | @@ -259,7 +259,7 @@ User requests change ### Change Request Log Format ```markdown -## Change Request - [Phase Name] +## Change Request - [Stage Name] **Timestamp**: [ISO timestamp] **Request**: [What user wants to change] **Current State**: [Where we are in workflow] diff --git a/aidlc/steering/construction-build-and-test.md b/aidlc/steering/construction-build-and-test.md index 85f5951..92dd965 100644 --- a/aidlc/steering/construction-build-and-test.md +++ b/aidlc/steering/construction-build-and-test.md @@ -306,37 +306,43 @@ Update `aidlc-docs/aidlc-state.md`: ## Step 9: Present Results to User -Present comprehensive message: +Present completion message in this structure: + 1. **Completion Announcement** (mandatory): Always start with this: +```markdown +# 🔨 Build and Test Complete ``` -"🔨 Build and Test Complete! -**Build Status**: [Success/Failed] + 2. **AI Summary** (optional): Provide structured bullet-point summary of build and test results + - Format: "Build and test has completed with the following results:" + - List build status and artifacts + - List test results by category (unit, integration, performance, etc.) + - List generated instruction files + - DO NOT include workflow instructions ("please review", "let me know", "proceed to next phase", "before we proceed") + - Keep factual and content-focused + 3. **Formatted Workflow Message** (mandatory): Always end with this exact format: -**Test Results**: -✅ Unit Tests: [X] passed -✅ Integration Tests: [X] scenarios passed -✅ Performance Tests: [Status] -✅ Additional Tests: [Status] +```markdown +> **📋 **REVIEW REQUIRED:**** +> Please examine the build and test summary at: `aidlc-docs/construction/build-and-test/build-and-test-summary.md` -**Generated Files**: -1. ✅ build-instructions.md -2. ✅ unit-test-instructions.md -3. ✅ integration-test-instructions.md -4. ✅ performance-test-instructions.md (if applicable) -5. ✅ [additional test files as needed] -6. ✅ build-and-test-summary.md -Review the summary in aidlc-docs/construction/build-and-test/build-and-test-summary.md -**Ready to proceed to Operations stage for deployment planning?"" +> **🚀 **WHAT'S NEXT?**** +> +> **You may:** +> +> 🔧 **Request Changes** - Ask for modifications to the build and test instructions based on your review +> ✅ **Approve & Continue** - Approve build and test results and proceed to **Operations** + +--- ``` --- ## Step 10: Log Interaction -**MANDATORY**: Log the phase completion in `aidlc-docs/audit.md`: +**MANDATORY**: Log the stage completion in `aidlc-docs/audit.md`: ```markdown ## Build and Test Stage diff --git a/aidlc/steering/construction-code-generation.md b/aidlc/steering/construction-code-generation.md index 36bbe23..bfb4cdf 100644 --- a/aidlc/steering/construction-code-generation.md +++ b/aidlc/steering/construction-code-generation.md @@ -39,6 +39,9 @@ This stage generates code for each unit of work through two integrated parts: - Repository Layer Generation - Repository Layer Unit Testing - Repository Layer Summary + - Frontend Components Generation (if applicable) + - Frontend Components Unit Testing (if applicable) + - Frontend Components Summary (if applicable) - Database Migration Scripts (if data models exist) - Documentation Generation (API docs, README updates) - Deployment Artifacts Generation @@ -84,7 +87,7 @@ This stage generates code for each unit of work through two integrated parts: - [ ] Mark the approval status clearly ## Step 9: Update Progress -- [ ] Mark Code Planning complete in `aidlc-state.md` +- [ ] Mark Code Generation Part 1 (Planning) complete in `aidlc-state.md` - [ ] Update the "Current Status" section - [ ] Prepare for transition to Code Generation @@ -198,6 +201,13 @@ This stage generates code for each unit of work through two integrated parts: - **STORY TRACEABILITY**: Mark unit stories [x] when functionality is implemented - **RESPECT DEPENDENCIES**: Only implement when unit dependencies are satisfied +### Automation Friendly Code Rules +When generating UI code (web, mobile, desktop), ensure elements are automation-friendly: +- Add `data-testid` attributes to interactive elements (buttons, inputs, links, forms) +- Use consistent naming: `{component}-{element-role}` (e.g., `login-form-submit-button`, `user-list-search-input`) +- Avoid dynamic or auto-generated IDs that change between renders +- Keep `data-testid` values stable across code changes (only change when element purpose changes) + ## Completion Criteria - Complete unit code generation plan created and approved - All steps in unit code generation plan marked [x] diff --git a/aidlc/steering/construction-functional-design.md b/aidlc/steering/construction-functional-design.md index 18b997c..86797d5 100644 --- a/aidlc/steering/construction-functional-design.md +++ b/aidlc/steering/construction-functional-design.md @@ -50,6 +50,7 @@ Design detailed business logic for the unit, technology-agnostic and focused pur - **Integration Points** - Ask about external system interactions, APIs, and data exchange - **Error Handling** - Ask about error scenarios, validation failures, and exception handling - **Business Scenarios** - Ask about edge cases, alternative flows, and complex business situations +- **Frontend Components** (if applicable) - Ask about UI component structure, user interactions, state management, and form handling ### Step 4: Store Plan - Save as `aidlc-docs/construction/plans/{unit-name}-functional-design-plan.md` @@ -67,6 +68,12 @@ Design detailed business logic for the unit, technology-agnostic and focused pur - Create `aidlc-docs/construction/{unit-name}/functional-design/business-logic-model.md` - Create `aidlc-docs/construction/{unit-name}/functional-design/business-rules.md` - Create `aidlc-docs/construction/{unit-name}/functional-design/domain-entities.md` +- If unit includes frontend/UI: Create `aidlc-docs/construction/{unit-name}/functional-design/frontend-components.md` + - Component hierarchy and structure + - Props and state definitions for each component + - User interaction flows + - Form validation rules + - API integration points (which backend endpoints each component uses) ### Step 7: Present Completion Message - Present completion message in this structure: diff --git a/aidlc/steering/construction-infrastructure-design.md b/aidlc/steering/construction-infrastructure-design.md index 8ff9b27..2cc89b7 100644 --- a/aidlc/steering/construction-infrastructure-design.md +++ b/aidlc/steering/construction-infrastructure-design.md @@ -21,20 +21,25 @@ Map logical software components to actual infrastructure choices for deployment - Each step should have a checkbox [] ### Step 3: Generate Context-Appropriate Questions -**DIRECTIVE**: Analyze the functional and NFR design to generate ONLY questions relevant to THIS specific unit's infrastructure needs. Use the categories below as inspiration, NOT as a mandatory checklist. Skip entire categories if not applicable. +**DIRECTIVE**: Thoroughly analyze the functional and NFR design to identify ALL areas where clarification would improve infrastructure decisions. Be proactive in asking questions to ensure comprehensive infrastructure coverage. + +**CRITICAL**: Default to asking questions when there is ANY ambiguity or missing detail that could affect infrastructure quality. It's better to ask too many questions than to make incorrect infrastructure assumptions. + +**MANDATORY**: Evaluate ALL of the following categories by asking targeted questions about each. For each category, determine applicability based on evidence from the functional and NFR design artifacts -- do not skip categories without explicit justification: - EMBED questions using [Answer]: tag format -- Focus on ambiguities and missing information specific to this unit -- Generate questions only where user input is needed for infrastructure decisions - -**Example question categories** (adapt as needed): -- **Deployment Environment** - Only if cloud provider or environment setup is unclear -- **Compute Infrastructure** - Only if compute service choice needs clarification -- **Storage Infrastructure** - Only if database or storage selection is ambiguous -- **Messaging Infrastructure** - Only if messaging/queuing services need specification -- **Networking Infrastructure** - Only if load balancing or API gateway approach is unclear -- **Monitoring Infrastructure** - Only if observability tooling needs clarification -- **Shared Infrastructure** - Only if infrastructure sharing strategy is ambiguous +- Focus on ANY ambiguities, missing information, or areas needing clarification +- Generate questions wherever user input would improve infrastructure decisions +- **When in doubt, ask the question** - overconfidence leads to poor infrastructure choices + +**Question categories to evaluate** (consider ALL categories): +- **Deployment Environment** - Ask about cloud provider preferences, environment setup, and deployment targets +- **Compute Infrastructure** - Ask about compute service choices, sizing, and scaling requirements +- **Storage Infrastructure** - Ask about database selection, storage patterns, and data lifecycle needs +- **Messaging Infrastructure** - Ask about messaging/queuing services, event-driven patterns, and async processing +- **Networking Infrastructure** - Ask about load balancing, API gateway approach, and network topology +- **Monitoring Infrastructure** - Ask about observability tooling, alerting strategy, and logging requirements +- **Shared Infrastructure** - Ask about infrastructure sharing strategy, multi-tenancy, and resource isolation ### Step 4: Store Plan - Save as `aidlc-docs/construction/plans/{unit-name}-infrastructure-design-plan.md` diff --git a/aidlc/steering/construction-nfr-design.md b/aidlc/steering/construction-nfr-design.md index 92b950b..d4f0019 100644 --- a/aidlc/steering/construction-nfr-design.md +++ b/aidlc/steering/construction-nfr-design.md @@ -20,18 +20,23 @@ Incorporate NFR requirements into unit design using patterns and logical compone - Each step should have a checkbox [] ### Step 3: Generate Context-Appropriate Questions -**DIRECTIVE**: Analyze the NFR requirements to generate ONLY questions relevant to THIS specific unit's NFR design. Use the categories below as inspiration, NOT as a mandatory checklist. Skip entire categories if not applicable. +**DIRECTIVE**: Thoroughly analyze the NFR requirements to identify ALL areas where clarification would improve NFR design quality. Be proactive in asking questions to ensure comprehensive non-functional design coverage. + +**CRITICAL**: Default to asking questions when there is ANY ambiguity or missing detail that could affect NFR design quality. It's better to ask too many questions than to make incorrect assumptions about non-functional patterns. + +**MANDATORY**: Evaluate ALL of the following categories by asking targeted questions about each. For each category, determine applicability based on evidence from the NFR requirements -- do not skip categories without explicit justification: - EMBED questions using [Answer]: tag format -- Focus on ambiguities and missing information specific to this unit -- Generate questions only where user input is needed for pattern and component decisions - -**Example question categories** (adapt as needed): -- **Resilience Patterns** - Only if fault tolerance approach needs clarification -- **Scalability Patterns** - Only if scaling mechanisms are unclear -- **Performance Patterns** - Only if performance optimization strategy is ambiguous -- **Security Patterns** - Only if security implementation approach needs input -- **Logical Components** - Only if infrastructure components (queues, caches, etc.) need clarification +- Focus on ANY ambiguities, missing information, or areas needing clarification +- Generate questions wherever user input would improve pattern and component decisions +- **When in doubt, ask the question** - overconfidence leads to poor non-functional designs + +**Question categories to evaluate** (consider ALL categories): +- **Resilience Patterns** - Ask about fault tolerance approach, retry strategies, and failure recovery expectations +- **Scalability Patterns** - Ask about scaling mechanisms, load boundaries, and growth projections +- **Performance Patterns** - Ask about optimization strategy, latency targets, and throughput requirements +- **Security Patterns** - Ask about security implementation approach, threat model, and compliance constraints +- **Logical Components** - Ask about infrastructure components (queues, caches, circuit breakers, etc.) and their integration patterns ### Step 4: Store Plan - Save as `aidlc-docs/construction/plans/{unit-name}-nfr-design-plan.md` diff --git a/aidlc/steering/core-workflow.md b/aidlc/steering/core-workflow.md index f77218c..f1d247a 100644 --- a/aidlc/steering/core-workflow.md +++ b/aidlc/steering/core-workflow.md @@ -52,6 +52,14 @@ The AI model intelligently assesses what stages are needed based on: ## MANDATORY: Rule Details Loading **CRITICAL**: When performing any phase, you MUST read and use relevant content from steering files within this power. +For developers running aidlc-workflows outside the power context, the following alternative paths are checked in order, using the first one that exists: +- `.aidlc/aidlc-rules/aws-aidlc-rule-details/` (typical with AI-assisted setup) +- `.aidlc-rule-details/` (typical with Cursor, Cline, Claude Code, GitHub Copilot, OpenAI Codex) +- `.kiro/aws-aidlc-rule-details/` (typical with Kiro IDE and CLI) +- `.amazonq/aws-aidlc-rule-details/` (typical with Amazon Q Developer) + +When loaded as a power (this power's typical execution mode), all references below resolve to files in this power's `steering/` directory. All subsequent rule detail file references (e.g., `common-process-overview.md`, `inception-workspace-detection.md`) are relative to whichever rule details directory was resolved. + **Common Rules**: ALWAYS load common rules at workflow start: - Load `common-process-overview.md` for workflow overview - Load `common-session-continuity.md` for session resumption guidance @@ -59,6 +67,29 @@ The AI model intelligently assesses what stages are needed based on: - Load `common-question-format-guide.md` for question formatting rules - Reference these throughout the workflow execution +## MANDATORY: Extensions Loading (Context-Optimized) +**CRITICAL**: At workflow start, scan for extension files (`extensions-*.opt-in.md` in this power's `steering/` directory, or `extensions/*/*` subdirectories in non-power deployments). Load ONLY lightweight opt-in files — NOT full rule files. Full rule files are loaded on-demand after the user opts in. + +**Loading process**: +1. List all `extensions-*.opt-in.md` files in `steering/` (or `extensions/` subdirectories in non-power deployments) +2. Load ONLY `*.opt-in.md` files — these contain the extension's opt-in prompt. The corresponding rules file is derived by convention: strip the `.opt-in.md` suffix and append `.md` (e.g., `extensions-security-baseline.opt-in.md` → `extensions-security-baseline.md`) +3. Do NOT load full rule files (e.g., `extensions-security-baseline.md`) at this stage + +**Deferred Rule Loading**: +- During Requirements Analysis, opt-in prompts from the loaded `*.opt-in.md` files are presented to the user +- When the user opts IN for an extension, load the corresponding rules file (derived by naming convention) at that point +- When the user opts OUT, the full rules file is never loaded — saving context +- Extensions without a matching `*.opt-in.md` file are always enforced — load their rule files immediately at workflow start + +**Enforcement** (applies only to loaded/enabled extensions): +- Extension rules are hard constraints, not optional guidance +- At each stage, the model intelligently evaluates which extension rules are applicable based on the stage's purpose, the artifacts being produced, and the context of the work — enforce only those rules that are relevant +- Rules that are not applicable to the current stage should be marked as N/A in the compliance summary (this is not a blocking finding) +- Non-compliance with any applicable enabled extension rule is a **blocking finding** — do NOT present stage completion until resolved +- When presenting stage completion, include a summary of extension rule compliance (compliant/non-compliant/N/A per rule, with brief rationale for N/A determinations) + +**Conditional Enforcement**: Extensions may be conditionally enabled/disabled. See `inception-requirements-analysis.md` for the opt-in mechanism. Before enforcing any extension at ANY stage, check its `Enabled` status in `aidlc-docs/aidlc-state.md` under `## Extension Configuration`. Skip disabled extensions and log the skip in audit.md. Default to enforced if no configuration exists. + ## MANDATORY: Content Validation **CRITICAL**: Before creating ANY file, you MUST validate content according to `common-content-validation.md` rules: - Validate Mermaid diagram syntax @@ -116,7 +147,7 @@ The AI model intelligently assesses what stages are needed based on: - Check for existing reverse engineering artifacts 4. Determine next phase: Reverse Engineering (if brownfield and no artifacts) OR Requirements Analysis 5. **MANDATORY**: Log findings in audit.md -6. Present completion message to user (see workspace-detection.md for message formats) +6. Present completion message to user (see inception-workspace-detection.md for message formats) 7. Automatically proceed to next phase ## Reverse Engineering (CONDITIONAL - Brownfield Only) @@ -134,7 +165,7 @@ The AI model intelligently assesses what stages are needed based on: 2. Load all steps from `inception-reverse-engineering.md` 3. Execute reverse engineering: - Analyze all packages and components - - Generate a busienss overview of the whole system covering the business transactions + - Generate a business overview of the whole system covering the business transactions - Generate architecture documentation - Generate code structure documentation - Generate API documentation @@ -143,7 +174,7 @@ The AI model intelligently assesses what stages are needed based on: - Generate technology stack documentation - Generate dependencies documentation -4. **Wait for Explicit Approval**: Present detailed completion message (see reverse-engineering.md for message format) - DO NOT PROCEED until user confirms +4. **Wait for Explicit Approval**: Present detailed completion message (see inception-reverse-engineering.md for message format) - DO NOT PROCEED until user confirms 5. **MANDATORY**: Log user's response in audit.md with complete raw input ## Requirements Analysis (ALWAYS EXECUTE - Adaptive Depth) @@ -164,7 +195,7 @@ The AI model intelligently assesses what stages are needed based on: - Ask clarifying questions (if needed) - Generate requirements document 4. Execute at appropriate depth (minimal/standard/comprehensive) -5. **Wait for Explicit Approval**: Follow approval format from requirements-analysis.md detailed steps - DO NOT PROCEED until user confirms +5. **Wait for Explicit Approval**: Follow approval format from inception-requirements-analysis.md detailed steps - DO NOT PROCEED until user confirms 6. **MANDATORY**: Log user's response in audit.md with complete raw input ## User Stories (CONDITIONAL) @@ -227,13 +258,13 @@ The AI model intelligently assesses what stages are needed based on: **Execution**: 1. **MANDATORY**: Log any user input during this phase in audit.md 2. Load all steps from `inception-user-stories.md` -3. **MANDATORY**: Perform intelligent assessment (Step 1 in user-stories.md) to validate user stories are needed +3. **MANDATORY**: Perform intelligent assessment (Step 1 in inception-user-stories.md) to validate user stories are needed 4. Load reverse engineering artifacts (if brownfield) 5. If Requirements exist, reference them when creating stories 6. Execute at appropriate depth (minimal/standard/comprehensive) 7. **PART 1 - Planning**: Create story plan with questions, wait for user answers, analyze for ambiguities, get approval 8. **PART 2 - Generation**: Execute approved plan to generate stories and personas -9. **Wait for Explicit Approval**: Follow approval format from user-stories.md detailed steps - DO NOT PROCEED until user confirms +9. **Wait for Explicit Approval**: Follow approval format from inception-user-stories.md detailed steps - DO NOT PROCEED until user confirms 10. **MANDATORY**: Log user's response in audit.md with complete raw input ## Workflow Planning (ALWAYS EXECUTE) @@ -251,8 +282,8 @@ The AI model intelligently assesses what stages are needed based on: - Determine depth level for each phase - Create multi-package change sequence (if brownfield) - Generate workflow visualization (VALIDATE Mermaid syntax before writing) -6. **MANDATORY**: Validate all content before file creation per content-validation.md rules -7. **Wait for Explicit Approval**: Present recommendations using language from workflow-planning.md Step 9, emphasizing user control to override recommendations - DO NOT PROCEED until user confirms +6. **MANDATORY**: Validate all content before file creation per common-content-validation.md rules +7. **Wait for Explicit Approval**: Present recommendations using language from inception-workflow-planning.md Step 9, emphasizing user control to override recommendations - DO NOT PROCEED until user confirms 8. **MANDATORY**: Log user's response in audit.md with complete raw input ## Application Design (CONDITIONAL) @@ -273,7 +304,7 @@ The AI model intelligently assesses what stages are needed based on: 2. Load all steps from `inception-application-design.md` 3. Load reverse engineering artifacts (if brownfield) 4. Execute at appropriate depth (minimal/standard/comprehensive) -5. **Wait for Explicit Approval**: Present detailed completion message (see application-design.md for message format) - DO NOT PROCEED until user confirms +5. **Wait for Explicit Approval**: Present detailed completion message (see inception-application-design.md for message format) - DO NOT PROCEED until user confirms 6. **MANDATORY**: Log user's response in audit.md with complete raw input ## Units Generation (CONDITIONAL) @@ -293,7 +324,7 @@ The AI model intelligently assesses what stages are needed based on: 2. Load all steps from `inception-units-generation.md` 3. Load reverse engineering artifacts (if brownfield) 4. Execute at appropriate depth (minimal/standard/comprehensive) -5. **Wait for Explicit Approval**: Present detailed completion message (see units-generation.md for message format) - DO NOT PROCEED until user confirms +5. **Wait for Explicit Approval**: Present detailed completion message (see inception-units-generation.md for message format) - DO NOT PROCEED until user confirms 6. **MANDATORY**: Log user's response in audit.md with complete raw input --- @@ -336,7 +367,7 @@ The AI model intelligently assesses what stages are needed based on: 1. **MANDATORY**: Log any user input during this stage in audit.md 2. Load all steps from `construction-functional-design.md` 3. Execute functional design for this unit -4. **MANDATORY**: Present standardized 2-option completion message as defined in functional-design.md - DO NOT use emergent 3-option behavior +4. **MANDATORY**: Present standardized 2-option completion message as defined in construction-functional-design.md - DO NOT use emergent 3-option behavior 5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms 6. **MANDATORY**: Log user's response in audit.md with complete raw input @@ -356,7 +387,7 @@ The AI model intelligently assesses what stages are needed based on: 1. **MANDATORY**: Log any user input during this stage in audit.md 2. Load all steps from `construction-nfr-requirements.md` 3. Execute NFR assessment for this unit -4. **MANDATORY**: Present standardized 2-option completion message as defined in nfr-requirements.md - DO NOT use emergent behavior +4. **MANDATORY**: Present standardized 2-option completion message as defined in construction-nfr-requirements.md - DO NOT use emergent behavior 5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms 6. **MANDATORY**: Log user's response in audit.md with complete raw input @@ -368,13 +399,13 @@ The AI model intelligently assesses what stages are needed based on: **Skip IF**: - No NFR requirements -- NFR Requirements Assessment was skipped +- NFR Requirements was skipped **Execution**: 1. **MANDATORY**: Log any user input during this stage in audit.md 2. Load all steps from `construction-nfr-design.md` 3. Execute NFR design for this unit -4. **MANDATORY**: Present standardized 2-option completion message as defined in nfr-design.md - DO NOT use emergent behavior +4. **MANDATORY**: Present standardized 2-option completion message as defined in construction-nfr-design.md - DO NOT use emergent behavior 5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms 6. **MANDATORY**: Log user's response in audit.md with complete raw input @@ -393,7 +424,7 @@ The AI model intelligently assesses what stages are needed based on: 1. **MANDATORY**: Log any user input during this stage in audit.md 2. Load all steps from `construction-infrastructure-design.md` 3. Execute infrastructure design for this unit -4. **MANDATORY**: Present standardized 2-option completion message as defined in infrastructure-design.md - DO NOT use emergent behavior +4. **MANDATORY**: Present standardized 2-option completion message as defined in construction-infrastructure-design.md - DO NOT use emergent behavior 5. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms 6. **MANDATORY**: Log user's response in audit.md with complete raw input @@ -410,7 +441,7 @@ The AI model intelligently assesses what stages are needed based on: 2. Load all steps from `construction-code-generation.md` 3. **PART 1 - Planning**: Create code generation plan with checkboxes, get user approval 4. **PART 2 - Generation**: Execute approved plan to generate code for this unit -5. **MANDATORY**: Present standardized 2-option completion message as defined in code-generation.md - DO NOT use emergent behavior +5. **MANDATORY**: Present standardized 2-option completion message as defined in construction-code-generation.md - DO NOT use emergent behavior 6. **Wait for Explicit Approval**: User must choose between "Request Changes" or "Continue to Next Stage" - DO NOT PROCEED until user confirms 7. **MANDATORY**: Log user's response in audit.md with complete raw input @@ -467,7 +498,7 @@ The Operations stage will eventually include: - **CRITICAL**: Never summarize or paraphrase user input in audit log - **CRITICAL**: Log every interaction, not just approvals - **Quality Focus**: Complex changes get full treatment, simple changes stay efficient -- **Content Validation**: Always validate content before file creation per content-validation.md rules +- **Content Validation**: Always validate content before file creation per common-content-validation.md rules - **NO EMERGENT BEHAVIOR**: Construction phases MUST use standardized 2-option completion messages as defined in their respective rule files. DO NOT create 3-option menus or other emergent navigation patterns. ## MANDATORY: Plan-Level Checkbox Enforcement @@ -489,7 +520,7 @@ The Operations stage will eventually include: - **MANDATORY**: Log every approval prompt with timestamp before asking the user - **MANDATORY**: Record every user response with timestamp after receiving it - **CRITICAL**: ALWAYS append changes to EDIT audit.md file, NEVER use tools and commands that completely overwrite its contents -- **CRITICAL**: Using file writing tools and commands that overwrite contents of the entire audit.md and cause duplication +- **CRITICAL**: NEVER use file writing tools and commands that overwrite the entire contents of audit.md, as this causes duplication - Use ISO 8601 format for timestamps (YYYY-MM-DDTHH:MM:SSZ) - Include stage context for each entry @@ -520,7 +551,7 @@ The Operations stage will eventually include: ```text / # ⚠️ APPLICATION CODE HERE -├── [project-specific structure] # Varies by project (see code-generation.md) +├── [project-specific structure] # Varies by project (see construction-code-generation.md) │ ├── aidlc-docs/ # 📄 DOCUMENTATION ONLY │ ├── inception/ # 🔵 INCEPTION PHASE @@ -546,4 +577,4 @@ The Operations stage will eventually include: **CRITICAL RULE**: - Application code: Workspace root (NEVER in aidlc-docs/) - Documentation: aidlc-docs/ only -- Project structure: See code-generation.md for patterns by project type +- Project structure: See construction-code-generation.md for patterns by project type diff --git a/aidlc/steering/extensions-property-based-testing.md b/aidlc/steering/extensions-property-based-testing.md new file mode 100644 index 0000000..dd4d773 --- /dev/null +++ b/aidlc/steering/extensions-property-based-testing.md @@ -0,0 +1,284 @@ +# Property-Based Testing Rules + +## Overview + +These property-based testing (PBT) rules are cross-cutting constraints that apply across applicable AI-DLC phases. They ensure that code with identifiable properties is tested using property-based techniques, complementing (not replacing) traditional example-based tests. + +Property-based testing defines invariants that must hold for all valid inputs, then uses a framework to generate random inputs and search for counterexamples. When a failure is found, the framework shrinks the input to a minimal reproducing case. This approach uncovers edge cases and subtle bugs that example-based testing routinely misses. + +**Enforcement**: At each applicable stage, the model MUST verify compliance with these rules before presenting the stage completion message to the user. + +### Blocking PBT Finding Behavior + +A **blocking PBT finding** means: +1. The finding MUST be listed in the stage completion message under a "PBT Findings" section with the PBT rule ID and description +2. The stage MUST NOT present the "Continue to Next Stage" option until all blocking findings are resolved +3. The model MUST present only the "Request Changes" option with a clear explanation of what needs to change +4. The finding MUST be logged in `aidlc-docs/audit.md` with the PBT rule ID, description, and stage context + +If a PBT rule is not applicable to the current project or unit (e.g., PBT-06 when no stateful components exist), mark it as **N/A** in the compliance summary — this is not a blocking finding. + +### Default Enforcement + +All rules in this document are **blocking** by default. If any rule's verification criteria are not met, it is a blocking PBT finding — follow the blocking finding behavior defined above. + +### Partial Enforcement Mode + +If the user selected **Partial** enforcement during opt-in, only rules PBT-02, PBT-03, PBT-07, PBT-08, and PBT-09 are enforced. All other rules are treated as advisory (non-blocking). Log the enforcement mode in `aidlc-docs/aidlc-state.md` under `## Extension Configuration`. + +### Verification Criteria Format + +Verification items in this document are plain bullet points describing compliance checks. Each item should be evaluated as compliant or non-compliant during review. + +--- + +## Rule PBT-01: Property Identification During Design + +**Rule**: Every unit containing business logic, data transformations, or algorithmic operations MUST be analyzed for testable properties during the Functional Design stage. The analysis MUST identify which of the following property categories apply: + +| Category | Description | Example | +|---|---|---| +| Round-trip | An operation paired with its inverse yields the original value | serialize → deserialize = identity | +| Invariant | A transformation preserves some measurable characteristic | sort preserves collection size and elements | +| Idempotence | Applying an operation twice yields the same result as once | dedup(dedup(list)) = dedup(list) | +| Commutativity | Different operation orderings produce the same result | add(a, b) = add(b, a) | +| Oracle | A reference implementation or simplified model can verify results | optimized algorithm vs brute-force | +| Induction | A property proven for smaller inputs extends to larger ones | recursive structures, divide-and-conquer | +| Easy verification | The result is hard to compute but easy to check | maze solver output can be walked to verify | + +The identified properties MUST be documented in the functional design artifacts for the unit, and carried forward into code generation as PBT test requirements. + +**Verification**: +- Functional design artifacts include a "Testable Properties" section listing identified properties per component +- Each identified property references one of the categories above +- Components with no identifiable properties are explicitly marked as "No PBT properties identified" with a brief rationale +- The property list is referenced during code generation planning + +--- + +## Rule PBT-02: Round-Trip Properties + +**Rule**: Any operation that has a logical inverse MUST have a property-based test verifying the round-trip. This includes but is not limited to: +- Serialization / deserialization (JSON, XML, Protobuf, binary formats) +- Encoding / decoding (Base64, URL encoding, compression) +- Parsing / formatting (date parsing, number formatting, template rendering with structured input) +- Encryption / decryption (where key is available) +- Database write / read (for the data transformation layer, not the I/O itself) +- Any pair of functions where `f_inverse(f(x)) = x` for all valid `x` + +The property-based test MUST generate random valid inputs using a domain-appropriate generator (see PBT-07) and assert that the round-trip produces a value equal to the original input. + +**Verification**: +- Every serialization/deserialization pair has a round-trip property test +- Every encoding/decoding pair has a round-trip property test +- Every parsing/formatting pair has a round-trip property test (or documents why the transformation is lossy) +- Round-trip tests use generated inputs, not hardcoded examples +- Lossy transformations (e.g., float formatting with precision loss) document the acceptable deviation and test within tolerance + +--- + +## Rule PBT-03: Invariant Properties + +**Rule**: Functions with documented invariants MUST have property-based tests verifying those invariants hold across generated inputs. Common invariants include: +- **Size preservation**: output collection has the same size as input (e.g., map, sort) +- **Element preservation**: output contains exactly the same elements as input, possibly reordered (e.g., sort, shuffle) +- **Ordering guarantees**: output satisfies an ordering constraint (e.g., sort produces non-decreasing order) +- **Range constraints**: output values fall within a defined range (e.g., normalize produces values in [0, 1]) +- **Type preservation**: output type matches expected type for all valid inputs +- **Business rule invariants**: domain-specific rules that must always hold (e.g., "account balance never goes negative after a valid transaction", "discount never exceeds item price") + +**Verification**: +- Each documented invariant has a corresponding property-based test +- Invariant tests generate a wide range of inputs including boundary values +- Business rule invariants identified in functional design are covered by PBT +- Invariant tests do not duplicate exact assertions from example-based tests — they test the general rule, not specific cases + +--- + +## Rule PBT-04: Idempotency Properties + +**Rule**: Any operation that claims or requires idempotency MUST have a property-based test proving it. The test MUST verify that `f(f(x)) = f(x)` for all valid generated inputs. This applies to: +- API endpoints documented as idempotent (PUT, DELETE) +- Data normalization or sanitization functions +- Cache population operations +- Deduplication logic +- Configuration application (applying config twice should not change state) +- Message processing in at-least-once delivery systems + +**Verification**: +- Every operation documented as idempotent has a PBT asserting `f(f(x)) = f(x)` +- Idempotency tests use domain-appropriate generators (not just primitives) +- For stateful operations, the test verifies observable state equivalence after single vs repeated application + +--- + +## Rule PBT-05: Oracle and Model-Based Testing + +**Rule**: When a reference implementation, simplified model, or known-correct algorithm exists, property-based tests MUST compare the system under test against the oracle. This applies to: +- Optimized algorithms replacing a known brute-force version +- Refactored code replacing legacy implementations +- Parallel/concurrent implementations compared against sequential versions +- Custom implementations of well-known algorithms (sorting, searching, graph traversal) +- New query engines compared against a reference database + +The property-based test MUST generate random valid inputs and assert that the system under test produces equivalent results to the oracle for all generated inputs. + +**Verification**: +- When a reference implementation exists (or can be trivially written), an oracle PBT is present +- Oracle tests generate diverse inputs covering normal, boundary, and adversarial cases +- Equivalence is defined precisely (exact equality, structural equality, or documented tolerance) +- If no oracle exists, this rule is marked N/A with rationale + +--- + +## Rule PBT-06: Stateful Property Testing + +**Rule**: Components that manage mutable state MUST be evaluated for stateful property testing. Stateful PBT generates random sequences of commands (operations) against the system and verifies that invariants hold after each step. This applies to: +- In-memory caches and data stores +- State machines and workflow engines +- Queue and buffer implementations +- Session management systems +- Shopping carts, order pipelines, and similar stateful business objects +- Any component where the result of an operation depends on prior operations + +Stateful PBT MUST: +- Define a simplified model (reference state) that mirrors the system under test +- Generate random sequences of valid commands (add, remove, update, query, etc.) +- Execute each command against both the real system and the model +- Assert that observable state or query results match between system and model after each command +- Test sequences of varying lengths, including empty sequences + +**Verification**: +- Stateful components identified in functional design have stateful PBT or document why it is not applicable +- A simplified model is defined for comparison +- Command generators produce valid operation sequences with realistic parameter distributions +- Invariants are checked after each command in the sequence, not just at the end +- If no stateful components exist, this rule is marked N/A + +--- + +## Rule PBT-07: Generator Quality + +**Rule**: Property-based tests MUST use domain-specific generators that produce realistic, structured inputs — not just primitive types. Poor generators (e.g., random strings for email fields, unbounded integers for age fields) produce meaningless test cases and miss real bugs. + +Generator requirements: +- **Domain types**: Custom generators MUST be created for domain objects (e.g., User, Order, Transaction) that respect business constraints (valid email format, positive amounts, valid date ranges) +- **Constrained primitives**: Numeric generators MUST be constrained to realistic ranges where the domain requires it +- **Structured data**: Generators for complex inputs (nested objects, lists of domain objects) MUST produce structurally valid data +- **Edge case inclusion**: Generators SHOULD be configured to include boundary values (empty collections, zero, maximum values, Unicode strings) alongside normal values +- **Reusability**: Domain generators SHOULD be defined as reusable test utilities, not duplicated across test files + +**Verification**: +- No PBT uses only raw primitive generators (e.g., `st.integers()` alone) for domain-typed parameters +- Custom generators exist for domain objects used in PBT +- Generators respect documented business constraints (e.g., positive amounts, valid formats) +- Generator definitions are centralized and reusable where multiple tests share the same domain types + +--- + +## Rule PBT-08: Shrinking and Reproducibility + +**Rule**: All property-based tests MUST support shrinking and deterministic reproducibility. + +- **Shrinking**: When a property fails, the PBT framework MUST automatically reduce the failing input to a minimal reproducing case. Tests MUST NOT disable or bypass the framework's shrinking mechanism unless there is a documented technical reason (e.g., shrinking is incompatible with external service calls in integration tests). +- **Reproducibility**: Every PBT run MUST be reproducible via a seed value. The seed MUST be logged on failure so that the exact failing scenario can be replayed. CI configurations MUST either use a fixed seed for deterministic runs or log the random seed on every run for post-failure reproduction. +- **CI integration**: PBT MUST be included in the project's CI pipeline. Flaky PBT failures (tests that pass on retry without code changes) MUST be investigated, not suppressed. + +**Verification**: +- PBT framework's shrinking is enabled (not overridden or disabled) +- Test output on failure includes the seed value and the shrunk minimal failing input +- CI configuration logs the seed for every PBT run or uses a fixed seed +- No PBT is excluded from CI without documented justification +- Flaky PBT failures are tracked and investigated, not silently retried + +--- + +## Rule PBT-09: Framework Selection + +**Rule**: The project MUST select and configure an appropriate property-based testing framework for its primary language(s). The framework MUST support: +- Custom generators / strategies for domain types +- Automatic shrinking of failing cases +- Seed-based reproducibility +- Integration with the project's existing test runner + +Recommended frameworks by language (non-exhaustive): + +| Language | Framework | Notes | +|---|---|---| +| Python | Hypothesis | Mature, excellent shrinking, Django integration | +| JavaScript / TypeScript | fast-check | Integrates with Jest, Vitest, Mocha | +| Java | jqwik | JUnit 5 integration, stateful testing support | +| Kotlin | Kotest Property Testing | Kotest framework integration | +| Scala | ScalaCheck | SBT integration, widely adopted | +| Rust | proptest | Macro-based, good shrinking | +| Go | rapid | Lightweight, idiomatic Go | +| Haskell | QuickCheck | The original PBT framework | +| C# / .NET | FsCheck | Works with xUnit, NUnit | +| Erlang / Elixir | PropEr / StreamData | OTP-aware, stateful testing | + +The selected framework MUST be documented in the tech stack decisions and included as a project dependency. + +**Verification**: +- A PBT framework is selected and documented in tech stack decisions +- The framework is included in project dependencies (package.json, pom.xml, requirements.txt, etc.) +- The framework supports custom generators, shrinking, and seed-based reproducibility +- If the project uses multiple languages, each language with PBT-applicable code has a framework selected + +--- + +## Rule PBT-10: Complementary Testing Strategy + +**Rule**: Property-based tests MUST complement, not replace, example-based tests. The two approaches serve different purposes: + +- **Example-based tests**: Document specific known scenarios, regression cases, and business-critical edge cases with explicit expected values. They serve as executable documentation of concrete behavior. +- **Property-based tests**: Verify general invariants across a wide input space. They find unknown edge cases and validate that properties hold universally. + +Requirements: +- Critical business scenarios identified in user stories or requirements MUST have explicit example-based tests, even if a PBT covers the same property +- PBT MUST NOT be the sole test for any business-critical path — at least one example-based test must pin the expected behavior for key scenarios +- When a PBT discovers a failing case, the shrunk minimal example SHOULD be added as a permanent example-based regression test +- Test documentation MUST clearly distinguish between example-based and property-based tests (separate test files, test classes, or clearly named test functions) + +**Verification**: +- Business-critical paths have both example-based and property-based tests +- PBT is not used as the only test coverage for any critical feature +- Test files or test classes clearly separate or label PBT vs example-based tests +- Regression tests from PBT-discovered failures are captured as permanent example-based tests + +--- + +## Enforcement Integration + +These rules are cross-cutting constraints that apply to the following AI-DLC stages: + +| Stage | Applicable Rules | Enforcement | +|---|---|---| +| Functional Design | PBT-01 | Property identification must appear in design artifacts | +| NFR Requirements | PBT-09 | Framework selection must be included in tech stack decisions | +| Code Generation (Planning) | PBT-01 through PBT-10 | Code generation plan must include PBT test steps for identified properties | +| Code Generation (Generation) | PBT-02 through PBT-08, PBT-10 | Generated tests must include PBT alongside example-based tests | +| Build and Test | PBT-08 | Test execution instructions must include PBT with seed logging and CI integration | + +At each applicable stage: +- Evaluate all PBT rule verification criteria against the artifacts produced +- Include a "PBT Compliance" section in the stage completion summary listing each rule as compliant, non-compliant, or N/A +- If any rule is non-compliant, this is a blocking PBT finding — follow the blocking finding behavior defined in the Overview +- Include PBT rule references in design documentation and test instructions + +--- + +## Appendix: Property Category Quick Reference + +For developers and AI models identifying properties during Functional Design (PBT-01): + +| Pattern Name | Formal Term | Test Shape | When to Use | +|---|---|---|---| +| There and back again | Invertible function | `f_inv(f(x)) == x` | Serialization, encoding, parsing | +| Some things never change | Invariant | `measure(f(x)) == measure(x)` | Sort, map, filter, transform | +| The more things change, the more they stay the same | Idempotence | `f(f(x)) == f(x)` | Normalization, dedup, cache writes | +| Different paths, same destination | Commutativity | `f(g(x)) == g(f(x))` | Arithmetic, set operations, independent transforms | +| Solve a smaller problem first | Structural induction | Property on `x` implies property on `x + element` | Recursive structures, lists, trees | +| Hard to prove, easy to verify | Verification | `verify(solve(x)) == true` | Solvers, optimizers, search algorithms | +| The test oracle | Reference comparison | `f(x) == oracle(x)` | Optimized vs brute-force, refactored vs legacy | + +Source: Property category taxonomy adapted from Scott Wlaschin's "Choosing properties for property-based testing" ([fsharpforfunandprofit.com](https://fsharpforfunandprofit.com/posts/property-based-testing-2/)). diff --git a/aidlc/steering/extensions-property-based-testing.opt-in.md b/aidlc/steering/extensions-property-based-testing.opt-in.md new file mode 100644 index 0000000..6042d9f --- /dev/null +++ b/aidlc/steering/extensions-property-based-testing.opt-in.md @@ -0,0 +1,19 @@ +# Property-Based Testing — Opt-In + +**Extension**: Property-Based Testing + +## Opt-In Prompt + +The following question is automatically included in the Requirements Analysis clarifying questions when this extension is loaded: + +```markdown +## Question: Property-Based Testing Extension +Should property-based testing (PBT) rules be enforced for this project? + +A) Yes — enforce all PBT rules as blocking constraints (recommended for projects with business logic, data transformations, serialization, or stateful components) +B) Partial — enforce PBT rules only for pure functions and serialization round-trips (suitable for projects with limited algorithmic complexity) +C) No — skip all PBT rules (suitable for simple CRUD applications, UI-only projects, or thin integration layers with no significant business logic) +X) Other (please describe after [Answer]: tag below) + +[Answer]: +``` diff --git a/aidlc/steering/extensions-security-baseline.md b/aidlc/steering/extensions-security-baseline.md new file mode 100644 index 0000000..85914f2 --- /dev/null +++ b/aidlc/steering/extensions-security-baseline.md @@ -0,0 +1,307 @@ +# Baseline Security Rules + +## Overview +These security rules are MANDATORY cross-cutting constraints that apply across all AI-DLC phases. They are not optional guidance — they are hard constraints that stages MUST enforce when generating questions, producing design artifacts, generating code, and presenting completion messages. + +**Enforcement**: At each applicable stage, the model MUST verify compliance with these rules before presenting the stage completion message to the user. + +### Blocking Security Finding Behavior +A **blocking security finding** means: +1. The finding MUST be listed in the stage completion message under a "Security Findings" section with the SECURITY rule ID and description +2. The stage MUST NOT present the "Continue to Next Stage" option until all blocking findings are resolved +3. The model MUST present only the "Request Changes" option with a clear explanation of what needs to change +4. The finding MUST be logged in `aidlc-docs/audit.md` with the SECURITY rule ID, description, and stage context + +If a SECURITY rule is not applicable to the current project (e.g., SECURITY-01 when no data stores exist), mark it as **N/A** in the compliance summary — this is not a blocking finding. + +### Default Enforcement +All rules in this document are **blocking** by default. If any rule's verification criteria are not met, it is a blocking security finding — follow the blocking finding behavior defined above. + +### Verification Criteria Format +Verification items in this document are plain bullet points describing compliance checks. They are distinct from the `- [ ]` / `- [x]` progress-tracking checkboxes used in stage plan files. Each item should be evaluated as compliant or non-compliant during review. + +--- + +## Rule SECURITY-01: Encryption at Rest and in Transit + +**Rule**: Every data persistence store (databases, object storage, file systems, caches, or any equivalent) MUST have: +- Encryption at rest enabled using a managed key service or customer-managed keys +- Encryption in transit enforced (TLS 1.2+ for all data movement in and out of the store) + +**Verification**: +- No storage resource is defined without an encryption configuration block +- No database connection string uses an unencrypted protocol +- Object storage enforces encryption at rest and rejects non-TLS requests via policy +- Database instances have storage encryption enabled and enforce TLS connections + +--- + +## Rule SECURITY-02: Access Logging on Network Intermediaries + +**Rule**: Every network-facing intermediary that handles external traffic MUST have access logging enabled. This includes: +- Load balancers → access logs to a persistent store +- API gateways → execution logging and access logging to a centralized log service +- CDN distributions → standard logging or real-time logs + +**Verification**: +- No load balancer resource is defined without access logging enabled +- No API gateway stage is defined without access logging configured +- No CDN distribution is defined without logging configuration + +--- + +## Rule SECURITY-03: Application-Level Logging + +**Rule**: Every deployed application component MUST include structured logging infrastructure: +- A logging framework MUST be configured +- Log output MUST be directed to a centralized log service +- Logs MUST include: timestamp, correlation/request ID, log level, and message +- Sensitive data (passwords, tokens, PII) MUST NOT appear in log output + +**Verification**: +- Every service/function entry point includes a configured logger +- No ad-hoc logging statements used as the primary logging mechanism in production code +- Log configuration routes output to a centralized log service +- No secrets, tokens, or PII are logged + +--- + +## Rule SECURITY-04: HTTP Security Headers for Web Applications + +**Rule**: The following HTTP response headers MUST be set on all HTML-serving endpoints: + +| Header | Required Value | +|---|---| +| `Content-Security-Policy` | Define a restrictive policy (at minimum: `default-src 'self'`) | +| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | +| `X-Content-Type-Options` | `nosniff` | +| `X-Frame-Options` | `DENY` (or `SAMEORIGIN` if framing is required) | +| `Referrer-Policy` | `strict-origin-when-cross-origin` | + +**Note**: `X-XSS-Protection` is deprecated in modern browsers. Use `Content-Security-Policy` instead. + +**Verification**: +- Middleware or response interceptor sets all required headers +- CSP policy does not use `unsafe-inline` or `unsafe-eval` without documented justification +- HSTS max-age is at least 31536000 (1 year) + +--- + +## Rule SECURITY-05: Input Validation on All API Parameters + +**Rule**: Every API endpoint (REST, GraphQL, gRPC, WebSocket) MUST validate all input parameters before processing. Validation MUST include: +- **Type checking**: Reject unexpected types +- **Length/size bounds**: Enforce maximum lengths on strings, maximum sizes on arrays and payloads +- **Format validation**: Use allowlists (regex or schema) for structured inputs (emails, dates, IDs) +- **Sanitization**: Escape or reject HTML/script content in user-supplied strings to prevent XSS +- **Injection prevention**: Use parameterized queries for all database operations (never string concatenation) + +**Verification**: +- Every API handler uses a validation library or schema +- No raw user input is concatenated into SQL, NoSQL, or OS commands +- String inputs have explicit max-length constraints +- Request body size limits are configured at the framework or gateway level + +--- + +## Rule SECURITY-06: Least-Privilege Access Policies + +**Rule**: Every identity and access management policy, role, or permission boundary MUST follow least privilege: +- Use specific resource identifiers — NEVER use wildcard resources unless the API does not support resource-level permissions (document the exception) +- Use specific actions — NEVER use wildcard actions +- Scope conditions where possible +- Separate read and write permissions into distinct policy statements + +**Verification**: +- No policy contains wildcard actions or wildcard resources without a documented exception +- No service role has broader permissions than what the service actually calls +- Inline policies are avoided in favor of managed policies where possible +- Every role has a trust policy scoped to the specific service or account + +--- + +## Rule SECURITY-07: Restrictive Network Configuration + +**Rule**: All network configurations (security groups, network ACLs, route tables) MUST follow deny-by-default: +- Firewall rules: Only open specific ports required by the application +- No inbound rule with source `0.0.0.0/0` except for public-facing load balancers on ports 80/443 +- No outbound rule with `0.0.0.0/0` on all ports unless explicitly justified +- Private subnets MUST NOT have direct internet gateway routes +- Use private endpoints for cloud service access where available + +**Verification**: +- No firewall rule allows inbound `0.0.0.0/0` on any port other than 80/443 on a public load balancer +- Database and application firewall rules restrict source to specific CIDR blocks or security group references +- Private subnets route through a NAT gateway (not an internet gateway) +- Private endpoints are used for high-traffic cloud service calls + +--- + +## Rule SECURITY-08: Application-Level Access Control + +**Rule**: Every application endpoint that accesses or mutates a resource MUST enforce authorization checks at the application layer: +- **Deny by default**: All routes/endpoints MUST require authentication unless explicitly marked as public +- **Object-level authorization**: Every request that references a resource by ID MUST verify the requesting user/principal owns or has permission to access that resource (prevent IDOR) +- **Function-level authorization**: Administrative or privileged operations MUST check the caller's role/permissions server-side — never rely on client-side hiding +- **CORS policy**: Cross-origin resource sharing MUST be restricted to explicitly allowed origins — never use `Access-Control-Allow-Origin: *` on authenticated endpoints +- **Token validation**: JWTs or session tokens MUST be validated server-side on every request (signature, expiration, audience, issuer) + +**Verification**: +- Every controller/handler has an authorization middleware or guard applied +- No endpoint returns data for a resource ID without verifying the caller's ownership or permission +- Admin/privileged routes have explicit role checks enforced server-side +- CORS configuration does not use wildcard origins on authenticated endpoints +- Token validation occurs server-side on every request (not just at login) + +--- + +## Rule SECURITY-09: Security Hardening and Misconfiguration Prevention + +**Rule**: All deployed components MUST follow a hardening baseline: +- **No default credentials**: Default usernames/passwords MUST be changed or disabled before deployment +- **Minimal installation**: Remove or disable unused features, frameworks, sample applications, and documentation endpoints +- **Error handling**: Production error responses MUST NOT expose stack traces, internal paths, framework versions, or database details to end users +- **Directory listing**: Web servers MUST disable directory listing +- **Cloud storage**: Cloud object storage MUST block public access unless explicitly required and documented +- **Patch management**: Runtime environments, frameworks, and OS images MUST use current, supported versions + +**Verification**: +- No default credentials exist in configuration files, environment variables, or IaC templates +- Error responses in production return generic messages (no stack traces or internal details) +- Cloud object storage has public access blocked unless a documented exception exists +- No sample/demo applications or default pages are deployed +- Framework and runtime versions are current and supported + + +--- + +## Rule SECURITY-10: Software Supply Chain Security + +**Rule**: Every project MUST manage its software supply chain: +- **Dependency pinning**: All dependencies MUST use exact versions or lock files +- **Vulnerability scanning**: A dependency vulnerability scanner MUST be configured +- **No unused dependencies**: Remove packages that are not actively used +- **Trusted sources only**: Dependencies MUST be pulled from official registries or verified private registries — no unvetted third-party sources +- **SBOM**: Projects MUST generate a Software Bill of Materials for production deployments +- **CI/CD integrity**: Build pipelines MUST use pinned tool versions and verified base images — no `latest` tags in production Dockerfiles or CI configurations + +**Verification**: +- A lock file exists and is committed to version control +- A dependency vulnerability scanning step is included in CI/CD or documented in build instructions +- No unused or abandoned dependencies are included +- Dockerfiles and CI configs do not use `latest` or unpinned image tags for production +- Dependencies are sourced from official or verified registries + +--- + +## Rule SECURITY-11: Secure Design Principles + +**Rule**: Application design MUST incorporate security from the start: +- **Separation of concerns**: Security-critical logic (authentication, authorization, payment processing) MUST be isolated in dedicated modules — not scattered across the codebase +- **Defense in depth**: No single control should be the sole line of defense — layer controls (validation + authorization + encryption) +- **Rate limiting**: Public-facing endpoints MUST implement rate limiting or throttling to prevent abuse +- **Business logic abuse**: Design MUST consider misuse cases — not just happy-path scenarios + +**Verification**: +- Security-critical logic is encapsulated in dedicated modules or services +- Rate limiting is configured on public-facing APIs +- Design documentation addresses at least one misuse/abuse scenario + +--- + +## Rule SECURITY-12: Authentication and Credential Management + +**Rule**: Every application with user authentication MUST implement: +- **Password policy**: Minimum 8 characters, check against breached password lists +- **Credential storage**: Passwords MUST be hashed using adaptive algorithms — never weak or non-adaptive hashing +- **Multi-factor authentication**: MFA MUST be supported for administrative accounts and SHOULD be available for all users +- **Session management**: Sessions MUST have server-side expiration, be invalidated on logout, and use secure/httpOnly/sameSite cookie attributes +- **Brute-force protection**: Login endpoints MUST implement account lockout, progressive delays, or CAPTCHA after repeated failures +- **No hardcoded credentials**: No passwords, API keys, or secrets in source code or IaC templates — use a secrets manager + +**Verification**: +- Password hashing uses adaptive algorithms (not weak or non-adaptive hashing) +- Session cookies set `Secure`, `HttpOnly`, and `SameSite` attributes +- Login endpoints have brute-force protection (lockout, delay, or CAPTCHA) +- No hardcoded credentials in source code or configuration files +- MFA is supported for admin accounts +- Sessions are invalidated on logout and have a defined expiration + +--- + +## Rule SECURITY-13: Software and Data Integrity Verification + +**Rule**: Systems MUST verify the integrity of software and data: +- **Deserialization safety**: Untrusted data MUST NOT be deserialized without validation — use safe deserialization libraries or allowlists of permitted types +- **Artifact integrity**: Downloaded dependencies, plugins, and updates MUST be verified via checksums or digital signatures +- **CI/CD pipeline security**: Build pipelines MUST restrict who can modify pipeline definitions — separate duties between code authors and deployment approvers +- **CDN and external resources**: Scripts or resources loaded from external CDNs MUST use Subresource Integrity (SRI) hashes +- **Data integrity**: Critical data modifications MUST be auditable (who changed what, when) + +**Verification**: +- No unsafe deserialization of untrusted input +- External scripts include SRI integrity attributes when loaded from CDNs +- CI/CD pipeline definitions are access-controlled and changes are auditable +- Critical data changes are logged with actor, timestamp, and before/after values + +--- + +## Rule SECURITY-14: Alerting and Monitoring + +**Rule**: In addition to logging (SECURITY-02, SECURITY-03), systems MUST include: +- **Security event alerting**: Alerts MUST be configured for high-value security events: repeated authentication failures, privilege escalation attempts, access from unusual locations, and authorization failures +- **Log integrity**: Logs MUST be stored in append-only or tamper-evident storage — application code MUST NOT be able to delete or modify its own audit logs +- **Log retention**: Logs MUST be retained for a minimum period appropriate to the application's compliance requirements (default: 90 days minimum) +- **Monitoring dashboards**: A monitoring dashboard or alarm configuration MUST be defined for key operational and security metrics + +**Verification**: +- Alerting is configured for authentication failures and authorization violations +- Application log groups have retention policies set (minimum 90 days) +- Application roles do not have permission to delete their own log groups/streams +- Security-relevant events (login failures, access denied, privilege changes) generate alerts + +--- + +## Rule SECURITY-15: Exception Handling and Fail-Safe Defaults + +**Rule**: Every application MUST handle exceptional conditions safely: +- **Catch and handle**: All external calls (database, API, file I/O) MUST have explicit error handling — no unhandled promise rejections or uncaught exceptions in production +- **Fail closed**: On error, the system MUST deny access or halt the operation — never fail open +- **Resource cleanup**: Error paths MUST release resources (connections, file handles, locks) — use try/finally, using statements, or equivalent patterns +- **User-facing errors**: Error messages shown to users MUST be generic — no internal details or system information +- **Global error handler**: Applications MUST have a global/top-level error handler that catches unhandled exceptions, logs them (per SECURITY-03), and returns a safe response + +**Verification**: +- All external calls (DB, HTTP, file I/O) have explicit error handling (try/catch, .catch(), error callbacks) +- A global error handler is configured at the application entry point +- Error paths do not bypass authorization or validation checks (fail closed) +- Resources are cleaned up in error paths (connections closed, transactions rolled back) +- No unhandled promise rejections or uncaught exception warnings in application code + +--- + +## Enforcement Integration + +These rules are cross-cutting constraints that apply to every AI-DLC stage. At each stage: +- Evaluate all SECURITY rule verification criteria against the artifacts produced +- Include a "Security Compliance" section in the stage completion summary listing each rule as compliant, non-compliant, or N/A +- If any rule is non-compliant, this is a blocking security finding — follow the blocking finding behavior defined in the Overview +- Include security rule references in design documentation and test instructions + +--- + +## Appendix: OWASP Reference Mapping + + +For human reviewers, the following maps SECURITY rules to OWASP Top 10 (2025) categories: + +| SECURITY Rule | OWASP Category | +|---|---| +| SECURITY-08 | A01:2025 – Broken Access Control | +| SECURITY-09 | A02:2025 – Security Misconfiguration | +| SECURITY-10 | A03:2025 – Software Supply Chain Failures | +| SECURITY-11 | A06:2025 – Insecure Design | +| SECURITY-12 | A07:2025 – Authentication Failures | +| SECURITY-13 | A08:2025 – Software or Data Integrity Failures | +| SECURITY-14 | A09:2025 – Logging & Alerting Failures | +| SECURITY-15 | A10:2025 – Mishandling of Exceptional Conditions | diff --git a/aidlc/steering/extensions-security-baseline.opt-in.md b/aidlc/steering/extensions-security-baseline.opt-in.md new file mode 100644 index 0000000..cd24766 --- /dev/null +++ b/aidlc/steering/extensions-security-baseline.opt-in.md @@ -0,0 +1,18 @@ +# Security Baseline — Opt-In + +**Extension**: Security Baseline + +## Opt-In Prompt + +The following question is automatically included in the Requirements Analysis clarifying questions when this extension is loaded: + +```markdown +## Question: Security Extensions +Should security extension rules be enforced for this project? + +A) Yes — enforce all SECURITY rules as blocking constraints (recommended for production-grade applications) +B) No — skip all SECURITY rules (suitable for PoCs, prototypes, and experimental projects) +X) Other (please describe after [Answer]: tag below) + +[Answer]: +``` diff --git a/aidlc/steering/inception-application-design.md b/aidlc/steering/inception-application-design.md index 9ad90f6..09d1b13 100644 --- a/aidlc/steering/inception-application-design.md +++ b/aidlc/steering/inception-application-design.md @@ -12,9 +12,9 @@ Application Design focuses on: **Note**: Detailed business logic design happens later in Functional Design (per-unit, CONSTRUCTION phase) ## Prerequisites -- Context Assessment must be complete -- Requirements Assessment recommended (provides functional context) -- Story Development recommended (user stories guide design decisions) +- Workspace Detection must be complete +- Requirements Analysis recommended (provides functional context) +- User Stories recommended (user stories guide design decisions) - Execution plan must indicate Application Design stage should execute ## Step-by-Step Execution @@ -38,18 +38,19 @@ Application Design focuses on: - [ ] Validate design completeness and consistency ### 4. Generate Context-Appropriate Questions -**DIRECTIVE**: Analyze the requirements and stories to generate ONLY questions relevant to THIS specific application design. Use the categories below as inspiration, NOT as a mandatory checklist. Skip entire categories if not applicable. +**DIRECTIVE**: Analyze the requirements and stories to generate questions relevant to THIS specific application design. Use the categories below as guidance. Evaluate each category and, when in doubt about applicability, ask the question rather than skipping it — overconfidence leads to poor outcomes (see common-overconfidence-prevention.md). - EMBED questions using [Answer]: tag format -- Focus on ambiguities and missing information specific to this context -- Generate questions only where user input is needed for design decisions +- Focus on ANY ambiguities, missing information, or areas needing clarification +- Generate questions wherever user input would improve design decisions +- **When in doubt, ask the question** - overconfidence leads to poor designs -**Example question categories** (adapt as needed): -- **Component Identification** - Only if component boundaries or organization is unclear -- **Component Methods** - Only if method signatures need clarification (detailed business rules come later) -- **Service Layer Design** - Only if service orchestration or boundaries are ambiguous -- **Component Dependencies** - Only if communication patterns or dependency management is unclear -- **Design Patterns** - Only if architectural style or pattern choice needs user input +**Question categories to evaluate** (consider ALL categories): +- **Component Identification** - Ask about component boundaries, organization, and grouping strategies +- **Component Methods** - Ask about method signatures, input/output expectations, and interface contracts (detailed business rules come later) +- **Service Layer Design** - Ask about service orchestration, boundaries, and coordination patterns +- **Component Dependencies** - Ask about communication patterns, dependency management, and coupling concerns +- **Design Patterns** - Ask about architectural style preferences, pattern choices, and design constraints ### 5. Store Application Design Plan - Save as `aidlc-docs/inception/plans/application-design-plan.md` @@ -103,6 +104,7 @@ If the analysis in step 8 reveals ANY ambiguous answers, you MUST: - Dependency matrix showing relationships - Communication patterns between components - Data flow diagrams +- Create `aidlc-docs/inception/application-design/application-design.md` that consolidates the multiple design docs created above in a single doc. ### 11. Log Approval - Log approval prompt with timestamp in `aidlc-docs/audit.md` diff --git a/aidlc/steering/inception-requirements-analysis.md b/aidlc/steering/inception-requirements-analysis.md index 2913159..ccc8ccc 100644 --- a/aidlc/steering/inception-requirements-analysis.md +++ b/aidlc/steering/inception-requirements-analysis.md @@ -90,6 +90,22 @@ Analyze whatever the user has provided: **When in doubt, ask questions** - incomplete requirements lead to poor implementations. +### Step 5.1: Extension Opt-In Prompts + +**MANDATORY**: Scan all loaded `*.opt-in.md` files (loaded at workflow start from `extensions-` prefixed files) for an `## Opt-In Prompt` section. For each extension that declares one, include that question in the clarifying questions file created in Step 6. Present each opt-in question in the same language as the user's conversation. + +After receiving answers: +1. Record each extension's enablement status in `aidlc-docs/aidlc-state.md` under `## Extension Configuration`: + +```markdown +## Extension Configuration +| Extension | Enabled | Decided At | +|---|---|---| +| [Extension Name] | [Yes/No] | Requirements Analysis | +``` + +2. **Deferred Rule Loading**: For each extension the user opted IN, load the full rules file now. The rules file is derived by naming convention: strip `.opt-in.md` from the opt-in filename and append `.md` (e.g., `extensions-security-baseline.opt-in.md` → `extensions-security-baseline.md`). For extensions the user opted OUT, do NOT load the full rules file. + ### Step 6: Generate Clarifying Questions (PROACTIVE APPROACH) - **ALWAYS** create `aidlc-docs/inception/requirements/requirement-verification-questions.md` unless requirements are exceptionally clear and complete - Ask questions about ANY missing, unclear, or ambiguous areas @@ -103,7 +119,12 @@ Analyze whatever the user has provided: - **MANDATORY**: Analyze ALL answers for ambiguities and create follow-up questions if needed - **MANDATORY**: Keep asking questions until ALL ambiguities are resolved OR user explicitly asks to proceed +### ⛔ GATE: Await User Answers +DO NOT proceed to Step 7 until all questions in requirement-verification-questions.md are answered and validated. +Present the question file to the user and STOP. + ### Step 7: Generate Requirements Document + - **PREREQUISITE**: Step 6 gate must be passed — all answers received and analyzed - Create `aidlc-docs/inception/requirements/requirements.md` - Include intent analysis summary at the top: - User request diff --git a/aidlc/steering/inception-reverse-engineering.md b/aidlc/steering/inception-reverse-engineering.md index f7b08f5..cba3ecd 100644 --- a/aidlc/steering/inception-reverse-engineering.md +++ b/aidlc/steering/inception-reverse-engineering.md @@ -6,7 +6,7 @@ **Skip when**: Greenfield project (no existing code) -**Rerun behavior**: Always rerun when brownfield project detected, even if artifacts exist. This ensures artifacts reflect current code state +**Rerun behavior**: Rerun is controlled by inception-workspace-detection.md. If existing reverse engineering artifacts are found and are still current, they are loaded and reverse engineering is skipped. If artifacts are stale (older than the codebase's last significant modification) or the user explicitly requests a rerun, reverse engineering executes again to ensure artifacts reflect current code state ## Step 1: Multi-Package Discovery @@ -43,7 +43,7 @@ - Linting configurations - CI/CD pipelines -## Step 1: Generate Business Overview Documentation +## Step 2: Generate Business Overview Documentation Create `aidlc-docs/inception/reverse-engineering/business-overview.md`: @@ -64,7 +64,7 @@ Create `aidlc-docs/inception/reverse-engineering/business-overview.md`: - **Responsibilities**: [Key responsibilities] ``` -## Step 2: Generate Architecture Documentation +## Step 3: Generate Architecture Documentation Create `aidlc-docs/inception/reverse-engineering/architecture.md`: @@ -98,7 +98,7 @@ Create `aidlc-docs/inception/reverse-engineering/architecture.md`: - **Networking**: [VPC, subnets, security groups] ``` -## Step 3: Generate Code Structure Documentation +## Step 4: Generate Code Structure Documentation Create `aidlc-docs/inception/reverse-engineering/code-structure.md`: @@ -131,7 +131,7 @@ Create `aidlc-docs/inception/reverse-engineering/code-structure.md`: - **Purpose**: [Why needed] ``` -## Step 4: Generate API Documentation +## Step 5: Generate API Documentation Create `aidlc-docs/inception/reverse-engineering/api-documentation.md`: @@ -159,7 +159,7 @@ Create `aidlc-docs/inception/reverse-engineering/api-documentation.md`: - **Validation**: [Validation rules] ``` -## Step 5: Generate Component Inventory +## Step 6: Generate Component Inventory Create `aidlc-docs/inception/reverse-engineering/component-inventory.md`: @@ -186,7 +186,7 @@ Create `aidlc-docs/inception/reverse-engineering/component-inventory.md`: - **Test**: [Number] ``` -## Step 6: Generate Technology Stack Documentation +## Step 7: Generate Technology Stack Documentation Create `aidlc-docs/inception/reverse-engineering/technology-stack.md`: @@ -209,7 +209,7 @@ Create `aidlc-docs/inception/reverse-engineering/technology-stack.md`: - [Tool] - [Version] - [Purpose] ``` -## Step 7: Generate Dependencies Documentation +## Step 8: Generate Dependencies Documentation Create `aidlc-docs/inception/reverse-engineering/dependencies.md`: @@ -230,7 +230,7 @@ Create `aidlc-docs/inception/reverse-engineering/dependencies.md`: - **License**: [License type] ``` -## Step 8: Generate Code Quality Assessment +## Step 9: Generate Code Quality Assessment Create `aidlc-docs/inception/reverse-engineering/code-quality-assessment.md`: @@ -255,7 +255,7 @@ Create `aidlc-docs/inception/reverse-engineering/code-quality-assessment.md`: - **Anti-patterns**: [List with locations] ``` -## Step 9: Create Timestamp File +## Step 10: Create Timestamp File Create `aidlc-docs/inception/reverse-engineering/reverse-engineering-timestamp.md`: @@ -277,7 +277,7 @@ Create `aidlc-docs/inception/reverse-engineering/reverse-engineering-timestamp.m - [x] code-quality-assessment.md ``` -## Step 10: Update State Tracking +## Step 11: Update State Tracking Update `aidlc-docs/aidlc-state.md`: @@ -287,7 +287,7 @@ Update `aidlc-docs/aidlc-state.md`: - **Artifacts Location**: aidlc-docs/inception/reverse-engineering/ ``` -## Step 11: Present Completion Message to User +## Step 12: Present Completion Message to User ```markdown # 🔍 Reverse Engineering Complete @@ -305,7 +305,7 @@ Update `aidlc-docs/aidlc-state.md`: > ✅ **Approve & Continue** - Approve analysis and proceed to **Requirements Analysis** ``` -## Step 12: Wait for User Approval +## Step 13: Wait for User Approval - **MANDATORY**: Do not proceed until user explicitly approves - **MANDATORY**: Log user's response in audit.md with complete raw input diff --git a/aidlc/steering/inception-units-generation.md b/aidlc/steering/inception-units-generation.md index db228c8..9f2dbd2 100644 --- a/aidlc/steering/inception-units-generation.md +++ b/aidlc/steering/inception-units-generation.md @@ -10,11 +10,11 @@ This stage decomposes the system into manageable units of work through two integ **Terminology**: Use "Service" for independently deployable components, "Module" for logical groupings within a service, "Unit of Work" for planning context. ## Prerequisites -- Context Assessment must be complete -- Requirements Assessment recommended (provides functional scope) -- Story Development recommended (stories map to units) -- Application Design phase REQUIRED (determines components, methods, and services) -- Execution plan must indicate Design phase should execute +- Workspace Detection must be complete +- Requirements Analysis recommended (provides functional scope) +- User Stories recommended (stories map to units) +- Application Design stage REQUIRED (determines components, methods, and services) +- Execution plan must indicate Design stage should execute --- @@ -30,24 +30,29 @@ This stage decomposes the system into manageable units of work through two integ - [ ] Generate `aidlc-docs/inception/application-design/unit-of-work.md` with unit definitions and responsibilities - [ ] Generate `aidlc-docs/inception/application-design/unit-of-work-dependency.md` with dependency matrix - [ ] Generate `aidlc-docs/inception/application-design/unit-of-work-story-map.md` mapping stories to units -- [ ] **Greenfield only**: Document code organization strategy in `unit-of-work.md` (see code-generation.md for structure patterns) +- [ ] **Greenfield only**: Document code organization strategy in `unit-of-work.md` (see construction-code-generation.md for structure patterns) - [ ] Validate unit boundaries and dependencies - [ ] Ensure all stories are assigned to units ## Step 3: Generate Context-Appropriate Questions -**DIRECTIVE**: Analyze the requirements, stories, and application design to generate ONLY questions relevant to THIS specific decomposition problem. Use the categories below as inspiration, NOT as a mandatory checklist. Skip entire categories if not applicable. +**DIRECTIVE**: Thoroughly analyze the requirements, stories, and application design to identify ALL areas where clarification would improve unit decomposition quality. Be proactive in asking questions to ensure comprehensive coverage of decomposition concerns. -- EMBED questions using [Answer]: tag format -- Focus on ambiguities and missing information specific to this context -- Generate questions only where user input is needed for decision-making +**CRITICAL**: Default to asking questions when there is ANY ambiguity or missing detail that could affect unit boundaries or decomposition quality. It's better to ask too many questions than to make incorrect assumptions about how the system should be decomposed. + +**MANDATORY**: Evaluate ALL of the following categories by asking targeted questions about each. For each category, determine applicability based on evidence from the requirements, stories, and application design -- do not skip categories without explicit justification: -**Example question categories** (adapt as needed): -- **Story Grouping** - Only if multiple stories exist and grouping strategy is unclear -- **Dependencies** - Only if multiple units likely and integration approach is ambiguous -- **Team Alignment** - Only if team structure or ownership is unclear -- **Technical Considerations** - Only if scalability/deployment requirements differ across units -- **Business Domain** - Only if domain boundaries or bounded contexts are unclear -- **Code Organization (Greenfield multi-unit only)** - Ask deployment model and directory structure preferences +- EMBED questions using [Answer]: tag format +- Focus on ANY ambiguities, missing information, or areas needing clarification +- Generate questions wherever user input would improve decomposition decisions +- **When in doubt, ask the question** - overconfidence leads to poor unit boundaries + +**Question categories to evaluate** (consider ALL categories): +- **Story Grouping** - Ask about grouping strategy, story affinity, and logical clustering approaches +- **Dependencies** - Ask about integration approach, shared resources, and inter-unit communication patterns +- **Team Alignment** - Ask about team structure, ownership boundaries, and collaboration models +- **Technical Considerations** - Ask about scalability/deployment requirements that may differ across units +- **Business Domain** - Ask about domain boundaries, bounded contexts, and business capability alignment +- **Code Organization (Greenfield multi-unit only)** - Ask about deployment model and directory structure preferences ## Step 4: Store UOW Plan - Save as `aidlc-docs/inception/plans/unit-of-work-plan.md` @@ -92,9 +97,9 @@ If the analysis in step 7 reveals ANY ambiguous answers, you MUST: - Include complete approval prompt text ## Step 11: Update Progress -- Mark Units Planning complete in aidlc-state.md +- Mark Units Generation Part 1 (Planning) complete in aidlc-state.md - Update the "Current Status" section -- Prepare for transition to Units Generation +- Prepare for transition to Units Generation Part 2 (Generation) --- diff --git a/aidlc/steering/inception-user-stories.md b/aidlc/steering/inception-user-stories.md index 0e1ab0d..8eb452c 100644 --- a/aidlc/steering/inception-user-stories.md +++ b/aidlc/steering/inception-user-stories.md @@ -244,7 +244,7 @@ If the analysis in step 9 reveals ANY ambiguous answers, you MUST: - [ ] Save all generated artifacts ## Step 18: Continue or Complete Generation -- [ ] If more steps remain, return to Step 14 +- [ ] If more steps remain, return to Step 15 - [ ] If all steps complete, verify stories are ready for next stage - [ ] Ensure all mandatory artifacts are generated diff --git a/aidlc/steering/inception-workflow-planning.md b/aidlc/steering/inception-workflow-planning.md index aa05c28..2e29f12 100644 --- a/aidlc/steering/inception-workflow-planning.md +++ b/aidlc/steering/inception-workflow-planning.md @@ -128,7 +128,7 @@ Evaluate risk level: - No new components or methods - Pure implementation changes -### 3.3 Design (Units Planning/Generation) - Execute IF: +### 3.3 Units Generation - Execute IF: - New data models or schemas - API changes or new endpoints - Complex algorithms or business logic @@ -203,7 +203,6 @@ Create Mermaid flowchart showing: **Styling rules** (add after flowchart): ``` style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff -style CP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff style US fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000 @@ -262,8 +261,7 @@ flowchart TD US["User Stories
                STATUS"] WP["Workflow Planning
                STATUS"] AD["Application Design
                STATUS"] - UP["Units Planning
                STATUS"] - UG["Units Generation
                STATUS"] + UG["Units Generation
                (Planning + Generation)
                STATUS"] end subgraph CONSTRUCTION["🟢 CONSTRUCTION PHASE"] @@ -271,8 +269,7 @@ flowchart TD NFRA["NFR Requirements
                STATUS"] NFRD["NFR Design
                STATUS"] ID["Infrastructure Design
                STATUS"] - CP["Code Planning
                EXECUTE"] - CG["Code Generation
                EXECUTE"] + CG["Code Generation
                (Planning + Generation)
                EXECUTE"] BT["Build and Test
                EXECUTE"] end @@ -283,8 +280,7 @@ flowchart TD Start --> WD WD --> RA RA --> WP - WP --> CP - CP --> CG + WP --> CG CG --> BT BT --> End(["Complete"]) @@ -299,13 +295,11 @@ flowchart TD ### 🔵 INCEPTION PHASE - [x] Workspace Detection (COMPLETED) - [x] Reverse Engineering (COMPLETED/SKIPPED) -- [x] Requirements Elaboration (COMPLETED) +- [x] Requirements Analysis (COMPLETED) - [x] User Stories (COMPLETED/SKIPPED) - [x] Execution Plan (IN PROGRESS) - [ ] Application Design - [EXECUTE/SKIP] - **Rationale**: [Why executing or skipping] -- [ ] Units Planning - [EXECUTE/SKIP] - - **Rationale**: [Why executing or skipping] - [ ] Units Generation - [EXECUTE/SKIP] - **Rationale**: [Why executing or skipping] @@ -318,10 +312,8 @@ flowchart TD - **Rationale**: [Why executing or skipping] - [ ] Infrastructure Design - [EXECUTE/SKIP] - **Rationale**: [Why executing or skipping] -- [ ] Code Planning - EXECUTE (ALWAYS) - - **Rationale**: Implementation approach needed - [ ] Code Generation - EXECUTE (ALWAYS) - - **Rationale**: Code implementation needed + - **Rationale**: Implementation planning and code generation needed - [ ] Build and Test - EXECUTE (ALWAYS) - **Rationale**: Build, test, and verification needed @@ -372,7 +364,6 @@ Update `aidlc-docs/aidlc-state.md`: - [x] User Stories (if applicable) - [x] Workflow Planning - [ ] Application Design - [EXECUTE/SKIP] -- [ ] Units Planning - [EXECUTE/SKIP] - [ ] Units Generation - [EXECUTE/SKIP] ### 🟢 CONSTRUCTION PHASE @@ -380,7 +371,6 @@ Update `aidlc-docs/aidlc-state.md`: - [ ] NFR Requirements - [EXECUTE/SKIP] - [ ] NFR Design - [EXECUTE/SKIP] - [ ] Infrastructure Design - [EXECUTE/SKIP] -- [ ] Code Planning - EXECUTE - [ ] Code Generation - EXECUTE - [ ] Build and Test - EXECUTE diff --git a/aidlc/steering/inception-workspace-detection.md b/aidlc/steering/inception-workspace-detection.md index b21b413..b3bcc2d 100644 --- a/aidlc/steering/inception-workspace-detection.md +++ b/aidlc/steering/inception-workspace-detection.md @@ -35,7 +35,11 @@ Check if `aidlc-docs/aidlc-state.md` exists: **IF workspace has existing code**: - Set flag: `brownfield = true` - Check for existing reverse engineering artifacts in `aidlc-docs/inception/reverse-engineering/` -- **IF reverse engineering artifacts exist**: Load them, skip to Requirements Analysis +- **IF reverse engineering artifacts exist**: + - Check if artifacts are stale (compare artifact timestamps against codebase's last significant modification) + - **IF artifacts are current**: Load them, skip to Requirements Analysis + - **IF artifacts are stale**: Next phase is Reverse Engineering (rerun to refresh artifacts) + - **IF user explicitly requests rerun**: Next phase is Reverse Engineering regardless of staleness - **IF no reverse engineering artifacts**: Next phase is Reverse Engineering ## Step 4: Create Initial State File