diff --git a/packages/@webex/contact-center/ai-docs/templates/README.md b/packages/@webex/contact-center/ai-docs/templates/README.md new file mode 100644 index 00000000000..028370baa37 --- /dev/null +++ b/packages/@webex/contact-center/ai-docs/templates/README.md @@ -0,0 +1,102 @@ +# Contact Center SDK - Templates + +> **Purpose**: Code generation templates for AI agents to create, modify, and document SDK components. + +--- + +## Template Categories + +| Category | Purpose | Use When | +|----------|---------|----------| +| **new-service/** | Creating new services (like AddressBook, Queue) | Adding new data/API services | +| **new-method/** | Adding methods to existing services | Extending service capabilities | +| **existing-service/** | Bug fixes, feature enhancements, and modifications to existing methods | Modifying existing code | +| **documentation/** | Generating AGENTS.md and ARCHITECTURE.md | Creating service-level docs | + +--- + +## Template Directory Structure + +``` +templates/ +├── README.md # This file +├── new-service/ # New service creation +│ ├── 00-master.md # Orchestrator +│ ├── 01-pre-questions.md # Requirements gathering (STOP gate) +│ ├── 02-code-generation.md # Service class generation +│ ├── 03-integration.md # Registration and exports +│ ├── 04-test-generation.md # Test file generation +│ └── 05-validation.md # Quality checklist +├── new-method/ # New method addition +│ ├── 00-master.md # Orchestrator +│ ├── 01-requirements.md # Method requirements (STOP gate) +│ ├── 02-implementation.md # Code implementation +│ ├── 03-tests.md # Test generation +│ └── 04-validation.md # Quality checklist +├── existing-service/ # Modifications +│ ├── bug-fix.md # Bug fix workflow (STOP gate in Section A) +│ └── feature-enhancement.md # Feature addition / modify existing method (STOP gate in Step 0) +└── documentation/ # Doc generation + ├── create-agents-md.md # AGENTS.md template + └── create-architecture-md.md # ARCHITECTURE.md template +``` + +--- + +## Quick Reference + +### Creating a New Service (Task Type A) +Start with: [`new-service/00-master.md`](new-service/00-master.md) + +### Adding a New Method (Task Type B) +Start with: [`new-method/00-master.md`](new-method/00-master.md) + +### Fixing a Bug (Task Type C) +Use: [`existing-service/bug-fix.md`](existing-service/bug-fix.md) + +### Adding a Feature (Task Type D) +Start with: [`existing-service/feature-enhancement.md`](existing-service/feature-enhancement.md) + +**Important:** Feature template includes a mandatory placement triage: +- if feature fits existing service -> continue feature-enhancement flow +- if feature needs standalone ownership -> reroute to [`new-service/00-master.md`](new-service/00-master.md) + +### Modifying an Existing Method (Task Type F) +Use: [`existing-service/feature-enhancement.md`](existing-service/feature-enhancement.md) + +**Important:** When modifying an existing method (changing signature, parameters, return type, or behavior), use the feature-enhancement template but **skip Step 0 (Placement Triage)** since the method already exists. Start directly at Step 0B (Pre-Enhancement Questions). + +### Creating Service Documentation (Task Type E) +Use: [`documentation/create-agents-md.md`](documentation/create-agents-md.md) + +--- + +## Template Usage Flow + +``` +1. Classify task using root AGENTS.md decision tree (../../AGENTS.md) + | + v +2. Route to appropriate template + | + v +3. STOP — Present pre-questions to developer, wait for answers + | + v +4. Present Spec Summary to developer, wait for approval + | + v +5. If task is "Add Feature", run placement triage (existing vs new service) + | + v +6. Load relevant patterns as specified + | + v +7. Generate/modify code + | + v +8. Run validation checklist + | + v +9. Update documentation if needed +``` diff --git a/packages/@webex/contact-center/ai-docs/templates/documentation/create-agents-md.md b/packages/@webex/contact-center/ai-docs/templates/documentation/create-agents-md.md new file mode 100644 index 00000000000..f4f1f9d98dd --- /dev/null +++ b/packages/@webex/contact-center/ai-docs/templates/documentation/create-agents-md.md @@ -0,0 +1,240 @@ +# Create AGENTS.md Template + +> **Purpose**: Template for generating service-level AGENTS.md files optimized for LLM consumption. + +--- + +## Pre-Generation Questions + +Answer before writing: + +1. **Package/Service Name**: What is this service called? +2. **Purpose**: What problem does this service solve? (1-2 sentences) +3. **Key Capabilities**: What are the main features? (3-5 bullets) +4. **Usage Examples**: What are the most common use cases? +5. **API Surface**: What methods/properties are exposed? +6. **Dependencies**: What does this service depend on? + +--- + +## AGENTS.md Structure + +```markdown +# [Service Name] - AI Agent Guide + +> **Purpose**: [One sentence describing what this service does] + +--- + +## Quick Start + +[3-5 line code example showing most basic usage] + +--- + +## Key Capabilities + +- [Capability 1]: [Brief description] +- [Capability 2]: [Brief description] +- [Capability 3]: [Brief description] + +--- + +## Usage Examples + +### [Use Case 1] +```typescript +// Example code +``` + +### [Use Case 2] +```typescript +// Example code +``` + +--- + +## API Reference + +### Properties + +| Property | Type | Description | +|----------|------|-------------| +| `propertyName` | `Type` | Description | + +### Methods + +#### `methodName(params)` + +Description of what this method does. + +**Parameters**: +- `param1` (Type): Description +- `param2` (Type, optional): Description + +**Returns**: `Promise` - Description + +**Example**: +```typescript +const result = await service.methodName({ + param1: 'value', +}); +``` + +--- + +## Events (if applicable) + +| Event | Data | When Emitted | +|-------|------|--------------| +| `event:name` | `EventData` | Description | + +--- + +## Common Patterns + +### [Pattern Name] +```typescript +// Pattern example +``` + +--- + +## Error Handling + +Errors are thrown as `Error` with: +- `message`: Error description +- `data.reason`: Error reason code + +```typescript +try { + await service.method(); +} catch (error) { + console.error(error.message); + console.error(error.data?.reason); +} +``` + +--- + +## Dependencies + +- Requires: [dependency description] +- Used by: [what uses this service] + +--- + +## Related Documentation + +- [ARCHITECTURE.md](ARCHITECTURE.md) - Technical deep-dive +- [Pattern files](../../../ai-docs/patterns/) - Coding patterns +``` + +--- + +## Content Guidelines + +### Purpose Section +- One clear sentence +- Focus on business value, not implementation + +### Quick Start +- Show the happy path +- Minimal code to demonstrate value +- Include all required setup steps + +### Examples +- Use realistic parameter values +- Show common variations +- Include error handling when relevant + +### API Reference +- List all public methods +- Include parameter types and descriptions +- Show return types +- Provide example for each method + +### Error Handling +- Document common error scenarios +- Show how to access error details + +--- + +## Token Optimization Strategy + +For LLM efficiency: +1. **AGENTS.md first**: Contains usage info (most commonly needed) +2. **ARCHITECTURE.md linked at end**: For deep technical questions +3. **Concise examples**: Just enough to demonstrate +4. **Tables for reference**: Quick scanning + +--- + +## Validation Checklist + +- [ ] Purpose is clear and concise +- [ ] Quick start works as-is +- [ ] All public methods documented +- [ ] Examples are realistic and working +- [ ] Error handling documented +- [ ] Links to ARCHITECTURE.md included +- [ ] No implementation details (save for ARCHITECTURE.md) + +--- + +## Example: Services/Agent AGENTS.md + +```markdown +# Agent Service - AI Agent Guide + +> **Purpose**: Manage agent lifecycle including login, logout, and state changes. + +--- + +## Quick Start + +```typescript +const cc = webex.cc; +await cc.register(); + +// Login +await cc.stationLogin({ + teamId: 'team-123', + loginOption: 'BROWSER', +}); + +// Set available +await cc.setAgentState({ + state: 'Available', + auxCodeId: '0', +}); +``` + +--- + +## Key Capabilities + +- **Station Login**: Login with browser, extension, or dial number +- **Station Logout**: Logout from current station +- **State Management**: Change between Available/Idle states +- **Buddy Agents**: Retrieve list of available agents + +--- + +## API Reference + +### `stationLogin(params)` + +Login agent to a station. + +**Parameters**: +- `teamId` (string): Team to login to +- `loginOption` ('BROWSER' | 'EXTENSION' | 'AGENT_DN'): Device type +- `dialNumber` (string, optional): Required for EXTENSION/AGENT_DN + +**Returns**: `Promise` + +--- + +See [ARCHITECTURE.md](ARCHITECTURE.md) for technical details. +``` diff --git a/packages/@webex/contact-center/ai-docs/templates/documentation/create-architecture-md.md b/packages/@webex/contact-center/ai-docs/templates/documentation/create-architecture-md.md new file mode 100644 index 00000000000..b192820db40 --- /dev/null +++ b/packages/@webex/contact-center/ai-docs/templates/documentation/create-architecture-md.md @@ -0,0 +1,293 @@ +# Create ARCHITECTURE.md Template + +> **Purpose**: Template for generating service-level ARCHITECTURE.md files with technical deep-dives. + +--- + +## Pre-Generation Questions + +Answer before writing: + +1. **Component Overview**: What are the main components/classes? +2. **File Structure**: How are files organized? +3. **Data Flow**: How does data move through the system? +4. **Integration Points**: How does this integrate with other services? +5. **Key Sequences**: What are the important operation sequences? +6. **Troubleshooting**: What are common issues and solutions? + +--- + +## ARCHITECTURE.md Structure + +```markdown +# [Service Name] - Architecture + +> **Purpose**: Technical documentation for the [service name] component. + +--- + +## Component Overview + +| Component | File | Responsibility | +|-----------|------|----------------| +| `ClassName` | `path/to/file.ts` | What it does | +| `ClassName2` | `path/to/file2.ts` | What it does | + +--- + +## File Structure + +``` +services/[name]/ +├── index.ts # Main service export +├── types.ts # Type definitions +├── constants.ts # Constants +└── ai-docs/ + ├── AGENTS.md # Usage documentation + └── ARCHITECTURE.md # This file +``` + +--- + +## Data Flow + +```mermaid +flowchart TD + A[User Action] --> B[cc.methodName] + B --> C[services.service.method] + C --> D[WebSocket/HTTP Request] + D --> E[Backend Response] + E --> F[Event Emission] +``` + +--- + +## Sequence Diagrams + +### [Operation Name] + +```mermaid +sequenceDiagram + participant App + participant CC as ContactCenter + participant Svc as Service + participant WS as WebSocket + participant BE as Backend + + App->>CC: methodName(params) + CC->>Svc: service.method({data}) + Svc->>WS: Send request + WS->>BE: WebSocket message + BE-->>WS: Response event + WS-->>Svc: Resolve promise + Svc-->>CC: Return response + CC-->>App: Promise resolves +``` + +--- + +## Key Patterns + +### [Pattern Name] + +Description of the pattern and why it's used. + +```typescript +// Code example +``` + +--- + +## Integration Points + +### With [Component] + +How this service integrates with other components. + +### With WebSocket + +How WebSocket events are handled. + +### With Metrics + +What metrics are tracked. + +--- + +## State Management + +### Lifecycle States + +``` +[State 1] → [State 2] → [State 3] + ↑ ↓ + └──────────────────────┘ +``` + +### State Transitions + +| From | To | Trigger | +|------|-----|---------| +| State1 | State2 | Action | + +--- + +## Error Handling + +### Error Types + +| Error | Cause | Resolution | +|-------|-------|------------| +| `REASON_CODE` | Why it happens | How to fix | + +### Error Flow + +```mermaid +flowchart TD + A[API Call] --> B{Success?} + B -->|Yes| C[Track Success Metric] + B -->|No| D[Cast to Failure] + D --> E[Track Failure Metric] + E --> F[getErrorDetails] + F --> G[Log Error] + G --> H[Upload Logs] + H --> I[Throw Error] +``` + +--- + +## Troubleshooting + +### [Issue]: [Symptom] + +**Cause**: Why this happens + +**Solution**: How to fix + +**Example**: +```typescript +// Code showing the fix +``` + +--- + +## Related Files + +- [Main implementation](../../path/to/file.ts) +- [Types](../../path/to/types.ts) +- [Tests](../../../../test/unit/spec/path/to/file.ts) +``` + +--- + +## Content Guidelines + +### Component Overview +- List main classes/functions +- Include file paths +- Brief responsibility description + +### Diagrams +- Use Mermaid for all diagrams +- Keep diagrams focused (not too complex) +- Include legends if needed + +### Sequence Diagrams +- Show key operations +- Include error paths for critical flows +- Label all participants clearly + +### Troubleshooting +- Document real issues encountered +- Provide concrete solutions +- Include code examples + +--- + +## Mermaid Diagram Guidelines + +### Flowchart +```mermaid +flowchart TD + A[Start] --> B{Decision} + B -->|Yes| C[Action] + B -->|No| D[Other Action] +``` + +### Sequence +```mermaid +sequenceDiagram + participant A as ActorA + participant B as ActorB + A->>B: Message + B-->>A: Response +``` + +### State +```mermaid +stateDiagram-v2 + [*] --> State1 + State1 --> State2 + State2 --> [*] +``` + +--- + +## Validation Checklist + +- [ ] All components listed with files +- [ ] Data flow diagram included +- [ ] Key sequence diagrams present +- [ ] Error handling documented +- [ ] Troubleshooting section has real issues +- [ ] Mermaid diagrams render correctly +- [ ] Links to source files included + +--- + +## Example: Task Service ARCHITECTURE.md + +```markdown +# Task Service - Architecture + +> Technical documentation for task lifecycle management. + +--- + +## Component Overview + +| Component | File | Responsibility | +|-----------|------|----------------| +| `TaskManager` | `task/TaskManager.ts` | Task lifecycle coordination | +| `contact` | `task/contact.ts` | Task operations (hold, transfer) | +| `dialer` | `task/dialer.ts` | Outbound call initiation | +| `AutoWrapup` | `task/AutoWrapup.ts` | Auto wrapup timer | + +--- + +## Sequence: Incoming Task + +```mermaid +sequenceDiagram + participant WS as WebSocket + participant TM as TaskManager + participant CC as ContactCenter + participant App as Application + + WS->>TM: AgentOfferContact event + TM->>TM: Create Task object + TM->>CC: emit task:incoming + CC->>App: trigger task:incoming + App->>App: Display incoming task UI +``` + +--- + +## Troubleshooting + +### Issue: Task events not received + +**Cause**: TaskManager listeners not registered + +**Solution**: Ensure register() is called before login +``` diff --git a/packages/@webex/contact-center/ai-docs/templates/existing-service/bug-fix.md b/packages/@webex/contact-center/ai-docs/templates/existing-service/bug-fix.md new file mode 100644 index 00000000000..583d664adf4 --- /dev/null +++ b/packages/@webex/contact-center/ai-docs/templates/existing-service/bug-fix.md @@ -0,0 +1,258 @@ +# Bug Fix Template + +> **Purpose**: Systematic workflow for fixing bugs in existing code. + +--- + +## Section A: Questions for the Developer (MANDATORY — Ask First) + +**STOP. Present the following questions to the developer and wait for their answers.** Do not read code, run tests, or start investigating until the developer has answered these questions. Do not infer or assume answers. + +If the developer cannot provide reproduction steps, ask for logs, error messages, or a description of expected vs actual behavior. + +### Questions to Ask: + +1. **"What is the unexpected behavior you are seeing?"** + - Get a clear description of what is going wrong. + +2. **"What should happen instead? What is the expected behavior?"** + +3. **"How do you reproduce this bug? What are the steps?"** + - If the developer cannot reproduce it, ask: + - "Do you have any error messages or stack traces?" + - "Do you have a trackingId from the logs?" + - "When did this start happening? Was there a recent code change?" + +4. **"Which layer do you think is affected?"** + - [ ] Plugin (`cc.ts`) + - [ ] Service (`services/*`) + - [ ] Core (`services/core/*`) + - [ ] Types + - [ ] Not sure (this is fine — you will investigate) + +5. **"Are there any error messages or stack traces you can share?"** + +6. **"Is there a trackingId from the logs associated with this bug?"** + +### Completion Gate for Section A + +**Before proceeding to investigation, verify:** + +- [ ] Unexpected behavior described by developer +- [ ] Expected behavior described by developer +- [ ] Reproduction steps provided (or logs/error messages if steps are unknown) +- [ ] Affected layer identified (or "not sure" — which is acceptable) + +**If the description is too vague to start investigating (e.g., "it's broken"), ask targeted follow-up questions. Do not proceed until you have enough context to know where to look.** + +--- + +## Section B: Agent Investigation Steps (After Developer Answers) + +Only proceed here after Section A questions are answered. + +### Step 1: Reproduce the Bug + +#### Understand Current Behavior + +1. Read the affected code — trace the execution flow +2. Identify where behavior diverges from the developer's expected behavior +3. Check the call chain: plugin -> service -> core + +#### Check Existing Tests + +```bash +# Run tests for the affected area +yarn workspace @webex/contact-center test:unit -- +``` + +Are there tests that should have caught this? Do they pass incorrectly? + +--- + +### Step 2: Identify Root Cause + +#### Common Bug Patterns in This SDK + +**A. Async/Promise Issues** +```typescript +// Bug: Not awaiting promise +this.services.agent.stateChange({data}); + +// Fix: Await the promise +await this.services.agent.stateChange({data}); +``` + +**B. Missing Error Handling** +```typescript +// Bug: Error swallowed +try { + await operation(); +} catch (e) {} + +// Fix: Proper error handling +try { + await operation(); +} catch (error) { + const {error: detailedError} = getErrorDetails(error, method, module); + throw detailedError; +} +``` + +**C. Event Listener Leaks** +```typescript +// Bug: Listener not removed +this.on('event', handler); + +// Fix: Store reference and remove +this.handler = (data) => { /* handle */ }; +this.on('event', this.handler); +// Later in cleanup: +this.off('event', this.handler); +``` + +**D. Type Mismatches** +```typescript +// Bug: Accessing wrong property +const id = response.data.agentId; // But it's response.agentId + +// Fix: Check actual response structure +const id = response.agentId; +``` + +**E. Missing Null Checks** +```typescript +// Bug: Crashes if undefined +const name = this.agentConfig.teams[0].teamName; + +// Fix: Optional chaining +const name = this.agentConfig?.teams?.[0]?.teamName; +``` + +--- + +### Step 3: Present Root Cause and Proposed Fix to Developer + +**STOP. Before writing any fix, present your findings to the developer:** + +``` +## Bug Analysis Summary + +**Bug**: [one-sentence description] +**Root cause**: [what is actually wrong in the code] +**Affected file(s)**: [file paths and line numbers] +**Root cause category**: [A/B/C/D/E from patterns above, or other] + +### Proposed Fix: +- [What will change in which file] +- [What the code will look like after the fix] + +### Risk Assessment: +- Could this fix break anything else? [Yes/No — if yes, what] +- Backward compatible? [Yes/No] + +### Tests to Add: +- [Regression test description] + +--- +Does this analysis look correct? Should I proceed with this fix? (Yes / No / Adjust) +``` + +**Wait for developer confirmation before implementing the fix.** + +--- + +### Step 4: Implement the Fix + +After developer approval: + +```typescript +// 1. Make the minimal fix +// 2. Add/update logging if it helps debugging +LoggerProxy.log('Processing data', { + module: MODULE, + method: METHOD, + data: { relevantField: value }, // Add context +}); + +// 3. Ensure error handling is complete +try { + // fixed code +} catch (error) { + LoggerProxy.error(`Operation failed: ${error}`, { + module: MODULE, + method: METHOD, + }); + // ... proper error handling +} +``` + +--- + +### Step 5: Add Regression Test + +```typescript +describe('methodName - Bug Fix', () => { + it('should handle [specific scenario that was buggy]', async () => { + // Arrange: Setup the conditions that triggered the bug + const bugTriggerInput = { /* ... */ }; + + // Act: Execute the fixed code + const result = await service.methodName(bugTriggerInput); + + // Assert: Verify correct behavior + expect(result).toEqual(expectedResult); + }); + + it('should not throw error when [edge case]', async () => { + // Test the specific edge case that was failing + }); +}); +``` + +--- + +### Step 6: Validation Checklist + +#### Code Changes +- [ ] Fix is minimal and focused +- [ ] No unrelated changes +- [ ] LoggerProxy used (no console.log) +- [ ] Error handling complete + +#### Tests +- [ ] Regression test added +- [ ] All existing tests still pass +- [ ] Test covers the specific bug scenario + +#### Verification +```bash +# Lint +yarn workspace @webex/contact-center test:style + +# All tests +yarn workspace @webex/contact-center test:unit + +# Build +yarn workspace @webex/contact-center build:src +``` + +--- + +## Documentation + +If the bug affected documented behavior: +- [ ] Update JSDoc if behavior changed +- [ ] Update the affected service's `AGENTS.md` if API behavior changed (find via root [`AGENTS.md` Service Routing Table](../../../AGENTS.md#service-routing-table)) +- [ ] Update the affected service's `ARCHITECTURE.md` if data flow changed + +--- + +## Complete! + +Bug fix is complete when: +1. Root cause identified and confirmed with developer +2. Fix implemented after developer approval +3. Regression test added +4. All tests pass +5. Build succeeds diff --git a/packages/@webex/contact-center/ai-docs/templates/existing-service/feature-enhancement.md b/packages/@webex/contact-center/ai-docs/templates/existing-service/feature-enhancement.md new file mode 100644 index 00000000000..b394839bc36 --- /dev/null +++ b/packages/@webex/contact-center/ai-docs/templates/existing-service/feature-enhancement.md @@ -0,0 +1,440 @@ +# Feature Enhancement Template + +> **Purpose**: Workflow for adding new features to existing services. + +--- + +## Step 0: Feature Placement Triage (MANDATORY) + +**STOP. Before any implementation, present these triage questions to the developer and wait for answers.** + +> **Note:** If you arrived here via **Type F (Modify Existing Method)** from the root [`AGENTS.md`](../../../AGENTS.md), skip this Step 0 entirely — the method already exists in an existing service. Jump to Step 0B (Pre-Enhancement Questions). + +### Triage Questions — Always Ask These: + +1. **"Does this feature fit within the responsibility of an existing service, or does it introduce a new domain/responsibility?"** + +2. **"Do you expect this feature to grow into multiple related methods in future iterations?"** + +3. **"Should this feature have independent ownership (its own state, events, dependencies) separate from current services?"** + +4. **"Is there an existing service you want to add this to? Or should it be a new standalone service/module?"** + +5. **"Are there backward compatibility constraints if we add this to an existing service?"** + +6. **"If this becomes a new service, do you have a preferred name for it?"** + +### Triage Decision Guide + +After the developer answers, use these signals to decide placement: + +**Existing service** when: +- Feature naturally extends current service responsibility +- Only 1-2 methods are needed in the same domain +- Existing service already owns required events/state/API integration +- Developer explicitly says "add it to [service]" + +**New service** when: +- Feature introduces a distinct domain boundary/responsibility +- It needs its own lifecycle/dependencies/state orchestration +- It is expected to grow into multiple related methods/classes +- Adding it to an existing service would create low cohesion or cross-domain coupling +- Developer explicitly wants a standalone module + +### Routing Rule + +- If triage => **existing service**: continue with this template (Step 0B below). +- If triage => **new service**: switch to [`../new-service/00-master.md`](../new-service/00-master.md). +- If still unclear after developer answers: ask one more clarifying question rather than guessing. + +--- + +## Step 0B: Pre-Enhancement Questions (MANDATORY) + +**Present these questions to the developer and wait for answers.** Do not start designing or implementing until all MANDATORY fields have explicit answers. + +### 1. Feature Definition (MANDATORY) + +7. **"What is this feature called? (Brief name)"** + +8. **"What does this feature do? Describe the expected behavior."** + +9. **"When would a developer use this feature? What is the use case?"** + +### 2. Scope and Placement (MANDATORY) + +10. **"Which existing files will be affected?"** + - [ ] `cc.ts` (main plugin) + - [ ] `services/[name]/index.ts` + - [ ] `types.ts` + - [ ] Other: ___ + +11. **"Will this introduce any breaking changes to existing APIs?"** + - If yes: "What is the migration path?" + +### 3. API Contract (MANDATORY) + +For each new or updated API call, ask: + +12. **"What API endpoint does this feature call? Provide:"** + + | Field | What to Ask | + |---|---| + | HTTP Method | "Is this a GET, POST, PUT, PATCH, or DELETE?" | + | Endpoint | "What is the full resource path?" | + | Request Payload | "What fields does the request contain? Which are required vs optional?" | + | Response Structure | "What does the response look like? (`data`, `trackingId`, metadata)" | + | Error Shape | "What error reason codes can this return?" | + + **If any field is unknown, STOP and ask the developer. Do not guess.** + +### 4. Event Contract (MANDATORY if the feature uses events, otherwise skip) + +13. **"Does this feature emit or listen to any events?"** + - If YES, for each event ask: + + | Field | What to Ask | + |---|---| + | Event Name | "What is the event name?" | + | Direction | "Is this incoming (WebSocket) or outgoing (emitted by SDK)?" | + | Emitted/Received On | "On which object is this event emitted or received?" (`cc`, `task`, `taskManager`, or a service instance) | + | Payload Type/Shape | "What data does the event carry?" | + | Emitted From | "Which class/file emits this event?" | + | Emission Trigger | "What causes this event to fire?" | + + - If NO: note "No events" + +### 5. Dependencies (MANDATORY) + +14. **"Does this feature require new API endpoints that don't exist yet?"** + +15. **"Does this feature require new types?"** + - If yes: "What should the type names be?" + +### Completion Gate + +**Before proceeding, verify:** + +- [ ] Feature name and description provided by developer +- [ ] Use case described +- [ ] Placement decision confirmed (existing service or new service) +- [ ] Affected files identified +- [ ] Breaking changes assessed +- [ ] API contract fully specified (or developer confirmed no new API calls) +- [ ] Event contract captured (or developer confirmed no events) +- [ ] Dependencies identified + +**If any MANDATORY field is missing, ask a follow-up question. Do not proceed.** + +--- + +## Spec Summary (MANDATORY — present before implementation) + +Once all questions are answered, present this summary to the developer: + +``` +## Spec Summary — Feature Enhancement + +**Feature**: [name] +**Description**: [what it does] +**Use case**: [when a developer would use this] +**Placement**: [existing service name] (or rerouted to new service) +**Breaking changes**: [Yes/No — details if yes] + +### Affected Files: +1. [file path] — [what changes] +2. [file path] — [what changes] + +### API Contract: +| Method | HTTP | Endpoint | Request | Response | +|---|---|---|---|---| +| [method] | [verb] | [path] | [payload] | [response] | +(or "No new API calls") + +### Events: +| Event | Direction | Object | Payload | Trigger | +|---|---|---|---|---| +| [event] | [in/out] | [object] | [payload] | [trigger] | +(or "No events") + +### New Types: [list or "None"] +### New Constants: [list or "None"] + +--- +Does this match your intent? (Yes / No / Adjust) +``` + +**Wait for developer approval. Do not proceed to implementation until confirmed.** + +--- + +## Step 1: Design the Feature + +### API Design + +Define the public interface: + +```typescript +/** + * What the feature does + * @param params - Description + * @returns Description + */ +async featureName(params: FeatureParams): Promise +``` + +### Data Flow + +``` +User calls cc.featureName(params) + | + v +Validate input + | + v +Call service/API + | + v +Process response + | + v +Return/emit result +``` + +--- + +## Step 2: Update Types + +### Add New Types + +In appropriate types file: + +```typescript +/** + * Parameters for feature operation + * @public + */ +export type FeatureParams = { + /** Description */ + field: string; +}; + +/** + * Response from feature operation + * @public + */ +export type FeatureResponse = { + /** Description */ + data: FeatureData; +}; +``` + +### Export Types + +In `src/types.ts`: + +```typescript +export type {FeatureParams, FeatureResponse} from './services/[location]'; +``` + +--- + +## Step 3: Implement Feature + +### Service Layer (if needed) + +Add method to existing service: + +```typescript +// In services/[name]/index.ts +featureMethod: routing.req((p: {data: FeatureParams}) => ({ + url: '/v1/feature', + host: WCC_API_GATEWAY, + data: p.data, + err: createErrDetailsObject, + method: HTTP_METHODS.POST, + notifSuccess: { + bind: {type: CC_EVENTS.FEATURE_SUCCESS, data: {type: CC_EVENTS.FEATURE_SUCCESS}}, + msg: {} as FeatureResponse, + }, + notifFail: { + bind: {type: CC_EVENTS.FEATURE_FAILED, data: {type: CC_EVENTS.FEATURE_FAILED}}, + errId: 'Service.aqm.feature.failed', + }, +})), +``` + +### Plugin Layer (cc.ts) + +Add public method: + +```typescript +/** + * Feature description. + * + * @param {FeatureParams} params - Parameters + * @returns {Promise} Result + * @throws {Error} If operation fails + * + * @public + * + * @example + * ```typescript + * const result = await cc.featureName({ + * field: 'value', + * }); + * ``` + */ +public async featureName(params: FeatureParams): Promise { + LoggerProxy.info('Starting feature operation', { + module: CC_FILE, + method: METHODS.FEATURE_NAME, + }); + + try { + this.metricsManager.timeEvent([ + METRIC_EVENT_NAMES.FEATURE_SUCCESS, + METRIC_EVENT_NAMES.FEATURE_FAILED, + ]); + + const result = await this.services.someService.featureMethod({ + data: params, + }); + + this.metricsManager.trackEvent( + METRIC_EVENT_NAMES.FEATURE_SUCCESS, + {...MetricsManager.getCommonTrackingFieldForAQMResponse(result)}, + ['behavioral', 'operational'] + ); + + LoggerProxy.log('Feature operation completed successfully', { + module: CC_FILE, + method: METHODS.FEATURE_NAME, + trackingId: result.trackingId, + }); + + return result; + } catch (error) { + const failure = error.details as Failure; + this.metricsManager.trackEvent( + METRIC_EVENT_NAMES.FEATURE_FAILED, + {...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(failure)}, + ['behavioral', 'operational'] + ); + const {error: detailedError} = getErrorDetails(error, METHODS.FEATURE_NAME, CC_FILE); + throw detailedError; + } +} +``` + +--- + +## Step 4: Add Constants + +### Method Constants + +```typescript +// src/constants.ts +export const METHODS = { + // ... existing + FEATURE_NAME: 'featureName', +} as const; +``` + +### Metric Constants + +```typescript +// src/metrics/constants.ts +export const METRIC_EVENT_NAMES = { + // ... existing + FEATURE_SUCCESS: 'feature success', + FEATURE_FAILED: 'feature failed', +} as const; +``` + +### Event Constants (if needed) + +```typescript +// services/config/types.ts +export const CC_FEATURE_EVENTS = { + FEATURE_SUCCESS: 'FeatureSuccess', + FEATURE_FAILED: 'FeatureFailed', +} as const; +``` + +--- + +## Step 5: Update Tests + +### Add Feature Tests + +```typescript +describe('cc.featureName', () => { + const mockParams = { + field: 'value', + }; + + const mockResponse = { + data: { /* ... */ }, + trackingId: 'track-123', + }; + + it('should complete feature operation successfully', async () => { + mockServicesInstance.someService.featureMethod.mockResolvedValue(mockResponse); + + const result = await webex.cc.featureName(mockParams); + + expect(result).toEqual(mockResponse); + }); + + it('should handle errors correctly', async () => { + mockServicesInstance.someService.featureMethod.mockRejectedValue(mockError); + + await expect(webex.cc.featureName(mockParams)).rejects.toThrow(); + }); +}); +``` + +--- + +## Step 6: Update Documentation + +### Update Service-Level Docs + +If the affected service has ai-docs, update them (find the right file via the root [`AGENTS.md` Service Routing Table](../../../AGENTS.md#service-routing-table)): +- Service `AGENTS.md` — add new method to API reference, add usage example +- Service `ARCHITECTURE.md` — update data flow if architecture changed + +### Update Root AGENTS.md + +If feature is significant, update the root [`AGENTS.md`](../../../AGENTS.md): +- Add to relevant section +- Update examples if needed + +--- + +## Validation Checklist + +- [ ] Types defined with JSDoc +- [ ] Types exported from `src/types.ts` +- [ ] Method implemented following patterns +- [ ] LoggerProxy used throughout +- [ ] MetricsManager tracking added +- [ ] Error handling follows pattern +- [ ] Constants added (methods, metrics, events) +- [ ] Unit tests added +- [ ] All tests pass +- [ ] Build succeeds +- [ ] Documentation updated + +```bash +yarn workspace @webex/contact-center test:style +yarn workspace @webex/contact-center test:unit +yarn workspace @webex/contact-center build:src +``` + +--- + +## Complete! + +Feature enhancement is complete when all checkboxes are checked.