From df2e654b1d666e784051c579607484578aca67e9 Mon Sep 17 00:00:00 2001 From: daymade Date: Sun, 16 Nov 2025 23:41:14 +0800 Subject: [PATCH] Release v1.11.0: Add prompt-optimizer skill with EARS methodology MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add new prompt-optimizer skill (v1.1.0) for transforming vague prompts into precise EARS specifications: New Features: - EARS (Easy Approach to Requirements Syntax) transformation with 5 patterns - 6-step optimization workflow (analyze, transform, theories, examples, enhance, present) - Domain theory grounding (40+ frameworks across 10 domains) - Role/Skills/Workflows/Examples/Formats prompt enhancement framework - Progressive disclosure with 4 bundled reference files Skill Improvements (v1.0.0 → v1.1.0): - Reduced SKILL.md from 369 to 195 lines (47% reduction) - Added advanced_techniques.md (325 lines) for complex scenarios - Added 4th complete example (password reset security) - Added attribution to 阿星AI工作室 (A-Xing AI Studio) - Enhanced reference loading guidance Marketplace Updates: - Updated marketplace to v1.11.0 (17 → 18 skills) - Updated all documentation (README.md, README.zh-CN.md, CLAUDE.md) - Added Chinese and English descriptions with attribution 🤖 Generated with Claude Code Co-Authored-By: Claude --- .claude-plugin/marketplace.json | 14 +- CHANGELOG.md | 34 ++ CLAUDE.md | 7 +- README.md | 72 +++- README.zh-CN.md | 72 +++- prompt-optimizer/.security-scan-passed | 4 + prompt-optimizer/SKILL.md | 195 +++++++++++ .../references/advanced_techniques.md | 325 ++++++++++++++++++ .../references/domain_theories.md | 245 +++++++++++++ prompt-optimizer/references/ears_syntax.md | 123 +++++++ prompt-optimizer/references/examples.md | 321 +++++++++++++++++ 11 files changed, 1401 insertions(+), 11 deletions(-) create mode 100644 prompt-optimizer/.security-scan-passed create mode 100644 prompt-optimizer/SKILL.md create mode 100644 prompt-optimizer/references/advanced_techniques.md create mode 100644 prompt-optimizer/references/domain_theories.md create mode 100644 prompt-optimizer/references/ears_syntax.md create mode 100644 prompt-optimizer/references/examples.md diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index a8454fb..4db0b35 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,8 +5,8 @@ "email": "daymadev89@gmail.com" }, "metadata": { - "description": "Professional Claude Code skills for GitHub operations, document conversion, diagram generation, statusline customization, Teams communication, repomix utilities, skill creation, CLI demo generation, LLM icon access, Cloudflare troubleshooting, UI design system extraction, professional presentation creation, YouTube video downloading, secure repomix packaging, ASR transcription correction, video comparison quality analysis, and comprehensive QA testing infrastructure", - "version": "1.10.0", + "description": "Professional Claude Code skills for GitHub operations, document conversion, diagram generation, statusline customization, Teams communication, repomix utilities, skill creation, CLI demo generation, LLM icon access, Cloudflare troubleshooting, UI design system extraction, professional presentation creation, YouTube video downloading, secure repomix packaging, ASR transcription correction, video comparison quality analysis, comprehensive QA testing infrastructure, and prompt optimization with EARS methodology", + "version": "1.11.0", "homepage": "https://github.com/daymade/claude-code-skills" }, "plugins": [ @@ -179,6 +179,16 @@ "category": "developer-tools", "keywords": ["qa", "testing", "test-cases", "bug-tracking", "google-standards", "owasp", "security", "automation", "quality-gates", "metrics"], "skills": ["./qa-expert"] + }, + { + "name": "prompt-optimizer", + "description": "Transform vague prompts into precise, well-structured specifications using EARS (Easy Approach to Requirements Syntax) methodology. Use when users provide loose requirements, ambiguous feature descriptions, need to enhance prompts for AI-generated code/products/documents, request prompt optimization, or want to improve requirements engineering. Applies domain theories (GTD, BJ Fogg, Gestalt, AIDA, Zero Trust) and structured Role/Skills/Workflows/Examples/Formats framework", + "source": "./", + "strict": false, + "version": "1.1.0", + "category": "productivity", + "keywords": ["prompt-engineering", "ears", "requirements", "specifications", "optimization", "domain-theory", "prompt-enhancement", "ai-prompting"], + "skills": ["./prompt-optimizer"] } ] } diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a2e686..6174ae4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Security - None +## [1.11.0] - 2025-11-16 + +### Added +- **New Skill**: prompt-optimizer - Transform vague prompts into precise EARS specifications + - EARS (Easy Approach to Requirements Syntax) transformation methodology + - 6-step optimization workflow: analyze, transform, identify theories, extract examples, enhance, present + - 5 EARS sentence patterns (ubiquitous, event-driven, state-driven, conditional, unwanted behavior) + - Domain theory grounding with 10+ categories (productivity, UX, gamification, learning, e-commerce, security) + - 40+ industry frameworks mapped to use cases (GTD, BJ Fogg, Gestalt, AIDA, Zero Trust, etc.) + - Role/Skills/Workflows/Examples/Formats prompt enhancement framework + - Advanced optimization techniques (multi-stakeholder, non-functional requirements, complex logic) + - Bundled references: ears_syntax.md, domain_theories.md, examples.md + - Complete transformation examples (procrastination app, e-commerce, learning platform, password reset) + - Progressive disclosure pattern (metadata → SKILL.md → bundled resources) + +### Changed +- Updated marketplace skills count from 17 to 18 +- Updated marketplace version from 1.10.0 to 1.11.0 +- Updated README.md badges (skills count, version) +- Updated README.md to include prompt-optimizer in skills listing +- Updated README.zh-CN.md badges (skills count, version) +- Updated README.zh-CN.md to include prompt-optimizer in skills listing +- Updated CLAUDE.md skills count from 17 to 18 +- Added prompt-optimizer use case section to README.md +- Added prompt-optimizer use case section to README.zh-CN.md +- Enhanced marketplace metadata description to include prompt optimization capability +- **prompt-optimizer v1.1.0**: Improved skill following Anthropic best practices + - Reduced SKILL.md from 369 to 195 lines (47% reduction) using progressive disclosure + - Added new reference: advanced_techniques.md (325 lines) for multi-stakeholder, non-functional, and complex logic patterns + - Added 4th complete example (password reset security) to examples.md + - Added attribution to 阿星AI工作室 (A-Xing AI Studio) for EARS methodology inspiration + - Enhanced reference loading guidance with specific triggers for each file + - Improved conciseness and clarity following skill authoring best practices + ## [1.10.0] - 2025-11-10 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 357bd97..d75b1b0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Repository Overview -This is a Claude Code skills marketplace containing 17 production-ready skills organized in a plugin marketplace structure. Each skill is a self-contained package that extends Claude's capabilities with specialized knowledge, workflows, and bundled resources. +This is a Claude Code skills marketplace containing 18 production-ready skills organized in a plugin marketplace structure. Each skill is a self-contained package that extends Claude's capabilities with specialized knowledge, workflows, and bundled resources. **Essential Skill**: `skill-creator` is the most important skill in this marketplace - it's a meta-skill that enables users to create their own skills. Always recommend it first for users interested in extending Claude Code. @@ -118,7 +118,7 @@ Skills for public distribution must NOT contain: ## Marketplace Configuration The marketplace is configured in `.claude-plugin/marketplace.json`: -- Contains 17 plugins, each mapping to one skill +- Contains 18 plugins, each mapping to one skill - Each plugin has: name, description, version, category, keywords, skills array - Marketplace metadata: name, owner, version, homepage @@ -128,7 +128,7 @@ The marketplace is configured in `.claude-plugin/marketplace.json`: 1. **Marketplace Version** (`.claude-plugin/marketplace.json` → `metadata.version`) - Tracks the marketplace catalog as a whole - - Current: v1.10.0 + - Current: v1.11.0 - Bump when: Adding/removing skills, major marketplace restructuring - Semantic versioning: MAJOR.MINOR.PATCH @@ -161,6 +161,7 @@ The marketplace is configured in `.claude-plugin/marketplace.json`: 15. **transcript-fixer** - ASR/STT transcription error correction with dictionary and AI learning 16. **video-comparer** - Video comparison and quality analysis with interactive HTML reports 17. **qa-expert** - Comprehensive QA testing infrastructure with autonomous LLM execution and Google Testing Standards +18. **prompt-optimizer** - Transform vague prompts into precise EARS specifications with domain theory grounding **Recommendation**: Always suggest `skill-creator` first for users interested in creating skills or extending Claude Code. diff --git a/README.md b/README.md index 3cc95fe..4bd4c29 100644 --- a/README.md +++ b/README.md @@ -6,15 +6,15 @@ [![简体中文](https://img.shields.io/badge/语言-简体中文-red)](./README.zh-CN.md) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Skills](https://img.shields.io/badge/skills-17-blue.svg)](https://github.com/daymade/claude-code-skills) -[![Version](https://img.shields.io/badge/version-1.10.0-green.svg)](https://github.com/daymade/claude-code-skills) +[![Skills](https://img.shields.io/badge/skills-18-blue.svg)](https://github.com/daymade/claude-code-skills) +[![Version](https://img.shields.io/badge/version-1.11.0-green.svg)](https://github.com/daymade/claude-code-skills) [![Claude Code](https://img.shields.io/badge/Claude%20Code-2.0.13+-purple.svg)](https://claude.com/code) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](./CONTRIBUTING.md) [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/daymade/claude-code-skills/graphs/commit-activity) -Professional Claude Code skills marketplace featuring 17 production-ready skills for enhanced development workflows. +Professional Claude Code skills marketplace featuring 18 production-ready skills for enhanced development workflows. ## 📑 Table of Contents @@ -145,6 +145,9 @@ claude plugin install video-comparer@daymade/claude-code-skills # QA testing infrastructure with autonomous execution claude plugin install qa-expert@daymade/claude-code-skills + +# Prompt optimization using EARS methodology +claude plugin install prompt-optimizer@daymade/claude-code-skills ``` Each skill can be installed independently - choose only what you need! @@ -633,6 +636,65 @@ python3 scripts/calculate_metrics.py tests/TEST-EXECUTION-TRACKING.csv --- +### 17. **prompt-optimizer** - Prompt Engineering with EARS Methodology + +Transform vague prompts into precise, well-structured specifications using EARS (Easy Approach to Requirements Syntax) - a methodology created by Rolls-Royce for converting natural language into testable requirements. + +**Methodology inspired by:** [阿星AI工作室 (A-Xing AI Studio)](https://mp.weixin.qq.com/s/yUVX-9FovSq7ZGChkHpuXQ), which pioneered combining EARS with domain theory grounding for practical prompt enhancement. + +**When to use:** +- Converting loose requirements into structured specifications +- Optimizing prompts for AI code generation or content creation +- Breaking down vague feature requests into atomic, testable statements +- Adding domain theory grounding to technical requirements +- Transforming "build X" requests into detailed implementation specs +- Learning prompt engineering best practices with proven frameworks + +**Key features:** +- **EARS transformation**: 5 sentence patterns (ubiquitous, event-driven, state-driven, conditional, unwanted behavior) +- **6-step optimization workflow**: Analyze → Transform → Identify theories → Extract examples → Enhance → Present +- **Domain theory catalog**: 40+ frameworks mapped to 10 domains (productivity, UX, gamification, learning, e-commerce, security) +- **Structured prompt framework**: Role/Skills/Workflows/Examples/Formats template +- **Advanced techniques**: Multi-stakeholder requirements, non-functional specs, complex conditional logic +- **Complete examples**: Procrastination app, e-commerce product page, learning dashboard, password reset +- **Theory grounding**: GTD, BJ Fogg Behavior Model, Gestalt Principles, AIDA, Zero Trust, and more +- **Progressive disclosure**: Bundled references (ears_syntax.md, domain_theories.md, examples.md) + +**Example usage:** +```markdown +# Before (vague) +"Build me a password reset feature" + +# After EARS transformation (7 atomic requirements) +1. When user clicks "Forgot Password", the system shall display email input field +2. When user submits valid email, the system shall send password reset link valid for 1 hour +3. When user clicks reset link, the system shall verify token has not expired +4. When token is valid, the system shall display password creation form requiring minimum 12 characters, 1 uppercase, 1 number, 1 special character +5. When user submits new password meeting requirements, the system shall hash password with bcrypt and invalidate reset token +6. When user attempts password reset more than 3 times in 1 hour, the system shall block further attempts for 1 hour +7. If reset token has expired, the system shall display error message and option to request new link + +# Enhanced with domain theories +- Zero Trust Architecture (verify at each step) +- Defense in Depth (rate limiting + token expiration + password complexity) +- Progressive Disclosure (multi-step UX flow) + +# Full prompt includes Role, Skills, Workflows, Examples, Formats +``` + +**🎬 Live Demo** + +*Coming soon* + +📚 **Documentation**: See [prompt-optimizer/references/](./prompt-optimizer/references/) for: +- `ears_syntax.md` - Complete EARS patterns and transformation rules +- `domain_theories.md` - 40+ theories mapped to domains with selection guidance +- `examples.md` - Full transformation examples with before/after comparisons + +**💡 Innovation**: EARS methodology eliminates ambiguity by forcing explicit conditions, triggers, and measurable criteria. Combined with domain theory grounding (GTD, BJ Fogg, Gestalt, etc.), it transforms "build a todo app" into a complete specification with behavioral psychology principles, UX best practices, and concrete test cases - enabling test-driven development from day one. + +--- + ## 🎬 Interactive Demo Gallery Want to see all demos in one place with click-to-enlarge functionality? Check out our [interactive demo gallery](./demos/index.html) or browse the [demos directory](./demos/). @@ -669,6 +731,9 @@ Use **transcript-fixer** to correct speech-to-text errors in meeting notes, lect ### For QA Testing & Quality Assurance Use **qa-expert** to establish comprehensive QA testing infrastructure with autonomous LLM execution, Google Testing Standards, and OWASP security testing. Perfect for project launches, third-party QA handoffs, and enforcing quality gates (100% execution, ≥80% pass rate, 0 P0 bugs). The master prompt enables 100x faster test execution with zero tracking errors. +### For Prompt Engineering & Requirements Engineering +Use **prompt-optimizer** to transform vague feature requests into precise EARS specifications with domain theory grounding. Perfect for product requirements documents, AI-assisted coding, and learning prompt engineering best practices. Combine with **skill-creator** to create well-structured skill prompts, or with **ppt-creator** to ensure presentation content requirements are clearly specified. + ## 📚 Documentation Each skill includes: @@ -694,6 +759,7 @@ Each skill includes: - **video-comparer**: See `video-comparer/references/video_metrics.md` for quality metrics interpretation and `video-comparer/references/configuration.md` for customization options - **transcript-fixer**: See `transcript-fixer/references/workflow_guide.md` for step-by-step workflows and `transcript-fixer/references/team_collaboration.md` for collaboration patterns - **qa-expert**: See `qa-expert/references/master_qa_prompt.md` for autonomous execution (100x speedup) and `qa-expert/references/google_testing_standards.md` for AAA pattern and OWASP testing +- **prompt-optimizer**: See `prompt-optimizer/references/ears_syntax.md` for EARS transformation patterns, `prompt-optimizer/references/domain_theories.md` for theory catalog, and `prompt-optimizer/references/examples.md` for complete transformations ## 🛠️ Requirements diff --git a/README.zh-CN.md b/README.zh-CN.md index 269fb6f..345c004 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -6,15 +6,15 @@ [![简体中文](https://img.shields.io/badge/语言-简体中文-red)](./README.zh-CN.md) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Skills](https://img.shields.io/badge/skills-17-blue.svg)](https://github.com/daymade/claude-code-skills) -[![Version](https://img.shields.io/badge/version-1.10.0-green.svg)](https://github.com/daymade/claude-code-skills) +[![Skills](https://img.shields.io/badge/skills-18-blue.svg)](https://github.com/daymade/claude-code-skills) +[![Version](https://img.shields.io/badge/version-1.11.0-green.svg)](https://github.com/daymade/claude-code-skills) [![Claude Code](https://img.shields.io/badge/Claude%20Code-2.0.13+-purple.svg)](https://claude.com/code) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](./CONTRIBUTING.md) [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/daymade/claude-code-skills/graphs/commit-activity) -专业的 Claude Code 技能市场,提供 17 个生产就绪的技能,用于增强开发工作流。 +专业的 Claude Code 技能市场,提供 18 个生产就绪的技能,用于增强开发工作流。 ## 📑 目录 @@ -145,6 +145,9 @@ claude plugin install video-comparer@daymade/claude-code-skills # QA 测试基础设施和自主执行 claude plugin install qa-expert@daymade/claude-code-skills + +# 使用 EARS 方法论优化提示词 +claude plugin install prompt-optimizer@daymade/claude-code-skills ``` 每个技能都可以独立安装 - 只选择你需要的! @@ -673,6 +676,65 @@ python3 scripts/calculate_metrics.py tests/TEST-EXECUTION-TRACKING.csv --- +### 17. **prompt-optimizer** - 使用 EARS 方法论进行提示词工程 + +使用 EARS(简易需求语法)将模糊的提示词转换为精确、结构化的规范 - 这是罗尔斯·罗伊斯公司创建的一种将自然语言转换为可测试需求的方法论。 + +**方法论灵感来源:** [阿星AI工作室](https://mp.weixin.qq.com/s/yUVX-9FovSq7ZGChkHpuXQ),他们开创性地将 EARS 与领域理论基础相结合,实现了实用的提示词增强。 + +**使用场景:** +- 将松散的需求转换为结构化规范 +- 优化 AI 代码生成或内容创作的提示词 +- 将模糊的功能请求分解为原子化、可测试的陈述 +- 为技术需求添加领域理论基础 +- 将"构建 X"请求转换为详细的实施规范 +- 通过经过验证的框架学习提示词工程最佳实践 + +**主要功能:** +- **EARS 转换**:5 种句式模式(普适、事件驱动、状态驱动、条件、不期望行为) +- **6 步优化工作流**:分析 → 转换 → 识别理论 → 提取示例 → 增强 → 呈现 +- **领域理论目录**:40+ 框架映射到 10 个领域(生产力、UX、游戏化、学习、电商、安全) +- **结构化提示框架**:角色/技能/工作流/示例/格式模板 +- **高级技术**:多利益相关者需求、非功能性规范、复杂条件逻辑 +- **完整示例**:拖延症应用、电商产品页、学习平台、密码重置 +- **理论基础**:GTD、BJ Fogg 行为模型、格式塔原则、AIDA、零信任等 +- **渐进式披露**:捆绑参考文档(ears_syntax.md、domain_theories.md、examples.md) + +**示例用法:** +```markdown +# 之前(模糊) +"帮我构建一个密码重置功能" + +# EARS 转换后(7 个原子需求) +1. 当用户点击"忘记密码"时,系统应显示邮箱输入框 +2. 当用户提交有效邮箱时,系统应发送有效期为 1 小时的密码重置链接 +3. 当用户点击重置链接时,系统应验证令牌是否未过期 +4. 当令牌有效时,系统应显示密码创建表单,要求最少 12 个字符、1 个大写字母、1 个数字、1 个特殊字符 +5. 当用户提交符合要求的新密码时,系统应使用 bcrypt 哈希密码并使令牌失效 +6. 当用户在 1 小时内尝试密码重置超过 3 次时,系统应阻止进一步尝试 1 小时 +7. 如果重置令牌已过期,系统应显示错误消息和请求新链接的选项 + +# 使用领域理论增强 +- 零信任架构(每步验证) +- 纵深防御(速率限制 + 令牌过期 + 密码复杂性) +- 渐进式披露(多步骤 UX 流程) + +# 完整提示包括角色、技能、工作流、示例、格式 +``` + +**🎬 实时演示** + +*即将推出* + +📚 **文档**:参见 [prompt-optimizer/references/](./prompt-optimizer/references/): +- `ears_syntax.md` - 完整的 EARS 模式和转换规则 +- `domain_theories.md` - 40+ 理论映射到领域并提供选择指导 +- `examples.md` - 包含前后对比的完整转换示例 + +**💡 创新**:EARS 方法论通过强制明确条件、触发器和可测量标准来消除歧义。结合领域理论基础(GTD、BJ Fogg、格式塔等),它将"构建一个待办事项应用"转换为包含行为心理学原则、UX 最佳实践和具体测试用例的完整规范 - 从第一天起就支持测试驱动开发。 + +--- + ## 🎬 交互式演示画廊 想要在一个地方查看所有演示并具有点击放大功能?访问我们的[交互式演示画廊](./demos/index.html)或浏览[演示目录](./demos/)。 @@ -709,6 +771,9 @@ python3 scripts/calculate_metrics.py tests/TEST-EXECUTION-TRACKING.csv ### QA 测试与质量保证 使用 **qa-expert** 建立具有自主 LLM 执行、Google 测试标准和 OWASP 安全测试的综合 QA 测试基础设施。非常适合项目启动、第三方 QA 交接和执行质量门禁(100% 执行、≥80% 通过率、0 个 P0 错误)。主提示可实现 100 倍更快的测试执行,零跟踪错误。 +### 提示词工程与需求工程 +使用 **prompt-optimizer** 将模糊的功能请求转换为具有领域理论基础的精确 EARS 规范。非常适合产品需求文档、AI 辅助编码和学习提示词工程最佳实践。与 **skill-creator** 结合使用以创建结构良好的技能提示,或与 **ppt-creator** 结合使用以确保演示内容需求清晰明确。 + ## 📚 文档 每个技能包括: @@ -736,6 +801,7 @@ python3 scripts/calculate_metrics.py tests/TEST-EXECUTION-TRACKING.csv - **video-comparer**:参见 `video-comparer/references/video_metrics.md` 了解质量指标解释和 `video-comparer/references/configuration.md` 了解自定义选项 - **transcript-fixer**:参见 `transcript-fixer/references/workflow_guide.md` 了解分步工作流和 `transcript-fixer/references/team_collaboration.md` 了解协作模式 - **qa-expert**:参见 `qa-expert/references/master_qa_prompt.md` 了解自主执行(100 倍加速)和 `qa-expert/references/google_testing_standards.md` 了解 AAA 模式和 OWASP 测试 +- **prompt-optimizer**:参见 `prompt-optimizer/references/ears_syntax.md` 了解 EARS 转换模式、`prompt-optimizer/references/domain_theories.md` 了解理论目录和 `prompt-optimizer/references/examples.md` 了解完整转换示例 ## 🛠️ 系统要求 diff --git a/prompt-optimizer/.security-scan-passed b/prompt-optimizer/.security-scan-passed new file mode 100644 index 0000000..3ab0af4 --- /dev/null +++ b/prompt-optimizer/.security-scan-passed @@ -0,0 +1,4 @@ +Security scan passed +Scanned at: 2025-11-16T23:30:38.515326 +Tool: gitleaks + pattern-based validation +Content hash: 91d8d92a27fc76565a0dc07dac515c2fd71d869ddf51b7046b3a0e512a7ff7c6 diff --git a/prompt-optimizer/SKILL.md b/prompt-optimizer/SKILL.md new file mode 100644 index 0000000..af34f86 --- /dev/null +++ b/prompt-optimizer/SKILL.md @@ -0,0 +1,195 @@ +--- +name: prompt-optimizer +description: Transform vague prompts into precise, well-structured specifications using EARS (Easy Approach to Requirements Syntax) methodology. This skill should be used when users provide loose requirements, ambiguous feature descriptions, or need to enhance prompts for AI-generated code, products, or documents. Triggers include requests to "optimize my prompt", "improve this requirement", "make this more specific", or when raw requirements lack detail and structure. +--- + +# Prompt Optimizer + +## Overview + +Optimize vague prompts into precise, actionable specifications using EARS (Easy Approach to Requirements Syntax) - a Rolls-Royce methodology for transforming natural language into structured, testable requirements. + +**Methodology inspired by:** This skill's approach to combining EARS with domain theory grounding was inspired by [阿星AI工作室 (A-Xing AI Studio)](https://mp.weixin.qq.com/s/yUVX-9FovSq7ZGChkHpuXQ), which demonstrated practical EARS application for prompt enhancement. + +**Four-layer enhancement process:** + +1. **EARS syntax transformation** - Convert descriptive language to normative specifications +2. **Domain theory grounding** - Apply relevant industry frameworks (GTD, BJ Fogg, Gestalt, etc.) +3. **Example extraction** - Surface concrete use cases with real data +4. **Structured prompt generation** - Format using Role/Skills/Workflows/Examples/Formats framework + +## When to Use + +Apply when: +- User provides vague feature requests ("build a dashboard", "create a reminder app") +- Requirements lack specific conditions, triggers, or measurable outcomes +- Natural language descriptions need conversion to testable specifications +- User explicitly requests prompt optimization or requirement refinement + +## Six-Step Optimization Workflow + +### Step 1: Analyze Original Requirement + +Identify weaknesses: +- **Overly broad** - "Add user authentication" → Missing password requirements, session management +- **Missing triggers** - "Send notifications" → Missing when/why notifications trigger +- **Ambiguous actions** - "Make it user-friendly" → No measurable usability criteria +- **No constraints** - "Process payments" → Missing security, compliance requirements + +### Step 2: Apply EARS Transformation + +Convert requirements to EARS patterns. See `references/ears_syntax.md` for complete syntax rules. + +**Five core patterns:** +1. **Ubiquitous**: `The system shall ` +2. **Event-driven**: `When , the system shall ` +3. **State-driven**: `While , the system shall ` +4. **Conditional**: `If , the system shall ` +5. **Unwanted behavior**: `If , the system shall prevent ` + +**Quick example:** +``` +Before: "Create a reminder app with task management" + +After (EARS): +1. When user creates a task, the system shall guide decomposition into executable sub-tasks +2. When task deadline is within 30 minutes AND user has not started, the system shall send notification with sound alert +3. When user completes a sub-task, the system shall update progress and provide positive feedback +``` + +**Transformation checklist:** +- [ ] Identify implicit conditions and make explicit +- [ ] Specify triggering events or states +- [ ] Use precise action verbs (shall, must, should) +- [ ] Add measurable criteria ("within 30 minutes", "at least 8 characters") +- [ ] Break compound requirements into atomic statements +- [ ] Remove ambiguous language ("user-friendly", "fast") + +### Step 3: Identify Domain Theories + +Match requirements to established frameworks. See `references/domain_theories.md` for full catalog. + +**Common domain mappings:** +- **Productivity** → GTD, Pomodoro, Eisenhower Matrix +- **Behavior Change** → BJ Fogg Model (B=MAT), Atomic Habits +- **UX Design** → Hick's Law, Fitts's Law, Gestalt Principles +- **Security** → Zero Trust, Defense in Depth, Privacy by Design + +**Selection process:** +1. Identify primary domain from requirement keywords +2. Match to 2-4 complementary theories +3. Apply theory principles to specific features +4. Cite theories in enhanced prompt for credibility + +### Step 4: Extract Concrete Examples + +Generate specific examples with real data: +- User scenarios: "When user logs in on mobile device..." +- Data examples: "Product: 'Laptop', Price: $999, Stock: 15" +- Workflow examples: "Task: Write report → Sub-tasks: Research (2h), Draft (3h), Edit (1h)" + +Examples must be **realistic**, **specific**, **varied** (success/error/edge cases), and **testable**. + +### Step 5: Generate Enhanced Prompt + +Structure using the standard framework: + +```markdown +# Role +[Specific expert role with domain expertise] + +## Skills +- [Core capability 1] +- [Core capability 2] +[List 5-8 skills aligned with domain theories] + +## Workflows +1. [Phase 1] - [Key activities] +2. [Phase 2] - [Key activities] +[Complete step-by-step process] + +## Examples +[Concrete examples with real data, not placeholders] + +## Formats +[Precise output specifications: +- File types, structure requirements +- Design/styling expectations +- Technical constraints +- Deliverable checklist] +``` + +**Quality criteria:** +- **Role specificity**: "Product designer specializing in time management apps" > "Designer" +- **Theory grounding**: Reference frameworks explicitly +- **Actionable workflows**: Clear inputs/outputs and decision points +- **Concrete examples**: Real data, not "Example 1", "Example 2" +- **Measurable formats**: Specific requirements, not "good design" + +### Step 6: Present Optimization Results + +Output in structured format: + +```markdown +## Original Requirement +[User's vague requirement] + +**Identified Issues:** +- [Issue 1: e.g., "Lacks specific trigger conditions"] +- [Issue 2: e.g., "No measurable success criteria"] + +## EARS Transformation +[Numbered list of EARS-formatted requirements] + +## Domain & Theories +**Primary Domain:** [e.g., Authentication Security] + +**Applicable Theories:** +- **[Theory 1]** - [Brief relevance] +- **[Theory 2]** - [Brief relevance] + +## Enhanced Prompt +[Complete Role/Skills/Workflows/Examples/Formats prompt] + +--- + +**How to use:** +[Brief guidance on applying the prompt] +``` + +## Advanced Techniques + +For complex scenarios, see `references/advanced_techniques.md`: +- **Multi-stakeholder requirements** - EARS statements for each user type +- **Non-functional requirements** - Performance, security, scalability with quantified thresholds +- **Complex conditional logic** - Nested conditions with boolean operators + +## Quick Reference + +**Do's:** +✅ Break down compound requirements (one EARS statement per requirement) +✅ Specify measurable criteria (numbers, timeframes, percentages) +✅ Include error/edge cases +✅ Ground in established theories +✅ Use concrete examples with real data + +**Don'ts:** +❌ Avoid vague language ("fast", "user-friendly") +❌ Don't assume implicit knowledge +❌ Don't mix multiple actions in one statement +❌ Don't use placeholders in examples + +## Resources + +Load these reference files as needed: + +- **`references/ears_syntax.md`** - Complete EARS syntax rules, all 5 patterns, transformation guidelines, benefits +- **`references/domain_theories.md`** - 40+ theories mapped to 10 domains (productivity, UX, gamification, learning, e-commerce, security, etc.) +- **`references/examples.md`** - Four complete transformation examples (procrastination app, e-commerce product page, learning dashboard, password reset security) with before/after comparisons and reusable template +- **`references/advanced_techniques.md`** - Multi-stakeholder requirements, non-functional specs, complex conditional logic patterns + +**When to load references:** +- EARS syntax clarification needed → `ears_syntax.md` +- Domain theory selection requires extensive options → `domain_theories.md` +- User requests multiple optimization examples → `examples.md` +- Complex requirements with multiple stakeholders or non-functional specs → `advanced_techniques.md` diff --git a/prompt-optimizer/references/advanced_techniques.md b/prompt-optimizer/references/advanced_techniques.md new file mode 100644 index 0000000..59acb3b --- /dev/null +++ b/prompt-optimizer/references/advanced_techniques.md @@ -0,0 +1,325 @@ +# Advanced Prompt Optimization Techniques + +## Overview + +This reference covers advanced EARS transformation patterns for complex requirements involving multiple stakeholders, non-functional constraints, and sophisticated conditional logic. + +## Multi-Stakeholder Requirements + +When requirements involve multiple user types with different needs and permissions: + +### Approach + +1. Create EARS statements for each stakeholder +2. Identify conflicting requirements (admin vs. user permissions) +3. Specify role-based conditions explicitly +4. Use nested conditions when access depends on multiple factors + +### Patterns + +**Basic role-based access:** +``` +If user role is 'Admin', the system shall display all user management controls +If user role is 'Editor', the system shall display content editing controls +If user role is 'Viewer', the system shall prevent access to editing functions +``` + +**Hierarchical permissions:** +``` +If user role is 'Owner' OR 'Admin', the system shall allow deletion of any content +If user role is 'Editor' AND content.author is current user, the system shall allow editing of that content +If user role is 'Viewer', the system shall display content in read-only mode +``` + +**Context-dependent access:** +``` +When user requests sensitive data: + - If user role is 'Manager' AND user.department matches data.department, the system shall grant access + - If user role is 'Executive', the system shall grant access regardless of department + - Otherwise, the system shall deny access and log the attempt +``` + +### Example: Content Management System + +**Requirement:** "Different users should have different permissions" + +**EARS transformation:** +``` +1. When user logs in with 'Admin' role, the system shall display dashboard with user management, content moderation, and system settings + +2. When user logs in with 'Author' role, the system shall display dashboard with create post, edit own posts, and view analytics + +3. When 'Author' attempts to publish post, the system shall set post status to 'pending review' + +4. When 'Editor' reviews pending post, the system shall provide approve/reject/request changes options + +5. If 'Author' attempts to access another author's draft, the system shall prevent access and display "Access Denied" message + +6. When 'Admin' accesses any post, the system shall grant full permissions (view, edit, delete, publish) regardless of author +``` + +## Non-Functional Requirements + +Performance, security, scalability, and reliability requirements need precise quantification. + +### Approach + +1. Quantify constraints explicitly (no vague terms like "fast" or "secure") +2. Specify measurement methods (how to verify the requirement) +3. Include threshold values (acceptable ranges) +4. Define degradation behavior (what happens when thresholds are exceeded) + +### Patterns + +**Performance requirements:** +``` +When search query is submitted, the system shall return results within 200ms for 95% of requests +When page load is initiated, the system shall display first contentful paint within 1.5 seconds for 90% of requests +While concurrent user count exceeds 10,000, the system shall maintain response time below 500ms +``` + +**Security requirements:** +``` +When user authentication fails 5 times within 15 minutes, the system shall lock the account for 30 minutes +When password is created, the system shall enforce minimum 12 characters, 1 uppercase, 1 number, 1 special character +While session is active, the system shall invalidate session after 30 minutes of inactivity +If SQL injection pattern is detected in input, the system shall sanitize input and log security event +``` + +**Scalability requirements:** +``` +When concurrent user count reaches 50,000, the system shall auto-scale to additional server instances +When database query time exceeds 100ms, the system shall use read replicas for load balancing +While system is under load, the system shall queue requests beyond 100,000/second and process FIFO +``` + +**Reliability requirements:** +``` +When service fails, the system shall attempt retry with exponential backoff (1s, 2s, 4s, 8s) +When database connection is lost, the system shall failover to backup database within 5 seconds +While maintenance window is active, the system shall display maintenance page and queue incoming requests +If data corruption is detected, the system shall rollback to last known good state within 10 minutes +``` + +### Example: E-commerce Checkout + +**Requirement:** "The checkout should be fast and secure" + +**EARS transformation:** +``` +1. When user clicks "Place Order", the system shall process payment within 3 seconds for 95% of transactions + +2. When payment processing exceeds 5 seconds, the system shall display "Processing..." indicator and prevent duplicate submissions + +3. When payment is processed, the system shall use TLS 1.3 encryption for all data transmission + +4. When credit card number is entered, the system shall tokenize the number and never store raw card data + +5. When payment gateway is unavailable, the system shall retry 3 times with 2-second intervals, then display user-friendly error + +6. If payment fails after retries, the system shall store order in "pending" state for 24 hours and email user with recovery link + +7. When concurrent checkout requests exceed 1,000/second, the system shall queue additional requests and process within 10 seconds + +8. When fraud detection score exceeds 70, the system shall require additional verification (SMS code or manual review) +``` + +## Complex Conditional Logic + +Multi-condition requirements with nested logic, boolean operators, and priority rules. + +### Approach + +1. Use nested conditions with clear hierarchy +2. Specify boolean operators explicitly (AND, OR, NOT) +3. Define priority when conditions conflict +4. Use parentheses to clarify precedence +5. Provide fallback behavior for unmatched conditions + +### Patterns + +**Nested conditions:** +``` +When user submits form: + If all required fields are filled: + If email format is valid: + If password strength is 'strong' OR 'very strong': + The system shall create account and send verification email + Else: + The system shall reject with "Password too weak" message + Else: + The system shall highlight email field and display format example + Else: + The system shall highlight missing fields and prevent submission +``` + +**Complex boolean logic:** +``` +If (user is logged in AND subscription is active) OR (user has free trial remaining AND trial end date > today): + The system shall grant access to premium features + If free trial: + The system shall display "X days remaining in trial" banner + If subscription expires within 7 days: + The system shall show renewal reminder in header +Else: + The system shall redirect to pricing page with upgrade prompt +``` + +**Priority-based rules:** +``` +When content moderation is triggered: + Priority 1: If content contains profanity, the system shall immediately hide content and flag for manual review + Priority 2: Else if content reports exceed 10, the system shall hide content and notify moderator + Priority 3: Else if AI toxicity score > 0.8, the system shall add warning label "potentially sensitive content" + Priority 4: Else if content is flagged but reports < 10, the system shall add to moderation queue + Default: The system shall display content normally +``` + +**Time-based conditions:** +``` +When user accesses course content: + If (current date >= course.start_date) AND (current date <= course.end_date): + If user.enrollment_status is 'active': + The system shall grant full access to all lessons + Else if user.enrollment_status is 'pending': + The system shall display "Enrollment pending approval" message + Else if current date < course.start_date: + The system shall display "Course starts on [date]" countdown + Else if (current date > course.end_date) AND (user.completion_rate >= 100%): + The system shall grant read-only access to completed course materials + Else: + The system shall display "Course has ended" message with re-enrollment option +``` + +### Example: Dynamic Pricing System + +**Requirement:** "Prices should change based on demand, inventory, and user type" + +**EARS transformation:** +``` +When user views product page: + Base calculation: system shall retrieve base_price from product.price + + Apply inventory adjustments: + If inventory_count < 10: + system shall multiply price by 1.2 (20% scarcity premium) + Else if inventory_count < 50: + system shall multiply price by 1.1 (10% low stock premium) + Else if inventory_count > 500: + system shall multiply price by 0.9 (10% overstock discount) + + Apply demand adjustments: + If view_count in last 24 hours > 1000: + system shall multiply price by 1.15 (15% high demand premium) + If purchase_count in last hour > 50: + system shall multiply price by 1.1 (10% trending premium) + + Apply user-specific adjustments: + If user is 'VIP' AND lifetime_purchase_value > $10,000: + system shall apply 15% discount + Else if user is 'VIP': + system shall apply 10% discount + Else if user is logged in AND first_purchase: + system shall apply 5% first-time discount + Else if user has abandoned cart for this product: + system shall apply 8% re-engagement discount + + Apply time-based promotions: + If current time is within flash_sale.time_window: + system shall apply flash_sale.discount_percentage + Else if current date is user.birthday: + system shall apply 20% birthday discount + + Final validation: + If calculated_price < product.minimum_price: + system shall set price to product.minimum_price + If calculated_price > product.maximum_price: + system shall set price to product.maximum_price + + Display: + system shall display final calculated price rounded to nearest $0.99 + If discount > 0: + system shall show original price crossed out with discount percentage badge +``` + +## Combining Techniques + +Real-world requirements often combine multiple techniques: + +### Example: Healthcare Appointment System + +**Requirement:** "Different user types should be able to book appointments with various rules" + +**Combined EARS transformation:** +``` +Multi-stakeholder + Non-functional + Complex conditional: + +When user attempts to book appointment: + + Authentication & Authorization: + If user role is 'Patient': + If user has verified insurance AND insurance.status is 'active': + system shall allow booking appointments with in-network providers + Else if user has no insurance OR insurance.status is 'expired': + system shall allow booking with cash payment option only + Else if user.insurance_verification is 'pending': + system shall display "Insurance verification in progress" message + + If user role is 'Provider': + system shall display manage schedule, view appointments, update availability options + + If user role is 'Admin': + system shall grant full access to all appointments, schedules, and patient records + + Availability checking (Performance requirement): + When user selects provider and date: + system shall retrieve available time slots within 100ms + If query exceeds 100ms: + system shall use cached availability data with staleness indicator + + Booking constraints (Complex conditional): + If selected_time is within 24 hours AND user role is 'Patient': + system shall require phone verification for last-minute bookings + Else if selected_time is more than 90 days in future: + system shall prevent booking and display "Cannot book more than 90 days ahead" + + If (appointment_count for user this_month >= 5) AND (user.subscription_tier is 'Basic'): + system shall prevent booking and prompt upgrade to 'Premium' tier + Else if (appointment_count for provider this_day >= 20): + system shall prevent booking and suggest alternative providers or dates + + Concurrent booking prevention (Non-functional - reliability): + When booking is confirmed: + system shall use distributed lock to prevent double-booking for 60 seconds + If lock cannot be acquired within 5 seconds: + system shall display "This time slot is being booked by another user" and refresh available slots + + Notification rules (Multi-stakeholder): + When appointment is successfully booked: + system shall send confirmation email to patient within 30 seconds + system shall send notification to provider via SMS and in-app notification + system shall add appointment to provider's calendar with patient details + If appointment is within 48 hours: + system shall schedule reminder SMS 24 hours before appointment + system shall schedule reminder email 2 hours before appointment +``` + +## Best Practices for Advanced Techniques + +1. **Layer incrementally** - Start with basic EARS, then add advanced patterns +2. **Test each condition** - Ensure every branch has a testable outcome +3. **Document assumptions** - Make implicit business rules explicit +4. **Use tables for complex logic** - Decision tables clarify multi-condition scenarios +5. **Validate with stakeholders** - Confirm priority and precedence with domain experts +6. **Consider edge cases** - What happens at boundaries (0, max, negative, null)? +7. **Plan for exceptions** - Every rule needs an "otherwise" clause +8. **Quantify everything** - Replace "many" with numbers, "fast" with milliseconds + +## Common Pitfalls + +❌ **Circular conditions** - "If A then B, if B then A" creates infinite loops +❌ **Unreachable branches** - Conditions that can never be true +❌ **Ambiguous precedence** - When multiple conditions match, which wins? +❌ **Missing default cases** - What if none of the conditions match? +❌ **Vague thresholds** - "High traffic" → Define "high" numerically +❌ **Incomplete error handling** - What happens when external systems fail? diff --git a/prompt-optimizer/references/domain_theories.md b/prompt-optimizer/references/domain_theories.md new file mode 100644 index 0000000..e93bf00 --- /dev/null +++ b/prompt-optimizer/references/domain_theories.md @@ -0,0 +1,245 @@ +# Domain Theories for Prompt Enhancement + +## Purpose + +When enhancing prompts, grounding the solution in established domain theories provides: +- Proven methodologies and frameworks +- Industry best practices +- Credibility and rigor +- Structured problem-solving approaches + +## Common Domain Theory Mappings + +### Productivity & Time Management + +**Applicable for:** Task management apps, productivity tools, scheduling systems + +**Relevant Theories:** +1. **Getting Things Done (GTD)** - David Allen + - Capture, Clarify, Organize, Reflect, Engage + - Next action principle + - Context-based task organization + +2. **Pomodoro Technique** - Francesco Cirillo + - 25-minute focused work intervals + - Regular breaks + - Distraction management + +3. **Eisenhower Matrix** + - Urgent/Important prioritization + - Four quadrants for task classification + +4. **Pareto Principle (80/20 Rule)** + - Focus on high-impact activities + - Effort vs. outcome optimization + +5. **Timeboxing** + - Fixed time allocations + - Deadline-driven focus + +### Behavior Change & Habit Formation + +**Applicable for:** Health apps, learning platforms, goal-tracking systems + +**Relevant Theories:** +1. **BJ Fogg Behavior Model (B=MAT)** + - Behavior = Motivation × Ability × Trigger + - Tiny habits principle + - Behavioral chains + +2. **Atomic Habits** - James Clear + - 1% improvement philosophy + - Habit stacking + - Identity-based habits + +3. **Operant Conditioning** + - Positive/negative reinforcement + - Reward schedules + - Immediate feedback loops + +4. **Self-Determination Theory** + - Autonomy, competence, relatedness + - Intrinsic vs. extrinsic motivation + +### User Experience & Interface Design + +**Applicable for:** UI/UX projects, web applications, mobile apps + +**Relevant Theories:** +1. **Hick's Law** + - Choice overload reduction + - Decision time optimization + +2. **Fitts's Law** + - Target size and distance relationship + - Touch target optimization + +3. **Miller's Law (7±2)** + - Cognitive load management + - Chunking information + +4. **Jakob's Law** + - Familiar design patterns + - User expectations + +5. **Progressive Disclosure** + - Layered information architecture + - Complexity management + +6. **Gestalt Principles** + - Proximity, similarity, closure + - Visual hierarchy + +### Gamification & Engagement + +**Applicable for:** Learning apps, fitness trackers, social platforms + +**Relevant Theories:** +1. **Octalysis Framework** - Yu-kai Chou + - 8 core drives of gamification + - White hat vs. black hat mechanics + +2. **Self-Determination Theory in Games** + - Challenge and mastery + - Social connection + - Autonomy in gameplay + +3. **Flow Theory** - Mihaly Csikszentmihalyi + - Skill-challenge balance + - Immediate feedback + - Clear goals + +4. **Variable Reward Schedules** + - Unpredictability and anticipation + - Dopamine-driven engagement + +### Learning & Education + +**Applicable for:** E-learning platforms, training systems, educational apps + +**Relevant Theories:** +1. **Bloom's Taxonomy** + - Knowledge → Comprehension → Application → Analysis → Synthesis → Evaluation + - Learning objective hierarchy + +2. **Spaced Repetition** + - Forgetting curve optimization + - Long-term memory consolidation + +3. **Active Recall** + - Retrieval practice + - Testing effect + +4. **Cognitive Load Theory** + - Intrinsic, extraneous, germane load + - Working memory limitations + +5. **Zone of Proximal Development** + - Scaffolding + - Guided learning + +### Data Visualization & Analytics + +**Applicable for:** Dashboard design, reporting tools, analytics platforms + +**Relevant Theories:** +1. **Tufte's Principles** + - Data-ink ratio + - Chartjunk elimination + - Small multiples + +2. **Gestalt Principles for Data** + - Pre-attentive attributes + - Visual encoding + +3. **Information Scent** + - Navigation cues + - Progressive exploration + +### E-commerce & Conversion + +**Applicable for:** Online stores, checkout flows, landing pages + +**Relevant Theories:** +1. **Cialdini's Principles of Persuasion** + - Reciprocity, commitment, social proof + - Scarcity, authority, liking + +2. **AIDA Model** + - Attention → Interest → Desire → Action + - Conversion funnel optimization + +3. **Paradox of Choice** + - Option limitation + - Decision fatigue reduction + +### Information Architecture + +**Applicable for:** Content-heavy sites, knowledge bases, documentation + +**Relevant Theories:** +1. **Information Foraging Theory** + - Scent trails + - Cost-benefit of navigation + +2. **Card Sorting Principles** + - User mental models + - Category optimization + +3. **LATCH Framework** (Location, Alphabet, Time, Category, Hierarchy) + - Information organization patterns + +### Security & Trust + +**Applicable for:** Authentication systems, privacy-sensitive apps, financial platforms + +**Relevant Theories:** +1. **Zero Trust Architecture** + - Never trust, always verify + - Least privilege access + +2. **Defense in Depth** + - Layered security controls + - Multiple fail-safes + +3. **Privacy by Design** + - Proactive privacy measures + - User control over data + +### Accessibility + +**Applicable for:** Inclusive design, government services, public platforms + +**Relevant Theories:** +1. **WCAG Principles** (POUR) + - Perceivable, Operable, Understandable, Robust + +2. **Universal Design** + - Equitable use + - Flexibility in use + - Simple and intuitive + +## How to Select Theories + +1. **Identify the domain** from user requirements +2. **Match to primary objective** (engagement, learning, conversion, etc.) +3. **Select 2-4 relevant theories** that complement each other +4. **Apply principles** to specific features and workflows +5. **Cite theories** in enhanced prompts to add credibility + +## Example Theory Selection + +**Requirement:** "Build a habit tracker app" + +**Domain:** Behavior Change & Habit Formation + +**Selected Theories:** +- BJ Fogg Behavior Model (for trigger design) +- Atomic Habits (for habit stacking) +- Gamification (for motivation and rewards) + +**Application:** +- Use tiny habits to lower barrier to entry +- Implement trigger notifications at optimal times +- Add streak tracking and badges for engagement +- Enable habit chains for compound behavior diff --git a/prompt-optimizer/references/ears_syntax.md b/prompt-optimizer/references/ears_syntax.md new file mode 100644 index 0000000..e4249fe --- /dev/null +++ b/prompt-optimizer/references/ears_syntax.md @@ -0,0 +1,123 @@ +# EARS (Easy Approach to Requirements Syntax) + +## Overview + +EARS (Easy Approach to Requirements Syntax) is a structured requirements writing methodology created by Rolls-Royce in 2009. It transforms natural language descriptions into precise, actionable specifications. + +## Core Principle + +Convert requirements from **descriptive** to **normative** by decomposing them into: + +1. **Entity** - What component/system is involved +2. **Action** - What operation/behavior should occur +3. **Relationship** - How entities interact +4. **Scope** - Under what conditions/constraints + +## EARS Sentence Patterns + +### Pattern 1: Ubiquitous (Unconditional) + +**Format:** `系统应 ` +**English:** `The system shall ` + +**Use when:** Requirement always applies, no preconditions + +**Example:** +- Natural: "The app needs a login page" +- EARS: "The system shall provide a login interface" + +### Pattern 2: Event-Driven + +**Format:** `当 时,系统应 ` +**English:** `When , the system shall ` + +**Use when:** Requirement applies upon specific event + +**Example:** +- Natural: "Send reminder before deadline" +- EARS: "When the task deadline is within 30 minutes, the system shall send a reminder notification" + +### Pattern 3: State-Driven + +**Format:** `在 状态下,系统应 ` +**English:** `While , the system shall ` + +**Use when:** Requirement applies during a specific state + +**Example:** +- Natural: "Show loading spinner during data fetch" +- EARS: "While data is being fetched, the system shall display a loading spinner" + +### Pattern 4: Optional Feature + +**Format:** `若 ,系统应 ` +**English:** `If , then the system shall ` + +**Use when:** Requirement is conditional + +**Example:** +- Natural: "Premium users get extra features" +- EARS: "If the user has a premium subscription, the system shall enable advanced analytics features" + +### Pattern 5: Unwanted Behavior + +**Format:** `若 ,系统应避免 ` +**English:** `If , the system shall prevent ` + +**Use when:** Specifying constraints or prohibited behaviors + +**Example:** +- Natural: "Don't allow duplicate submissions" +- EARS: "If a submission is already in progress, the system shall prevent duplicate form submissions" + +## Complex EARS Patterns + +### Multi-Condition Events + +**Format:** `当 时,系统应 ` + +**Example:** +``` +When the task deadline is within 30 minutes +AND the user has not started the task, +the system shall trigger a notification with encouraging message and sound alert. +``` + +### Conditional Actions with Alternatives + +**Format:** +``` +When : +- If , the system shall +- If , the system shall +- Otherwise, the system shall +``` + +**Example:** +``` +When user submits a form: +- If all required fields are filled, the system shall process the submission +- If any required field is empty, the system shall highlight missing fields +- Otherwise, the system shall display a general error message +``` + +## EARS Transformation Checklist + +When converting natural language to EARS: + +- [ ] Identify all implicit conditions and make them explicit +- [ ] Specify the triggering event or state +- [ ] Define the actor (usually "the system") +- [ ] Use precise action verbs (shall, should, must) +- [ ] Specify measurable outcomes where possible +- [ ] Break compound requirements into atomic statements +- [ ] Remove ambiguous language ("user-friendly", "fast", "intuitive") +- [ ] Add quantitative criteria ("within 30 minutes", "at least 8 characters") + +## Benefits + +1. **Clarity** - Eliminates ambiguity through structured syntax +2. **Completeness** - Forces specification of conditions and triggers +3. **Testability** - Clear requirements enable automated testing +4. **Atomicity** - Each requirement is independent and self-contained +5. **Traceability** - Easy to map requirements to features diff --git a/prompt-optimizer/references/examples.md b/prompt-optimizer/references/examples.md new file mode 100644 index 0000000..138df3a --- /dev/null +++ b/prompt-optimizer/references/examples.md @@ -0,0 +1,321 @@ +# Prompt Optimization Examples + +> **Attribution:** Example 1 (Procrastination Eliminator App) is adapted from [阿星AI工作室 (A-Xing AI Studio)](https://mp.weixin.qq.com/s/yUVX-9FovSq7ZGChkHpuXQ), which pioneered the practical application of EARS methodology combined with domain theory grounding for AI prompt enhancement. + +## Example 1: Procrastination Eliminator App (from 阿星AI工作室) + +### Original Requirement (Vague) + +``` +帮我开发一个拖延症消除器网页应用,需要有提醒功能和任务管理功能。 +比如可以提醒大家通过拆解步骤完成工作,把大任务拆解为小任务 + +Translation: Help me develop a procrastination eliminator web app with reminder and task management features. For example, it can remind people to complete work by breaking down steps, decomposing big tasks into small tasks. +``` + +**Problems:** +- Functional description too broad, lacks specific details +- Technical solution standardized, lacks specificity +- No consideration of behavioral psychology factors +- Missing specific interaction design guidance + +### EARS Transformation + +**Requirement rewritten using EARS syntax:** + +1. When a user creates a new task, the system shall guide the user to decompose the large task into executable small task steps + +2. When a user sets task timing, the system shall send scheduled reminder notifications + +3. When a user completes a sub-task, the system shall update overall task progress and provide positive feedback + +4. When a user accesses the application, the system shall display the to-do task list and completion statistics + +### Domain Theory Identification + +**Domain:** Behavior Psychology, Time Management, Human-Computer Interaction Design + +**Relevant Mature Theories:** +- **Getting Things Done (GTD)** - David Allen's task management methodology +- **Pomodoro Technique** - Time segmentation management technique +- **Behavior Change Theory** - BJ Fogg's Behavior Model (B=MAT) +- **Gamification Design Theory** - Enhance user engagement through reward mechanisms + +### Enhanced Prompt Output + +```markdown +# Role +You are a professional product designer and frontend development engineer, specializing in time management applications and user experience design, with a background in psychology, deeply understanding the causes and solutions of procrastination. + +## Skills +- Design intuitive and easy-to-use task management interfaces +- Implement scientific task decomposition guidance mechanisms +- Develop effective reminder and notification systems +- Apply behavioral psychology principles to enhance user stickiness +- Master modern frontend development technology stack +- Understand user experience design best practices + +## Workflows +1. Requirement analysis - Deeply understand procrastination user pain points and usage scenarios +2. Function design - Design task decomposition process based on GTD theory +3. Interface planning - Create simple and efficient user interface layout +4. Interaction design - Design guided task creation and management process +5. Technical implementation - Use modern web technologies to develop responsive applications +6. Testing optimization - Verify user experience and functional completeness + +## Examples +**Large task example:** Complete quarterly work report → Decompose into: Collect data (2 hours) → Analyze data (3 hours) → Write initial draft (4 hours) → Revise and improve (2 hours) → Format adjustment (1 hour) + +**Reminder function:** Set daily 9 AM reminder "Start today's most important task", Pomodoro timer 25-minute work reminder + +**Progress visualization:** Display "This week completed tasks 8/12, progress 67%", with progress bar and achievement badges + +## Formats +Output a complete HTML web application, including: +- Responsive design layout +- Task creation and decomposition forms +- Task list and progress display +- Reminder setting functionality +- Local storage data persistence +- Modern UI design style +- Interactive animations and feedback effects +``` + +--- + +## More Examples + +### Example 2: E-commerce Product Page + +**Original (Vague):** +``` +Create a product page with add to cart button and reviews +``` + +**EARS Transformation:** +``` +1. When a user visits a product page, the system shall display product images, title, price, and description +2. When a user clicks "Add to Cart", the system shall add the item to their shopping cart and show confirmation +3. When a product page loads, the system shall display customer reviews sorted by most helpful +4. When a user scrolls below the fold, the system shall lazy-load additional review content +``` + +**Domain Theories:** +- Cialdini's Principles of Persuasion (social proof through reviews) +- AIDA Model (Attention, Interest, Desire, Action) +- Progressive Disclosure (lazy loading) + +**Enhanced Prompt:** +```markdown +# Role +Expert e-commerce UX designer with deep knowledge of conversion optimization and persuasion psychology + +## Skills +- Design high-converting product pages +- Apply social proof principles effectively +- Optimize for mobile and desktop experiences +- Implement performance best practices (lazy loading, image optimization) + +## Workflows +1. Product information architecture - Hero image, pricing, key features above fold +2. Social proof integration - Star ratings, review count, verified purchases +3. Call-to-action optimization - Prominent "Add to Cart" with clear availability status +4. Progressive content loading - Reviews load on scroll to optimize initial page load +5. Mobile-first responsive design - Touch-optimized buttons, readable typography + +## Examples +- Hero section: Large product image gallery, price with strikethrough for discounts +- Reviews section: "4.8/5 stars (1,247 reviews)" with filter by rating +- CTA: "Add to Cart - In Stock" button, green color, 48px height for easy tapping + +## Formats +Responsive HTML/CSS product page with: +- Image carousel with thumbnails +- Sticky add-to-cart bar on scroll +- Collapsible product details +- Paginated reviews with helpful/not helpful voting +``` + +### Example 3: Learning Platform Dashboard + +**Original (Vague):** +``` +Build a dashboard for students to track their courses and progress +``` + +**EARS Transformation:** +``` +1. When a student logs in, the system shall display enrolled courses with current progress percentages +2. When a course deadline is within 7 days, the system shall highlight it with an urgent indicator +3. When a student completes a lesson, the system shall update the course progress bar and award points +4. When a student accesses the dashboard, the system shall show recommended next lessons based on learning path +``` + +**Domain Theories:** +- Bloom's Taxonomy (learning progression) +- Gamification (points, progress bars) +- Information Architecture (dashboard layout) +- Spaced Repetition (recommended next lessons) + +**Enhanced Prompt:** +```markdown +# Role +Educational technology designer specializing in learning management systems and student engagement + +## Skills +- Design effective learning dashboards +- Apply gamification principles ethically +- Visualize learning progress clearly +- Implement personalized learning paths +- Understand educational psychology + +## Workflows +1. Dashboard layout - Course cards in grid, progress visualization prominent +2. Progress tracking - Circular progress indicators, percentage complete, estimated time remaining +3. Gamification elements - Points system, achievement badges, streak tracking +4. Recommendation engine - Next lessons based on prerequisites and learning velocity +5. Urgent/deadline management - Color-coded priorities, countdown timers + +## Examples +- Course card: "Python Fundamentals | 67% complete | 5 hours remaining | Due in 3 days" +- Achievement: "7-day streak! Keep going 🔥" +- Recommendation: "Ready for the next lesson: Advanced Functions (15 min)" + +## Formats +Dashboard with: +- Grid layout of course cards (responsive 1-3 columns) +- Progress rings with percentage labels +- Upcoming deadlines section (sorted by urgency) +- Achievements sidebar +- "Continue Learning" CTA for most recent course +``` + +--- + +## Transformation Pattern Template + +Use this template for any prompt optimization task: + +```markdown +### Original Requirement +[Paste user's vague requirement here] + +### EARS Transformation +1. When , the system shall +2. When , the system shall +[Add more EARS statements as needed] + +### Domain Theories +**Domain:** [Identify the primary domain] + +**Relevant Theories:** +- Theory 1 - [Brief description] +- Theory 2 - [Brief description] +- Theory 3 - [Brief description] + +### Enhanced Prompt +# Role +[Specific expert role with domain expertise] + +## Skills +- [Skill 1] +- [Skill 2] +[List 5-8 relevant skills] + +## Workflows +1. [Step 1] - [Brief description] +2. [Step 2] - [Brief description] +[List complete workflow steps] + +## Examples +[Extract concrete examples from original requirement or create relevant ones] + +## Formats +[Specify exact output format requirements] +``` + +--- + +## Example 4: Password Reset Feature (Security-Focused) + +### Original Requirement (Vague) + +``` +Build me a password reset feature +``` + +**Problems:** +- No specification of reset method (email, SMS, security questions) +- Missing security constraints (rate limiting, token expiration) +- No UX flow defined (how user initiates, confirms reset) +- Lack of error handling requirements + +### EARS Transformation + +``` +1. When user clicks "Forgot Password", the system shall display email input field + +2. When user submits valid email, the system shall send password reset link valid for 1 hour + +3. When user clicks reset link, the system shall verify token has not expired + +4. When token is valid, the system shall display password creation form requiring minimum 12 characters, 1 uppercase, 1 number, 1 special character + +5. When user submits new password meeting requirements, the system shall hash password with bcrypt and invalidate reset token + +6. When user attempts password reset more than 3 times in 1 hour, the system shall block further attempts for 1 hour + +7. If reset token has expired, the system shall display error message and option to request new link +``` + +### Domain Theories + +**Domain:** Authentication Security, User Experience Design + +**Relevant Theories:** +- **Zero Trust Architecture** - Never trust input; verify token at each step +- **Defense in Depth** - Multiple security layers (rate limiting, token expiration, password complexity) +- **Progressive Disclosure** - Guide user through multi-step flow without overwhelming + +### Enhanced Prompt + +```markdown +# Role +Senior security engineer and UX designer specializing in authentication systems, with expertise in OWASP security standards and user-friendly security design. + +## Skills +- Design secure password reset flows resistant to common attacks (brute force, token leakage) +- Implement cryptographic best practices (bcrypt, secure token generation) +- Apply UX principles to security-sensitive interactions +- Handle edge cases and error states gracefully +- Comply with GDPR and data protection regulations + +## Workflows +1. Request initiation - User enters email, client-side validation for format +2. Token generation - Server generates cryptographically random token (256-bit), stores with 1-hour expiration +3. Email delivery - Send reset link via transactional email service with clear instructions +4. Link validation - Verify token exists, not expired, not already used +5. Password creation - Enforce complexity requirements with real-time feedback +6. Password storage - Hash with bcrypt (cost factor 12), invalidate token, log security event +7. Rate limiting - Track attempts by IP and email, implement exponential backoff + +## Examples +- **Reset email:** Subject: "Password Reset Request", Body: "Click here to reset your password (link expires in 1 hour): https://example.com/reset?token=abc123..." +- **Password requirements:** "Minimum 12 characters, at least 1 uppercase letter (A-Z), 1 number (0-9), 1 special character (!@#$%)" +- **Error messages:** "This reset link has expired. Please request a new password reset link." +- **Rate limiting:** "Too many reset attempts. Please try again in 59 minutes." + +## Formats +Implement the following: +- Backend API endpoints: POST /api/auth/forgot-password, POST /api/auth/reset-password +- Email template (HTML) with reset link and instructions +- Frontend pages: Forgot password form, Reset password form +- Database schema: password_reset_tokens table (token, email, created_at, expires_at, used) +- Security measures: Rate limiting middleware, token hashing in database, HTTPS-only cookies +- Error handling: User-friendly messages, detailed server logs +``` + +**How to use:** +Provide this to an AI code assistant or development team. The EARS requirements enable test-driven development, the theories justify security decisions, and the examples provide concrete test cases. + +**Next steps:** Implement the password reset feature using this specification, or iterate with additional security requirements (2FA, account recovery, etc.)