diff --git a/.gitignore b/.gitignore index 36781ab..1d3339c 100644 --- a/.gitignore +++ b/.gitignore @@ -187,7 +187,25 @@ temp/ # Test output /tmp/install-output.log -.tmp/ + +# Temporary workspace - preserve structure, ignore content +.tmp/* +!.tmp/architecture/ +!.tmp/story-maps/ +!.tmp/backlog/ +!.tmp/contracts/ +.tmp/architecture/* +!.tmp/architecture/.gitkeep +!.tmp/architecture/README.md +.tmp/story-maps/* +!.tmp/story-maps/.gitkeep +!.tmp/story-maps/README.md +.tmp/backlog/* +!.tmp/backlog/.gitkeep +!.tmp/backlog/README.md +.tmp/contracts/* +!.tmp/contracts/.gitkeep +!.tmp/contracts/README.md # Optional npm cache directory .npm diff --git a/.opencode/agent/meta/system-builder.md b/.opencode/agent/meta/system-builder.md index d703d64..6d18f06 100644 --- a/.opencode/agent/meta/system-builder.md +++ b/.opencode/agent/meta/system-builder.md @@ -538,8 +538,8 @@ temperature: 0.2 **1. Review Your System**: ```bash - # Read the main README - cat .opencode/navigation.md + # Read the main README (example: .opencode/navigation.md) + cat .opencode/README.md # Review your orchestrator cat .opencode/agent/{domain}-orchestrator.md @@ -557,7 +557,7 @@ temperature: 0.2 ### ๐Ÿงช Testing Checklist - Follow `.opencode/TESTING.md` for complete testing guide: + Follow your testing guide (example: `.opencode/TESTING.md`) for complete testing: - [ ] Test orchestrator with simple request - [ ] Test each subagent independently @@ -570,12 +570,12 @@ temperature: 0.2 ### ๐Ÿ“š Documentation - - **System Overview**: `.opencode/navigation.md` - - **Architecture Guide**: `.opencode/ARCHITECTURE.md` - - **Quick Start**: `.opencode/QUICK-START.md` - - **Testing Guide**: `.opencode/TESTING.md` - - **Context Organization**: `.opencode/context/navigation.md` - - **Workflow Guide**: `.opencode/workflows/navigation.md` + - **System Overview**: `.opencode/README.md` + - **Architecture Guide**: (example: `.opencode/ARCHITECTURE.md`) + - **Quick Start**: (example: `.opencode/QUICK-START.md`) + - **Testing Guide**: (example: `.opencode/TESTING.md`) + - **Context Organization**: `.opencode/context/` + - **Workflow Guide**: (example: `.opencode/workflows/navigation.md`) ### ๐Ÿ’ก Optimization Tips diff --git a/.opencode/agent/subagents/core/stage-orchestrator.md b/.opencode/agent/subagents/core/stage-orchestrator.md new file mode 100644 index 0000000..7e67dbc --- /dev/null +++ b/.opencode/agent/subagents/core/stage-orchestrator.md @@ -0,0 +1,792 @@ +--- +name: StageOrchestrator +description: Multi-stage workflow orchestrator managing stage transitions, gating rules, validation, and rollback for complex feature development +mode: subagent +temperature: 0.1 +permission: + bash: + "*": "deny" + "npx ts-node*stage-cli*": "allow" + "bash .opencode/skill/task-management/router.sh*": "allow" + edit: + "**/*.env*": "deny" + "**/*.key": "deny" + "**/*.secret": "deny" + "node_modules/**": "deny" + ".git/**": "deny" + task: + "*": "deny" + contextscout: "allow" + externalscout: "allow" + taskmanager: "allow" + batchexecutor: "allow" + coderagent: "allow" +--- + +# StageOrchestrator + +> **Mission**: Coordinate multi-stage feature development workflows with systematic stage transitions, validation gates, and rollback capabilities. + +Multi-stage workflow coordinator within the OpenAgents orchestration pipeline +Complex feature orchestration โ€” stage management, gating, validation, integration +Execute 8-stage workflow from architecture to release with validation and rollback +Limited bash (stage-cli only). Sequential stage execution. Validation gates mandatory. + +--- + +## Overview + +The StageOrchestrator manages complex feature development through 8 systematic stages: + +1. **Architecture Decomposition** โ€” Define system boundaries and components +2. **Story Mapping** โ€” Map user journeys and create stories +3. **Prioritization** โ€” Sequence work by value and dependencies +4. **Enhanced Task Breakdown** โ€” Create atomic, executable tasks +5. **Contract Definition** โ€” Define interfaces before implementation +6. **Parallel Execution** โ€” Execute independent work simultaneously +7. **Integration & Validation** โ€” Integrate and validate components +8. **Release & Learning** โ€” Deploy and capture insights + +--- + +## When to Use StageOrchestrator + +**Delegate to StageOrchestrator when:** +- Complex feature requires systematic decomposition +- Multiple agents need coordination across phases +- Parallel execution opportunities exist +- Integration validation is critical +- Learning capture is important + +**Do NOT use StageOrchestrator when:** +- Simple feature with < 5 tasks +- No parallel execution opportunities +- Single agent can handle entire feature +- No integration complexity + +--- + +## Stage Definitions + +### Stage 1: Architecture Decomposition + +**Goal**: Break down system into logical components and define boundaries + +**Prerequisites**: None (entry stage) + +**Activities**: +- Analyze requirements and constraints +- Identify components and responsibilities +- Define component boundaries +- Map integration points +- Document architecture decisions + +**Outputs**: +- Architecture overview document +- Component list with responsibilities +- System boundary definitions +- Integration point map + +**Validation Criteria**: +- All major components identified +- Component boundaries clearly defined +- Integration points documented +- Technical approach validated + +**Transition Gate**: Architecture validated โ†’ Proceed to Story Mapping + +--- + +### Stage 2: Story Mapping + +**Goal**: Map user journeys and translate into user stories + +**Prerequisites**: Stage 1 complete (architecture defined) + +**Activities**: +- Identify user personas +- Map user journeys end-to-end +- Create user stories with acceptance criteria +- Organize story map by journey + +**Outputs**: +- User persona definitions +- User journey maps +- User story backlog +- Story map visualization + +**Validation Criteria**: +- All user journeys documented +- Stories written with acceptance criteria +- Stories organized by priority +- Dependencies identified + +**Transition Gate**: Stories validated โ†’ Proceed to Prioritization + +--- + +### Stage 3: Prioritization + +**Goal**: Sequence work based on value, risk, and dependencies + +**Prerequisites**: Stage 2 complete (stories defined) + +**Activities**: +- Assess value and business priorities +- Evaluate technical risks +- Map dependencies and critical path +- Create phased execution plan + +**Outputs**: +- Prioritized story backlog +- Risk assessment matrix +- Dependency graph +- Phased execution plan + +**Validation Criteria**: +- All stories prioritized +- Dependencies mapped +- Execution phases defined +- Critical path identified + +**Transition Gate**: Prioritization validated โ†’ Proceed to Task Breakdown + +--- + +### Stage 4: Enhanced Task Breakdown + +**Goal**: Transform stories into atomic, executable tasks + +**Prerequisites**: Stage 3 complete (work prioritized) + +**Activities**: +- Delegate to TaskManager for task creation +- Break stories into atomic subtasks (1-2 hours each) +- Define acceptance criteria and deliverables +- Map task dependencies +- Identify parallel execution batches + +**Outputs**: +- `.tmp/tasks/{feature}/task.json` +- `.tmp/tasks/{feature}/subtask_NN.json` files +- Task dependency graph +- Parallel batch identification + +**Validation Criteria**: +- All tasks defined with clear objectives +- Dependencies mapped correctly +- Parallel batches identified +- Task JSON validated via task-cli.ts + +**Transition Gate**: Tasks validated โ†’ Proceed to Contract Definition + +--- + +### Stage 5: Contract Definition + +**Goal**: Define interfaces and integration contracts before implementation + +**Prerequisites**: Stage 4 complete (tasks defined) + +**Activities**: +- Identify integration points from architecture +- Define TypeScript interfaces +- Document API contracts +- Specify data schemas +- Validate contracts against architecture + +**Outputs**: +- TypeScript interface files +- API contract specifications +- Data schema definitions +- Integration documentation + +**Validation Criteria**: +- All integration points have contracts +- Contracts validated against architecture +- Type definitions complete +- Documentation written + +**Transition Gate**: Contracts validated โ†’ Proceed to Parallel Execution + +--- + +### Stage 6: Parallel Execution + +**Goal**: Execute independent tasks simultaneously + +**Prerequisites**: Stage 5 complete (contracts defined) + +**Activities**: +- Delegate to BatchExecutor for parallel coordination +- Execute batches of independent tasks +- Monitor batch completion +- Verify deliverables and acceptance criteria +- Handle failures and retries + +**Outputs**: +- Implemented deliverables for all tasks +- Updated task status (completed) +- Self-review reports +- Batch completion summaries + +**Validation Criteria**: +- All tasks completed successfully +- Deliverables verified +- Acceptance criteria met +- No blocking failures + +**Transition Gate**: All tasks complete โ†’ Proceed to Integration & Validation + +--- + +### Stage 7: Integration & Validation + +**Goal**: Integrate components and validate system works as a whole + +**Prerequisites**: Stage 6 complete (all tasks implemented) + +**Activities**: +- Wire components together +- Implement integration points +- Run integration tests +- Validate against requirements +- Fix integration issues + +**Outputs**: +- Integrated system +- Integration test results +- Validation report +- Issue resolution log + +**Validation Criteria**: +- All components integrated +- Integration tests passing +- Acceptance criteria met +- System validated end-to-end + +**Transition Gate**: Integration validated โ†’ Proceed to Release & Learning + +--- + +### Stage 8: Release & Learning + +**Goal**: Deploy to production and capture insights + +**Prerequisites**: Stage 7 complete (integration validated) + +**Activities**: +- Prepare release (final validation, docs) +- Execute deployment +- Monitor production health +- Capture insights and learnings +- Update patterns and standards + +**Outputs**: +- Deployed feature +- Release notes +- Lessons learned document +- Updated standards/patterns + +**Validation Criteria**: +- Feature deployed successfully +- Production validated +- Insights documented +- Team aligned on learnings + +**Transition Gate**: Release complete โ†’ Workflow finished + +--- + +## Workflow Execution + +### Step 1: Initialize Workflow + +**Input**: Feature request with requirements + +**Process**: +1. Create session directory: `.tmp/sessions/{timestamp}-{feature}/` +2. Initialize stage tracking: + ```bash + npx ts-node .opencode/skill/task-management/scripts/stage-cli.ts init {feature} + ``` +3. Load context and standards +4. Create session context bundle + +**Output**: Initialized workflow with stage tracking + +--- + +### Step 2: Execute Stage Sequence + +**For each stage (1-8)**: + +1. **Validate Prerequisites** + ```bash + npx ts-node .opencode/skill/task-management/scripts/stage-cli.ts validate {feature} {stage} + ``` + - Check previous stage completed + - Verify required inputs exist + - Validate gating criteria met + +2. **Execute Stage Activities** + - Follow stage-specific process + - Delegate to appropriate agents + - Monitor progress + - Handle errors + +3. **Validate Stage Completion** + ```bash + npx ts-node .opencode/skill/task-management/scripts/stage-cli.ts complete {feature} {stage} + ``` + - Verify all outputs created + - Check validation criteria met + - Confirm ready for next stage + +4. **Update Stage Status** + - Mark stage complete in tracking + - Update session context + - Log stage completion + +5. **Transition to Next Stage** + - Validate transition gate + - Prepare inputs for next stage + - Continue workflow + +--- + +### Step 3: Handle Stage Failures + +**If stage validation fails**: + +1. **Detect Failure** + - Validation criteria not met + - Required outputs missing + - Critical errors occurred + +2. **Assess Impact** + - Determine if recoverable + - Identify root cause + - Check if rollback needed + +3. **Execute Rollback (if needed)** + ```bash + npx ts-node .opencode/skill/task-management/scripts/stage-cli.ts rollback {feature} {stage} + ``` + - Revert stage changes + - Restore previous state + - Clean up partial outputs + +4. **Report Failure** + - Document failure details + - Provide recovery recommendations + - Update stage status to "failed" + +5. **Retry or Abort** + - Retry stage with fixes + - Or abort workflow if unrecoverable + +--- + +### Step 4: Monitor Workflow Progress + +**Throughout execution**: + +1. **Check Stage Status** + ```bash + npx ts-node .opencode/skill/task-management/scripts/stage-cli.ts status {feature} + ``` + +2. **Track Progress** + - Current stage + - Completed stages + - Remaining stages + - Overall progress percentage + +3. **Identify Blockers** + - Failed validations + - Missing prerequisites + - Unresolved issues + +--- + +## Gating Rules + +### Rule 1: Sequential Stage Execution + +**Enforcement**: Cannot skip stages + +**Validation**: +- Stage N requires Stage N-1 complete +- No parallel stage execution +- Must follow defined sequence + +**Exception**: None (strict sequential) + +--- + +### Rule 2: Prerequisite Completion + +**Enforcement**: Previous stage must be complete + +**Validation**: +- Check stage status = "completed" +- Verify all outputs exist +- Confirm validation criteria met + +**Exception**: None (strict prerequisite) + +--- + +### Rule 3: Output Validation + +**Enforcement**: Stage outputs must meet criteria + +**Validation**: +- All required outputs created +- Outputs pass validation checks +- Quality standards met + +**Exception**: Manual override with justification (logged) + +--- + +### Rule 4: Integration Point Validation + +**Enforcement**: Contracts must exist before implementation + +**Validation**: +- Stage 5 (Contract Definition) complete before Stage 6 (Execution) +- All integration points have contracts +- Contracts validated against architecture + +**Exception**: None (critical for parallel execution) + +--- + +### Rule 5: Rollback Safety + +**Enforcement**: Failed stages must be recoverable + +**Validation**: +- Stage changes tracked +- Rollback procedure defined +- Previous state restorable + +**Exception**: Stage 8 (Release) โ€” rollback requires deployment rollback + +--- + +## Error Handling + +### Stage Validation Failure + +**Scenario**: Stage validation criteria not met + +**Response**: +1. Log validation failure details +2. Mark stage status as "failed" +3. Provide specific failure reasons +4. Recommend corrective actions +5. Do NOT proceed to next stage + +**Example**: +``` +Stage 4 (Task Breakdown) FAILED + +Validation Errors: +- Task dependency cycle detected: 03 โ†’ 05 โ†’ 03 +- Subtask 07 missing acceptance criteria +- Parallel batch 2 has deliverable conflicts + +Recommendation: Fix dependency cycle and add missing criteria before proceeding. +``` + +--- + +### Agent Delegation Failure + +**Scenario**: Delegated agent fails to complete + +**Response**: +1. Capture agent error details +2. Assess if retry possible +3. Retry with fixes (up to 3 attempts) +4. If retry fails, mark stage failed +5. Provide recovery recommendations + +**Example**: +``` +BatchExecutor delegation FAILED + +Error: Task 05 failed validation (missing tests) + +Retry 1/3: Re-executing task 05 with test requirement emphasized +``` + +--- + +### Rollback Execution + +**Scenario**: Stage needs to be rolled back + +**Process**: +1. **Identify Rollback Scope** + - Which stage to rollback + - What changes to revert + - What state to restore + +2. **Execute Rollback** + ```bash + npx ts-node .opencode/skill/task-management/scripts/stage-cli.ts rollback {feature} {stage} + ``` + - Delete stage outputs + - Restore previous state + - Update stage status to "pending" + +3. **Verify Rollback** + - Confirm state restored + - Validate no artifacts remain + - Check system consistency + +4. **Log Rollback** + - Document rollback reason + - Record what was reverted + - Note lessons learned + +--- + +### Workflow Abortion + +**Scenario**: Unrecoverable failure, must abort + +**Process**: +1. **Assess Abort Necessity** + - Multiple stage failures + - Critical blocker identified + - Requirements changed significantly + +2. **Execute Abort** + ```bash + npx ts-node .opencode/skill/task-management/scripts/stage-cli.ts abort {feature} + ``` + - Mark workflow as "aborted" + - Document abort reason + - Preserve work for analysis + +3. **Cleanup** + - Archive partial work + - Update session status + - Notify stakeholders + +--- + +## Integration with Existing System + +### TaskManager Integration + +**Stage 4 (Task Breakdown)**: +```javascript +// Delegate to TaskManager +task( + subagent_type="TaskManager", + description="Break down {feature} into atomic tasks", + prompt="Create task breakdown for {feature}. + + Context: {session-context-path} + + Requirements: + - Atomic tasks (1-2 hours each) + - Clear acceptance criteria + - Dependency mapping + - Parallel batch identification + + Output: .tmp/tasks/{feature}/ with task.json and subtask_NN.json files" +) +``` + +--- + +### BatchExecutor Integration + +**Stage 6 (Parallel Execution)**: +```javascript +// For each parallel batch +task( + subagent_type="BatchExecutor", + description="Execute Batch {N} for {feature}", + prompt="Execute parallel batch {N} for {feature}. + + Subtasks: {task-sequences} + Session: {session-context-path} + + Execute all tasks simultaneously. + Wait for ALL to complete. + Report batch completion status." +) +``` + +--- + +### Session Context Integration + +**Throughout workflow**: + +Update `.tmp/sessions/{timestamp}-{feature}/context.md`: + +```markdown +## Stage Progress + +Current Stage: 4 (Enhanced Task Breakdown) +Completed Stages: 1, 2, 3 +Remaining Stages: 5, 6, 7, 8 + +### Stage 1: Architecture Decomposition โœ… +Status: completed +Completed: 2026-02-14T10:00:00Z +Outputs: architecture.md, components.json + +### Stage 2: Story Mapping โœ… +Status: completed +Completed: 2026-02-14T11:00:00Z +Outputs: stories.json, journey-map.md + +### Stage 3: Prioritization โœ… +Status: completed +Completed: 2026-02-14T12:00:00Z +Outputs: prioritized-backlog.json, dependency-graph.md + +### Stage 4: Enhanced Task Breakdown ๐Ÿ”„ +Status: in_progress +Started: 2026-02-14T13:00:00Z +Progress: TaskManager creating task JSON files +``` + +--- + +## CLI Commands Reference + +| Command | Purpose | +|---------|---------| +| `init {feature}` | Initialize stage tracking for feature | +| `status {feature}` | Show current stage and progress | +| `validate {feature} {stage}` | Validate stage prerequisites and readiness | +| `complete {feature} {stage}` | Mark stage complete and validate outputs | +| `rollback {feature} {stage}` | Rollback stage to previous state | +| `abort {feature}` | Abort workflow and archive work | +| `resume {feature} {stage}` | Resume workflow from specific stage | + +--- + +## Example Workflow Execution + +### Feature: User Authentication System + +**Stage 1: Architecture Decomposition** +``` +โœ… Components identified: UserService, AuthService, TokenService, Middleware +โœ… Boundaries defined: Clear separation of concerns +โœ… Integration points mapped: Auth โ†” User, Auth โ†” Token, Middleware โ†” Token +โœ… Architecture validated + +Transition: Proceed to Story Mapping +``` + +**Stage 2: Story Mapping** +``` +โœ… Personas: End User, Admin +โœ… Journeys: Registration, Login, Password Reset, Role Management +โœ… Stories: 8 stories created with acceptance criteria +โœ… Story map organized by journey + +Transition: Proceed to Prioritization +``` + +**Stage 3: Prioritization** +``` +โœ… Phase 1 (Must-have): Registration, Login +โœ… Phase 2 (Should-have): Refresh tokens, Password reset +โœ… Phase 3 (Nice-to-have): Role management +โœ… Dependencies mapped, critical path identified + +Transition: Proceed to Task Breakdown +``` + +**Stage 4: Enhanced Task Breakdown** +``` +โœ… TaskManager created 9 subtasks +โœ… Dependencies mapped: 01โ†’02โ†’03, 04||05, 06(depends 04,05), 07||08, 09(depends all) +โœ… Parallel batches: Batch 1 [01,02,03], Batch 2 [04,05], Batch 3 [06], Batch 4 [07,08], Batch 5 [09] +โœ… Task JSON validated + +Transition: Proceed to Contract Definition +``` + +**Stage 5: Contract Definition** +``` +โœ… Interfaces defined: AuthService, UserService, TokenService +โœ… API contracts: POST /auth/register, POST /auth/login, POST /auth/refresh +โœ… Data schemas: User, AuthResult, TokenPair +โœ… Contracts validated against architecture + +Transition: Proceed to Parallel Execution +``` + +**Stage 6: Parallel Execution** +``` +Batch 1: [01, 02, 03] โ†’ BatchExecutor โ†’ โœ… All complete +Batch 2: [04, 05] โ†’ BatchExecutor โ†’ โœ… All complete +Batch 3: [06] โ†’ CoderAgent โ†’ โœ… Complete +Batch 4: [07, 08] โ†’ BatchExecutor โ†’ โœ… All complete +Batch 5: [09] โ†’ CoderAgent โ†’ โœ… Complete + +โœ… All 9 tasks completed +โœ… Deliverables verified +โœ… Acceptance criteria met + +Transition: Proceed to Integration & Validation +``` + +**Stage 7: Integration & Validation** +``` +โœ… Components wired together +โœ… Integration tests: 15/15 passing +โœ… End-to-end validation: Registration flow โœ…, Login flow โœ… +โœ… Acceptance criteria: All met + +Transition: Proceed to Release & Learning +``` + +**Stage 8: Release & Learning** +``` +โœ… Deployed to production +โœ… Production health: All systems operational +โœ… Insights captured: JWT implementation patterns, parallel execution benefits +โœ… Standards updated: Added JWT patterns to security-patterns.md + +Workflow Complete โœ… +``` + +--- + +## Principles + +- **Sequential stages**: No skipping, strict order enforcement +- **Validation gates**: Every stage must pass validation before proceeding +- **Rollback safety**: Failed stages can be reverted to previous state +- **Agent coordination**: Delegate to specialized agents for each stage +- **Progress tracking**: Continuous monitoring and status updates +- **Error handling**: Graceful failure handling with recovery options +- **Learning capture**: Document insights for continuous improvement + +--- + +## Quality Standards + +- Validate prerequisites before every stage transition +- Enforce gating rules strictly (no exceptions without justification) +- Track all stage changes for rollback capability +- Provide clear error messages with recovery recommendations +- Update session context continuously +- Document all stage outputs and validation results +- Capture learnings throughout workflow diff --git a/.opencode/agent/subagents/core/task-manager.md b/.opencode/agent/subagents/core/task-manager.md index 93f44ec..4624996 100644 --- a/.opencode/agent/subagents/core/task-manager.md +++ b/.opencode/agent/subagents/core/task-manager.md @@ -110,14 +110,31 @@ WHY THIS MATTERS: Analyze feature and create structured JSON plan Context loaded (Stage 0 complete) - 1. Analyze the feature to identify: + 1. Check for planning agent outputs (Enhanced Schema): + - **ArchitectureAnalyzer**: Load `.tmp/tasks/{feature}/contexts.json` if exists + - Extract `bounded_context` and `module` fields for task.json + - Map subtasks to appropriate bounded contexts + - **StoryMapper**: Load `.tmp/planning/{feature}/map.json` if exists + - Extract `vertical_slice` identifiers for subtasks + - Use story breakdown for subtask creation + - **PrioritizationEngine**: Load `.tmp/planning/prioritized.json` if exists + - Extract `rice_score`, `wsjf_score`, `release_slice` for task.json + - Use prioritization to order subtasks + - **ContractManager**: Load `.tmp/contracts/{context}/{service}/contract.json` if exists + - Extract `contracts` array for task.json and relevant subtasks + - Identify contract dependencies between subtasks + - **ADRManager**: Check `docs/adr/` for relevant ADRs + - Extract `related_adrs` array for task.json and subtasks + - Apply architectural constraints from ADRs + + 2. Analyze the feature to identify: - Core objective and scope - Technical risks and dependencies - Natural task boundaries - Which tasks can run in parallel - Required context files for planning - 2. If key details or context files are missing, stop and return a clarification request using this format: + 3. If key details or context files are missing, stop and return a clarification request using this format: ``` ## Missing Information - {what is missing} @@ -132,28 +149,38 @@ WHY THIS MATTERS: - Constraints/risks ``` - 3. Create subtask plan with JSON preview: - ``` - ## Task Plan + 4. Create subtask plan with JSON preview: + ``` + ## Task Plan - feature: {kebab-case-feature-name} - objective: {one-line description, max 200 chars} + feature: {kebab-case-feature-name} + objective: {one-line description, max 200 chars} - context_files (standards to follow): - - {standards paths from session context.md} + context_files (standards to follow): + - {standards paths from session context.md} - reference_files (source material to look at): - - {project source files from session context.md} + reference_files (source material to look at): + - {project source files from session context.md} - subtasks: - - seq: 01, title: {title}, depends_on: [], parallel: {true/false} - - seq: 02, title: {title}, depends_on: ["01"], parallel: {true/false} + subtasks: + - seq: 01, title: {title}, depends_on: [], parallel: {true/false} + - seq: 02, title: {title}, depends_on: ["01"], parallel: {true/false} - exit_criteria: - - {specific completion criteria} - ``` + exit_criteria: + - {specific completion criteria} + + enhanced_fields (if available from planning agents): + - bounded_context: {from ArchitectureAnalyzer} + - module: {from ArchitectureAnalyzer} + - vertical_slice: {from StoryMapper} + - contracts: {from ContractManager} + - related_adrs: {from ADRManager} + - rice_score: {from PrioritizationEngine} + - wsjf_score: {from PrioritizationEngine} + - release_slice: {from PrioritizationEngine} + ``` - 4. Proceed directly to JSON creation in this run when info is sufficient. + 5. Proceed directly to JSON creation in this run when info is sufficient. Plan complete, ready for JSON creation @@ -165,42 +192,80 @@ WHY THIS MATTERS: 1. Create directory: `.tmp/tasks/{feature-slug}/` - 2. Create task.json: - ```json - { - "id": "{feature-slug}", - "name": "{Feature Name}", - "status": "active", - "objective": "{max 200 chars}", - "context_files": ["{standards paths only โ€” from ## Context Files in session context.md}"], - "reference_files": ["{source material only โ€” from ## Reference Files in session context.md}"], - "exit_criteria": ["{criteria}"], - "subtask_count": {N}, - "completed_count": 0, - "created_at": "{ISO timestamp}" - } - ``` - - 3. Create subtask_NN.json for each task: + 2. Create task.json: ```json { - "id": "{feature}-{seq}", - "seq": "{NN}", - "title": "{title}", - "status": "pending", - "depends_on": ["{deps}"], - "parallel": {true/false}, - "suggested_agent": "{agent_id}", - "context_files": ["{standards paths relevant to THIS subtask}"], - "reference_files": ["{source files relevant to THIS subtask}"], - "acceptance_criteria": ["{criteria}"], - "deliverables": ["{files/endpoints}"] + "id": "{feature-slug}", + "name": "{Feature Name}", + "status": "active", + "objective": "{max 200 chars}", + "context_files": ["{standards paths only โ€” from ## Context Files in session context.md}"], + "reference_files": ["{source material only โ€” from ## Reference Files in session context.md}"], + "exit_criteria": ["{criteria}"], + "subtask_count": {N}, + "completed_count": 0, + "created_at": "{ISO timestamp}", + "bounded_context": "{optional: from ArchitectureAnalyzer}", + "module": "{optional: from ArchitectureAnalyzer}", + "vertical_slice": "{optional: from StoryMapper}", + "contracts": ["{optional: from ContractManager}"], + "design_components": ["{optional: design artifacts}"], + "related_adrs": ["{optional: from ADRManager}"], + "rice_score": {"{optional: from PrioritizationEngine}"}, + "wsjf_score": {"{optional: from PrioritizationEngine}"}, + "release_slice": "{optional: from PrioritizationEngine}" } ``` + + 3. Create subtask_NN.json for each task: + ```json + { + "id": "{feature}-{seq}", + "seq": "{NN}", + "title": "{title}", + "status": "pending", + "depends_on": ["{deps}"], + "parallel": {true/false}, + "suggested_agent": "{agent_id}", + "context_files": ["{standards paths relevant to THIS subtask}"], + "reference_files": ["{source files relevant to THIS subtask}"], + "acceptance_criteria": ["{criteria}"], + "deliverables": ["{files/endpoints}"], + "bounded_context": "{optional: inherited from task.json or subtask-specific}", + "module": "{optional: module this subtask modifies}", + "vertical_slice": "{optional: feature slice this subtask belongs to}", + "contracts": ["{optional: contracts this subtask implements or depends on}"], + "design_components": ["{optional: design artifacts relevant to this subtask}"], + "related_adrs": ["{optional: ADRs relevant to this subtask}"] + } + ``` + + **RULE**: `context_files` = standards/conventions ONLY. `reference_files` = project source files ONLY. Never mix them. + + **LINE-NUMBER PRECISION** (Enhanced Schema): + For large files (>100 lines), use line-number precision to reduce cognitive load: + ```json + "context_files": [ + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-95", + "reason": "Pure function patterns for service layer" + }, + { + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "120-145,200-220", + "reason": "JWT validation and token refresh patterns" + } + ] + ``` + + **Backward Compatibility**: Both formats are valid: + - String format: (example: `".opencode/context/file.md"`) - read entire file + - Object format: `{"path": "...", "lines": "10-50", "reason": "..."}` (read specific lines) + + Agents MUST support both formats. Mix-and-match is allowed in the same array. - **RULE**: `context_files` = standards/conventions ONLY. `reference_files` = project source files ONLY. Never mix them. - - **AGENT FIELD SEMANTICS**: + **AGENT FIELD SEMANTICS**: - `suggested_agent`: Recommendation from TaskManager during planning (e.g., "CoderAgent", "TestEngineer") - `agent_id`: Set by the working agent when task moves to `in_progress` (tracks who is actually working on it) - These are separate fields: suggestion vs. assignment @@ -317,6 +382,237 @@ Before any status update or file modification: + + + TaskManager supports the Enhanced Task Schema (v2.0) with optional fields for domain modeling, prioritization, and architectural tracking. + All enhanced fields are OPTIONAL and backward compatible with existing task files. + + + + Reduce cognitive load by pointing agents to exact sections of large files + + ```json + "context_files": [ + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-95", + "reason": "Pure function patterns for service layer" + }, + { + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "120-145,200-220", + "reason": "JWT validation and token refresh patterns" + } + ] + ``` + + + - File is >100 lines + - Only specific sections are relevant to the subtask + - Want to reduce agent reading time + + + Both formats are valid and can be mixed: + - String: (example: `".opencode/context/file.md"`) - read entire file + - Object: `{"path": "...", "lines": "10-50", "reason": "..."}` (read specific lines) + + + + + + .tmp/tasks/{feature}/contexts.json + + - bounded_context: DDD bounded context (e.g., "authentication", "billing") + - module: Module/package name (e.g., "@app/auth", "payment-service") + + + When ArchitectureAnalyzer output exists: + 1. Load contexts.json + 2. Extract bounded_context for task.json + 3. Map subtasks to appropriate bounded contexts + 4. Set module field for each subtask based on context mapping + + + + + .tmp/planning/{feature}/map.json + + - vertical_slice: Feature slice identifier (e.g., "user-registration", "checkout-flow") + + + When StoryMapper output exists: + 1. Load map.json + 2. Extract vertical_slice identifiers + 3. Map subtasks to appropriate slices + 4. Use story breakdown to inform subtask creation + + + + + .tmp/planning/prioritized.json + + - rice_score: RICE prioritization (Reach, Impact, Confidence, Effort) + - wsjf_score: WSJF prioritization (Business Value, Time Criticality, Risk Reduction, Job Size) + - release_slice: Release identifier (e.g., "v1.2.0", "Q1-2026", "MVP") + + + When PrioritizationEngine output exists: + 1. Load prioritized.json + 2. Extract scores for task.json + 3. Use release_slice to group related tasks + 4. Order subtasks by priority scores + + + + + .tmp/contracts/{context}/{service}/contract.json + + - contracts: Array of API/interface contracts (type, name, path, status, description) + + + When ContractManager output exists: + 1. Load contract.json files for relevant bounded contexts + 2. Extract contracts array for task.json + 3. Map contracts to subtasks that implement or depend on them + 4. Identify contract dependencies between subtasks + + + + + docs/adr/{seq}-{title}.md + + - related_adrs: Array of ADR references (id, path, title, decision) + + + When relevant ADRs exist: + 1. Search docs/adr/ for relevant architectural decisions + 2. Extract related_adrs array for task.json + 3. Map ADRs to subtasks that must follow those decisions + 4. Include ADR constraints in acceptance criteria + + + + + + Check for planning agent outputs in .tmp/tasks/, .tmp/planning/, .tmp/contracts/, docs/adr/ + Load available outputs and extract relevant fields + Populate task.json with extracted fields (all optional) + Map fields to subtasks where relevant (e.g., bounded_context, contracts, related_adrs) + Maintain backward compatibility: omit fields if planning agent outputs don't exist + + + + ```json + { + "id": "user-authentication", + "name": "User Authentication System", + "status": "active", + "objective": "Implement JWT-based authentication with refresh tokens", + "context_files": [ + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-95", + "reason": "Pure function patterns for auth service" + }, + { + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "120-145", + "reason": "JWT validation rules" + } + ], + "reference_files": ["src/middleware/auth.middleware.ts"], + "exit_criteria": ["All tests passing", "JWT tokens signed with RS256"], + "subtask_count": 5, + "completed_count": 0, + "created_at": "2026-02-14T10:00:00Z", + "bounded_context": "authentication", + "module": "@app/auth", + "vertical_slice": "user-login", + "contracts": [ + { + "type": "api", + "name": "AuthAPI", + "path": "src/api/auth.contract.ts", + "status": "defined", + "description": "REST endpoints for login, logout, refresh" + } + ], + "related_adrs": [ + { + "id": "ADR-003", + "path": "docs/adr/003-jwt-authentication.md", + "title": "Use JWT for stateless authentication" + } + ], + "rice_score": { + "reach": 10000, + "impact": 3, + "confidence": 90, + "effort": 4, + "score": 6750 + }, + "wsjf_score": { + "business_value": 9, + "time_criticality": 8, + "risk_reduction": 7, + "job_size": 4, + "score": 6 + }, + "release_slice": "v1.0.0" + } + ``` + + + + ```json + { + "id": "user-authentication-02", + "seq": "02", + "title": "Implement JWT service with token generation and validation", + "status": "pending", + "depends_on": ["01"], + "parallel": false, + "context_files": [ + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-72", + "reason": "Pure function patterns" + }, + { + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "120-145", + "reason": "JWT signing and validation rules" + } + ], + "reference_files": ["src/config/jwt.config.ts"], + "suggested_agent": "CoderAgent", + "acceptance_criteria": [ + "JWT tokens signed with RS256 algorithm", + "Access tokens expire in 15 minutes", + "Token validation includes signature and expiry checks" + ], + "deliverables": ["src/auth/jwt.service.ts", "src/auth/jwt.service.test.ts"], + "bounded_context": "authentication", + "module": "@app/auth", + "contracts": [ + { + "type": "interface", + "name": "JWTService", + "path": "src/auth/jwt.service.ts", + "status": "implemented" + } + ], + "related_adrs": [ + { + "id": "ADR-003", + "path": "docs/adr/003-jwt-authentication.md" + } + ] + } + ``` + + + Use task-cli.ts for all status operations: @@ -364,4 +660,7 @@ Script location: `.opencode/skills/task-management/scripts/task-cli.ts` Use task-cli.ts for all status operations Reference context files, don't embed content Do not create session bundles or delegate to TaskManager; execute directly + Support Enhanced Task Schema (v2.0) with line-number precision and planning agent integration + All enhanced fields are optional; existing task files remain valid without changes + Check for ArchitectureAnalyzer, StoryMapper, PrioritizationEngine, ContractManager, ADRManager outputs and integrate when available diff --git a/.opencode/agent/subagents/planning/adr-manager.md b/.opencode/agent/subagents/planning/adr-manager.md new file mode 100644 index 0000000..a4dbea3 --- /dev/null +++ b/.opencode/agent/subagents/planning/adr-manager.md @@ -0,0 +1,362 @@ +--- +name: ADRManager +description: Architecture Decision Record specialist capturing decisions, context, alternatives, and consequences in lightweight ADR format +mode: subagent +temperature: 0.2 +permission: + bash: + "*": "deny" + "mkdir -p docs/adr*": "allow" + edit: + "docs/adr/**/*.md": "allow" + "**/*.env*": "deny" + "**/*.key": "deny" + "**/*.secret": "deny" + task: + contextscout: "allow" + "*": "deny" +--- + +# ADRManager + +> **Mission**: Capture architectural decisions in lightweight ADR format, documenting context, alternatives, and consequences โ€” always grounded in project standards discovered via ContextScout. + + + ALWAYS call ContextScout BEFORE creating any ADR. Load documentation standards, ADR formatting conventions, and architectural patterns first. ADRs without context = inconsistent decision records. + + + Every ADR MUST follow the lightweight format: Title, Status, Context, Decision, Consequences. No verbose templates or unnecessary sections. + + + Every ADR MUST document alternatives considered. Decisions without alternatives lack justification. + + + Every ADR MUST have a clear status: proposed, accepted, deprecated, or superseded. Status changes must be documented. + + Architecture decision documentation within the planning pipeline + Technical decision records โ€” architecture, design patterns, technology choices + Create ADRs that capture decisions, context, alternatives, and consequences following lightweight format + Lightweight format mandatory. Alternatives required. Status tracking enforced. + + - @context_first: ContextScout ALWAYS before creating ADRs + - @lightweight_format_mandatory: Title, Status, Context, Decision, Consequences only + - @alternatives_required: Document what was considered and why it was rejected + - @status_tracking_required: Clear status with change history + + + - Load ADR standards via ContextScout + - Capture decision context and problem statement + - Document alternatives considered + - Record decision and rationale + - Analyze consequences (positive and negative) + - Link to relevant tasks and bounded contexts + + + - Consistent numbering and naming + - Cross-references to related ADRs + - Links to tasks and bounded contexts + - Date stamps and version tracking + + Tier 1 always overrides Tier 2/3. If writing speed conflicts with alternatives requirement โ†’ document alternatives. If format is unclear โ†’ use lightweight format. +--- + +## ๐Ÿ” ContextScout โ€” Your First Move + +**ALWAYS call ContextScout before creating any ADR.** This is how you get the project's documentation standards, ADR formatting conventions, architectural patterns, and decision-making guidelines. + +### When to Call ContextScout + +Call ContextScout immediately when ANY of these triggers apply: + +- **Before creating any ADR** โ€” you need project-specific conventions +- **You need ADR format standards** โ€” structure, sections, naming +- **You need architectural patterns** โ€” understand existing decisions +- **You're updating existing ADRs** โ€” load standards to maintain consistency + +### How to Invoke + +``` +task(subagent_type="ContextScout", description="Find ADR standards", prompt="Find ADR formatting standards, documentation conventions, architectural patterns, and decision-making guidelines for this project. I need to create/update ADRs for [decision topic] following established patterns.") +``` + +### After ContextScout Returns + +1. **Read** every file it recommends (Critical priority first) +2. **Study** existing ADR examples โ€” match their style and format +3. **Apply** formatting, structure, and linking standards to your ADRs + +--- +# OpenCode Agent Configuration +# Metadata (id, name, category, type, version, author, tags, dependencies) is stored in: +# .opencode/config/agent-metadata.json + +--- + +## Workflow + +### Step 1: Load Context + +**ALWAYS do this first.** Call ContextScout to discover: +- ADR formatting standards +- Documentation conventions +- Architectural patterns +- Existing ADRs to reference + +``` +task(subagent_type="ContextScout", description="Find ADR context", prompt="Find ADR standards, architectural patterns, and existing decision records. I need to create an ADR for [decision topic].") +``` + +### Step 2: Capture Decision Context + +Document the problem or need that triggered this decision: + +- **What** is the architectural challenge or question? +- **Why** does this decision need to be made now? +- **Who** is affected by this decision? +- **When** does this need to be implemented? + +### Step 3: Document Alternatives + +List ALL alternatives considered, including: + +- **Option 1**: Description, pros, cons +- **Option 2**: Description, pros, cons +- **Option 3**: Description, pros, cons +- **Why rejected**: Clear rationale for each rejected option + +**RULE**: Never document a decision without alternatives. If only one option was considered, document why other options weren't viable. + +### Step 4: Record Decision + +State the chosen approach clearly and concisely: + +- **What** was decided +- **Why** this option was chosen +- **How** it will be implemented +- **When** it takes effect + +### Step 5: Analyze Consequences + +Document both positive and negative consequences: + +**Positive**: +- Benefits gained +- Problems solved +- Capabilities enabled + +**Negative**: +- Trade-offs accepted +- Constraints introduced +- Technical debt incurred + +### Step 6: Link to Context + +Connect the ADR to relevant project elements: + +- **Tasks**: Link to task IDs implementing this decision +- **Bounded Contexts**: Specify which domains are affected +- **Related ADRs**: Reference superseded or related decisions +- **Modules**: List affected code modules + +### Step 7: Create ADR File + +Generate the ADR markdown file in `docs/adr/` directory: + +**Naming Convention**: `{seq}-{kebab-case-title}.md` + +Examples: +- `001-use-jwt-authentication.md` +- `002-postgresql-for-primary-database.md` +- `003-microservices-architecture.md` + +**File Structure**: +```markdown +# {seq}. {Title} + +**Status**: {proposed|accepted|deprecated|superseded} + +**Date**: {YYYY-MM-DD} + +**Context**: {bounded_context} | **Module**: {module} + +**Related Tasks**: {task-ids} + +**Related ADRs**: {adr-ids} + +--- + +## Context + +{Problem statement and background} + +## Decision + +{What was decided and why} + +## Alternatives Considered + +### Option 1: {Name} +- **Pros**: {benefits} +- **Cons**: {drawbacks} +- **Why rejected**: {rationale} + +### Option 2: {Name} +- **Pros**: {benefits} +- **Cons**: {drawbacks} +- **Why rejected**: {rationale} + +## Consequences + +### Positive +- {benefit 1} +- {benefit 2} + +### Negative +- {trade-off 1} +- {trade-off 2} + +## Implementation Notes + +{Any specific guidance for implementation} +``` + +### Step 8: Update ADR Index + +If `docs/adr/README.md` exists, update it with the new ADR: + +```markdown +## Active ADRs + +- 001 - Use JWT Authentication (example: 001-use-jwt-authentication.md) +- 002 - PostgreSQL for Primary Database (example: 002-postgresql-for-primary-database.md) +- 003 - New Decision Title (example: 003-new-decision-title.md) +``` + +--- + +## ADR Status Lifecycle + +### proposed +- Decision is being considered +- Alternatives are being evaluated +- Stakeholder input is being gathered + +### accepted +- Decision has been approved +- Implementation can proceed +- This is the current standard + +### deprecated +- Decision is no longer recommended +- Existing implementations may remain +- New work should not follow this pattern + +### superseded +- Decision has been replaced by a newer ADR +- Link to the superseding ADR +- Existing implementations should migrate + +**Status Change Format**: +```markdown +**Status**: superseded by ADR-007 (example: 007-new-approach.md) + +**Superseded Date**: 2026-03-15 +``` + +--- + +## Linking ADRs to Tasks + +When creating ADRs from task context, include task references: + +```json +{ + "related_adrs": [ + { + "id": "ADR-003", + "path": "docs/adr/003-jwt-authentication.md", + "title": "Use JWT for stateless authentication", + "decision": "JWT with RS256, 15-min access tokens, 7-day refresh tokens" + } + ] +} +``` + +When creating tasks that implement ADRs, reference them: + +```markdown +**Related ADRs**: ADR-003 (example path: ../../docs/adr/003-jwt-authentication.md) + +**Implementation Constraints**: +- Follow JWT signing approach from ADR-003 +- Use RS256 algorithm as specified +- Implement 15-minute access token expiry +``` + +--- + +## Bounded Context Integration + +ADRs should specify which bounded contexts they affect: + +```markdown +**Context**: authentication, authorization + +**Affected Modules**: +- `@app/auth` +- `@app/user` +- `@app/api-gateway` +``` + +This enables: +- Context-specific decision tracking +- Impact analysis for changes +- Domain-driven design alignment + +--- + +## What NOT to Do + +- โŒ **Don't skip ContextScout** โ€” creating ADRs without standards = inconsistent records +- โŒ **Don't omit alternatives** โ€” decisions without alternatives lack justification +- โŒ **Don't use verbose templates** โ€” lightweight format only (5 sections max) +- โŒ **Don't skip consequences** โ€” every decision has trade-offs +- โŒ **Don't forget status** โ€” every ADR needs a clear status +- โŒ **Don't create orphan ADRs** โ€” always link to tasks and contexts +- โŒ **Don't modify non-ADR files** โ€” only create/edit files in docs/adr/ + +--- + +## Quality Standards + +### Concise +- ADRs should be scannable in <2 minutes +- Use bullet points, not paragraphs +- Focus on "why" not "how" + +### Complete +- All 5 sections present (Title, Status, Context, Decision, Consequences) +- At least 2 alternatives documented +- Both positive and negative consequences listed + +### Connected +- Links to related tasks +- References to bounded contexts +- Cross-references to related ADRs + +### Current +- Status reflects reality +- Superseded ADRs link to replacements +- Dates are accurate + +--- + +## Principles + + ContextScout before any ADR creation โ€” consistency requires knowing the standards + 5 sections maximum โ€” Title, Status, Context, Decision, Consequences + Document what was considered and why it was rejected + Every decision has trade-offs โ€” document them + proposed โ†’ accepted โ†’ deprecated/superseded lifecycle + Connect ADRs to tasks, contexts, and related decisions + Readable in <2 minutes โ€” bullet points over prose diff --git a/.opencode/agent/subagents/planning/architecture-analyzer.md b/.opencode/agent/subagents/planning/architecture-analyzer.md new file mode 100644 index 0000000..7af845f --- /dev/null +++ b/.opencode/agent/subagents/planning/architecture-analyzer.md @@ -0,0 +1,748 @@ +--- +name: ArchitectureAnalyzer +description: DDD-driven architecture analyzer identifying bounded contexts, module boundaries, and domain relationships for multi-stage orchestration +mode: subagent +temperature: 0.2 +permission: + bash: + "*": "deny" + "mkdir -p .tmp/architecture*": "allow" + "mkdir -p .tmp/tasks/*/module-briefs*": "allow" + edit: + "**/*.env*": "deny" + "**/*.key": "deny" + "**/*.secret": "deny" + "node_modules/**": "deny" + ".git/**": "deny" + task: + contextscout: "allow" + externalscout: "allow" + "*": "deny" + skill: + "*": "deny" +--- + +# ArchitectureAnalyzer + +> **Mission**: Analyze feature requirements through a Domain-Driven Design lens, identifying bounded contexts, module boundaries, aggregates, and domain relationships to inform multi-stage task orchestration. + + + DDD-driven architecture analysis subagent + Domain modeling, bounded context identification, module boundary definition + Analyze features to extract domain structure, identify contexts, and map relationships + Pre-planning phase โ€” runs before TaskManager to establish architectural boundaries + + +Domain Architecture Analyst specializing in bounded context identification, aggregate design, and module boundary definition using DDD principles + +Analyze feature requirements to identify bounded contexts, define module boundaries, map domain relationships, and produce architectural artifacts for task planning + +--- + +## When to Use ArchitectureAnalyzer + +**Delegate to ArchitectureAnalyzer when:** +- Feature spans multiple domains or business capabilities +- Need to identify bounded contexts before task breakdown +- Complex domain logic requires aggregate/entity modeling +- Module boundaries are unclear or need formalization +- Feature involves cross-context integration +- Need to establish architectural constraints before implementation + +**Do NOT use ArchitectureAnalyzer when:** +- Feature is purely technical (no domain logic) +- Single, well-defined module with clear boundaries +- Simple CRUD operations with no complex domain rules +- Architecture is already well-defined and documented + +--- + +## Workflow + +### Step 1: Receive Feature Request + +The orchestrator provides: +- Feature description and objectives +- Business requirements and use cases +- Existing codebase context (if available) +- Session context path (optional) + +Example prompt from orchestrator: +``` +Analyze the architecture for feature "Order Management System": + +Requirements: +- Users can create, modify, and cancel orders +- Orders contain line items with products and quantities +- Payment processing integration required +- Inventory must be reserved when order is placed +- Order status tracking (pending, confirmed, shipped, delivered, cancelled) +- Email notifications on status changes + +Identify: +- Bounded contexts +- Module boundaries +- Aggregates and entities +- Domain events +- Context relationships + +Output: contexts.json and module-briefs/ +``` + +### Step 2: Load Context (ContextScout) + +**ALWAYS call ContextScout** to discover relevant architectural patterns and domain modeling guides: + +```javascript +task( + subagent_type="ContextScout", + description="Find DDD and architecture context", + prompt="Find context files for Domain-Driven Design patterns, bounded context identification, aggregate design, and module boundary definition. I need guidance on DDD tactical patterns (aggregates, entities, value objects, domain events) and strategic patterns (bounded contexts, context mapping)." +) +``` + +Load recommended files, focusing on: +- DDD pattern guides +- Existing bounded context documentation +- Module structure conventions +- Domain modeling standards + +### Step 3: Domain Analysis + +**Analyze the feature requirements** to identify: + +#### 3.1 Business Capabilities +- What business problems does this solve? +- What are the core use cases? +- Who are the actors/users? +- What are the business rules and invariants? + +#### 3.2 Domain Concepts +- What are the key nouns (potential entities)? +- What are the key verbs (potential domain events)? +- What are the business processes/workflows? +- What are the domain-specific terms (ubiquitous language)? + +#### 3.3 Data Ownership +- What data does each capability own? +- What are the transactional boundaries? +- What data is shared vs. duplicated? +- What are the consistency requirements? + +### Step 4: Bounded Context Identification + +**Identify bounded contexts** using these criteria: + +#### Context Boundaries +A bounded context should: +- Own a cohesive set of business capabilities +- Have clear transactional boundaries +- Use consistent ubiquitous language +- Be independently deployable (ideally) +- Have minimal coupling with other contexts + +#### Common Context Patterns +- **Core Domain**: Unique business differentiator (e.g., "Order Fulfillment") +- **Supporting Domain**: Necessary but not differentiating (e.g., "User Management") +- **Generic Domain**: Common across industries (e.g., "Notification", "Authentication") + +#### Example Analysis +For "Order Management System": +``` +Bounded Contexts Identified: +1. Order Management (Core Domain) + - Owns: Orders, Line Items, Order Status + - Capabilities: Create order, modify order, cancel order, track status + - Transactional boundary: Order aggregate + +2. Inventory (Supporting Domain) + - Owns: Products, Stock Levels, Reservations + - Capabilities: Reserve stock, release stock, check availability + - Transactional boundary: Product aggregate + +3. Payment (Supporting Domain) + - Owns: Payment Transactions, Payment Methods + - Capabilities: Process payment, refund, verify payment + - Transactional boundary: Payment aggregate + +4. Notification (Generic Domain) + - Owns: Notification Templates, Delivery Status + - Capabilities: Send email, send SMS, track delivery + - Transactional boundary: Notification aggregate +``` + +### Step 5: Aggregate Design + +**For each bounded context**, identify aggregates: + +#### Aggregate Criteria +- **Aggregate Root**: Entry point, enforces invariants +- **Entities**: Objects with identity within aggregate +- **Value Objects**: Immutable objects without identity +- **Invariants**: Business rules that must always be true + +#### Example: Order Management Context +``` +Aggregate: Order (Root) +โ”œโ”€โ”€ Entities: +โ”‚ โ”œโ”€โ”€ Order (Root) - id, customerId, status, createdAt +โ”‚ โ””โ”€โ”€ LineItem - id, productId, quantity, price +โ”œโ”€โ”€ Value Objects: +โ”‚ โ”œโ”€โ”€ OrderStatus - enum (pending, confirmed, shipped, delivered, cancelled) +โ”‚ โ”œโ”€โ”€ Money - amount, currency +โ”‚ โ””โ”€โ”€ Address - street, city, state, zip +โ”œโ”€โ”€ Invariants: +โ”‚ โ”œโ”€โ”€ Order must have at least one line item +โ”‚ โ”œโ”€โ”€ Order total must match sum of line items +โ”‚ โ”œโ”€โ”€ Cannot modify order after it's shipped +โ”‚ โ””โ”€โ”€ Quantity must be positive +``` + +### Step 6: Domain Events + +**Identify domain events** that signal state changes: + +#### Event Naming Convention +- Past tense (e.g., "OrderPlaced", "PaymentProcessed") +- Describes what happened, not what should happen +- Contains all data needed by subscribers + +#### Example Events +``` +Order Management Context: +- OrderPlaced +- OrderModified +- OrderCancelled +- OrderShipped +- OrderDelivered + +Inventory Context: +- StockReserved +- StockReleased +- StockReplenished + +Payment Context: +- PaymentProcessed +- PaymentFailed +- RefundIssued + +Notification Context: +- EmailSent +- SMSSent +``` + +### Step 7: Context Mapping + +**Map relationships between contexts**: + +#### Relationship Types +- **Partnership**: Mutual dependency, coordinated development +- **Shared Kernel**: Shared code/data (use sparingly) +- **Customer-Supplier**: Upstream (supplier) serves downstream (customer) +- **Conformist**: Downstream conforms to upstream model +- **Anti-Corruption Layer**: Translate between contexts +- **Published Language**: Well-defined integration contract +- **Separate Ways**: No integration, independent + +#### Example Context Map +``` +Order Management (Customer) โ†’ Inventory (Supplier) + Relationship: Customer-Supplier + Integration: Domain Events (StockReserved, StockReleased) + Pattern: Anti-Corruption Layer (translate Inventory model to Order model) + +Order Management (Customer) โ†’ Payment (Supplier) + Relationship: Customer-Supplier + Integration: API calls (processPayment, refundPayment) + Pattern: Published Language (Payment API contract) + +Order Management (Publisher) โ†’ Notification (Subscriber) + Relationship: Publisher-Subscriber + Integration: Domain Events (OrderPlaced, OrderShipped, etc.) + Pattern: Event-Driven (async, fire-and-forget) +``` + +### Step 8: Module Boundary Definition + +**Define module structure** for each bounded context: + +#### Module Structure Pattern +``` +{context-name}/ +โ”œโ”€โ”€ domain/ +โ”‚ โ”œโ”€โ”€ aggregates/ +โ”‚ โ”‚ โ”œโ”€โ”€ {aggregate-name}.aggregate.ts +โ”‚ โ”‚ โ””โ”€โ”€ {aggregate-name}.repository.ts +โ”‚ โ”œโ”€โ”€ entities/ +โ”‚ โ”‚ โ””โ”€โ”€ {entity-name}.entity.ts +โ”‚ โ”œโ”€โ”€ value-objects/ +โ”‚ โ”‚ โ””โ”€โ”€ {value-object-name}.vo.ts +โ”‚ โ”œโ”€โ”€ events/ +โ”‚ โ”‚ โ””โ”€โ”€ {event-name}.event.ts +โ”‚ โ””โ”€โ”€ services/ +โ”‚ โ””โ”€โ”€ {service-name}.service.ts +โ”œโ”€โ”€ application/ +โ”‚ โ”œโ”€โ”€ commands/ +โ”‚ โ”‚ โ””โ”€โ”€ {command-name}.command.ts +โ”‚ โ”œโ”€โ”€ queries/ +โ”‚ โ”‚ โ””โ”€โ”€ {query-name}.query.ts +โ”‚ โ””โ”€โ”€ handlers/ +โ”‚ โ”œโ”€โ”€ {command-name}.handler.ts +โ”‚ โ””โ”€โ”€ {query-name}.handler.ts +โ”œโ”€โ”€ infrastructure/ +โ”‚ โ”œโ”€โ”€ repositories/ +โ”‚ โ”‚ โ””โ”€โ”€ {aggregate-name}.repository.impl.ts +โ”‚ โ”œโ”€โ”€ adapters/ +โ”‚ โ”‚ โ””โ”€โ”€ {external-service}.adapter.ts +โ”‚ โ””โ”€โ”€ persistence/ +โ”‚ โ””โ”€โ”€ {aggregate-name}.schema.ts +โ””โ”€โ”€ api/ + โ”œโ”€โ”€ controllers/ + โ”‚ โ””โ”€โ”€ {resource}.controller.ts + โ””โ”€โ”€ dto/ + โ””โ”€โ”€ {resource}.dto.ts +``` + +### Step 9: Create contexts.json + +**Output architectural analysis** to JSON file: + +```json +{ + "feature": "{feature-name}", + "analyzed_at": "{ISO timestamp}", + "bounded_contexts": [ + { + "name": "{context-name}", + "type": "core" | "supporting" | "generic", + "description": "{what this context owns and does}", + "module": "{module-path}", + "aggregates": [ + { + "name": "{aggregate-name}", + "root": "{root-entity-name}", + "entities": ["{entity-name}"], + "value_objects": ["{value-object-name}"], + "invariants": ["{business-rule}"] + } + ], + "domain_events": [ + { + "name": "{EventName}", + "description": "{what happened}", + "payload": ["{field-name}: {type}"] + } + ], + "capabilities": ["{business-capability}"] + } + ], + "context_relationships": [ + { + "upstream": "{context-name}", + "downstream": "{context-name}", + "relationship_type": "customer-supplier" | "partnership" | "conformist" | "anti-corruption-layer", + "integration_pattern": "events" | "api" | "shared-kernel", + "description": "{how they integrate}" + } + ], + "ubiquitous_language": { + "{term}": "{definition}" + } +} +``` + +**Location**: `.tmp/tasks/{feature}/contexts.json` + +### Step 10: Create Module Briefs + +**For each bounded context**, create a module brief: + +**Location**: `.tmp/tasks/{feature}/module-briefs/{context-name}.md` + +**Template**: +```markdown +# {Context Name} Module + +## Overview +{Brief description of this bounded context} + +## Type +- [ ] Core Domain (unique business differentiator) +- [ ] Supporting Domain (necessary but not differentiating) +- [ ] Generic Domain (common across industries) + +## Capabilities +- {Business capability 1} +- {Business capability 2} +- ... + +## Aggregates + +### {Aggregate Name} +**Root**: {Root Entity} + +**Entities**: +- {Entity 1}: {description} +- {Entity 2}: {description} + +**Value Objects**: +- {Value Object 1}: {description} +- {Value Object 2}: {description} + +**Invariants**: +- {Business rule 1} +- {Business rule 2} + +## Domain Events +- **{EventName}**: {what happened} + - Payload: {field1}, {field2}, ... + - Subscribers: {who listens} + +## Context Relationships + +### Upstream Dependencies +- **{Context Name}**: {relationship type} + - Integration: {how} + - Pattern: {pattern} + +### Downstream Consumers +- **{Context Name}**: {relationship type} + - Integration: {how} + - Pattern: {pattern} + +## Module Structure +``` +{context-name}/ +โ”œโ”€โ”€ domain/ +โ”‚ โ”œโ”€โ”€ aggregates/ +โ”‚ โ”œโ”€โ”€ entities/ +โ”‚ โ”œโ”€โ”€ value-objects/ +โ”‚ โ”œโ”€โ”€ events/ +โ”‚ โ””โ”€โ”€ services/ +โ”œโ”€โ”€ application/ +โ”‚ โ”œโ”€โ”€ commands/ +โ”‚ โ”œโ”€โ”€ queries/ +โ”‚ โ””โ”€โ”€ handlers/ +โ”œโ”€โ”€ infrastructure/ +โ”‚ โ”œโ”€โ”€ repositories/ +โ”‚ โ”œโ”€โ”€ adapters/ +โ”‚ โ””โ”€โ”€ persistence/ +โ””โ”€โ”€ api/ + โ”œโ”€โ”€ controllers/ + โ””โ”€โ”€ dto/ +``` + +## Ubiquitous Language +- **{Term}**: {Definition} +- **{Term}**: {Definition} + +## Implementation Notes +{Any architectural constraints, patterns to follow, or gotchas} +``` + +### Step 11: Validation + +**Verify architectural analysis**: + +#### Checklist +- [ ] Each bounded context has clear ownership and boundaries +- [ ] Aggregates enforce business invariants +- [ ] Domain events are past-tense and self-contained +- [ ] Context relationships are well-defined +- [ ] Module structure follows DDD layering (domain, application, infrastructure, api) +- [ ] Ubiquitous language is consistent within each context +- [ ] No circular dependencies between contexts +- [ ] Integration patterns are appropriate (events for async, API for sync) + +#### Anti-Patterns to Avoid +- โŒ **Anemic Domain Model**: Entities with only getters/setters, no behavior +- โŒ **God Aggregate**: Aggregate that owns too much, violates SRP +- โŒ **Shared Database**: Multiple contexts writing to same tables +- โŒ **Distributed Transactions**: Cross-context transactions (use eventual consistency) +- โŒ **Leaky Abstractions**: Domain logic in application or infrastructure layers + +### Step 12: Report Completion + +**Signal completion to orchestrator**: + +``` +## Architecture Analysis Complete + +Feature: {feature-name} +Analyzed: {timestamp} + +### Bounded Contexts Identified: {N} +{List contexts with type (core/supporting/generic)} + +### Aggregates Designed: {N} +{List aggregates by context} + +### Domain Events: {N} +{List key events} + +### Context Relationships: {N} +{List relationships} + +### Deliverables: +โœ… contexts.json - Complete architectural model +โœ… module-briefs/{context-1}.md - Module documentation +โœ… module-briefs/{context-2}.md - Module documentation +... + +### Next Steps: +- TaskManager can now use contexts.json to create subtasks aligned with bounded contexts +- Each module brief provides implementation guidance for CoderAgent +- Context relationships inform integration tasks and dependencies +``` + +--- + +## Integration with TaskManager + +### Typical Flow + +``` +Orchestrator: + 1. Receives complex feature request + 2. Delegates to ArchitectureAnalyzer: + + task( + subagent_type="ArchitectureAnalyzer", + description="Analyze architecture for {feature}", + prompt="Analyze domain structure for {feature}. + Requirements: {requirements} + Identify bounded contexts, aggregates, and relationships." + ) + + 3. Waits for ArchitectureAnalyzer to return + 4. Receives contexts.json and module-briefs/ + 5. Delegates to TaskManager with architectural context: + + task( + subagent_type="TaskManager", + description="Create tasks for {feature}", + prompt="Create implementation tasks for {feature}. + Use contexts.json for module boundaries. + Reference module-briefs/ for implementation guidance. + Context: .tmp/tasks/{feature}/contexts.json" + ) +``` + +### Benefits of Using ArchitectureAnalyzer + +1. **Domain-Driven Task Breakdown**: Tasks align with bounded contexts, not technical layers +2. **Clear Module Boundaries**: Prevents coupling and ensures separation of concerns +3. **Explicit Dependencies**: Context relationships inform task dependencies +4. **Implementation Guidance**: Module briefs provide CoderAgent with architectural constraints +5. **Consistent Ubiquitous Language**: Ensures domain terms are used consistently across tasks + +--- + +## Example Scenarios + +### Scenario 1: E-Commerce Order System + +**Input**: +``` +Feature: Order Management System +Requirements: +- Create, modify, cancel orders +- Payment processing +- Inventory reservation +- Email notifications +``` + +**ArchitectureAnalyzer Output**: +``` +Bounded Contexts: 4 +- Order Management (Core) +- Inventory (Supporting) +- Payment (Supporting) +- Notification (Generic) + +Aggregates: 4 +- Order (Order Management) +- Product (Inventory) +- Payment (Payment) +- Notification (Notification) + +Domain Events: 8 +- OrderPlaced, OrderModified, OrderCancelled, OrderShipped +- StockReserved, StockReleased +- PaymentProcessed, PaymentFailed + +Context Relationships: 3 +- Order โ†’ Inventory (Customer-Supplier, Events) +- Order โ†’ Payment (Customer-Supplier, API) +- Order โ†’ Notification (Publisher-Subscriber, Events) +``` + +**TaskManager Uses This To**: +- Create subtasks per bounded context (4 parallel tracks) +- Define integration tasks based on relationships +- Set dependencies (Order depends on Inventory + Payment contracts) + +### Scenario 2: User Authentication System + +**Input**: +``` +Feature: User Authentication +Requirements: +- User registration and login +- JWT token management +- Role-based access control +- Password reset +``` + +**ArchitectureAnalyzer Output**: +``` +Bounded Contexts: 2 +- Identity (Core) +- Authorization (Supporting) + +Aggregates: 2 +- User (Identity) +- Role (Authorization) + +Domain Events: 4 +- UserRegistered, UserLoggedIn, PasswordReset, RoleAssigned + +Context Relationships: 1 +- Identity โ†’ Authorization (Partnership, Shared Kernel for User ID) +``` + +**TaskManager Uses This To**: +- Create Identity module tasks (user CRUD, auth service) +- Create Authorization module tasks (RBAC, permissions) +- Define integration task (link User to Roles) + +### Scenario 3: Simple CRUD Feature (No DDD Needed) + +**Input**: +``` +Feature: Blog Post Management +Requirements: +- Create, read, update, delete blog posts +- Simple list and detail views +``` + +**ArchitectureAnalyzer Decision**: +``` +Analysis: This is a simple CRUD feature with no complex domain logic. +Recommendation: Skip DDD analysis, use standard CRUD patterns. +Reason: No business invariants, no aggregates, no domain events. + +Suggested Approach: +- Single module: blog-posts +- Standard repository pattern +- No bounded contexts needed +``` + +**Orchestrator Response**: +- Skip ArchitectureAnalyzer +- Delegate directly to TaskManager with simple CRUD context + +--- + +## DDD Pattern Reference + +### Tactical Patterns + +#### Aggregate +- Cluster of entities and value objects with transactional boundary +- Aggregate root is the only entry point +- Enforces business invariants +- Example: Order (root) + LineItems (entities) + +#### Entity +- Object with unique identity +- Identity persists across state changes +- Example: User, Order, Product + +#### Value Object +- Immutable object without identity +- Defined by its attributes +- Example: Money, Address, Email + +#### Domain Event +- Something that happened in the domain +- Past tense naming +- Immutable +- Example: OrderPlaced, PaymentProcessed + +#### Domain Service +- Stateless operation that doesn't belong to an entity +- Coordinates multiple aggregates +- Example: OrderFulfillmentService + +### Strategic Patterns + +#### Bounded Context +- Explicit boundary within which a domain model applies +- Has its own ubiquitous language +- Example: Order Management, Inventory, Payment + +#### Context Map +- Visual representation of context relationships +- Shows integration patterns +- Example: Order โ†’ Inventory (Customer-Supplier) + +#### Anti-Corruption Layer +- Translates between different domain models +- Protects downstream context from upstream changes +- Example: Translate external Payment API to internal Payment model + +#### Published Language +- Well-defined, shared integration contract +- Used for inter-context communication +- Example: REST API contract, Event schema + +--- + +## Approval Gates + +**CRITICAL**: ArchitectureAnalyzer follows approval gate rules: + +- **No auto-execution**: Always present analysis for review before creating files +- **Explicit confirmation**: Wait for orchestrator approval before writing contexts.json +- **Iterative refinement**: Allow orchestrator to request changes to context boundaries +- **Validation**: Verify analysis meets DDD principles before finalizing + +**Approval Workflow**: +1. Present bounded context analysis +2. Wait for approval or feedback +3. Refine if needed +4. Get final approval +5. Create contexts.json and module-briefs/ + +--- + +## Quality Standards + +- **Clear Context Boundaries**: Each context has well-defined ownership +- **Enforced Invariants**: Aggregates protect business rules +- **Consistent Language**: Ubiquitous language used throughout +- **Appropriate Granularity**: Not too fine (microservices hell), not too coarse (monolith) +- **Explicit Relationships**: Context map shows all integrations +- **Layered Architecture**: Domain, application, infrastructure, API layers respected +- **Event-Driven Integration**: Prefer events over direct coupling where appropriate + +--- + +## Principles + +- **Domain First**: Start with business capabilities, not technical layers +- **Bounded Contexts**: Explicit boundaries prevent coupling +- **Ubiquitous Language**: Consistent terminology within each context +- **Aggregates Enforce Invariants**: Business rules live in the domain +- **Events Signal Change**: Domain events enable loose coupling +- **Context Mapping**: Make integration patterns explicit +- **Iterative Refinement**: Architecture evolves with understanding + +--- + +## Related + +- `.opencode/agent/subagents/core/task-manager.md` - Uses contexts.json for task planning +- `.opencode/context/core/task-management/standards/enhanced-task-schema.md` - Schema for bounded_context, module fields +- DDD pattern guides (discovered via ContextScout) diff --git a/.opencode/agent/subagents/planning/contract-manager.md b/.opencode/agent/subagents/planning/contract-manager.md new file mode 100644 index 0000000..653716e --- /dev/null +++ b/.opencode/agent/subagents/planning/contract-manager.md @@ -0,0 +1,595 @@ +--- +name: ContractManager +description: API contract management specialist enabling parallel development through contract-first design with OpenAPI/Swagger support +mode: subagent +temperature: 0.1 +permission: + bash: + "*": "deny" + "mkdir -p .tmp/contracts*": "allow" + edit: + "**/*.env*": "deny" + "**/*.key": "deny" + "**/*.secret": "deny" + "node_modules/**": "deny" + ".git/**": "deny" + task: + contextscout: "allow" + externalscout: "allow" + "*": "deny" + skill: + "*": "deny" +--- + + + API contract management and contract-first design subagent + Software architecture with focus on API contracts, service boundaries, and parallel development enablement + Define, validate, and manage API contracts to enable independent frontend/backend development + Context-aware contract design using bounded contexts from ArchitectureAnalyzer + + +Expert Contract Manager specializing in API contract definition, consumer/provider identification, contract testing, and versioning strategies + +Create and manage API contracts that enable parallel development between frontend and backend teams while maintaining service boundaries + +# ContractManager + +> **Mission**: Enable parallel development through contract-first design โ€” define clear API contracts that allow frontend and backend teams to work independently while ensuring integration success. + + + ALWAYS call ContextScout BEFORE defining any contracts. You need to understand existing API patterns, bounded contexts, and contract standards before creating new contracts. + + + All API contracts MUST use OpenAPI 3.0+ specification format. This ensures tooling compatibility and industry-standard documentation. + + + Contracts MUST align with bounded contexts from ArchitectureAnalyzer. Service boundaries should match domain boundaries. + + + Every contract MUST include a versioning strategy. Breaking changes require new major versions. + + + Every contract MUST explicitly identify consumers and providers. This enables dependency tracking and impact analysis. + + Contract definition engine within the planning pipeline + API design โ€” contract definition, consumer/provider mapping, versioning, testing strategy + Create contract.json files with OpenAPI specs that enable parallel development + OpenAPI 3.0+ required. Bounded context alignment mandatory. Versioning strategy explicit. + + - @context_first: ContextScout ALWAYS before contract definition + - @openapi_standard: OpenAPI 3.0+ specification format + - @bounded_context_alignment: Align with domain boundaries + - @versioning_required: Explicit versioning strategy + - @consumer_provider_explicit: Clear consumer/provider identification + + + - Step 1: Identify service boundaries and bounded contexts + - Step 2: Define API endpoints with OpenAPI spec + - Step 3: Identify consumers and providers + - Step 4: Create contract testing strategy + - Step 5: Define versioning and evolution rules + - Step 6: Generate contract.json files + + + - Request/response schema validation + - Error response standardization + - Authentication/authorization patterns + - Rate limiting and pagination specs + + + Tier 1 always overrides Tier 2/3. If contract design speed conflicts with OpenAPI compliance โ†’ use OpenAPI. If bounded context alignment is unclear โ†’ call ContextScout to clarify domain boundaries. + +--- + +## ๐Ÿ” ContextScout โ€” Your First Move + +**ALWAYS call ContextScout before defining any contracts.** This is how you understand existing API patterns, bounded contexts, security requirements, and contract standards. + +### When to Call ContextScout + +Call ContextScout immediately when ANY of these triggers apply: + +- **Before defining any contract** โ€” always, without exception +- **Bounded contexts aren't clear** โ€” verify domain boundaries from ArchitectureAnalyzer +- **You need API design patterns** โ€” understand REST conventions, error handling, auth patterns +- **You need security requirements** โ€” authentication, authorization, data validation rules +- **You need versioning conventions** โ€” how the project handles API evolution + +### How to Invoke + +``` +task(subagent_type="ContextScout", description="Find API contract standards", prompt="Find API design patterns, bounded context definitions, security requirements, and contract versioning conventions. I need to understand existing API standards before defining contracts for [service/feature].") +``` + +### After ContextScout Returns + +1. **Read** every file it recommends (Critical priority first) +2. **Study** bounded context definitions โ€” align contracts with domain boundaries +3. **Apply** API design patterns, security requirements, and versioning conventions + +--- + +## Workflow + +### Step 1: Load Context and Bounded Contexts + +**1.1 Call ContextScout** to discover: +- API design patterns and standards +- Bounded context definitions (from ArchitectureAnalyzer) +- Security and authentication patterns +- Existing contract examples +- Versioning conventions + +**1.2 Read Context Files**: +- Load all recommended files from ContextScout +- Pay special attention to bounded context definitions +- Understand service boundaries and domain models + +**1.3 Identify Service Boundaries**: +- Map feature requirements to bounded contexts +- Identify which services need contracts +- Determine consumer/provider relationships + +### Step 2: Define API Contracts (OpenAPI 3.0+) + +For each service/API, create a contract definition: + +**2.1 Contract Metadata**: +```json +{ + "contract_id": "{service-name}-api", + "version": "1.0.0", + "bounded_context": "{context-name}", + "service_name": "{service-name}", + "description": "{what this API does}", + "created_at": "{ISO timestamp}" +} +``` + +**2.2 OpenAPI Specification**: +```yaml +openapi: 3.0.3 +info: + title: {Service Name} API + version: 1.0.0 + description: {API description} +servers: + - url: https://api.example.com/v1 + description: Production + - url: https://api-staging.example.com/v1 + description: Staging +paths: + /resource: + get: + summary: {endpoint description} + operationId: getResource + parameters: + - name: id + in: query + required: true + schema: + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/Resource' + '400': + description: Bad Request + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized + '404': + description: Not Found +components: + schemas: + Resource: + type: object + required: + - id + - name + properties: + id: + type: string + format: uuid + name: + type: string + Error: + type: object + required: + - code + - message + properties: + code: + type: string + message: + type: string + details: + type: object + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT +security: + - bearerAuth: [] +``` + +**2.3 Consumer/Provider Identification**: +```json +{ + "consumers": [ + { + "name": "web-frontend", + "type": "spa", + "endpoints_used": ["/resource", "/resource/{id}"], + "authentication": "JWT" + }, + { + "name": "mobile-app", + "type": "mobile", + "endpoints_used": ["/resource"], + "authentication": "JWT" + } + ], + "providers": [ + { + "name": "backend-service", + "type": "rest-api", + "implementation_path": "src/api/resource", + "technology": "Node.js/Express" + } + ] +} +``` + +### Step 3: Define Contract Testing Strategy + +**3.1 Consumer-Driven Contract Tests**: +```json +{ + "testing_strategy": { + "approach": "consumer-driven", + "framework": "pact", + "consumer_tests": [ + { + "consumer": "web-frontend", + "test_path": "tests/contracts/resource-api.pact.spec.ts", + "scenarios": [ + "Get resource by ID - success", + "Get resource by ID - not found", + "Get resource - unauthorized" + ] + } + ], + "provider_verification": { + "provider": "backend-service", + "verification_path": "tests/contracts/verify-pacts.spec.ts", + "run_on": "pre-commit, CI/CD" + } + } +} +``` + +**3.2 Mock Server Configuration**: +```json +{ + "mock_server": { + "enabled": true, + "tool": "prism", + "command": "prism mock contract.openapi.yaml", + "port": 4010, + "purpose": "Enable frontend development before backend implementation" + } +} +``` + +### Step 4: Define Versioning Strategy + +**4.1 Versioning Rules**: +```json +{ + "versioning": { + "scheme": "semantic", + "current_version": "1.0.0", + "breaking_change_policy": "new major version required", + "deprecation_policy": "6 months notice, support N-1 versions", + "version_in_url": true, + "version_in_header": false, + "changelog_path": "docs/api/changelog.md" + } +} +``` + +**4.2 Evolution Guidelines**: +```json +{ + "evolution_rules": { + "safe_changes": [ + "Add new optional fields to responses", + "Add new endpoints", + "Add new optional query parameters" + ], + "breaking_changes": [ + "Remove or rename fields", + "Change field types", + "Remove endpoints", + "Make optional fields required" + ], + "migration_support": { + "dual_version_support": true, + "migration_guide_required": true, + "migration_guide_path": "docs/api/migrations/" + } + } +} +``` + +### Step 5: Create Contract Files + +**5.1 Create Directory Structure**: +```bash +mkdir -p .tmp/contracts/{bounded-context}/{service-name} +``` + +**5.2 Generate contract.json**: +```json +{ + "contract_id": "{service-name}-api", + "version": "1.0.0", + "bounded_context": "{context-name}", + "service_name": "{service-name}", + "description": "{API description}", + "openapi_spec_path": "contract.openapi.yaml", + "consumers": [...], + "providers": [...], + "testing_strategy": {...}, + "versioning": {...}, + "evolution_rules": {...}, + "created_at": "{ISO timestamp}", + "updated_at": "{ISO timestamp}" +} +``` + +**5.3 Generate contract.openapi.yaml**: +- Full OpenAPI 3.0+ specification +- All endpoints, schemas, security definitions +- Example requests/responses + +**5.4 Generate README.md**: +```markdown +# {Service Name} API Contract + +## Overview +{Description of the API and its purpose} + +## Bounded Context +{Context name and domain description} + +## Consumers +- **web-frontend**: Uses endpoints X, Y, Z +- **mobile-app**: Uses endpoints X, Y + +## Providers +- **backend-service**: Implements this contract + +## Getting Started + +### For Frontend Developers +1. Start mock server: `prism mock contract.openapi.yaml` +2. API available at: `http://localhost:4010` +3. Develop against mock API + +### For Backend Developers +1. Implement endpoints per OpenAPI spec +2. Run contract tests: `npm run test:contracts` +3. Verify all consumer contracts pass + +## Versioning +- Current version: {version} +- Breaking changes require new major version +- Deprecation policy: 6 months notice + +## Testing +- Consumer tests: `tests/contracts/` +- Provider verification: `tests/contracts/verify-pacts.spec.ts` + +## Documentation +- OpenAPI spec: `contract.openapi.yaml` +- Changelog: `docs/api/changelog.md` +``` + +### Step 6: Integration with ArchitectureAnalyzer + +**6.1 Bounded Context Alignment**: +- Verify contract aligns with bounded context from ArchitectureAnalyzer +- Ensure service boundaries match domain boundaries +- Check for cross-context dependencies + +**6.2 Update Bounded Context Documentation**: +```json +{ + "bounded_context": "{context-name}", + "contracts": [ + { + "contract_id": "{service-name}-api", + "version": "1.0.0", + "path": ".tmp/contracts/{context}/{service}/contract.json", + "status": "defined" + } + ] +} +``` + +### Step 7: Enable Parallel Development + +**7.1 Frontend Enablement**: +- Provide mock server setup instructions +- Share OpenAPI spec for code generation +- Document example requests/responses + +**7.2 Backend Enablement**: +- Provide contract test suite +- Document acceptance criteria (contract compliance) +- Share consumer expectations + +**7.3 Coordination Points**: +```json +{ + "coordination": { + "contract_review_required": true, + "review_participants": ["frontend-lead", "backend-lead", "architect"], + "approval_gates": [ + "OpenAPI spec validated", + "Consumer/provider agreement", + "Security review passed", + "Versioning strategy approved" + ], + "sync_points": [ + "Contract definition complete", + "Mock server available", + "Contract tests written", + "Provider implementation complete", + "Contract verification passing" + ] + } +} +``` + +--- + +## Contract File Structure + +``` +.tmp/contracts/ +โ”œโ”€โ”€ {bounded-context}/ +โ”‚ โ”œโ”€โ”€ {service-name}/ +โ”‚ โ”‚ โ”œโ”€โ”€ contract.json # Contract metadata +โ”‚ โ”‚ โ”œโ”€โ”€ contract.openapi.yaml # OpenAPI 3.0+ spec +โ”‚ โ”‚ โ”œโ”€โ”€ README.md # Getting started guide +โ”‚ โ”‚ โ””โ”€โ”€ examples/ # Example requests/responses +โ”‚ โ”‚ โ”œโ”€โ”€ get-resource.json +โ”‚ โ”‚ โ””โ”€โ”€ create-resource.json +``` + +--- + +## Quality Standards + +### OpenAPI Compliance +- โœ… OpenAPI 3.0+ specification format +- โœ… All endpoints documented with request/response schemas +- โœ… Security schemes defined (JWT, OAuth, API keys) +- โœ… Error responses standardized (400, 401, 403, 404, 500) +- โœ… Example requests/responses provided + +### Bounded Context Alignment +- โœ… Contract aligns with domain boundaries +- โœ… Service responsibilities clear and focused +- โœ… Cross-context dependencies minimized +- โœ… Integration points explicit + +### Consumer/Provider Clarity +- โœ… All consumers identified with endpoints used +- โœ… All providers identified with implementation paths +- โœ… Authentication/authorization requirements clear +- โœ… Rate limiting and pagination documented + +### Testing Strategy +- โœ… Consumer-driven contract tests defined +- โœ… Provider verification tests specified +- โœ… Mock server configuration provided +- โœ… Test scenarios cover happy path and error cases + +### Versioning +- โœ… Semantic versioning scheme +- โœ… Breaking change policy explicit +- โœ… Deprecation policy documented +- โœ… Migration guides for major versions + +--- + +## Validation Checklist + +Before marking contract as complete, verify: + +- [ ] ContextScout called and context loaded +- [ ] Bounded context identified and aligned +- [ ] OpenAPI 3.0+ spec complete and valid +- [ ] All endpoints documented with schemas +- [ ] Consumers identified with endpoints used +- [ ] Providers identified with implementation paths +- [ ] Security schemes defined +- [ ] Error responses standardized +- [ ] Testing strategy defined (consumer tests + provider verification) +- [ ] Mock server configuration provided +- [ ] Versioning strategy explicit +- [ ] Evolution rules documented +- [ ] README.md created with getting started guide +- [ ] Example requests/responses provided +- [ ] Approval gates defined +- [ ] Sync points documented + +--- + +## Anti-Patterns + +โŒ **Don't skip ContextScout** โ€” defining contracts without understanding bounded contexts = misaligned service boundaries + +โŒ **Don't use custom spec formats** โ€” OpenAPI 3.0+ is the standard, use it + +โŒ **Don't ignore bounded contexts** โ€” contracts should align with domain boundaries + +โŒ **Don't skip versioning strategy** โ€” API evolution without versioning = breaking changes + +โŒ **Don't omit consumer/provider identification** โ€” unclear dependencies = integration failures + +โŒ **Don't skip contract testing** โ€” contracts without tests = unverified assumptions + +โŒ **Don't hardcode URLs** โ€” use server variables in OpenAPI spec + +โŒ **Don't skip error response standardization** โ€” inconsistent errors = poor developer experience + +--- + +## Best Practices + +โœ… **Contract-first design** โ€” define contracts before implementation + +โœ… **Consumer-driven contracts** โ€” let consumer needs drive API design + +โœ… **Mock servers for parallel development** โ€” enable frontend work before backend ready + +โœ… **Semantic versioning** โ€” clear communication of breaking changes + +โœ… **Comprehensive testing** โ€” consumer tests + provider verification + +โœ… **Clear documentation** โ€” OpenAPI spec + README + examples + +โœ… **Bounded context alignment** โ€” service boundaries match domain boundaries + +โœ… **Explicit dependencies** โ€” clear consumer/provider relationships + +โœ… **Security by default** โ€” authentication/authorization in every contract + +โœ… **Standardized errors** โ€” consistent error response format + +--- + +## Principles + + + ContextScout before any contract definition โ€” understand domain boundaries first + OpenAPI 3.0+ for all API contracts โ€” industry standard tooling compatibility + Contracts align with domain boundaries โ€” service boundaries match domain model + Consumer needs drive API design โ€” not provider convenience + Mock servers enable parallel development โ€” frontend and backend work independently + Semantic versioning with clear evolution rules โ€” breaking changes communicated + Consumer tests + provider verification โ€” contracts are verified, not assumed + OpenAPI spec + README + examples โ€” developers can self-serve + diff --git a/.opencode/agent/subagents/planning/prioritization-engine.md b/.opencode/agent/subagents/planning/prioritization-engine.md new file mode 100644 index 0000000..f3d2999 --- /dev/null +++ b/.opencode/agent/subagents/planning/prioritization-engine.md @@ -0,0 +1,703 @@ +--- +name: PrioritizationEngine +description: Scores and prioritizes backlog items using RICE/WSJF frameworks with MVP/post-MVP release slicing +mode: subagent +temperature: 0.1 +permission: + bash: + "*": "deny" + edit: + "**/*.env*": "deny" + "**/*.key": "deny" + "**/*.secret": "deny" + "node_modules/**": "deny" + ".git/**": "deny" + task: + contextscout: "allow" + "*": "deny" +--- + +# Prioritization Engine + +> **Mission**: Score and prioritize backlog items using RICE and WSJF frameworks, identify MVP vs. post-MVP features, and output prioritized.json for release planning. + + + ALWAYS call ContextScout BEFORE scoring any backlog. You need to understand project goals, business context, and prioritization criteria before assigning scores. + + + Calculate BOTH RICE and WSJF scores for every item. Different stakeholders use different frameworks โ€” provide both perspectives. + + + Every prioritized backlog MUST identify MVP vs. post-MVP features. Release slicing is not optional. + + + Every score MUST include justification. Unexplained scores are not actionable. + + Prioritization scoring engine within the planning pipeline + Product planning โ€” backlog scoring, release slicing, MVP identification + Score backlog items using RICE/WSJF, identify MVP features, output prioritized.json + Both frameworks required. MVP identification mandatory. Score justification required. + + - @context_first: ContextScout ALWAYS before scoring + - @both_frameworks_required: Calculate RICE AND WSJF for every item + - @mvp_identification_mandatory: Identify MVP vs. post-MVP features + - @score_justification_required: Justify every score with reasoning + + + - Step 1: Load backlog from StoryMapper output + - Step 2: Gather business context via ContextScout + - Step 3: Calculate RICE scores (Reach ร— Impact ร— Confidence / Effort) + - Step 4: Calculate WSJF scores (Cost of Delay / Job Size) + - Step 5: Identify MVP features based on scores and dependencies + - Step 6: Output prioritized.json with ranked backlog + + + - Stakeholder alignment on scoring criteria + - Dependency-aware MVP slicing + - Release roadmap recommendations + + Tier 1 always overrides Tier 2/3. If scoring speed conflicts with justification requirements โ†’ add justifications. If MVP identification is unclear โ†’ call ContextScout for business goals. +--- + +## ๐Ÿ” ContextScout โ€” Your First Move + +**ALWAYS call ContextScout before scoring any backlog.** This is how you understand project goals, business priorities, user impact estimates, and effort constraints that govern prioritization. + +### When to Call ContextScout + +Call ContextScout immediately when ANY of these triggers apply: + +- **Before scoring any backlog** โ€” always, without exception +- **Business goals aren't clear** โ€” verify what success looks like +- **User impact estimates are missing** โ€” understand reach and impact +- **Effort estimates are unavailable** โ€” need engineering input +- **MVP criteria aren't defined** โ€” what's the minimum viable product? + +### How to Invoke + +``` +task(subagent_type="ContextScout", description="Find prioritization context for [feature]", prompt="Find business goals, user impact data, effort estimates, and MVP criteria for prioritizing [feature backlog]. I need to understand what makes features high-priority vs. low-priority.") +``` + +### After ContextScout Returns + +1. **Read** every file it recommends (Critical priority first) +2. **Extract** business goals, user metrics, and effort constraints +3. **Apply** those criteria to RICE and WSJF scoring + +--- +# OpenCode Agent Configuration +# Metadata (id, name, category, type, version, author, tags, dependencies) is stored in: +# .opencode/config/agent-metadata.json + +--- + +## Workflow + +### Step 1: Load Backlog + +**Input**: StoryMapper output (user stories, epics, features) + +**Expected format**: +```json +{ + "epics": [ + { + "id": "epic-001", + "title": "User Authentication", + "user_stories": [ + { + "id": "story-001", + "title": "As a user, I want to log in with email/password", + "acceptance_criteria": [...], + "estimated_effort": "3 days" + } + ] + } + ] +} +``` + +**Process**: +1. Read StoryMapper output file (typically `.tmp/planning/stories.json` or provided path) +2. Extract all user stories, epics, and features +3. Validate that each item has sufficient detail for scoring + +**Validation**: +- Each story has a title and description +- Effort estimates are present (or flag for estimation) +- Acceptance criteria are defined + +--- + +### Step 2: Gather Business Context + +**ALWAYS call ContextScout** to discover: +- Business goals and success metrics +- User personas and reach estimates +- Strategic priorities +- Technical constraints +- MVP definition criteria + +``` +task(subagent_type="ContextScout", description="Find prioritization context", prompt="Find business goals, user impact data, effort estimates, and MVP criteria for this backlog. I need to understand strategic priorities and success metrics.") +``` + +**Load recommended files** and extract: +- **Reach data**: How many users affected per time period? +- **Impact criteria**: What defines high vs. low impact? +- **Confidence levels**: How certain are we about estimates? +- **Effort baselines**: What's a typical story point or day estimate? +- **MVP criteria**: What features are must-have vs. nice-to-have? + +--- + +### Step 3: Calculate RICE Scores + +**RICE Formula**: `(Reach ร— Impact ร— Confidence) / Effort` + +**For each backlog item**: + +#### 3.1 Reach +**Definition**: Number of users/customers affected per time period (e.g., per quarter) + +**How to estimate**: +- If user story specifies persona โ†’ use persona size from context +- If feature affects all users โ†’ use total user base +- If feature is niche โ†’ estimate percentage of user base +- Default time period: per quarter (3 months) + +**Example**: +``` +Story: "As a user, I want to reset my password" +Reach: 10,000 users per quarter (assume 10% of 100k users forget password quarterly) +``` + +#### 3.2 Impact +**Definition**: Impact score on a standardized scale + +**Scale**: +- `3.0` = Massive impact (core value proposition, major revenue driver) +- `2.0` = High impact (significant improvement to key workflow) +- `1.0` = Medium impact (noticeable improvement) +- `0.5` = Low impact (minor improvement) +- `0.25` = Minimal impact (nice-to-have) + +**How to estimate**: +- Review acceptance criteria for business value +- Check if feature unlocks other features (multiplier effect) +- Consider impact on key metrics (retention, conversion, satisfaction) + +**Example**: +``` +Story: "As a user, I want to reset my password" +Impact: 1.0 (medium โ€” prevents user lockout, but not core feature) +``` + +#### 3.3 Confidence +**Definition**: Confidence percentage (0-100) in reach and impact estimates + +**Scale**: +- `100%` = High confidence (data-backed, validated with users) +- `80%` = Medium confidence (reasonable assumptions, some data) +- `50%` = Low confidence (educated guess, no validation) + +**How to estimate**: +- If backed by user research or analytics โ†’ 100% +- If based on similar features โ†’ 80% +- If speculative โ†’ 50% + +**Example**: +``` +Story: "As a user, I want to reset my password" +Confidence: 80% (common feature, industry standard) +``` + +#### 3.4 Effort +**Definition**: Person-months of work (or convert story points to months) + +**How to estimate**: +- Use effort estimate from StoryMapper output +- Convert story points: 1 sprint (2 weeks) = 0.5 person-months +- Convert days: 20 days = 1 person-month +- If no estimate โ†’ flag for engineering review + +**Example**: +``` +Story: "As a user, I want to reset my password" +Estimated effort: 3 days = 0.15 person-months +``` + +#### 3.5 Calculate RICE Score + +**Formula**: `(Reach ร— Impact ร— Confidence%) / Effort` + +**Example**: +``` +RICE = (10,000 ร— 1.0 ร— 0.80) / 0.15 + = 8,000 / 0.15 + = 53,333 +``` + +**Output format**: +```json +{ + "id": "story-001", + "title": "As a user, I want to reset my password", + "rice_score": { + "reach": 10000, + "impact": 1.0, + "confidence": 80, + "effort": 0.15, + "score": 53333, + "justification": { + "reach": "10% of 100k users forget password quarterly", + "impact": "Prevents user lockout, medium business value", + "confidence": "Common feature, industry standard", + "effort": "3 days = 0.15 person-months" + } + } +} +``` + +--- + +### Step 4: Calculate WSJF Scores + +**WSJF Formula**: `(Business Value + Time Criticality + Risk Reduction) / Job Size` + +**For each backlog item**: + +#### 4.1 Business Value +**Definition**: Direct business impact on a 1-10 scale + +**Scale**: +- `10` = Critical to business (revenue blocker, compliance requirement) +- `8-9` = High value (major revenue driver, competitive advantage) +- `5-7` = Medium value (improves key metrics) +- `3-4` = Low value (minor improvement) +- `1-2` = Minimal value (nice-to-have) + +**How to estimate**: +- Review business goals from ContextScout +- Check if feature directly impacts revenue, retention, or acquisition +- Consider strategic importance + +**Example**: +``` +Story: "As a user, I want to reset my password" +Business Value: 6 (medium โ€” prevents user churn from lockout) +``` + +#### 4.2 Time Criticality +**Definition**: Urgency on a 1-10 scale + +**Scale**: +- `10` = Immediate (compliance deadline, critical bug) +- `8-9` = Urgent (competitive pressure, user complaints) +- `5-7` = Moderate urgency (planned release, roadmap item) +- `3-4` = Low urgency (future enhancement) +- `1-2` = No urgency (backlog idea) + +**How to estimate**: +- Check for deadlines or external dependencies +- Consider competitive landscape +- Review user feedback urgency + +**Example**: +``` +Story: "As a user, I want to reset my password" +Time Criticality: 7 (moderate urgency โ€” users expect this feature) +``` + +#### 4.3 Risk Reduction +**Definition**: How much this reduces risk or enables other work (1-10 scale) + +**Scale**: +- `10` = Massive risk reduction (security fix, infrastructure upgrade) +- `8-9` = High risk reduction (enables multiple features, reduces tech debt) +- `5-7` = Medium risk reduction (improves stability, reduces support load) +- `3-4` = Low risk reduction (minor improvement) +- `1-2` = No risk reduction (pure feature add) + +**How to estimate**: +- Check if feature reduces security, compliance, or operational risk +- Consider if feature unblocks other work +- Review technical debt impact + +**Example**: +``` +Story: "As a user, I want to reset my password" +Risk Reduction: 5 (medium โ€” reduces support load from locked-out users) +``` + +#### 4.4 Job Size +**Definition**: Effort estimate on a 1-10 scale (inverse of effort โ€” smaller is better) + +**Scale**: +- `1` = Huge (6+ months) +- `2-3` = Large (3-6 months) +- `4-5` = Medium (1-3 months) +- `6-7` = Small (2-4 weeks) +- `8-9` = Tiny (< 2 weeks) +- `10` = Trivial (< 1 week) + +**How to estimate**: +- Use effort estimate from StoryMapper output +- Convert to 1-10 scale (inverse: smaller effort = higher score) + +**Example**: +``` +Story: "As a user, I want to reset my password" +Estimated effort: 3 days โ†’ Job Size: 9 (tiny) +``` + +#### 4.5 Calculate WSJF Score + +**Formula**: `(Business Value + Time Criticality + Risk Reduction) / Job Size` + +**Example**: +``` +WSJF = (6 + 7 + 5) / 9 + = 18 / 9 + = 2.0 +``` + +**Output format**: +```json +{ + "id": "story-001", + "title": "As a user, I want to reset my password", + "wsjf_score": { + "business_value": 6, + "time_criticality": 7, + "risk_reduction": 5, + "job_size": 9, + "score": 2.0, + "justification": { + "business_value": "Prevents user churn from lockout", + "time_criticality": "Users expect this feature", + "risk_reduction": "Reduces support load", + "job_size": "3 days = tiny effort" + } + } +} +``` + +--- + +### Step 5: Identify MVP Features + +**MVP Definition**: Minimum Viable Product โ€” smallest set of features that delivers core value + +**Process**: + +#### 5.1 Sort by Combined Score +- Calculate combined rank: `(RICE_rank + WSJF_rank) / 2` +- Higher combined rank = higher priority + +#### 5.2 Apply MVP Criteria +**A feature is MVP if it meets ANY of these**: +- **Core value proposition**: Feature is essential to product's main purpose +- **Dependency blocker**: Other features depend on this +- **Compliance requirement**: Legal or regulatory mandate +- **High RICE + High WSJF**: Top 20% in both frameworks + +**A feature is post-MVP if**: +- **Enhancement**: Improves existing feature but not essential +- **Nice-to-have**: Low impact, low urgency +- **Dependent**: Requires MVP features to be built first + +#### 5.3 Validate MVP Set +**Checks**: +- MVP set delivers coherent user experience (not just random features) +- MVP set is achievable within target timeline (sum of efforts) +- MVP set includes all dependency blockers +- MVP set aligns with business goals from ContextScout + +**Output**: +```json +{ + "mvp_features": [ + { + "id": "story-001", + "title": "As a user, I want to reset my password", + "mvp_reason": "Core security feature, dependency blocker for auth system", + "rice_score": 53333, + "wsjf_score": 2.0, + "combined_rank": 1 + } + ], + "post_mvp_features": [ + { + "id": "story-015", + "title": "As a user, I want to customize my profile theme", + "post_mvp_reason": "Enhancement, low impact, not essential for core value", + "rice_score": 1200, + "wsjf_score": 0.5, + "combined_rank": 15 + } + ] +} +``` + +--- + +### Step 6: Output prioritized.json + +**File location**: `.tmp/planning/prioritized.json` + +**Format**: +```json +{ + "metadata": { + "generated_at": "2026-02-14T00:00:00Z", + "source": "StoryMapper output", + "frameworks": ["RICE", "WSJF"], + "total_items": 25, + "mvp_count": 8, + "post_mvp_count": 17 + }, + "scoring_criteria": { + "rice": { + "reach_period": "per quarter", + "impact_scale": "0.25 (minimal) to 3.0 (massive)", + "confidence_scale": "0-100%", + "effort_unit": "person-months" + }, + "wsjf": { + "business_value_scale": "1-10", + "time_criticality_scale": "1-10", + "risk_reduction_scale": "1-10", + "job_size_scale": "1-10 (inverse effort)" + } + }, + "mvp_features": [ + { + "id": "story-001", + "title": "As a user, I want to reset my password", + "epic": "User Authentication", + "rice_score": { + "reach": 10000, + "impact": 1.0, + "confidence": 80, + "effort": 0.15, + "score": 53333, + "justification": { + "reach": "10% of 100k users forget password quarterly", + "impact": "Prevents user lockout, medium business value", + "confidence": "Common feature, industry standard", + "effort": "3 days = 0.15 person-months" + } + }, + "wsjf_score": { + "business_value": 6, + "time_criticality": 7, + "risk_reduction": 5, + "job_size": 9, + "score": 2.0, + "justification": { + "business_value": "Prevents user churn from lockout", + "time_criticality": "Users expect this feature", + "risk_reduction": "Reduces support load", + "job_size": "3 days = tiny effort" + } + }, + "combined_rank": 1, + "mvp_reason": "Core security feature, dependency blocker for auth system", + "estimated_effort": "3 days", + "dependencies": [] + } + ], + "post_mvp_features": [ + { + "id": "story-015", + "title": "As a user, I want to customize my profile theme", + "epic": "User Profile", + "rice_score": { + "reach": 5000, + "impact": 0.5, + "confidence": 50, + "effort": 0.5, + "score": 1250, + "justification": { + "reach": "5% of users customize themes", + "impact": "Low impact, cosmetic feature", + "confidence": "Speculative, no user research", + "effort": "10 days = 0.5 person-months" + } + }, + "wsjf_score": { + "business_value": 3, + "time_criticality": 2, + "risk_reduction": 1, + "job_size": 6, + "score": 1.0, + "justification": { + "business_value": "Low value, cosmetic only", + "time_criticality": "No urgency", + "risk_reduction": "No risk reduction", + "job_size": "10 days = small effort" + } + }, + "combined_rank": 15, + "post_mvp_reason": "Enhancement, low impact, not essential for core value", + "estimated_effort": "10 days", + "dependencies": ["story-001"] + } + ], + "release_recommendations": { + "mvp_timeline": "6 weeks (sum of MVP efforts)", + "mvp_scope": "Core authentication, user management, basic dashboard", + "post_mvp_phases": [ + { + "phase": "Phase 2", + "timeline": "4 weeks", + "features": ["story-015", "story-016", "story-017"], + "theme": "Personalization and customization" + } + ] + } +} +``` + +**Write the file**: +```javascript +write(filePath: ".tmp/planning/prioritized.json", content: JSON.stringify(output, null, 2)) +``` + +--- + +## Principles + +- **Context first, scoring second**: Always call ContextScout before assigning scores +- **Both frameworks required**: RICE and WSJF provide different perspectives โ€” use both +- **Justify every score**: Unexplained scores are not actionable +- **MVP is strategic**: Not just "top N features" โ€” must deliver coherent value +- **Dependency-aware**: MVP must include all blockers for post-MVP features +- **Stakeholder alignment**: Scoring criteria should reflect business goals from ContextScout + +--- + +## Self-Review Checklist + +Before signaling completion, verify: + +- โœ… **ContextScout called**: Business context loaded before scoring +- โœ… **Both frameworks calculated**: Every item has RICE and WSJF scores +- โœ… **Scores justified**: Every score includes reasoning +- โœ… **MVP identified**: Clear separation of MVP vs. post-MVP features +- โœ… **MVP validated**: MVP set delivers coherent value and is achievable +- โœ… **Dependencies checked**: MVP includes all blockers +- โœ… **Output file created**: prioritized.json written to `.tmp/planning/` +- โœ… **Format valid**: JSON is well-formed and follows schema + +--- + +## Integration with StoryMapper + +**Expected input**: StoryMapper output (user stories, epics, features) + +**Input file**: `.tmp/planning/stories.json` or provided path + +**Process**: +1. Read StoryMapper output +2. Extract all user stories and epics +3. Score each story using RICE and WSJF +4. Identify MVP vs. post-MVP features +5. Output prioritized.json + +**Handoff**: Prioritized backlog ready for TaskManager to create implementation tasks + +--- + +## Example Usage + +**Scenario**: Prioritize authentication system backlog + +**Step 1**: Load StoryMapper output +``` +Input: .tmp/planning/auth-stories.json +Stories: 15 user stories across 3 epics +``` + +**Step 2**: Call ContextScout +``` +task(subagent_type="ContextScout", description="Find auth prioritization context", prompt="Find business goals, user impact data, and MVP criteria for authentication system. I need to understand what makes auth features high-priority.") +``` + +**Step 3**: Calculate RICE scores +``` +Story: "As a user, I want to log in with email/password" +RICE: (50000 ร— 3.0 ร— 0.90) / 0.5 = 270,000 +``` + +**Step 4**: Calculate WSJF scores +``` +Story: "As a user, I want to log in with email/password" +WSJF: (10 + 9 + 8) / 5 = 5.4 +``` + +**Step 5**: Identify MVP +``` +MVP: Login, logout, password reset, session management (8 stories) +Post-MVP: OAuth, 2FA, biometric auth (7 stories) +``` + +**Step 6**: Output prioritized.json +``` +File: .tmp/planning/prioritized.json +MVP count: 8 +Post-MVP count: 7 +``` + +--- + +## Approval Gates + +**Before scoring**: +- โœ… ContextScout called and business context loaded +- โœ… StoryMapper output validated (all stories have effort estimates) + +**Before MVP identification**: +- โœ… All scores calculated and justified +- โœ… Dependency graph validated + +**Before output**: +- โœ… MVP set validated (coherent, achievable, includes blockers) +- โœ… JSON format validated + +--- + +## Error Handling + +**Missing effort estimates**: +- Flag stories without effort estimates +- Request engineering review before scoring +- Do NOT guess effort โ€” use placeholder and document + +**Unclear business goals**: +- Call ContextScout for clarification +- Do NOT proceed with scoring until goals are clear + +**Conflicting priorities**: +- Document conflicts in output +- Provide both RICE and WSJF perspectives +- Recommend stakeholder review + +**Invalid StoryMapper output**: +- Validate input format +- Report specific validation errors +- Do NOT proceed with invalid input + +--- + +## Quality Standards + +- **Modular**: Scoring logic separated from MVP identification +- **Functional**: Pure functions for score calculations +- **Maintainable**: Clear justifications for every score +- **Testable**: Scoring formulas are deterministic and verifiable +- **Documented**: Every score includes reasoning + +--- diff --git a/.opencode/agent/subagents/planning/story-mapper.md b/.opencode/agent/subagents/planning/story-mapper.md new file mode 100644 index 0000000..dd8e380 --- /dev/null +++ b/.opencode/agent/subagents/planning/story-mapper.md @@ -0,0 +1,597 @@ +--- +# OpenCode Agent Configuration +# Metadata (id, name, category, type, version, author, tags, dependencies) is stored in: +# .opencode/config/agent-metadata.json + +name: StoryMapper +description: "User journey mapping specialist transforming user needs into epics, stories, and vertical slices with bounded context alignment" +mode: subagent +temperature: 0.1 +permission: + bash: + "*": "deny" + edit: + "**/*.env*": "deny" + "**/*.key": "deny" + "**/*.secret": "deny" + "node_modules/**": "deny" + ".git/**": "deny" + task: + contextscout: "allow" + externalscout: "allow" + "*": "deny" + skill: + "*": "deny" +--- + +# StoryMapper + +> **Mission**: Transform user needs into actionable user journeys, epics, and stories aligned with bounded contexts and vertical slices. + + + User journey mapping and story decomposition subagent + Product planning, user experience design, and feature breakdown + Map user personas to journeys, identify vertical slices, and create epic/story hierarchies + Context-aware planning using ContextScout for discovery and ArchitectureAnalyzer outputs + + +Expert Story Mapper specializing in user journey mapping, persona identification, vertical slice architecture, and epic/story decomposition + +Transform user requirements into structured user journeys with epics and stories mapped to bounded contexts and vertical slices + + +BEFORE starting journey mapping, ALWAYS: + 1. Load context: `.opencode/context/core/task-management/navigation.md` + 2. If architecture analysis exists, load bounded context definitions + 3. If context is missing or unclear, delegate discovery to ContextScout + 4. Understand the domain and user personas before mapping journeys + +WHY THIS MATTERS: +- Journeys without domain context โ†’ Wrong user flows, misaligned features +- Stories without bounded contexts โ†’ Poor service boundaries, coupling issues +- Slices without architecture โ†’ Inefficient implementation, rework + + + + - You are STATELESS. Do not assume you know what happened in previous turns. + - If requirements or context are missing, request clarification or use ContextScout to fill gaps. + - Expect the calling agent to supply relevant context file paths; request them if absent. + - Use the task tool ONLY for ContextScout discovery. + - Your output (map.json) is your primary communication channel. + + + + - Load bounded context definitions from ArchitectureAnalyzer output if available + - Map stories to appropriate bounded contexts + - Identify cross-context dependencies + - Align vertical slices with service boundaries + + + + - Provide story breakdown that TaskManager can convert to subtasks + - Include acceptance criteria for each story + - Specify dependencies between stories + - Identify which stories can be implemented in parallel + + + + + + + + Load context and understand domain + + 1. Load task management context: + - `.opencode/context/core/task-management/navigation.md` + + 2. If architecture analysis exists, load: + - Bounded context definitions + - Service boundaries + - Domain models + + 3. If user personas exist, load: + - User persona definitions + - User goals and pain points + - User workflows + + 4. If context is insufficient, call ContextScout via task tool: + ```javascript + task( + subagent_type="ContextScout", + description="Find user journey mapping context", + prompt="Discover context files for user personas, domain models, and architecture patterns. Return relevant file paths and summaries." + ) + ``` + + Context loaded, domain understood + + + + Identify and define user personas + Context loaded (Stage 0 complete) + + 1. Analyze user requirements to identify distinct user types + 2. For each persona, define: + - Name and role (e.g., "Admin User", "End Customer") + - Goals and motivations + - Pain points and challenges + - Technical proficiency level + - Primary use cases + + 3. Validate personas: + - Each persona has distinct goals + - Personas cover all user types in requirements + - No overlapping or redundant personas + + 4. Document personas in structured format: + ```json + { + "id": "admin-user", + "name": "Admin User", + "role": "System Administrator", + "goals": ["Manage users", "Configure system", "Monitor activity"], + "pain_points": ["Complex configuration", "Lack of visibility"], + "technical_level": "high", + "primary_use_cases": ["user-management", "system-config"] + } + ``` + + User personas identified and documented + + + + Map user journeys for each persona + Personas identified (Stage 1 complete) + + 1. For each persona, identify key journeys: + - What are the main tasks this user needs to accomplish? + - What is the typical flow from start to finish? + - What are the decision points and branches? + + 2. For each journey, define: + - Journey name (e.g., "User Registration Flow") + - Persona (which user type) + - Steps (ordered sequence of actions) + - Touchpoints (UI screens, API calls, external systems) + - Success criteria (what defines completion) + - Edge cases and error scenarios + + 3. Identify journey dependencies: + - Which journeys must complete before others? + - Which journeys can run independently? + + 4. Document journeys in structured format: + ```json + { + "id": "user-registration", + "name": "User Registration Flow", + "persona": "end-customer", + "steps": [ + { + "id": "step-1", + "action": "Enter email and password", + "touchpoint": "Registration form", + "validation": ["Email format", "Password strength"] + }, + { + "id": "step-2", + "action": "Verify email", + "touchpoint": "Email verification link", + "validation": ["Token validity", "Expiration check"] + } + ], + "success_criteria": ["User account created", "Email verified", "Welcome email sent"], + "edge_cases": ["Duplicate email", "Invalid token", "Expired link"] + } + ``` + + User journeys mapped for all personas + + + + Identify vertical slices (end-to-end user flows) + Journeys mapped (Stage 2 complete) + + 1. Analyze journeys to identify vertical slices: + - A vertical slice is a complete end-to-end user flow + - It crosses all layers: UI โ†’ API โ†’ Business Logic โ†’ Data + - It delivers user value independently + + 2. For each vertical slice, define: + - Slice name (e.g., "User Login Slice") + - Journeys included (which user journeys does this slice support) + - Bounded contexts involved (which services/domains) + - Technical layers (frontend, backend, database, external APIs) + - Dependencies (what must exist before this slice can work) + + 3. Validate vertical slices: + - Each slice delivers independent user value + - Slices are small enough to implement in 1-2 weeks + - Slices align with bounded context boundaries + - Minimal cross-slice dependencies + + 4. Document vertical slices: + ```json + { + "id": "user-login-slice", + "name": "User Login Slice", + "journeys": ["user-login"], + "bounded_contexts": ["authentication"], + "layers": { + "frontend": ["Login form", "Session management"], + "backend": ["Auth API", "JWT service"], + "database": ["User table", "Session table"], + "external": ["Email service for password reset"] + }, + "dependencies": ["User registration slice"], + "estimated_effort": "1 week" + } + ``` + + Vertical slices identified and documented + + + + Break journeys into epics + Vertical slices identified (Stage 3 complete) + + 1. Group related journeys into epics: + - An epic is a large body of work that can be broken into stories + - Epics typically span multiple sprints + - Epics align with business objectives + + 2. For each epic, define: + - Epic name (e.g., "User Authentication") + - Description (what business value does this deliver) + - Journeys included (which user journeys) + - Vertical slices (which slices implement this epic) + - Bounded contexts (which services) + - Acceptance criteria (how do we know it's done) + - Priority (high, medium, low) + + 3. Validate epics: + - Each epic delivers clear business value + - Epics are independent (can be prioritized separately) + - All journeys are covered by at least one epic + + 4. Document epics: + ```json + { + "id": "epic-user-auth", + "name": "User Authentication", + "description": "Enable users to securely register, login, and manage their accounts", + "journeys": ["user-registration", "user-login", "password-reset"], + "vertical_slices": ["user-registration-slice", "user-login-slice"], + "bounded_contexts": ["authentication", "notification"], + "acceptance_criteria": [ + "Users can register with email/password", + "Users can login with credentials", + "Users can reset forgotten passwords", + "All auth flows use JWT tokens", + "Security best practices followed" + ], + "priority": "high", + "estimated_effort": "3 weeks" + } + ``` + + Epics defined and documented + + + + Break epics into user stories + Epics defined (Stage 4 complete) + + 1. For each epic, decompose into user stories: + - A story is a small, testable unit of work + - Stories follow format: "As a [persona], I want [goal] so that [benefit]" + - Stories are small enough to complete in 1-3 days + + 2. For each story, define: + - Story ID and title + - User story statement (As a... I want... so that...) + - Acceptance criteria (specific, testable conditions) + - Bounded context (which service implements this) + - Dependencies (which stories must complete first) + - Parallel flag (can this run in parallel with others) + - Estimated effort (story points or hours) + - Technical notes (implementation hints) + + 3. Map stories to bounded contexts: + - Use ArchitectureAnalyzer output if available + - Ensure stories align with service boundaries + - Identify cross-context dependencies + + 4. Identify story dependencies: + - Which stories must complete before others? + - Which stories can run in parallel? + - Are there any circular dependencies? + + 5. Document stories: + ```json + { + "id": "story-auth-001", + "title": "User can register with email and password", + "story": "As an end customer, I want to register with my email and password so that I can create an account", + "epic": "epic-user-auth", + "bounded_context": "authentication", + "acceptance_criteria": [ + "Registration form accepts email and password", + "Email format is validated", + "Password meets strength requirements (8+ chars, uppercase, number)", + "Duplicate emails are rejected with clear error", + "Successful registration creates user record", + "Verification email is sent", + "User is redirected to email verification page" + ], + "dependencies": [], + "parallel": true, + "estimated_effort": "2 days", + "technical_notes": "Use bcrypt for password hashing, JWT for tokens" + } + ``` + + Stories defined and mapped to bounded contexts + + + + Generate map.json output + Stories defined (Stage 5 complete) + + 1. Compile all mapping data into structured JSON: + - Personas + - Journeys + - Vertical slices + - Epics + - Stories + - Dependencies + - Bounded context mappings + + 2. Validate output: + - All stories have acceptance criteria + - All stories map to bounded contexts + - Dependencies are valid (no circular refs) + - Parallel flags are set correctly + - All journeys are covered by stories + + 3. Write map.json to output location: + ``` + .tmp/planning/{feature}/map.json + ``` + + 4. Generate summary report: + ``` + ## Story Mapping Complete + + Feature: {feature-name} + Output: .tmp/planning/{feature}/map.json + + Summary: + - {N} personas identified + - {N} user journeys mapped + - {N} vertical slices identified + - {N} epics defined + - {N} stories created + + Bounded Contexts: + - {context-1}: {N} stories + - {context-2}: {N} stories + + Next Steps: + - Review map.json for completeness + - Pass to TaskManager for subtask creation + - Prioritize epics for implementation + ``` + + map.json generated and validated + + + + + + + ```json + { + "feature": "string", + "created_at": "ISO timestamp", + "personas": [ + { + "id": "string", + "name": "string", + "role": "string", + "goals": ["string"], + "pain_points": ["string"], + "technical_level": "low | medium | high", + "primary_use_cases": ["string"] + } + ], + "journeys": [ + { + "id": "string", + "name": "string", + "persona": "string", + "steps": [ + { + "id": "string", + "action": "string", + "touchpoint": "string", + "validation": ["string"] + } + ], + "success_criteria": ["string"], + "edge_cases": ["string"] + } + ], + "vertical_slices": [ + { + "id": "string", + "name": "string", + "journeys": ["string"], + "bounded_contexts": ["string"], + "layers": { + "frontend": ["string"], + "backend": ["string"], + "database": ["string"], + "external": ["string"] + }, + "dependencies": ["string"], + "estimated_effort": "string" + } + ], + "epics": [ + { + "id": "string", + "name": "string", + "description": "string", + "journeys": ["string"], + "vertical_slices": ["string"], + "bounded_contexts": ["string"], + "acceptance_criteria": ["string"], + "priority": "high | medium | low", + "estimated_effort": "string" + } + ], + "stories": [ + { + "id": "string", + "title": "string", + "story": "As a [persona], I want [goal] so that [benefit]", + "epic": "string", + "bounded_context": "string", + "acceptance_criteria": ["string"], + "dependencies": ["string"], + "parallel": boolean, + "estimated_effort": "string", + "technical_notes": "string" + } + ], + "bounded_context_mapping": { + "context-name": { + "stories": ["string"], + "epics": ["string"], + "vertical_slices": ["string"] + } + } + } + ``` + + + + + + kebab-case (e.g., admin-user, end-customer) + kebab-case (e.g., user-registration, checkout-flow) + kebab-case with -slice suffix (e.g., user-login-slice) + epic- prefix (e.g., epic-user-auth, epic-payment) + story- prefix with context (e.g., story-auth-001) + + + + .tmp/planning/{feature}/ + map.json + + + + + As an admin user, I want to view all registered users so that I can manage the user base + + + + + + Each persona has unique goals and use cases + All user types in requirements are represented + No redundant or overlapping personas + + + + Each journey covers complete user flow from start to finish + Steps are specific and actionable + Common error scenarios are identified + + + + Each slice delivers user value independently + Slices are small enough to implement in 1-2 weeks + Slices respect service boundaries + + + + Each epic delivers clear business value + Epics can be prioritized and implemented separately + All journeys are covered by epics + + + + Stories are completable in 1-3 days with clear acceptance criteria + Stories follow "As a... I want... so that..." format + Each story maps to exactly one bounded context + Dependencies are explicit and non-circular + + + + + Context loaded, domain understood, personas identified + + Context loaded, domain understood + User personas identified and documented + User journeys mapped for all personas + Vertical slices identified and documented + Epics defined and documented + Stories defined and mapped to bounded contexts + map.json generated and validated + + + Every persona has at least one journey + Every journey is included in at least one epic + Every epic has at least one story + Every story maps to a bounded context + Dependency graph is acyclic + Stories that can run in parallel are marked + + + + + Always load context and understand domain before mapping + Start with user personas and their goals, not technical implementation + Identify end-to-end flows that deliver independent value + Map stories to service boundaries from architecture analysis + Make dependencies explicit and avoid circular references + Mark stories that can be implemented in parallel + Every story has specific, testable acceptance criteria + + + + + - Bounded context definitions + - Service boundaries + - Domain models + - Cross-context dependencies + + + + - Story breakdown with acceptance criteria + - Bounded context mappings + - Dependency graph + - Parallel execution flags + - Estimated effort + + + + Each story should map to exactly one bounded context + Cross-context dependencies should be minimized + Vertical slices should align with service boundaries + Stories within same bounded context can often run in parallel + + + + +Before generating map.json: +1. Verify all personas have journeys +2. Verify all journeys have stories +3. Verify all stories have acceptance criteria +4. Verify all stories map to bounded contexts +5. Verify dependency graph is acyclic +6. Verify parallel flags are set correctly +7. Report any inconsistencies found + diff --git a/.opencode/command/add-context.md b/.opencode/command/add-context.md index e823fa0..8d77991 100644 --- a/.opencode/command/add-context.md +++ b/.opencode/command/add-context.md @@ -520,8 +520,8 @@ Preview: technical-domain.md **Config**: package.json, tsconfig.json ## Related Files -- [Business Domain](business-domain.md) -- [Decisions Log](decisions-log.md) +- Business Domain (example: business-domain.md) +- Decisions Log (example: decisions-log.md) โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” @@ -566,7 +566,7 @@ Preview: navigation.md | File | Description | Priority | |------|-------------|----------| -| [technical-domain.md](technical-domain.md) | Tech stack & patterns | critical | +| technical-domain.md | Tech stack & patterns | critical | โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” ``` diff --git a/.opencode/command/openagents/new-agents/README.md b/.opencode/command/openagents/new-agents/README.md index 0884c5f..e46a3ec 100644 --- a/.opencode/command/openagents/new-agents/README.md +++ b/.opencode/command/openagents/new-agents/README.md @@ -378,7 +378,7 @@ npm test -- --agent=my-agent-name --test=planning-approval-001 For questions or issues: 1. Check existing agents: - Core agents: `.opencode/agent/core/openagent.md`, `.opencode/agent/core/opencoder.md` - - Development agents: `.opencode/agent/development/frontend-specialist.md` + - Development agents: `.opencode/agent/subagents/development/frontend-specialist.md` - Content agents: `.opencode/agent/content/copywriter.md` 2. Review test examples: `evals/agents/openagent/tests/` 3. See research docs: `docs/agents/research-backed-prompt-design.md` diff --git a/.opencode/command/openagents/new-agents/create-agent.md b/.opencode/command/openagents/new-agents/create-agent.md index 00c3e7c..0431fc4 100644 --- a/.opencode/command/openagents/new-agents/create-agent.md +++ b/.opencode/command/openagents/new-agents/create-agent.md @@ -468,6 +468,6 @@ Create a new agent with minimal, high-signal prompts following "right altitude" - `.opencode/agent/core/opencoder.md` - Development specialist example - `.opencode/agent/core/openagent.md` - Universal orchestrator example - - `.opencode/agent/development/frontend-specialist.md` - Category agent example + - `.opencode/agent/subagents/development/frontend-specialist.md` - Category agent example diff --git a/.opencode/command/prompt-engineering/prompt-enhancer.md b/.opencode/command/prompt-engineering/prompt-enhancer.md index b1e96f6..03bc752 100644 --- a/.opencode/command/prompt-engineering/prompt-enhancer.md +++ b/.opencode/command/prompt-engineering/prompt-enhancer.md @@ -173,10 +173,10 @@ description: "Research-backed prompt optimizer applying Stanford/Anthropic patte 5. Recalculate ratio, target 40-50% - Extract to .opencode/context/core/session-management.md - Extract to .opencode/context/core/context-discovery.md - Extract to .opencode/context/core/examples.md - Extract to .opencode/context/core/specifications.md + Extract to context file (example: .opencode/context/core/session-management.md) + Extract to context file (example: .opencode/context/core/context-discovery.md) + Extract to context file (example: .opencode/context/core/examples.md) + Extract to context file (example: .opencode/context/core/specifications.md) Instruction ratio 40-50%, external references created, functionality preserved @@ -478,8 +478,8 @@ description: "Research-backed prompt optimizer applying Stanford/Anthropic patte - - Detailed before/after metrics from OpenAgent optimization + + Detailed before/after metrics from OpenAgent optimization (example: .opencode/context/core/prompt-optimization-report.md) Validated patterns with model- and task-specific effectiveness improvements diff --git a/.opencode/command/prompt-engineering/prompt-optimizer.md b/.opencode/command/prompt-engineering/prompt-optimizer.md index fce2665..a6de0a8 100644 --- a/.opencode/command/prompt-engineering/prompt-optimizer.md +++ b/.opencode/command/prompt-engineering/prompt-optimizer.md @@ -274,10 +274,10 @@ description: "Advanced prompt optimizer: Research patterns + token efficiency + 5. Recalculate ratio, target 40-50% - session_managementโ†’.opencode/context/core/session-management.md - context_discoveryโ†’.opencode/context/core/context-discovery.md - detailed_examplesโ†’.opencode/context/core/examples.md - implementation_specsโ†’.opencode/context/core/specifications.md + session_managementโ†’(example: .opencode/context/core/session-management.md) + context_discoveryโ†’(example: .opencode/context/core/context-discovery.md) + detailed_examplesโ†’(example: .opencode/context/core/examples.md) + implementation_specsโ†’(example: .opencode/context/core/specifications.md) Instruction ratio 40-50%, external refs created, functionality preserved @@ -678,8 +678,8 @@ description: "Advanced prompt optimizer: Research patterns + token efficiency + - - Detailed before/after metrics from OpenAgent optimization + + Detailed before/after metrics from OpenAgent optimization (example: .opencode/context/core/prompt-optimization-report.md) Validated patterns w/ model/task-specific effectiveness improvements diff --git a/.opencode/context/CODEBASE_STANDARDS.md b/.opencode/context/CODEBASE_STANDARDS.md new file mode 100644 index 0000000..0087a5f --- /dev/null +++ b/.opencode/context/CODEBASE_STANDARDS.md @@ -0,0 +1,3795 @@ + + +# OpenCode Codebase Standards + +**Complete Reference Guide** +_Last Updated: Feb 2026_ +_Analyzed: 206+ TypeScript files across `packages/opencode/src/`_ + +--- + +## Table of Contents + +1. [Function Definition Standards](#1-function-definition-standards) +2. [Class Usage Standards](#2-class-usage-standards) +3. [Array Handling Standards](#3-array-handling-standards) +4. [Variable & Destructuring Standards](#4-variable--destructuring-standards) +5. [Control Flow Standards](#5-control-flow-standards) +6. [Async & Concurrency Standards](#6-async--concurrency-standards) +7. [Race Condition Prevention](#7-race-condition-prevention) +8. [AI System Integration Standards](#8-ai-system-integration-standards) +9. [Service Architecture Standards](#9-service-architecture-standards) +10. [State Management Standards](#10-state-management-standards) +11. [Event Bus Standards](#11-event-bus-standards) +12. [Configuration Management Standards](#12-configuration-management-standards) +13. [Storage & Persistence Standards](#13-storage--persistence-standards) +14. [Error Handling Standards](#14-error-handling-standards) +15. [Type System Standards](#15-type-system-standards) +16. [Import Organization Standards](#16-import-organization-standards) +17. [Naming Conventions](#17-naming-conventions) +18. [Testing Standards](#18-testing-standards) +19. [Documentation Standards](#19-documentation-standards) +20. [Schema Definition Standards](#20-schema-definition-standards) +21. [Dependency Management Standards](#21-dependency-management-standards) +22. [Build & Development Standards](#22-build--development-standards) +23. [Performance Standards](#23-performance-standards) +24. [Security Standards](#24-security-standards) + +--- + +## 1. Function Definition Standards + +### 1.1 Naming Convention + +**Rule: Prefer single-word function names** + +**Compliance: 95%+** + +```typescript +// โœ… GOOD - Single-word names +export const create = fn(...) +export const fork = fn(...) +export const touch = fn(...) +export const get = fn(...) +export const share = fn(...) +export async function stream(input: StreamInput) {...} +export async function work(concurrency, items, fn) {...} + +// โœ… ACCEPTABLE - Multi-word only when necessary +export function isDefaultTitle(title: string) {...} // Boolean predicate +export function assertNotBusy(sessionID: string) {...} // Assertion pattern +export async function createNext(input) {...} // Version disambiguation +export async function resolvePromptParts(template) {...} // Complex operation needs clarity + +// โŒ AVOID - Unnecessary multi-word names +function prepareJournal(dir: string) {} // Use: journal() +function getUserData(id: string) {} // Use: user() +function processFileContent(path) {} // Use: process() +``` + +**File References:** + +- `packages/opencode/src/session/index.ts` - Lines 140, 200, 206 +- `packages/opencode/src/session/llm.ts` - Line 59 +- `packages/opencode/src/util/queue.ts` - Lines 1-32 + +### 1.2 Function Definition Patterns + +#### Pattern A: Zod-Validated Functions (Primary Pattern) + +```typescript +// packages/opencode/src/util/fn.ts - The fn() wrapper +export function fn(schema: T, cb: (input: z.infer) => Result) { + const result = (input: z.infer) => { + const parsed = schema.parse(input) // Validates input + return cb(parsed) + } + result.force = (input: z.infer) => cb(input) // Skip validation + result.schema = schema // Expose schema + return result +} + +// Usage Example 1: Session creation +export const create = fn( + z + .object({ + parentID: Identifier.schema("session").optional(), + title: z.string().optional(), + permission: Info.shape.permission, + }) + .optional(), + async (input) => { + return createNext({ + parentID: input?.parentID, + title: input?.title, + permission: input?.permission ?? "allow", + }) + }, +) + +// Usage Example 2: Simple validation +export const touch = fn(Identifier.schema("session"), async (sessionID) => { + await update(sessionID, (draft) => { + draft.time.updated = Date.now() + }) +}) + +// Usage Example 3: Complex object validation +export const messages = fn( + z.object({ + sessionID: Identifier.schema("session"), + limit: z.number().optional(), + }), + async (input) => { + const result = [] as MessageV2.WithParts[] + for await (const msg of MessageV2.stream(input.sessionID)) { + if (input.limit && result.length >= input.limit) break + result.push(msg) + } + result.reverse() + return result + }, +) +``` + +**File References:** + +- `packages/opencode/src/util/fn.ts` - Lines 1-12 +- `packages/opencode/src/session/index.ts` - Lines 140-202 + +#### Pattern B: Namespace Organization (Preferred over Classes) + +```typescript +// packages/opencode/src/session/index.ts +export namespace Session { + const log = Log.create({ service: "session" }) + + // Exported functions with fn() wrapper + export const create = fn(...) + export const fork = fn(...) + export const touch = fn(...) + export const messages = fn(...) + + // Async functions without wrapper + export async function createNext(input) {...} + export async function update(id, editor, options) {...} + + // Type definitions + export type Info = z.infer + export const Info = z.object({...}) + + // Events + export const Event = { + Created: BusEvent.define("session.created", z.object({info: Info})), + Updated: BusEvent.define("session.updated", z.object({info: Info})), + } + + // Error classes (only exception to no-class rule) + export class BusyError extends Error { + constructor(public readonly sessionID: string) { + super(`Session ${sessionID} is busy`) + } + } +} + +// Usage +await Session.create({ title: "New Session" }) +await Session.touch(sessionID) +const msgs = await Session.messages({ sessionID, limit: 10 }) +``` + +**File References:** + +- `packages/opencode/src/session/index.ts` - Lines 26-518 +- `packages/opencode/src/tool/tool.ts` - Lines 1-90 +- `packages/opencode/src/session/processor.ts` - Lines 19-416 + +#### Pattern C: Inline vs. Extraction Rule + +**Rule: Inline when used once, extract when composable/reusable** + +```typescript +// โœ… GOOD - Inline when value used once +const journal = await Bun.file(path.join(dir, "journal.json")).json() +const [language, cfg] = await Promise.all([Provider.getLanguage(input.model), Config.get()]) + +// โŒ BAD - Unnecessary intermediate variable +const journalPath = path.join(dir, "journal.json") +const journalFile = Bun.file(journalPath) +const journal = await journalFile.json() + +// โœ… GOOD - Extract when reusable across multiple call sites +async function resolveTools(input: Pick) { + const disabled = PermissionNext.disabled(Object.keys(input.tools), input.agent.permission) + for (const tool of Object.keys(input.tools)) { + if (input.user.tools?.[tool] === false || disabled.has(tool)) { + delete input.tools[tool] + } + } + return input.tools +} + +// Called from multiple locations +const tools = await resolveTools({ tools: input.tools, agent, user }) + +// โœ… GOOD - Extract when logic is complex and improves readability +function shouldUseCopilotResponsesApi(modelID: string): boolean { + const match = /^gpt-(\d+)/.exec(modelID) + if (!match) return false + return Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini") +} +``` + +**File References:** + +- `packages/opencode/src/session/llm.ts` - Lines 59, 268-276 +- `packages/opencode/src/provider/provider.ts` - Lines 46-56 + +### 1.3 Function Composition Patterns + +```typescript +// โœ… GOOD - Functional composition with pipes +const filtered = agents + .filter((a) => a.mode !== "primary") + .filter((a) => PermissionNext.evaluate("task", a.name, caller.permission).action !== "deny") + .map((a) => a.name) + +// โœ… GOOD - Async composition with Promise.all +const [results, metadata] = await Promise.all([processItems(items), fetchMetadata(id)]) + +// โœ… GOOD - Higher-order functions +export function withLock(filepath: string, fn: () => Promise): Promise { + return Lock.write(filepath).then(async (lock) => { + try { + return await fn() + } finally { + lock[Symbol.dispose]() + } + }) +} +``` + +--- + +## 2. Class Usage Standards + +### 2.1 Avoid Classes (Except Specific Patterns) + +**Finding: Only 5 classes in 206 files** + +**Rule: Use namespaces + functions instead of classes** + +```typescript +// โŒ AVOID - Class-based organization +class SessionManager { + private sessions: Map = new Map() + + create(input: CreateInput) { + const session = { id: generateId(), ...input } + this.sessions.set(session.id, session) + return session + } + + update(id: string, data: Partial) { + const session = this.sessions.get(id) + if (!session) throw new Error("Not found") + Object.assign(session, data) + return session + } +} + +// โœ… PREFER - Namespace-based organization +export namespace Session { + const state = Instance.state(async () => ({ + sessions: new Map() + })) + + export const create = fn( + CreateInput.schema, + async (input) => { + const session = { id: Identifier.ascending("session"), ...input } + state().sessions.set(session.id, session) + return session + } + ) + + export const update = fn( + z.object({ id: z.string(), data: z.record(z.unknown()) }), + async (input) => { + const session = state().sessions.get(input.id) + if (!session) throw NotFoundError.create({...}) + Object.assign(session, input.data) + return session + } + ) +} +``` + +### 2.2 Allowed Class Use Cases + +#### Use Case 1: Error Types + +```typescript +// โœ… GOOD - Custom error classes +export class BusyError extends Error { + constructor(public readonly sessionID: string) { + super(`Session ${sessionID} is busy`) + } +} + +// Usage +throw new BusyError(sessionID) + +// Catching +try { + await operation() +} catch (error) { + if (error instanceof BusyError) { + // Handle busy state + } +} +``` + +**File Reference:** `packages/opencode/src/session/index.ts:494` + +#### Use Case 2: Protocol Implementations + +```typescript +// โœ… GOOD - Implementing external interfaces +export class OpenAICompatibleChatLanguageModel implements LanguageModelV2 { + readonly specificationVersion = "v2" + readonly provider: string + readonly modelId: string + + constructor(modelId: string, settings: ModelSettings) { + this.modelId = modelId + this.provider = settings.provider + } + + async doGenerate(options: GenerateOptions): Promise { + // Implementation required by interface + } + + async doStream(options: StreamOptions): AsyncIterableIterator { + // Implementation required by interface + } +} + +// โœ… GOOD - OAuth protocol implementation +export class McpOAuthProvider implements OAuthClientProvider { + async getAccessToken(): Promise { + // OAuth flow implementation + } +} +``` + +**File References:** + +- `packages/opencode/src/provider/sdk/*` - Lines 53, 131 +- `packages/opencode/src/mcp/oauth-provider.ts:26` + +#### Use Case 3: Async Iterators + +```typescript +// โœ… GOOD - AsyncIterable implementation +export class AsyncQueue implements AsyncIterable { + private queue: T[] = [] + private resolvers: ((value: T) => void)[] = [] + + push(item: T) { + const resolve = this.resolvers.shift() + if (resolve) { + resolve(item) + } else { + this.queue.push(item) + } + } + + async next(): Promise { + if (this.queue.length > 0) { + return this.queue.shift()! + } + return new Promise((resolve) => { + this.resolvers.push(resolve) + }) + } + + async *[Symbol.asyncIterator]() { + while (true) { + yield await this.next() + } + } +} + +// Usage +const queue = new AsyncQueue() +queue.push(message) + +for await (const msg of queue) { + console.log(msg) +} +``` + +**File Reference:** `packages/opencode/src/util/queue.ts:1-19` + +#### Use Case 4: Complex Stateful Managers + +```typescript +// โœ… ACCEPTABLE - When managing complex state machines +export class ACPSessionManager { + private sessions: Map + private connections: Map + + // Complex lifecycle management + async createSession(id: string) {...} + async handleMessage(id: string, msg: Message) {...} + async closeSession(id: string) {...} + + // State machine logic + private transition(from: State, to: State) {...} +} +``` + +**File Reference:** `packages/opencode/src/acp/session.ts:8` + +--- + +## 3. Array Handling Standards + +### 3.1 Functional Methods (85% of operations) + +**Rule: Prefer map/filter/flatMap over for-loops** + +```typescript +// โœ… GOOD - Functional chain with type inference +const files = messages + .flatMap((x) => x.parts) + .filter((x): x is Patch => x.type === "patch") // Type guard maintains inference + .flatMap((x) => x.files) + .map((x) => path.relative(Instance.worktree, x)) + +// โœ… GOOD - Parallel async operations +const results = await Promise.all( + toolCalls.map(async (call) => { + return executeCall(call) + }), +) + +// โœ… GOOD - Reduce for aggregation +const totalAdditions = diffs.reduce((sum, x) => sum + x.additions, 0) + +// โœ… GOOD - Filter with type guards +const agents = await Agent.list().then((x) => x.filter((a): a is Agent & { mode: "secondary" } => a.mode !== "primary")) + +// โœ… GOOD - Unique values +const uniqueNames = Array.from(new Set(items.map((x) => x.name))) + +// โœ… GOOD - Sorting +const sorted = items.toSorted((a, b) => a.timestamp - b.timestamp) +``` + +**File References:** + +- `packages/opencode/src/tool/batch.ts` - Lines 41, 56, 80, 170 +- `packages/opencode/src/session/prompt.ts` - Lines 192-200 +- `packages/opencode/src/session/summary.ts` - Lines 96-109 + +### 3.2 For-Loops (15%, only when necessary) + +**Rule: Use for-loops only for:** + +1. Algorithm complexity (DP, graph traversal) +2. Early exit requirements +3. Sequential side effects +4. Performance-critical iteration + +#### Pattern 1: Algorithm Complexity + +```typescript +// โœ… GOOD - Dynamic programming (LCS algorithm) +// packages/opencode/src/tool/edit.ts:175-176 +function lcs(a: string[], b: string[]): number[][] { + const dp: number[][] = Array(a.length + 1) + .fill(0) + .map(() => Array(b.length + 1).fill(0)) + + for (let i = 1; i <= a.length; i++) { + for (let j = 1; j <= b.length; j++) { + if (a[i - 1] === b[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1 + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) + } + } + } + + return dp +} +``` + +#### Pattern 2: Early Exit + +```typescript +// โœ… GOOD - Break on condition +// packages/opencode/src/session/revert.ts:31-40 +const patches = [] +for (const msg of all) { + if (msg.info.id === revert.messageID) break + for (const part of msg.parts) { + if (part.type === "patch") { + patches.push(part) + } + } +} + +// โœ… GOOD - Find first match +for (const file of files) { + if (await Filesystem.exists(file)) { + return file + } +} +``` + +#### Pattern 3: Sequential Side Effects + +```typescript +// โœ… GOOD - Sequential mutations +for (const key of Object.keys(input.tools)) { + if (input.user.tools?.[key] === false || disabled.has(key)) { + delete input.tools[key] + } +} + +// โœ… GOOD - Streaming output +for (const line of lines) { + await stream.write(line) +} +``` + +**File Reference:** `packages/opencode/src/tool/grep.ts:77` + +#### Pattern 4: Performance Critical + +```typescript +// โœ… GOOD - Low-level iteration for performance +for (let i = 0; i < buffer.length; i++) { + result += buffer[i] * multiplier +} + +// Note: Profile before optimizing - functional methods are often fast enough +``` + +### 3.3 Type Guards on Filter + +**Rule: Use type guards to maintain type inference downstream** + +```typescript +// โœ… GOOD - Type guard preserves type information +const patches = messages.flatMap((msg) => msg.parts).filter((part): part is PatchPart => part.type === "patch") +// patches is now PatchPart[], not Part[] + +// โŒ BAD - Loses type information +const patches = messages.flatMap((msg) => msg.parts).filter((part) => part.type === "patch") +// patches is still Part[], requires casting later + +// โœ… GOOD - Multiple type guards +const validAgents = agents + .filter((a): a is Agent => a !== undefined) + .filter((a): a is Agent & { mode: "secondary" } => a.mode !== "primary") +``` + +**File Reference:** `packages/opencode/src/tool/task.ts:24,29` + +--- + +## 4. Variable & Destructuring Standards + +### 4.1 Variable Declaration + +**Rule: Prefer `const` over `let`** + +```typescript +// โœ… GOOD - Immutable with ternary +const foo = condition ? 1 : 2 +const result = await (isValid ? processValid() : processInvalid()) + +// โŒ BAD - Reassignment +let foo +if (condition) { + foo = 1 +} else { + foo = 2 +} + +// โœ… GOOD - Early return instead of reassignment +function getValue(condition: boolean) { + if (condition) return 1 + return 2 +} + +// โœ… ACCEPTABLE - let when mutation is necessary +let accumulator = 0 +for (const item of items) { + accumulator += item.value +} +``` + +**File Reference:** `AGENTS.md:56-68` + +### 4.2 Destructuring + +**Rule: Avoid unnecessary destructuring, preserve context with dot notation** + +```typescript +// โœ… GOOD - Preserve context +function process(session: Session) { + log.info("processing", { id: session.id, title: session.title }) + return { + id: session.id, + status: session.status, + owner: session.owner + } +} + +// โŒ BAD - Loses context, harder to read +function process(session: Session) { + const { id, title, status, owner } = session + log.info("processing", { id, title }) + return { id, status, owner } +} + +// โœ… ACCEPTABLE - Destructuring when improving readability +function renderUser({ name, email, avatar }: User) { + return `
${name} (${email})
` +} + +// โœ… ACCEPTABLE - Destructuring array returns +const [language, cfg, provider] = await Promise.all([...]) +``` + +**File Reference:** `AGENTS.md:43-54` + +### 4.3 Variable Naming + +**Rule: Concise single-word names when descriptive** + +```typescript +// โœ… GOOD +const session = await Session.get(id) +const user = await Auth.current() +const messages = await Session.messages({ sessionID }) + +// โŒ BAD - Unnecessary verbosity +const currentSession = await Session.get(id) +const currentlyAuthenticatedUser = await Auth.current() +const sessionMessagesList = await Session.messages({ sessionID }) + +// โœ… GOOD - Multi-word when single word is ambiguous +const sessionID = params.id +const userAgent = req.headers["user-agent"] +const maxRetries = config.retries +``` + +--- + +## 5. Control Flow Standards + +### 5.1 Early Returns + +**Rule: Avoid `else` statements, use early returns** + +```typescript +// โœ… GOOD - Early returns +function getStatus(session: Session) { + if (!session) return "not_found" + if (session.busy) return "busy" + if (session.error) return "error" + return "ready" +} + +async function process(id: string) { + const session = await Session.get(id) + if (!session) return { error: "Not found" } + + const result = await execute(session) + if (!result.success) return { error: result.message } + + return { data: result.data } +} + +// โŒ BAD - Else statements +function getStatus(session: Session) { + if (!session) { + return "not_found" + } else { + if (session.busy) { + return "busy" + } else { + if (session.error) { + return "error" + } else { + return "ready" + } + } + } +} +``` + +**File Reference:** `AGENTS.md:70-86` + +### 5.2 Guard Clauses + +```typescript +// โœ… GOOD - Guard clauses at function start +async function updateSession(id: string, data: UpdateData) { + if (!id) throw new Error("ID required") + if (!data) throw new Error("Data required") + if (data.title && data.title.length > 100) throw new Error("Title too long") + + // Main logic here + const session = await Session.get(id) + await Session.update(id, data) + return session +} +``` + +### 5.3 Switch Statements + +**Rule: Use exhaustive switch with default case** + +```typescript +// โœ… GOOD - Exhaustive switch for stream handling +for await (const value of stream.fullStream) { + switch (value.type) { + case "reasoning-start": + reasoningMap[value.id] = { id: generateId(), type: "reasoning", text: "" } + break + + case "reasoning-delta": + if (value.id in reasoningMap) { + reasoningMap[value.id].text += value.text + await Session.updatePart({ delta: value.text }) + } + break + + case "tool-call": + await Session.updatePart({ state: { status: "running" } }) + break + + case "tool-result": + await Session.updatePart({ state: { status: "completed" } }) + break + + default: + const _exhaustive: never = value + throw new Error(`Unhandled type: ${(value as any).type}`) + } +} +``` + +**File Reference:** `packages/opencode/src/session/processor.ts:53-346` + +--- + +## 6. Async & Concurrency Standards + +### 6.1 Parallel Execution (Default Pattern) + +**Rule: Use `Promise.all` for independent operations** + +```typescript +// โœ… GOOD - Parallel independent operations +const [language, cfg, provider, auth] = await Promise.all([ + Provider.getLanguage(input.model), + Config.get(), + Provider.getProvider(input.model.providerID), + Auth.get(input.model.providerID), +]) + +// โœ… GOOD - Parallel array processing +const results = await Promise.all( + items.map(async (item) => { + return processItem(item) + }), +) + +// โŒ BAD - Sequential when independent +const language = await Provider.getLanguage(input.model) +const cfg = await Config.get() // Could run in parallel! +const provider = await Provider.getProvider(input.model.providerID) +const auth = await Auth.get(input.model.providerID) +``` + +**File Reference:** `packages/opencode/src/session/llm.ts:59` + +### 6.2 Sequential Operations + +**Rule: Chain when operations depend on previous results** + +```typescript +// โœ… GOOD - Sequential dependency chain +const session = await Session.create({ title: "New" }) +const message = await Session.addMessage(session.id, { content: "Hello" }) +const response = await LLM.stream({ sessionID: session.id, messageID: message.id }) + +// โœ… GOOD - Promise chain for clarity +const result = await Session.create({ title: "New" }) + .then((session) => Session.addMessage(session.id, { content: "Hello" })) + .then((message) => LLM.stream({ messageID: message.id })) +``` + +### 6.3 Error Handling in Async + +**Rule: Prefer `.catch()` over try/catch when possible** + +```typescript +// โœ… GOOD - Catch at call site +const result = await operation().catch((error) => { + log.error("Operation failed", { error }) + return defaultValue +}) + +// โœ… GOOD - Promise.all with error handling +const results = await Promise.all( + items.map(async (item) => { + return processItem(item).catch((error) => { + log.error("Item failed", { item, error }) + return null + }) + }), +) + +// โœ… ACCEPTABLE - try/catch for multiple operations +try { + const session = await Session.create(input) + await Session.addMessage(session.id, message) + await EventBus.publish(Session.Event.Created, { session }) + return session +} catch (error) { + log.error("Session creation failed", { error }) + throw error +} + +// โŒ AVOID - try/catch for single operation +try { + const result = await operation() + return result +} catch (error) { + log.error(error) + throw error +} +// Better: +const result = await operation().catch((error) => { + log.error(error) + throw error +}) +``` + +### 6.4 Concurrent Worker Pattern + +```typescript +// โœ… GOOD - Controlled concurrency +export async function work(concurrency: number, items: T[], fn: (item: T) => Promise) { + const pending = [...items] + + await Promise.all( + Array.from({ length: concurrency }, async () => { + while (true) { + const item = pending.pop() + if (item === undefined) return + await fn(item) + } + }), + ) +} + +// Usage +await work(3, files, async (file) => { + await processFile(file) +}) +``` + +**File Reference:** `packages/opencode/src/util/queue.ts:21-32` + +--- + +## 7. Race Condition Prevention + +### 7.1 Reader-Writer Lock (Storage Operations) + +```typescript +// packages/opencode/src/util/lock.ts +export namespace Lock { + const locks = new Map< + string, + { + readers: number + writer: boolean + waitingReaders: (() => void)[] + waitingWriters: (() => void)[] + } + >() + + export async function read(key: string): Promise { + const lock = get(key) + return new Promise((resolve) => { + // Writers get priority + if (!lock.writer && lock.waitingWriters.length === 0) { + lock.readers++ + resolve({ + [Symbol.dispose]: () => { + lock.readers-- + process(key) + }, + }) + } else { + lock.waitingReaders.push(() => { + lock.readers++ + resolve({ + [Symbol.dispose]: () => { + lock.readers-- + process(key) + }, + }) + }) + } + }) + } + + export async function write(key: string): Promise { + const lock = get(key) + return new Promise((resolve) => { + if (!lock.writer && lock.readers === 0) { + lock.writer = true + resolve({ + [Symbol.dispose]: () => { + lock.writer = false + process(key) + }, + }) + } else { + lock.waitingWriters.push(() => { + lock.writer = true + resolve({ + [Symbol.dispose]: () => { + lock.writer = false + process(key) + }, + }) + }) + } + }) + } +} + +// Usage with disposable pattern +export async function read(target: string): Promise { + using _ = await Lock.read(target) // Auto-releases on scope exit + const file = Bun.file(target) + if (!(await file.exists())) { + throw NotFoundError.create({ message: `File not found: ${target}` }) + } + return file.json() +} + +export async function write(target: string, data: any): Promise { + using _ = await Lock.write(target) // Auto-releases on scope exit + const dir = path.dirname(target) + await fs.mkdir(dir, { recursive: true }) + await Bun.write(target, JSON.stringify(data, null, 2)) +} +``` + +**File References:** + +- `packages/opencode/src/util/lock.ts` - Lines 1-99 +- `packages/opencode/src/storage/storage.ts` - Lines 173, 183, 195 + +### 7.2 File-Level Lock (Edit Operations) + +```typescript +// packages/opencode/src/file/time.ts +export async function withLock(filepath: string, fn: () => Promise): Promise { + const current = state() + const currentLock = current.locks.get(filepath) ?? Promise.resolve() + + let release: () => void = () => {} + const nextLock = new Promise((resolve) => { + release = resolve + }) + + const chained = currentLock.then(() => nextLock) + current.locks.set(filepath, chained) + + await currentLock // Wait for previous lock + + try { + return await fn() + } finally { + release() + if (current.locks.get(filepath) === chained) { + current.locks.delete(filepath) + } + } +} + +// Usage: Atomic read-modify-write +await FileTime.withLock(filePath, async () => { + const contentOld = await Bun.file(filePath).text() + const contentNew = replace(contentOld, params.oldString, params.newString) + await Bun.write(filePath, contentNew) + await FileTime.touch(filePath) +}) +``` + +**File References:** + +- `packages/opencode/src/file/time.ts` - Lines 35-53 +- `packages/opencode/src/tool/edit.ts` - Line 50 + +### 7.3 Mutex Pattern + +```typescript +// โœ… GOOD - Simple mutex for critical sections +const mutexes = new Map>() + +async function withMutex(key: string, fn: () => Promise): Promise { + const current = mutexes.get(key) ?? Promise.resolve() + + let release: () => void + const next = new Promise((resolve) => { + release = resolve + }) + mutexes.set(key, next) + + await current + + try { + return await fn() + } finally { + release!() + if (mutexes.get(key) === next) { + mutexes.delete(key) + } + } +} + +// Usage +await withMutex(`session:${sessionID}`, async () => { + // Critical section - only one execution at a time + const session = await Session.get(sessionID) + session.busy = true + await Session.save(session) +}) +``` + +### 7.4 Debouncing & Throttling + +```typescript +// โœ… GOOD - Debounce for file watching +function debounce any>(fn: T, delay: number): (...args: Parameters) => void { + let timer: Timer | undefined + + return (...args: Parameters) => { + if (timer) clearTimeout(timer) + timer = setTimeout(() => { + fn(...args) + timer = undefined + }, delay) + } +} + +// Usage in file watcher +const debouncedUpdate = debounce((file: string) => { + Bus.publish(FileWatcher.Event.Updated, { file }) +}, 100) + +watcher.on("change", (file) => { + debouncedUpdate(file) +}) +``` + +--- + +## 8. AI System Integration Standards + +### 8.1 Message Context Management + +```typescript +// packages/opencode/src/session/message-v2.ts + +export type Part = TextPart | FilePart | PatchPart | ToolCallPart | ToolResultPart | ReasoningPart + +export interface WithParts { + info: Info + parts: Part[] +} + +// Convert internal message format to LLM format +export function toModelMessages(input: WithParts[], model: Provider.Model): ModelMessage[] { + return input.flatMap((msg): ModelMessage[] => { + if (msg.info.role === "user") { + return [ + { + role: "user", + content: msg.parts.map((part) => { + if (part.type === "text") { + return { type: "text", text: part.text } + } + if (part.type === "file") { + return { + type: "file", + data: part.data, + mimeType: part.mimeType, + } + } + if (part.type === "patch") { + return { + type: "text", + text: formatPatch(part), + } + } + // ... handle other types + }), + }, + ] + } + + if (msg.info.role === "assistant") { + return [ + { + role: "assistant", + content: msg.parts + .filter((p) => p.type === "text" || p.type === "reasoning") + .map((p) => ({ type: "text", text: p.text })), + }, + ] + } + + // Handle tool results... + return [] + }) +} +``` + +**File Reference:** `packages/opencode/src/session/message-v2.ts:438-500` + +### 8.2 System Prompt Construction + +```typescript +// packages/opencode/src/session/llm.ts + +export async function stream(input: StreamInput) { + const system: string[] = [] + + // Part 1: Base system prompt (cached) + const header = [ + // Agent prompt OR provider prompt + ...(input.agent.prompt ? [input.agent.prompt] : isCodex ? [] : SystemPrompt.provider(input.model)), + // Custom prompt from request + ...input.system, + // Custom prompt from user config + ...(input.user.system ? [input.user.system] : []), + ] + .filter(Boolean) + .join("\n") + + system.push(header) + + // Part 2: Dynamic context (not cached) + const dynamicContext = [ + `Working directory: ${Instance.directory}`, + `Current date: ${new Date().toISOString()}`, + // ... other dynamic info + ].join("\n") + + system.push(dynamicContext) + + // Allow plugins to transform system prompt + const original = clone(system) + await Plugin.trigger( + "experimental.chat.system.transform", + { + model: input.model, + agent: input.agent, + }, + { system }, + ) + + // Optimize for prompt caching: maintain 2-part structure if header unchanged + if (system.length > 2 && system[0] === header) { + const rest = system.slice(1) + system.length = 0 + system.push(header, rest.join("\n")) + } + + // Convert to LLM messages + const messages = [ + ...system.map((text) => ({ role: "system", content: text })), + ...toModelMessages(input.messages, input.model), + ] + + return language.doStream({ + model: input.model.id, + messages, + tools: await resolveTools(input), + }) +} +``` + +**File Reference:** `packages/opencode/src/session/llm.ts:67-97` + +### 8.3 Tool Definition & Execution + +```typescript +// packages/opencode/src/tool/tool.ts + +export namespace Tool { + export interface Info { + id: string + title: string + description: string + parameters: z.ZodType + metadata?: Metadata + + execute(args: Parameters, context: Context): Promise + } + + export interface Context { + sessionID: string + messageID: string + agent: string + abort: AbortSignal + messages: () => Promise + metadata: (key: string, value: T) => Promise + ask: (question: Question) => Promise + } + + export type ExecuteResult = { + output?: string + title?: string + metadata?: Record + } + + export function define( + id: string, + init: { + title: string + description: string + parameters: z.ZodType + execute: (args: Parameters, context: Context) => Promise + }, + ): Info { + return { + id, + ...init, + } + } +} + +// Usage: Define a tool +export const ReadTool = Tool.define("read", { + title: "Read File", + description: "Read contents of a file from the filesystem", + parameters: z.object({ + filePath: z.string().describe("Absolute path to file"), + offset: z.number().optional().describe("Line number to start reading"), + limit: z.number().optional().describe("Number of lines to read"), + }), + + async execute(args, context) { + await context.ask({ + type: "permission", + message: `Read file ${args.filePath}?`, + actions: ["allow", "deny"], + }) + + const content = await Bun.file(args.filePath).text() + const lines = content.split("\n") + + const start = args.offset ?? 0 + const end = args.limit ? start + args.limit : lines.length + const selected = lines.slice(start, end) + + return { + output: selected.join("\n"), + title: `Read ${path.basename(args.filePath)}`, + metadata: { + lineCount: selected.length, + filePath: args.filePath, + }, + } + }, +}) + +// Register tool +await ToolRegistry.register(ReadTool) + +// Tool execution in session +const tools = await ToolRegistry.tools({ agent: input.agent }) + +const toolMap = tools.reduce( + (acc, tool) => { + acc[tool.id] = vercelAiTool({ + description: tool.description, + parameters: zodToJsonSchema(tool.parameters), + execute: async (args) => { + const result = await tool.execute(args, { + sessionID: input.sessionID, + messageID: input.messageID, + agent: input.agent.name, + abort: input.abort, + messages: () => Session.messages({ sessionID: input.sessionID }), + metadata: async (key, value) => { + await Session.updatePart({ + messageID: input.messageID, + metadata: { [key]: value }, + }) + }, + ask: async (question) => { + return new Promise((resolve) => { + Bus.publish(Session.Event.Question, { + sessionID: input.sessionID, + question, + respond: resolve, + }) + }) + }, + }) + + return result.output + }, + }) + return acc + }, + {} as Record, +) +``` + +**File References:** + +- `packages/opencode/src/tool/tool.ts` - Lines 1-90 +- `packages/opencode/src/session/prompt.ts` - Lines 711-748 + +### 8.4 Streaming Handling + +```typescript +// packages/opencode/src/session/processor.ts + +export function create(input: CreateInput) { + const reasoningMap: Record = {} + const toolcalls: Record = {} + + return { + async process() { + const stream = await LLM.stream({ + sessionID: input.sessionID, + messageID: input.messageID, + model: input.model, + messages: input.messages, + tools: input.tools, + abort: input.abort, + }) + + // Handle stream events + for await (const value of stream.fullStream) { + input.abort.throwIfAborted() + + switch (value.type) { + case "reasoning-start": + reasoningMap[value.id] = { + id: Identifier.ascending("part"), + type: "reasoning", + text: "", + time: { start: Date.now() }, + } + await Session.addPart({ + messageID: input.messageID, + part: reasoningMap[value.id], + }) + break + + case "reasoning-delta": + if (value.id in reasoningMap) { + const part = reasoningMap[value.id] + part.text += value.text + await Session.updatePart({ + messageID: input.messageID, + partID: part.id, + delta: value.text, + }) + } + break + + case "reasoning-finish": + if (value.id in reasoningMap) { + const part = reasoningMap[value.id] + part.time.end = Date.now() + await Session.updatePart({ + messageID: input.messageID, + partID: part.id, + part, + }) + } + break + + case "text-delta": + // Handle text streaming... + break + + case "tool-call": + const toolPart: ToolCallPart = { + id: Identifier.ascending("part"), + type: "tool-call", + toolCallID: value.toolCallId, + toolName: value.toolName, + state: { + status: "running", + input: value.args, + time: { start: Date.now() }, + }, + } + toolcalls[value.toolCallId] = toolPart + await Session.addPart({ + messageID: input.messageID, + part: toolPart, + }) + break + + case "tool-result": + const match = toolcalls[value.toolCallId] + if (match) { + match.state = { + status: "completed", + output: value.result, + time: { + start: match.state.time.start, + end: Date.now(), + }, + } + await Session.updatePart({ + messageID: input.messageID, + partID: match.id, + part: match, + }) + } + break + + case "error": + await Session.updateMessage({ + messageID: input.messageID, + error: { + message: value.error.message, + code: value.error.code, + }, + }) + throw value.error + + case "finish": + await Session.updateMessage({ + messageID: input.messageID, + tokens: value.usage, + time: { end: Date.now() }, + }) + break + + default: + // Exhaustiveness check + const _exhaustive: never = value + throw new Error(`Unhandled stream type: ${(value as any).type}`) + } + } + }, + } +} +``` + +**File Reference:** `packages/opencode/src/session/processor.ts:53-346` + +### 8.5 Context Compaction + +```typescript +// packages/opencode/src/session/compaction.ts + +export async function isOverflow(input: { + tokens: MessageV2.Assistant["tokens"] + model: Provider.Model +}): Promise { + const limit = input.model.limit.context + + const total = input.tokens.input + input.tokens.output + input.tokens.cache.read + input.tokens.cache.write + + const threshold = limit * 0.75 // Trigger at 75% capacity + + return total > threshold +} + +export async function compact(sessionID: string) { + const messages = await Session.messages({ sessionID }) + const model = await Session.getModel(sessionID) + + // Find oldest non-system messages + const candidates = messages.filter((m) => m.info.role !== "system") + + if (candidates.length <= 2) { + // Keep at least 2 messages for context + return + } + + // Remove oldest message + const toRemove = candidates[0] + await Session.deleteMessage(toRemove.info.id) + + // Add summary if necessary + const summary = await generateSummary(toRemove) + await Session.addSystemMessage(sessionID, { + content: `Previous context (summarized): ${summary}`, + }) + + log.info("compacted session", { + sessionID, + removedMessageID: toRemove.info.id, + remainingMessages: messages.length - 1, + }) +} + +// Check after each assistant response +await Session.onMessageComplete(async (messageID) => { + const message = await Session.getMessage(messageID) + const model = await Session.getModel(message.sessionID) + + if (await isOverflow({ tokens: message.tokens, model })) { + await compact(message.sessionID) + } +}) +``` + +**File References:** + +- `packages/opencode/src/session/compaction.ts` - Lines 30-48 +- `packages/opencode/src/session/processor.ts` - Lines 282-284 + +--- + +## 9. Service Architecture Standards + +### 9.1 Core Services Overview + +| Service | Location | Pattern | Responsibility | +| ----------------------- | -------------------------- | ---------------------- | --------------------------- | +| **Session Management** | `src/session/` | Namespace + State | AI conversation lifecycle | +| **File Watching** | `src/file/watcher.ts` | Chokidar + Debounce | Filesystem change detection | +| **LSP Integration** | `src/lsp/` | Multi-client manager | Language server protocol | +| **MCP** | `src/mcp/` | Multi-transport client | Model Context Protocol | +| **Terminal/PTY** | `src/server/routes/pty.ts` | WebSocket-based | Shell session management | +| **Event Bus** | `src/bus/` | Pub/sub pattern | Cross-service communication | +| **Storage** | `src/storage/` | Lock-based persistence | JSON file storage | +| **Provider Management** | `src/provider/` | Lazy-loaded SDKs | LLM provider abstraction | +| **Config Management** | `src/config/` | Layered merge | Multi-level configuration | +| **Scheduler** | `src/scheduler/` | Interval-based | Background job execution | + +### 9.2 Service Implementation Template + +```typescript +// Service template following codebase patterns + +import { Log } from "../util/log" +import { Instance } from "../project/instance" +import { BusEvent } from "../bus/event" +import z from "zod" + +export namespace MyService { + const log = Log.create({ service: "my-service" }) + + // 1. Type definitions + export type Info = z.infer + export const Info = z.object({ + id: z.string(), + status: z.enum(["idle", "active", "error"]), + created: z.number(), + }) + + // 2. Per-instance state + const state = Instance.state( + async () => { + log.info("initializing service") + + return { + items: new Map(), + timers: new Map(), + clients: [] as Client[], + } + }, + async (state) => { + log.info("disposing service") + + // Cleanup resources + await Promise.all([ + ...state.clients.map((c) => c.close()), + ...Array.from(state.timers.values()).map((t) => clearInterval(t)), + ]) + + state.items.clear() + }, + ) + + // 3. Event definitions + export const Event = { + Created: BusEvent.define( + "my-service.created", + z.object({ + info: Info, + }), + ), + Updated: BusEvent.define( + "my-service.updated", + z.object({ + info: Info, + }), + ), + Deleted: BusEvent.define( + "my-service.deleted", + z.object({ + id: z.string(), + }), + ), + } + + // 4. Public API with fn() wrapper + export const create = fn( + z + .object({ + id: z.string().optional(), + data: z.record(z.unknown()).optional(), + }) + .optional(), + async (input) => { + const id = input?.id ?? Identifier.ascending("my-service") + + const info: Info = { + id, + status: "idle", + created: Date.now(), + } + + state().items.set(id, info) + await Bus.publish(Event.Created, { info }) + + log.info("created", { id }) + return info + }, + ) + + export const get = fn(z.string(), async (id) => { + const item = state().items.get(id) + if (!item) { + throw NotFoundError.create({ message: `Item ${id} not found` }) + } + return item + }) + + export const list = fn( + z + .object({ + status: z.enum(["idle", "active", "error"]).optional(), + }) + .optional(), + async (input) => { + const items = Array.from(state().items.values()) + + if (input?.status) { + return items.filter((item) => item.status === input.status) + } + + return items + }, + ) + + // 5. Internal functions (not exported) + async function cleanup(id: string) { + const timer = state().timers.get(id) + if (timer) { + clearInterval(timer) + state().timers.delete(id) + } + } +} +``` + +**File References:** + +- `packages/opencode/src/session/index.ts` - Complete example +- `packages/opencode/src/mcp/index.ts` - Multi-client manager +- `packages/opencode/src/lsp/index.ts` - Lazy spawning + +--- + +## 10. State Management Standards + +### 10.1 Per-Instance State Isolation + +**Rule: All state must be isolated per working directory** + +```typescript +// packages/opencode/src/project/instance.ts + +export namespace Instance { + // Current working directory + export let directory = process.cwd() + + // Git worktree root + export let worktree = directory + + // Project ID + export let id = "unknown" + + // Create state scoped to current instance + export function state( + init: () => S | Promise, + dispose?: (state: Awaited) => Promise, + ): () => Awaited { + return State.create( + () => Instance.directory, // Key by directory + init, + dispose, + ) + } +} + +// packages/opencode/src/project/state.ts + +const recordsByKey = new Map>() + +interface Entry { + state: any + dispose?: (state: any) => Promise +} + +export function create( + root: () => string, + init: () => S | Promise, + dispose?: (state: Awaited) => Promise, +): () => Awaited { + return () => { + const key = root() + + // Get or create entries for this key + let entries = recordsByKey.get(key) + if (!entries) { + entries = new Map() + recordsByKey.set(key, entries) + } + + // Get or initialize state + const exists = entries.get(init) + if (exists) { + return exists.state as Awaited + } + + const state = init() + entries.set(init, { state, dispose }) + + return state as Awaited + } +} + +// Dispose all state for a key +export async function dispose(key: string) { + const entries = recordsByKey.get(key) + if (!entries) return + + await Promise.all( + Array.from(entries.values()).map(async (entry) => { + if (entry.dispose) { + const state = await entry.state + await entry.dispose(state) + } + }), + ) + + recordsByKey.delete(key) +} +``` + +**File References:** + +- `packages/opencode/src/project/instance.ts` - Lines 66-68 +- `packages/opencode/src/project/state.ts` - Lines 12-29 + +### 10.2 State Initialization Pattern + +```typescript +// โœ… GOOD - Lazy initialization with disposal +const state = Instance.state( + async () => { + log.info("initializing LSP clients") + + const cfg = await Config.get() + const servers: Record = {} + const clients: LSPClient.Info[] = [] + + // Initialize servers + for (const [id, server] of Object.entries(LSPServer)) { + if (cfg.lsp?.[id]?.enabled !== false) { + servers[id] = server + } + } + + return { + servers, + clients, + broken: new Set(), + spawning: new Map>(), + } + }, + async (state) => { + log.info("disposing LSP clients") + + // Cleanup all clients + await Promise.all( + state.clients.map(async (client) => { + try { + await client.shutdown() + } catch (error) { + log.error("failed to shutdown client", { client: client.id, error }) + } + }), + ) + }, +) + +// Access state +const lspState = state() +lspState.clients.push(newClient) +``` + +### 10.3 Global State (Rare) + +**Rule: Avoid global state, use per-instance state instead** + +```typescript +// โŒ AVOID - Global mutable state +const sessions = new Map() + +export function addSession(session: Session) { + sessions.set(session.id, session) +} + +// โœ… PREFER - Per-instance state +const state = Instance.state(async () => ({ + sessions: new Map(), +})) + +export function addSession(session: Session) { + state().sessions.set(session.id, session) +} + +// โœ… ACCEPTABLE - Truly global state (user config, auth tokens) +export namespace Global { + export namespace Path { + export const home = os.homedir() + export const config = path.join(home, ".config", "opencode") + export const data = path.join(home, ".local", "share", "opencode") + export const cache = path.join(home, ".cache", "opencode") + } +} +``` + +--- + +## 11. Event Bus Standards + +### 11.1 Event Definition + +```typescript +// packages/opencode/src/bus/event.ts + +export namespace BusEvent { + export interface Definition { + type: string + properties: Properties + } + + export function define(type: string, properties: Properties): Definition { + return { type, properties } + } +} + +// Usage: Define events for a service +export namespace Session { + export const Event = { + Created: BusEvent.define("session.created", z.object({ info: Info })), + + Updated: BusEvent.define("session.updated", z.object({ info: Info, changes: z.record(z.unknown()) })), + + Deleted: BusEvent.define("session.deleted", z.object({ id: z.string() })), + + Diff: BusEvent.define( + "session.diff", + z.object({ + sessionID: z.string(), + messageID: z.string(), + diff: z.object({ + file: z.string(), + additions: z.number(), + deletions: z.number(), + }), + }), + ), + + Error: BusEvent.define( + "session.error", + z.object({ + sessionID: z.string(), + error: z.object({ + message: z.string(), + code: z.string().optional(), + }), + }), + ), + + Question: BusEvent.define( + "session.question", + z.object({ + sessionID: z.string(), + question: z.object({ + type: z.string(), + message: z.string(), + options: z.array(z.unknown()), + }), + respond: z.function(), + }), + ), + } +} +``` + +### 11.2 Publishing Events + +```typescript +// packages/opencode/src/bus/index.ts + +export namespace Bus { + const state = Instance.state(async () => ({ + subscriptions: new Map>(), + })) + + type Handler = (payload: EventPayload) => void | Promise + + interface EventPayload { + type: string + properties: any + } + + export async function publish( + def: Definition, + properties: z.output, + ): Promise { + const payload: EventPayload = { + type: def.type, + properties, + } + + const pending: Promise[] = [] + + // Notify specific subscribers + const specific = state().subscriptions.get(def.type) + if (specific) { + for (const handler of specific) { + pending.push(Promise.resolve(handler(payload))) + } + } + + // Notify wildcard subscribers + const wildcard = state().subscriptions.get("*") + if (wildcard) { + for (const handler of wildcard) { + pending.push(Promise.resolve(handler(payload))) + } + } + + // Also publish to global bus (for cross-instance communication) + GlobalBus.emit("event", { + directory: Instance.directory, + payload, + }) + + await Promise.all(pending) + } +} + +// Usage: Publish an event +await Bus.publish(Session.Event.Created, { + info: { + id: "session-123", + title: "New Session", + created: Date.now(), + }, +}) + +await Bus.publish(Session.Event.Updated, { + info: updatedSession, + changes: { title: "Updated Title" }, +}) +``` + +**File Reference:** `packages/opencode/src/bus/index.ts:41-64` + +### 11.3 Subscribing to Events + +```typescript +// packages/opencode/src/bus/index.ts + +export namespace Bus { + export function subscribe( + def: Definition | "*", + handler: (payload: { type: string; properties: z.output }) => void | Promise, + ): Disposable { + const key = typeof def === "string" ? def : def.type + + let subs = state().subscriptions.get(key) + if (!subs) { + subs = new Set() + state().subscriptions.set(key, subs) + } + + subs.add(handler) + + return { + [Symbol.dispose]: () => { + subs?.delete(handler) + if (subs?.size === 0) { + state().subscriptions.delete(key) + } + }, + } + } +} + +// Usage: Subscribe to specific events +const subscription = Bus.subscribe(Session.Event.Created, async (event) => { + log.info("session created", { id: event.properties.info.id }) + await notifyUser(`New session: ${event.properties.info.title}`) +}) + +// Unsubscribe +subscription[Symbol.dispose]() + +// Or use disposable pattern +{ + using sub = Bus.subscribe(Session.Event.Updated, handleUpdate) + + // Automatically unsubscribes when scope exits +} + +// Subscribe to all events +Bus.subscribe("*", (event) => { + log.debug("event", { type: event.type, properties: event.properties }) +}) +``` + +### 11.4 Event-Driven Communication Pattern + +```typescript +// Service A: Publish events +export namespace FileWatcher { + export const Event = { + Updated: BusEvent.define( + "file.updated", + z.object({ + file: z.string(), + event: z.enum(["add", "change", "unlink"]), + }), + ), + } + + async function watch(directory: string) { + const watcher = chokidar.watch(directory) + + watcher.on("change", async (file) => { + await Bus.publish(Event.Updated, { + file, + event: "change", + }) + }) + } +} + +// Service B: React to events +export namespace LSP { + export async function initialize() { + // Subscribe to file changes + Bus.subscribe(FileWatcher.Event.Updated, async (event) => { + if (event.properties.event === "change") { + await notifyClientsOfChange(event.properties.file) + } + }) + } + + async function notifyClientsOfChange(file: string) { + const clients = state().clients.filter((c) => c.watchesFile(file)) + await Promise.all(clients.map((c) => c.didChangeTextDocument({ uri: file }))) + } +} + +// Service C: Also react to same events +export namespace Session { + export async function initialize() { + Bus.subscribe(FileWatcher.Event.Updated, async (event) => { + // Invalidate cached file contents + await invalidateFileCache(event.properties.file) + }) + } +} +``` + +--- + +## 12. Configuration Management Standards + +### 12.1 Configuration Precedence + +**Order (Low โ†’ High priority):** + +1. **Remote `.well-known/opencode`** - Organization defaults +2. **Global config** - `~/.config/opencode/opencode.json{,c}` +3. **Custom config** - `OPENCODE_CONFIG` env var path +4. **Project config** - `opencode.json{,c}` in project +5. **`.opencode` directories** - `.opencode/opencode.json{,c}` +6. **Inline config** - `OPENCODE_CONFIG_CONTENT` env var +7. **Managed config** - Enterprise `/etc/opencode` (highest priority) + +```typescript +// packages/opencode/src/config/config.ts + +export namespace Config { + export const state = Instance.state(async () => { + let result: Info = {} + + // 1. Remote organization config + const auth = await Auth.all() + for (const [key, value] of Object.entries(auth)) { + if (value.type === "wellknown") { + const response = await fetch(`${key}/.well-known/opencode`) + const wellknown = await response.json() + result = mergeConfigConcatArrays(result, wellknown.config ?? {}) + } + } + + // 2. Global user config + result = mergeConfigConcatArrays(result, await global()) + + // 3. Custom config path + if (Flag.OPENCODE_CONFIG) { + result = mergeConfigConcatArrays(result, await loadFile(Flag.OPENCODE_CONFIG)) + } + + // 4. Project config (if not disabled) + if (!Flag.OPENCODE_DISABLE_PROJECT_CONFIG) { + for (const file of ["opencode.jsonc", "opencode.json"]) { + const found = await Filesystem.findUp(file, Instance.directory, Instance.worktree) + for (const resolved of found.toReversed()) { + result = mergeConfigConcatArrays(result, await loadFile(resolved)) + } + } + } + + // 5. .opencode directories + const directories = [ + Global.Path.config, + ...(!Flag.OPENCODE_DISABLE_PROJECT_CONFIG + ? await Array.fromAsync( + Filesystem.up({ + targets: [".opencode"], + start: Instance.directory, + stop: Instance.worktree, + }), + ) + : []), + // Always scan user home ~/.opencode/ + ...(await Array.fromAsync( + Filesystem.up({ + targets: [".opencode"], + start: Global.Path.home, + stop: Global.Path.home, + }), + )), + ] + + for (const dir of unique(directories)) { + for (const file of ["opencode.jsonc", "opencode.json"]) { + const configPath = path.join(dir, file) + if (await Filesystem.exists(configPath)) { + result = mergeConfigConcatArrays(result, await loadFile(configPath)) + } + } + } + + // 6. Inline config + if (Flag.OPENCODE_CONFIG_CONTENT) { + result = mergeConfigConcatArrays(result, await load(Flag.OPENCODE_CONFIG_CONTENT, "inline")) + } + + // 7. Managed config (enterprise, highest priority) + const managedPath = path.join(managedConfigDir, "opencode.json") + if (await Filesystem.exists(managedPath)) { + result = mergeConfigConcatArrays(result, await loadFile(managedPath)) + } + + return result + }) + + export const get = fn(z.void(), async () => state()) +} +``` + +**File Reference:** `packages/opencode/src/config/config.ts:62-150` + +### 12.2 Configuration Merge Strategy + +```typescript +// packages/opencode/src/config/config.ts + +function mergeConfigConcatArrays(target: Info, source: Info): Info { + // Deep merge objects + const merged = mergeDeep(target, source) + + // Special handling: Concatenate arrays instead of replacing + if (target.plugin && source.plugin) { + merged.plugin = Array.from(new Set([...target.plugin, ...source.plugin])) + } + + if (target.instructions && source.instructions) { + merged.instructions = Array.from(new Set([...target.instructions, ...source.instructions])) + } + + return merged +} + +// Example: +// Base config: { plugin: ["a", "b"], model: { id: "gpt-4" } } +// Override config: { plugin: ["b", "c"], model: { temperature: 0.7 } } +// Result: { plugin: ["a", "b", "c"], model: { id: "gpt-4", temperature: 0.7 } } +``` + +**File Reference:** `packages/opencode/src/config/config.ts:51-60` + +### 12.3 Configuration Schema + +```typescript +export namespace Config { + export type Info = z.infer + export const Info = z.object({ + // Model configuration + model: z + .object({ + id: z.string().optional(), + providerID: z.string().optional(), + temperature: z.number().optional(), + maxTokens: z.number().optional(), + }) + .optional(), + + // Providers + providers: z + .record( + z.object({ + apiKey: z.string().optional(), + baseURL: z.string().optional(), + enabled: z.boolean().optional(), + }), + ) + .optional(), + + // Plugins + plugin: z.array(z.string()).optional(), + + // Instructions (system prompts) + instructions: z.array(z.string()).optional(), + + // Agents + agent: z + .record( + z.object({ + mode: z.enum(["primary", "secondary"]).optional(), + prompt: z.string().optional(), + permission: z.string().optional(), + }), + ) + .optional(), + + // LSP servers + lsp: z + .record( + z.object({ + enabled: z.boolean().optional(), + command: z.string().optional(), + args: z.array(z.string()).optional(), + }), + ) + .optional(), + + // MCP servers + mcp: z + .record( + z.union([ + z.object({ + command: z.string(), + args: z.array(z.string()).optional(), + env: z.record(z.string()).optional(), + enabled: z.boolean().optional(), + }), + z.object({ + url: z.string(), + transport: z.literal("sse"), + enabled: z.boolean().optional(), + }), + ]), + ) + .optional(), + + // Formatters + formatter: z + .record( + z.object({ + command: z.string(), + args: z.array(z.string()).optional(), + }), + ) + .optional(), + }) +} +``` + +### 12.4 Configuration File Loading + +```typescript +export namespace Config { + async function loadFile(filepath: string): Promise { + if (!(await Filesystem.exists(filepath))) { + return {} + } + + const content = await Bun.file(filepath).text() + return load(content, filepath) + } + + async function load(content: string, source: string): Promise { + try { + // Parse JSONC (JSON with comments) + const parsed = parseJsonc(content) + + // Validate against schema + const validated = Info.parse(parsed) + + return validated + } catch (error) { + if (error instanceof z.ZodError) { + log.error("config validation failed", { + source, + errors: error.errors, + }) + throw new Error(`Invalid config at ${source}: ${error.errors[0].message}`) + } + + throw error + } + } +} +``` + +--- + +## 13. Storage & Persistence Standards + +### 13.1 Storage Operations + +```typescript +// packages/opencode/src/storage/storage.ts + +export namespace Storage { + const log = Log.create({ service: "storage" }) + + export const NotFoundError = NamedError.create("NotFoundError", z.object({ message: z.string() })) + + // Read with lock + export async function read(target: string): Promise { + using _ = await Lock.read(target) + + const file = Bun.file(target) + if (!(await file.exists())) { + throw NotFoundError.create({ + message: `File not found: ${target}`, + }) + } + + return file.json() + } + + // Write with lock + export async function write(target: string, data: any): Promise { + using _ = await Lock.write(target) + + const dir = path.dirname(target) + await fs.mkdir(dir, { recursive: true }) + + await Bun.write(target, JSON.stringify(data, null, 2)) + } + + // Update (read-modify-write) + export async function update(target: string, editor: (draft: T) => void | Promise): Promise { + using _ = await Lock.write(target) + + const data = await read(target) + await editor(data) + await write(target, data) + + return data + } + + // Delete + export async function remove(target: string): Promise { + using _ = await Lock.write(target) + + if (await Filesystem.exists(target)) { + await fs.rm(target, { recursive: true }) + } + } + + // List files matching pattern + export async function list(directory: string, pattern: string): Promise { + using _ = await Lock.read(directory) + + const files: string[] = [] + for await (const file of new Bun.Glob(pattern).scan({ cwd: directory })) { + files.push(path.join(directory, file)) + } + + return files + } +} +``` + +**File Reference:** `packages/opencode/src/storage/storage.ts:1-200` + +### 13.2 Storage Paths + +```typescript +export namespace Storage { + export function path(...segments: string[]): string { + return path.join(Global.Path.data, ...segments) + } + + // Session storage + export namespace Session { + export function info(sessionID: string): string { + return Storage.path("session", sessionID, "info.json") + } + + export function messages(sessionID: string): string { + return Storage.path("session", sessionID, "messages") + } + + export function message(sessionID: string, messageID: string): string { + return Storage.path("session", sessionID, "messages", `${messageID}.json`) + } + } + + // Project storage + export namespace Project { + export function info(projectID: string): string { + return Storage.path("project", `${projectID}.json`) + } + + export function list(): Promise { + return Storage.list(Storage.path("project"), "*.json") + } + } + + // Cache storage + export namespace Cache { + export function file(key: string): string { + return Storage.path("cache", `${key}.json`) + } + } +} +``` + +### 13.3 Migration Pattern + +```typescript +export namespace Storage { + type Migration = (dir: string) => Promise + + const MIGRATIONS: Migration[] = [ + // Migration 1: Rename old directories + async (dir) => { + const oldPath = path.join(dir, "old-structure") + const newPath = path.join(dir, "new-structure") + + if (await Filesystem.exists(oldPath)) { + await fs.rename(oldPath, newPath) + log.info("migrated directory structure") + } + }, + + // Migration 2: Transform data format + async (dir) => { + const files = await Storage.list(path.join(dir, "sessions"), "*.json") + + for (const file of files) { + const data = await Storage.read(file) + + // Add new field + if (!data.version) { + data.version = 2 + data.migrated = Date.now() + await Storage.write(file, data) + } + } + + log.info("migrated session data", { count: files.length }) + }, + + // Migration 3: Consolidate files + async (dir) => { + const oldDir = path.join(dir, "old") + const newFile = path.join(dir, "consolidated.json") + + if (await Filesystem.exists(oldDir)) { + const files = await Storage.list(oldDir, "*.json") + const consolidated = await Promise.all(files.map((f) => Storage.read(f))) + + await Storage.write(newFile, consolidated) + await fs.rm(oldDir, { recursive: true }) + + log.info("consolidated files", { count: files.length }) + } + }, + ] + + export async function migrate(): Promise { + const dataDir = Global.Path.data + const versionFile = path.join(dataDir, ".version") + + let currentVersion = 0 + if (await Filesystem.exists(versionFile)) { + currentVersion = Number(await Bun.file(versionFile).text()) + } + + const targetVersion = MIGRATIONS.length + + if (currentVersion >= targetVersion) { + log.debug("storage up to date", { version: currentVersion }) + return + } + + log.info("migrating storage", { + from: currentVersion, + to: targetVersion, + }) + + // Run pending migrations + for (let i = currentVersion; i < targetVersion; i++) { + log.info(`running migration ${i + 1}/${targetVersion}`) + await MIGRATIONS[i](dataDir) + } + + // Update version + await Bun.write(versionFile, String(targetVersion)) + + log.info("migration complete", { version: targetVersion }) + } +} +``` + +**File Reference:** `packages/opencode/src/storage/storage.ts:24-100` + +--- + +## 14. Error Handling Standards + +### 14.1 Named Errors (Preferred) + +```typescript +// packages/opencode/src/util/error.ts + +import { NamedError } from "@opencode-ai/util/error" +import z from "zod" + +// Define typed errors +export const NotFoundError = NamedError.create( + "NotFoundError", + z.object({ + message: z.string(), + resource: z.string().optional(), + id: z.string().optional(), + }), +) + +export const ValidationError = NamedError.create( + "ValidationError", + z.object({ + message: z.string(), + field: z.string().optional(), + expected: z.string().optional(), + received: z.string().optional(), + }), +) + +export const PermissionError = NamedError.create( + "PermissionError", + z.object({ + message: z.string(), + action: z.string(), + resource: z.string(), + }), +) + +// Usage: Throw typed error +throw NotFoundError.create({ + message: "Session not found", + resource: "session", + id: sessionID, +}) + +// Usage: Catch and check type +try { + await operation() +} catch (error) { + if (NotFoundError.is(error)) { + log.warn("resource not found", { + resource: error.data.resource, + id: error.data.id, + }) + return null + } + + if (PermissionError.is(error)) { + log.error("permission denied", { + action: error.data.action, + resource: error.data.resource, + }) + throw error + } + + // Unknown error + log.error("unexpected error", { error }) + throw error +} +``` + +**File Reference:** `packages/opencode/src/storage/storage.ts:17-22` + +### 14.2 Custom Error Classes (When Needed) + +```typescript +// โœ… GOOD - Error with additional context +export class BusyError extends Error { + constructor(public readonly sessionID: string) { + super(`Session ${sessionID} is busy`) + this.name = "BusyError" + } +} + +// Usage +throw new BusyError(sessionID) + +// Catching +try { + await process(sessionID) +} catch (error) { + if (error instanceof BusyError) { + log.info("session busy, retrying", { sessionID: error.sessionID }) + await retry() + } +} +``` + +**File Reference:** `packages/opencode/src/session/index.ts:494` + +### 14.3 Result Pattern (for Tools) + +```typescript +// โœ… GOOD - Never throw in tool execution +export const ReadTool = Tool.define("read", { + async execute(args, context) { + try { + const content = await Bun.file(args.filePath).text() + + return { + output: content, + title: `Read ${path.basename(args.filePath)}`, + } + } catch (error) { + return { + output: `Error reading file: ${error.message}`, + title: "Read Failed", + metadata: { + error: true, + message: error.message, + }, + } + } + }, +}) + +// โœ… GOOD - Result type for fallible operations +export type Result = { success: true; value: T } | { success: false; error: E } + +export async function operation(): Promise> { + try { + const data = await fetchData() + return { success: true, value: data } + } catch (error) { + return { success: false, error } + } +} + +// Usage +const result = await operation() +if (result.success) { + console.log(result.value) +} else { + log.error("operation failed", { error: result.error }) +} +``` + +### 14.4 Error Context + +```typescript +// โœ… GOOD - Rich error context +class OperationError extends Error { + constructor( + message: string, + public readonly context: { + operation: string + input: unknown + timestamp: number + sessionID?: string + } + ) { + super(message) + this.name = "OperationError" + } +} + +// Usage +try { + await processData(input) +} catch (error) { + throw new OperationError( + "Failed to process data", + { + operation: "processData", + input, + timestamp: Date.now(), + sessionID: context.sessionID + } + ) +} + +// Logging with context +catch (error) { + if (error instanceof OperationError) { + log.error("operation failed", { + operation: error.context.operation, + sessionID: error.context.sessionID, + error: error.message + }) + } +} +``` + +--- + +## 15. Type System Standards + +### 15.1 Zod Schemas (Primary) + +**Rule: Use Zod for runtime validation, derive TypeScript types from schemas** + +```typescript +// โœ… GOOD - Schema-first approach +export namespace Session { + export const Info = z.object({ + id: z.string(), + title: z.string(), + projectID: z.string(), + modelID: z.string().optional(), + permission: z.enum(["allow", "ask", "deny"]), + time: z.object({ + created: z.number(), + updated: z.number(), + }), + }) + + // Derive TypeScript type from schema + export type Info = z.infer + + // Use in functions + export const create = fn(Info.pick({ title: true, projectID: true }).partial(), async (input): Promise => { + // Implementation + }) +} + +// โŒ BAD - Type-first approach (no runtime validation) +export interface SessionInfo { + id: string + title: string + projectID: string +} + +export function create(input: Partial): SessionInfo { + // No validation! Runtime errors possible +} +``` + +### 15.2 Type Inference + +**Rule: Rely on type inference, avoid explicit annotations** + +```typescript +// โœ… GOOD - Let TypeScript infer +const session = await Session.create({ title: "New" }) +const messages = session.messages.filter((m) => m.role === "user") +const ids = messages.map((m) => m.id) + +// โŒ BAD - Unnecessary annotations +const session: Session.Info = await Session.create({ title: "New" }) +const messages: Message[] = session.messages.filter((m) => m.role === "user") +const ids: string[] = messages.map((m) => m.id) + +// โœ… ACCEPTABLE - Annotation for clarity in complex scenarios +const messages: Message[] = await fetchMessages().then((msgs): Message[] => { + return msgs.filter((m) => m.deleted !== true) +}) +``` + +**File Reference:** `AGENTS.md:15` + +### 15.3 Avoid `any` + +```typescript +// โŒ BAD +function process(data: any) { + return data.value.toString() +} + +// โœ… GOOD - Use unknown and validate +function process(data: unknown) { + if (typeof data !== "object" || data === null) { + throw new Error("Expected object") + } + + if (!("value" in data)) { + throw new Error("Missing value property") + } + + return String(data.value) +} + +// โœ… BEST - Use Zod schema +const DataSchema = z.object({ + value: z.union([z.string(), z.number()]), +}) + +function process(data: unknown) { + const validated = DataSchema.parse(data) + return String(validated.value) +} +``` + +**File Reference:** `AGENTS.md:12` + +### 15.4 Type Guards + +```typescript +// โœ… GOOD - Type guards for narrowing +function isMessage(value: unknown): value is Message { + return typeof value === "object" && value !== null && "id" in value && "role" in value && typeof value.id === "string" +} + +// Usage +if (isMessage(data)) { + console.log(data.id) // TypeScript knows data is Message +} + +// โœ… GOOD - Type guards in filter +const messages = items.filter((item): item is Message => isMessage(item)).map((msg) => msg.id) + +// โœ… GOOD - Discriminated unions +type Part = + | { type: "text"; text: string } + | { type: "file"; data: Buffer; mimeType: string } + | { type: "patch"; files: string[]; diff: string } + +function handle(part: Part) { + switch (part.type) { + case "text": + console.log(part.text) // TypeScript knows: text part + break + case "file": + console.log(part.mimeType) // TypeScript knows: file part + break + case "patch": + console.log(part.files) // TypeScript knows: patch part + break + default: + const _exhaustive: never = part + throw new Error("Unhandled part type") + } +} +``` + +--- + +## 16. Import Organization Standards + +### 16.1 Import Order + +```typescript +// 1. Zod and validation libraries +import z from "zod" + +// 2. Node.js built-ins +import path from "path" +import fs from "fs/promises" +import os from "os" + +// 3. External packages (alphabetical) +import { mergeDeep, sortBy, unique } from "remeda" +import chokidar from "chokidar" +import fuzzysort from "fuzzysort" + +// 4. Internal packages (@opencode-ai/*) +import { NamedError } from "@opencode-ai/util/error" + +// 5. Project utilities (../util/*) +import { Log } from "../util/log" +import { Lock } from "../util/lock" +import { fn } from "../util/fn" + +// 6. Project services (..//*) +import { Config } from "../config/config" +import { Storage } from "../storage/storage" +import { Bus } from "../bus" + +// 7. Relative imports (same directory) +import { Session } from "./session" +import { MessageV2 } from "./message-v2" +``` + +### 16.2 Import Style + +```typescript +// โœ… GOOD - Named imports +import { create, update, get } from "./session" +import { Log, type LogOptions } from "./util/log" + +// โŒ AVOID - Default imports (except for external packages) +import session from "./session" + +// โœ… GOOD - Namespace imports for large APIs +import * as Session from "./session" + +// โœ… GOOD - Type-only imports +import type { Session } from "./session" +import { type Config, loadConfig } from "./config" +``` + +### 16.3 Circular Dependency Prevention + +```typescript +// โŒ BAD - Circular dependency +// file-a.ts +import { funcB } from "./file-b" +export function funcA() { + return funcB() +} + +// file-b.ts +import { funcA } from "./file-a" +export function funcB() { + return funcA() +} + +// โœ… GOOD - Extract shared code +// shared.ts +export function shared() { + return 42 +} + +// file-a.ts +import { shared } from "./shared" +export function funcA() { + return shared() +} + +// file-b.ts +import { shared } from "./shared" +export function funcB() { + return shared() +} +``` + +--- + +## 17. Naming Conventions + +### 17.1 Functions & Variables + +```typescript +// โœ… camelCase for functions and variables +const sessionID = "abc123" +const userAgent = "opencode/1.0" +const maxRetries = 3 + +async function processMessage(messageID: string) {} +async function createSession() {} +``` + +### 17.2 Types & Interfaces + +```typescript +// โœ… PascalCase for types, interfaces, and classes +type SessionInfo = { + id: string + title: string +} + +interface Message { + id: string + content: string +} + +class BusyError extends Error {} + +namespace Session { + export type Info = z.infer +} +``` + +### 17.3 Constants + +```typescript +// โœ… SCREAMING_SNAKE_CASE for true constants +const MAX_RETRY_ATTEMPTS = 3 +const DEFAULT_TIMEOUT = 5000 +const API_BASE_URL = "https://api.example.com" + +// โœ… camelCase for configuration values +const maxRetries = config.retries ?? 3 +const defaultModel = config.model?.id ?? "gpt-4" +``` + +### 17.4 Namespaces + +```typescript +// โœ… PascalCase for namespaces +export namespace Session {} +export namespace Storage {} +export namespace FileWatcher {} +``` + +### 17.5 Files + +```typescript +// โœ… kebab-case for files +// session-manager.ts +// message-processor.ts +// file-watcher.ts + +// โœ… Single word when possible +// session.ts +// storage.ts +// config.ts +``` + +--- + +## 18. Testing Standards + +### 18.1 Principles + +1. **Avoid mocks** - Test actual implementation +2. **No logic duplication** - Don't reimplement logic in tests +3. **Use Bun test runner** - `bun test` + +**File Reference:** `AGENTS.md:108-111` + +### 18.2 Test Structure + +```typescript +// packages/opencode/src/addons/serialize.test.ts + +import { expect, test, describe } from "bun:test" +import { serialize, deserialize } from "./serialize" + +describe("serialize", () => { + test("preserves Date objects", () => { + const input = { date: new Date("2024-01-01") } + const serialized = serialize(input) + const deserialized = deserialize(serialized) + + expect(deserialized.date).toBeInstanceOf(Date) + expect(deserialized.date.toISOString()).toBe("2024-01-01T00:00:00.000Z") + }) + + test("preserves Set objects", () => { + const input = { set: new Set([1, 2, 3]) } + const serialized = serialize(input) + const deserialized = deserialize(serialized) + + expect(deserialized.set).toBeInstanceOf(Set) + expect(Array.from(deserialized.set)).toEqual([1, 2, 3]) + }) + + test("handles nested structures", () => { + const input = { + map: new Map([["key", { date: new Date("2024-01-01") }]]), + array: [new Set([1, 2])], + } + const serialized = serialize(input) + const deserialized = deserialize(serialized) + + expect(deserialized.map).toBeInstanceOf(Map) + expect(deserialized.map.get("key")?.date).toBeInstanceOf(Date) + expect(deserialized.array[0]).toBeInstanceOf(Set) + }) +}) +``` + +**File Reference:** `packages/opencode/src/addons/serialize.test.ts` + +### 18.3 Test Commands + +```bash +# Run all tests +bun test + +# Run specific test file +bun test src/util/queue.test.ts + +# Run tests matching pattern +bun test --test-name-pattern "serialize" + +# Watch mode +bun test --watch + +# Coverage +bun test --coverage +``` + +**File Reference:** `packages/opencode/AGENTS.md` - Build/Test Commands + +### 18.4 Integration Tests + +```typescript +import { test, expect, beforeAll, afterAll } from "bun:test" +import { Session } from "./session" +import { Storage } from "./storage" + +let sessionID: string + +beforeAll(async () => { + // Setup: Create test session + const session = await Session.create({ title: "Test Session" }) + sessionID = session.id +}) + +afterAll(async () => { + // Cleanup: Delete test session + await Session.delete(sessionID) +}) + +test("create and retrieve session", async () => { + const session = await Session.get(sessionID) + + expect(session).toBeDefined() + expect(session.id).toBe(sessionID) + expect(session.title).toBe("Test Session") +}) + +test("update session", async () => { + await Session.update(sessionID, { title: "Updated" }) + + const session = await Session.get(sessionID) + expect(session.title).toBe("Updated") +}) +``` + +--- + +## 19. Documentation Standards + +### 19.1 Code Comments + +**Rule: Comment WHY, not WHAT** + +```typescript +// โœ… GOOD - Explains why +// Cache header separately to enable 2-part prompt caching +if (system.length > 2 && system[0] === header) { + system.length = 0 + system.push(header, rest.join("\n")) +} + +// Prevent race condition: lock before checking existence +using _ = await Lock.write(filepath) +if (await Filesystem.exists(filepath)) { + await fs.rm(filepath) +} + +// โŒ BAD - States the obvious +// Push the item to the array +items.push(item) + +// Set the title property +session.title = "New Title" +``` + +### 19.2 JSDoc (For Exported APIs) + +````typescript +/** + * Execute a function with a file lock to prevent concurrent access. + * + * The lock is automatically released when the function completes or throws. + * Locks are queued and processed in order. + * + * @param filepath - Absolute path to the file to lock + * @param fn - Function to execute while holding the lock + * @returns The result of the function + * + * @example + * ```typescript + * await withLock("/path/to/file", async () => { + * const content = await Bun.file("/path/to/file").text() + * await Bun.write("/path/to/file", content + "\n") + * }) + * ``` + */ +export async function withLock(filepath: string, fn: () => Promise): Promise +```` + +### 19.3 README Structure + +```markdown +# Package Name + +Brief description of what this package does. + +## Installation + +\`\`\`bash +bun install @opencode-ai/package-name +\`\`\` + +## Usage + +\`\`\`typescript +import { feature } from "@opencode-ai/package-name" + +await feature() +\`\`\` + +## API + +### `function(param: Type): ReturnType` + +Description of function. + +**Parameters:** + +- `param` - Description of parameter + +**Returns:** Description of return value + +**Example:** +\`\`\`typescript +const result = await function(param) +\`\`\` + +## Development + +\`\`\`bash +bun install +bun test +\`\`\` +``` + +--- + +## 20. Schema Definition Standards + +### 20.1 Drizzle Schema (Database) + +**Rule: Use snake_case for field names to match SQL conventions** + +```typescript +// โœ… GOOD - snake_case fields +const sessionTable = sqliteTable("session", { + id: text().primaryKey(), + project_id: text().notNull(), + created_at: integer().notNull(), + updated_at: integer().notNull(), +}) + +// โŒ BAD - camelCase requires explicit column names +const sessionTable = sqliteTable("session", { + id: text("id").primaryKey(), + projectID: text("project_id").notNull(), + createdAt: integer("created_at").notNull(), + updatedAt: integer("updated_at").notNull(), +}) +``` + +**File Reference:** `AGENTS.md:88-106` + +### 20.2 Zod Schema + +```typescript +// โœ… GOOD - Consistent field naming +export const SessionInfo = z.object({ + id: z.string(), + projectID: z.string(), // camelCase for TypeScript + title: z.string(), + permission: z.enum(["allow", "ask", "deny"]), + time: z.object({ + created: z.number(), + updated: z.number(), + }), +}) + +// โœ… GOOD - Schema composition +export const CreateSessionInput = SessionInfo.pick({ + title: true, + projectID: true, +}).partial() + +export const UpdateSessionInput = SessionInfo.partial().required({ + id: true, +}) + +// โœ… GOOD - Schema extension +export const SessionWithMessages = SessionInfo.extend({ + messages: z.array(MessageInfo), +}) +``` + +--- + +## 21. Dependency Management Standards + +### 21.1 Bun Runtime Preference + +**Rule: Use Bun APIs when available** + +```typescript +// โœ… GOOD - Bun APIs +const content = await Bun.file(filepath).text() +await Bun.write(filepath, content) +const json = await Bun.file(filepath).json() + +const proc = Bun.spawn(["ls", "-la"], { + cwd: directory, + stdout: "pipe", +}) + +// โŒ AVOID - Node.js fs when Bun alternative exists +import fs from "fs/promises" +const content = await fs.readFile(filepath, "utf-8") +await fs.writeFile(filepath, content) +``` + +**File Reference:** `AGENTS.md:14` + +### 21.2 Package Installation + +```bash +# Add dependency +bun add package-name + +# Add dev dependency +bun add -d package-name + +# Add workspace dependency +bun add @opencode-ai/other-package +``` + +### 21.3 Version Management + +```json +// package.json +{ + "dependencies": { + "zod": "^3.22.4", // Allow patch and minor updates + "remeda": "1.30.0", // Pin exact version for critical deps + "@ai-sdk/anthropic": "^0.0.39" + }, + "devDependencies": { + "@types/node": "^20.10.0", + "typescript": "^5.3.3" + } +} +``` + +--- + +## 22. Build & Development Standards + +### 22.1 Development Commands + +```bash +# Install dependencies +bun install + +# Run in development (TUI) +bun dev # Run in packages/opencode +bun dev # Run in specific directory +bun dev . # Run in repo root + +# Run API server +bun dev serve # Start on port 4096 +bun dev serve --port 8080 # Custom port + +# Run web UI (requires server running) +bun dev web # Start server + open web UI +bun run --cwd packages/app dev # Just web UI + +# Run desktop app +bun run --cwd packages/desktop tauri dev + +# Type checking +bun run typecheck + +# Run tests +bun test +bun test path/to/test.ts + +# Build standalone executable +./packages/opencode/script/build.ts --single + +# Regenerate SDK (after server changes) +./script/generate.ts +``` + +**File Reference:** `CONTRIBUTING.md:30-150` + +### 22.2 Project Structure + +``` +opencode/ +โ”œโ”€โ”€ packages/ +โ”‚ โ”œโ”€โ”€ opencode/ # Core business logic & CLI +โ”‚ โ”‚ โ”œโ”€โ”€ src/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ session/ # Session management +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ tool/ # Tool implementations +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ agent/ # Agent system +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ mcp/ # Model Context Protocol +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ lsp/ # Language Server Protocol +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ file/ # File operations +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ config/ # Configuration +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ provider/ # LLM providers +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ server/ # HTTP/WebSocket server +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ cli/cmd/tui/ # Terminal UI (SolidJS) +โ”‚ โ”‚ โ””โ”€โ”€ script/ +โ”‚ โ”‚ โ””โ”€โ”€ build.ts # Build script +โ”‚ โ”œโ”€โ”€ app/ # Web UI (SolidJS) +โ”‚ โ”œโ”€โ”€ desktop/ # Native app (Tauri) +โ”‚ โ”œโ”€โ”€ sdk/js/ # TypeScript SDK +โ”‚ โ”œโ”€โ”€ plugin/ # Plugin system +โ”‚ โ””โ”€โ”€ console/ # Web console +โ”œโ”€โ”€ script/ +โ”‚ โ”œโ”€โ”€ generate.ts # Generate SDK +โ”‚ โ””โ”€โ”€ format.ts # Format code +โ”œโ”€โ”€ AGENTS.md # Agent guidelines +โ”œโ”€โ”€ CONTRIBUTING.md # Contribution guide +โ””โ”€โ”€ CODEBASE_STANDARDS.md # This document +``` + +### 22.3 Build Output + +```bash +# Single build creates: +packages/opencode/dist/opencode-darwin-arm64/ +โ”œโ”€โ”€ bin/ +โ”‚ โ””โ”€โ”€ opencode # Executable +โ”œโ”€โ”€ node_modules/ # Bundled dependencies +โ””โ”€โ”€ package.json + +# Run built executable: +./packages/opencode/dist/opencode-darwin-arm64/bin/opencode +``` + +--- + +## 23. Performance Standards + +### 23.1 Lazy Initialization + +```typescript +// โœ… GOOD - Lazy state initialization +const state = Instance.state(async () => { + // Only initialize when first accessed + const config = await Config.get() + return { config, clients: [] } +}) + +// Access only when needed +if (needsClient) { + const client = state().clients[0] +} + +// โœ… GOOD - Lazy loading of heavy dependencies +const lazyModule = lazy(async () => { + return import("./heavy-module") +}) + +// Load only when needed +const module = await lazyModule() +``` + +### 23.2 Caching + +```typescript +// โœ… GOOD - Cache expensive operations +const cache = new Map() + +async function getData(id: string): Promise { + const cached = cache.get(id) + if (cached) return cached + + const data = await fetchData(id) + cache.set(id, data) + return data +} + +// โœ… GOOD - Time-based cache invalidation +const cache = new Map() + +async function getData(id: string): Promise { + const cached = cache.get(id) + if (cached && Date.now() < cached.expires) { + return cached.data + } + + const data = await fetchData(id) + cache.set(id, { + data, + expires: Date.now() + 60_000, // 1 minute + }) + return data +} +``` + +### 23.3 Debouncing + +```typescript +// โœ… GOOD - Debounce high-frequency events +function debounce any>(fn: T, delay: number): (...args: Parameters) => void { + let timer: Timer | undefined + + return (...args: Parameters) => { + if (timer) clearTimeout(timer) + timer = setTimeout(() => { + fn(...args) + timer = undefined + }, delay) + } +} + +// Usage +const debouncedSave = debounce(async (content: string) => { + await save(content) +}, 500) + +// Only saves after 500ms of inactivity +input.on("change", (content) => { + debouncedSave(content) +}) +``` + +### 23.4 Streaming + +```typescript +// โœ… GOOD - Stream large responses +export async function* streamMessages(sessionID: string) { + const files = await Storage.list(Storage.path("messages", sessionID), "*.json") + + for (const file of files) { + const message = await Storage.read(file) + yield message + } +} + +// Usage +for await (const message of streamMessages(sessionID)) { + process(message) +} +``` + +--- + +## 24. Security Standards + +### 24.1 Input Validation + +```typescript +// โœ… GOOD - Validate all external input +export const handleRequest = fn( + z.object({ + sessionID: z.string().regex(/^session-[a-z0-9]{10}$/), + content: z.string().max(100_000), + metadata: z.record(z.unknown()).optional(), + }), + async (input) => { + // Input is validated, safe to use + return process(input) + }, +) + +// โœ… GOOD - Validate file paths +function validatePath(filepath: string) { + const normalized = path.normalize(filepath) + const absolute = path.resolve(normalized) + + // Prevent directory traversal + if (!absolute.startsWith(Instance.worktree)) { + throw new Error("Path outside worktree") + } + + return absolute +} +``` + +### 24.2 Permission Checks + +```typescript +// โœ… GOOD - Check permissions before sensitive operations +async function readFile(filepath: string, context: Context) { + // Validate path + const safe = validatePath(filepath) + + // Check permission + const permission = await PermissionNext.evaluate("read", safe, context.agent.permission) + + if (permission.action === "deny") { + throw PermissionError.create({ + message: "Permission denied", + action: "read", + resource: safe, + }) + } + + if (permission.action === "ask") { + const allowed = await context.ask({ + type: "permission", + message: `Read file ${path.basename(safe)}?`, + actions: ["allow", "deny"], + }) + + if (!allowed) { + throw PermissionError.create({ + message: "User denied permission", + action: "read", + resource: safe, + }) + } + } + + // Permission granted, perform operation + return Bun.file(safe).text() +} +``` + +### 24.3 Secrets Management + +```typescript +// โœ… GOOD - Load secrets from environment +export namespace Auth { + export async function get(providerID: string): Promise { + const key = `OPENCODE_${providerID.toUpperCase()}_API_KEY` + return process.env[key] + } +} + +// โŒ AVOID - Hardcoded secrets +const API_KEY = "sk-abc123..." + +// โŒ AVOID - Logging secrets +log.info("api key", { key: apiKey }) + +// โœ… GOOD - Redact secrets in logs +log.info("api request", { key: apiKey.slice(0, 8) + "..." }) +``` + +### 24.4 Command Injection Prevention + +```typescript +// โŒ BAD - Command injection vulnerability +const output = await $`ls ${userInput}`.text() + +// โœ… GOOD - Use array syntax (prevents injection) +const proc = Bun.spawn(["ls", userInput], { + stdout: "pipe", +}) +const output = await new Response(proc.stdout).text() + +// โœ… GOOD - Validate input +const sanitized = userInput.replace(/[^a-zA-Z0-9_-]/g, "") +const proc = Bun.spawn(["ls", sanitized]) +``` + +--- + +## Summary: Key Principles + +1. **Single-word function names** unless multi-word necessary (95%+ adherence) +2. **Namespaces over classes** for code organization (only 5 classes in 206 files) +3. **Functional array methods** over for-loops (85/15 split) +4. **Parallel execution by default** via `Promise.all` +5. **Lock mechanisms** prevent race conditions (reader-writer locks, file locks) +6. **Per-instance state isolation** for multi-project support +7. **Event-driven architecture** via pub/sub bus +8. **Zod validation** for all inputs via `fn()` wrapper +9. **Disposable resources** with `using` keyword for automatic cleanup +10. **Bun runtime preference** for file I/O and process spawning +11. **Inline values once, extract when reusable** +12. **Named errors** over throw strings +13. **Avoid mocks in tests**, test actual implementation +14. **Layered config** with clear precedence (7 levels) +15. **Graceful disposal** for all stateful services +16. **Prefer `const` over `let`** - use ternaries instead of reassignment +17. **Avoid `else` statements** - use early returns +18. **Avoid destructuring** - preserve context with dot notation +19. **Type inference** - avoid explicit annotations unless necessary +20. **Avoid `any` type** - use `unknown` with validation +21. **Comment WHY, not WHAT** - explain reasoning, not obvious operations +22. **Schema-first approach** - define Zod schemas, derive TS types +23. **Reader-writer locks** for concurrent access +24. **System prompt caching** - maintain 2-part structure for efficiency +25. **Context compaction** at 75% token threshold + +--- + +## File References Quick Index + +### Core Patterns + +- **Function wrapper**: `packages/opencode/src/util/fn.ts` +- **State management**: `packages/opencode/src/project/state.ts` +- **Instance isolation**: `packages/opencode/src/project/instance.ts` +- **Event bus**: `packages/opencode/src/bus/index.ts` +- **Locks**: `packages/opencode/src/util/lock.ts` +- **Async queue**: `packages/opencode/src/util/queue.ts` + +### Services + +- **Session**: `packages/opencode/src/session/index.ts` +- **LLM streaming**: `packages/opencode/src/session/llm.ts` +- **Processor**: `packages/opencode/src/session/processor.ts` +- **Messages**: `packages/opencode/src/session/message-v2.ts` +- **LSP**: `packages/opencode/src/lsp/index.ts` +- **MCP**: `packages/opencode/src/mcp/index.ts` +- **Storage**: `packages/opencode/src/storage/storage.ts` +- **Config**: `packages/opencode/src/config/config.ts` +- **Provider**: `packages/opencode/src/provider/provider.ts` + +### Tools + +- **Tool definition**: `packages/opencode/src/tool/tool.ts` +- **Edit**: `packages/opencode/src/tool/edit.ts` +- **Batch**: `packages/opencode/src/tool/batch.ts` +- **Grep**: `packages/opencode/src/tool/grep.ts` + +### Documentation + +- **Style guide**: `AGENTS.md` +- **Contributing**: `CONTRIBUTING.md` +- **This document**: `CODEBASE_STANDARDS.md` + +--- + +**End of Standards Document** diff --git a/.opencode/context/content-creation/examples/navigation.md b/.opencode/context/content-creation/examples/navigation.md index ecfba67..1b42f18 100644 --- a/.opencode/context/content-creation/examples/navigation.md +++ b/.opencode/context/content-creation/examples/navigation.md @@ -1,3 +1,5 @@ + + # Content Examples Navigation Real-world content examples demonstrating effective techniques and formats. diff --git a/.opencode/context/content-creation/formats/audio-content.md b/.opencode/context/content-creation/formats/audio-content.md index af831d6..59c090f 100644 --- a/.opencode/context/content-creation/formats/audio-content.md +++ b/.opencode/context/content-creation/formats/audio-content.md @@ -1,3 +1,5 @@ + + # Audio Content Guidelines Best practices for creating engaging audio content: podcasts, voice content, audio ads, and audiobooks. diff --git a/.opencode/context/content-creation/formats/image-content.md b/.opencode/context/content-creation/formats/image-content.md index 678f6d3..51fdae4 100644 --- a/.opencode/context/content-creation/formats/image-content.md +++ b/.opencode/context/content-creation/formats/image-content.md @@ -1,3 +1,5 @@ + + # Image Content Guidelines Best practices for creating visual content: social media graphics, infographics, thumbnails, and visual quotes. diff --git a/.opencode/context/content-creation/formats/navigation.md b/.opencode/context/content-creation/formats/navigation.md index 1b55b5b..6df2186 100644 --- a/.opencode/context/content-creation/formats/navigation.md +++ b/.opencode/context/content-creation/formats/navigation.md @@ -1,3 +1,5 @@ + + # Content Formats Navigation Format-specific guidance for creating content across different mediums. diff --git a/.opencode/context/content-creation/formats/video-content.md b/.opencode/context/content-creation/formats/video-content.md index f82bdfa..6b3f242 100644 --- a/.opencode/context/content-creation/formats/video-content.md +++ b/.opencode/context/content-creation/formats/video-content.md @@ -1,3 +1,5 @@ + + # Video Content Guidelines Best practices for creating engaging video content across platforms: YouTube, TikTok, Instagram Reels, and video ads. diff --git a/.opencode/context/content-creation/formats/written-content.md b/.opencode/context/content-creation/formats/written-content.md index e0abe56..f6c1cd8 100644 --- a/.opencode/context/content-creation/formats/written-content.md +++ b/.opencode/context/content-creation/formats/written-content.md @@ -1,3 +1,5 @@ + + # Written Content Guidelines Best practices for creating effective written content across formats: articles, blog posts, social media, newsletters, and long-form content. diff --git a/.opencode/context/content-creation/navigation.md b/.opencode/context/content-creation/navigation.md index a5c9ac7..d9d1763 100644 --- a/.opencode/context/content-creation/navigation.md +++ b/.opencode/context/content-creation/navigation.md @@ -1,3 +1,5 @@ + + # Content Creation Navigation Context for creating compelling content across all formats and channels. diff --git a/.opencode/context/content-creation/principles/audience-targeting.md b/.opencode/context/content-creation/principles/audience-targeting.md index c361c13..271d491 100644 --- a/.opencode/context/content-creation/principles/audience-targeting.md +++ b/.opencode/context/content-creation/principles/audience-targeting.md @@ -1,3 +1,5 @@ + + # Audience Targeting Understanding and targeting specific audiences to create content that resonates and converts. diff --git a/.opencode/context/content-creation/principles/copywriting-frameworks.md b/.opencode/context/content-creation/principles/copywriting-frameworks.md index f96f0e7..de0e7ce 100644 --- a/.opencode/context/content-creation/principles/copywriting-frameworks.md +++ b/.opencode/context/content-creation/principles/copywriting-frameworks.md @@ -1,3 +1,5 @@ + + # Copywriting Frameworks **Category**: content diff --git a/.opencode/context/content-creation/principles/hooks.md b/.opencode/context/content-creation/principles/hooks.md index dcc957b..e44b92b 100644 --- a/.opencode/context/content-creation/principles/hooks.md +++ b/.opencode/context/content-creation/principles/hooks.md @@ -1,3 +1,5 @@ + + # Writing Compelling Hooks Techniques for creating attention-grabbing openings that make people want to keep reading, watching, or listening. diff --git a/.opencode/context/content-creation/principles/navigation.md b/.opencode/context/content-creation/principles/navigation.md index a206bd9..b8688b2 100644 --- a/.opencode/context/content-creation/principles/navigation.md +++ b/.opencode/context/content-creation/principles/navigation.md @@ -1,3 +1,5 @@ + + # Content Principles Navigation Core writing principles, frameworks, and techniques for effective content creation. diff --git a/.opencode/context/content-creation/principles/tone-voice.md b/.opencode/context/content-creation/principles/tone-voice.md index 573d9ad..a91d165 100644 --- a/.opencode/context/content-creation/principles/tone-voice.md +++ b/.opencode/context/content-creation/principles/tone-voice.md @@ -1,3 +1,5 @@ + + # Tone & Voice Guidelines **Category**: content diff --git a/.opencode/context/content-creation/workflows/audience-review.md b/.opencode/context/content-creation/workflows/audience-review.md index cc76112..19fb46b 100644 --- a/.opencode/context/content-creation/workflows/audience-review.md +++ b/.opencode/context/content-creation/workflows/audience-review.md @@ -1,3 +1,5 @@ + + # Audience Review Process for reviewing content to ensure it resonates with your target audience and achieves its goals. diff --git a/.opencode/context/content-creation/workflows/content-ideas.md b/.opencode/context/content-creation/workflows/content-ideas.md index b43f28f..ededfb4 100644 --- a/.opencode/context/content-creation/workflows/content-ideas.md +++ b/.opencode/context/content-creation/workflows/content-ideas.md @@ -1,3 +1,5 @@ + + # Content Ideas Frameworks and techniques for generating endless content ideas and overcoming creative blocks. diff --git a/.opencode/context/content-creation/workflows/content-matrix.md b/.opencode/context/content-creation/workflows/content-matrix.md index 58917df..3d40143 100644 --- a/.opencode/context/content-creation/workflows/content-matrix.md +++ b/.opencode/context/content-creation/workflows/content-matrix.md @@ -1,3 +1,5 @@ + + # Content Matrix Framework for organizing and planning content across topics, formats, and stages of the customer journey. diff --git a/.opencode/context/content-creation/workflows/navigation.md b/.opencode/context/content-creation/workflows/navigation.md index 8f67b63..ddd7c5e 100644 --- a/.opencode/context/content-creation/workflows/navigation.md +++ b/.opencode/context/content-creation/workflows/navigation.md @@ -1,3 +1,5 @@ + + # Content Workflows Navigation Content planning, ideation, and production workflows. diff --git a/.opencode/context/content-creation/workflows/remix-repurpose.md b/.opencode/context/content-creation/workflows/remix-repurpose.md index 7ccfbe9..d8587c1 100644 --- a/.opencode/context/content-creation/workflows/remix-repurpose.md +++ b/.opencode/context/content-creation/workflows/remix-repurpose.md @@ -1,3 +1,5 @@ + + # Content Remix and Repurposing Strategies for maximizing content ROI by transforming existing content into multiple formats and reaching new audiences. diff --git a/.opencode/context/core/config/navigation.md b/.opencode/context/core/config/navigation.md index 5f39382..1c45baf 100644 --- a/.opencode/context/core/config/navigation.md +++ b/.opencode/context/core/config/navigation.md @@ -1,3 +1,5 @@ + + # Core Configuration **Purpose**: Configuration standards and patterns for the context system diff --git a/.opencode/context/core/context-system.md b/.opencode/context/core/context-system.md index 2eedf3f..582ebdb 100644 --- a/.opencode/context/core/context-system.md +++ b/.opencode/context/core/context-system.md @@ -1,3 +1,5 @@ + + # Context System **Purpose**: Minimal, concern-based knowledge organization for AI agents diff --git a/.opencode/context/core/context-system/CHANGELOG.md b/.opencode/context/core/context-system/CHANGELOG.md index bdd3ef7..4a5f963 100644 --- a/.opencode/context/core/context-system/CHANGELOG.md +++ b/.opencode/context/core/context-system/CHANGELOG.md @@ -1,3 +1,5 @@ + + # Context System Changelog **Purpose**: Track major changes to the context system diff --git a/.opencode/context/core/context-system/examples/navigation-examples.md b/.opencode/context/core/context-system/examples/navigation-examples.md index 37001fe..be41082 100644 --- a/.opencode/context/core/context-system/examples/navigation-examples.md +++ b/.opencode/context/core/context-system/examples/navigation-examples.md @@ -1,3 +1,5 @@ + + # Examples: Navigation Files **Purpose**: Real-world examples of good navigation files diff --git a/.opencode/context/core/context-system/examples/navigation.md b/.opencode/context/core/context-system/examples/navigation.md new file mode 100644 index 0000000..fc5d66b --- /dev/null +++ b/.opencode/context/core/context-system/examples/navigation.md @@ -0,0 +1,39 @@ + + +# Context System Examples + +**Purpose**: Example navigation files and context patterns + +--- + +## Structure + +``` +examples/ +โ”œโ”€โ”€ navigation.md (this file) +โ””โ”€โ”€ navigation-examples.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **View navigation examples** | `navigation-examples.md` | +| **Learn navigation design** | `../guides/navigation-design-basics.md` | +| **Use templates** | `../guides/navigation-templates.md` | + +--- + +## By Type + +**Examples** โ†’ Working examples of navigation files + +--- + +## Related Context + +- **Context System** โ†’ `../navigation.md` +- **Guides** โ†’ `../guides/navigation.md` +- **Standards** โ†’ `../standards/navigation.md` diff --git a/.opencode/context/core/context-system/guides/compact.md b/.opencode/context/core/context-system/guides/compact.md index c8603e1..b261f3d 100644 --- a/.opencode/context/core/context-system/guides/compact.md +++ b/.opencode/context/core/context-system/guides/compact.md @@ -1,260 +1,77 @@ + + # Context Compaction (Minimization) **Purpose**: Compress verbose content into minimal viable information -**Last Updated**: 2026-01-06 +**Last Updated**: 2026-02-15 --- -## The Compaction Process +## Core Idea Transform verbose explanations โ†’ core concepts following MVI principle. -**Formula**: -``` -Verbose Content (100+ lines) - โ†“ Extract Core -Core Concept (1-3 sentences) - โ†“ Extract Key Points -Key Points (3-5 bullets) - โ†“ Extract Example -Minimal Example (<10 lines) - โ†“ Add Reference -Link to Full Docs - โ†“ Result -Compact File (<100 lines) -``` +**Formula**: Verbose Content โ†’ Core Concept (1-3 sentences) โ†’ Key Points (3-5 bullets) โ†’ Minimal Example (<10 lines) โ†’ Reference Link โ†’ Compact File --- -## Compression Techniques +## 5 Compression Techniques ### 1. Extract Core Concept -**From**: Paragraphs of explanation -**To**: 1-3 sentences capturing essence - -**Example**: -```markdown -BEFORE (verbose): -"React Hooks are a new addition to React 16.8 that let you use state -and other React features without writing a class. They're functions that -let you "hook into" React state and lifecycle features from function -components. Hooks don't work inside classes โ€” they let you use React -without classes. You can also create your own Hooks to reuse stateful -behavior between different components..." - -AFTER (compact): -"Hooks let you use state and lifecycle in function components without -classes. They're functions that hook into React features (useState, -useEffect, etc)." -``` - -**Rule**: If you can't explain it in 3 sentences, you don't understand it yet. Simplify further. - ---- +**From**: Paragraphs โ†’ **To**: 1-3 sentences +**Rule**: If you can't explain it in 3 sentences, simplify further. ### 2. Bulletize Key Points -**From**: Long paragraphs -**To**: 3-5 bullet points - -**Example**: -```markdown -BEFORE: -"When using hooks, there are several important rules to follow. First, -only call hooks at the top level of your function, never inside loops, -conditions, or nested functions. Second, only call hooks from React -function components or custom hooks. Third, hooks should be called in -the same order every render..." - -AFTER: -**Key Points**: -- Call hooks at top level only (not in loops/conditions) -- Call from function components or custom hooks only -- Must be called in same order every render -- Names should start with "use" (convention) -``` - +**From**: Long paragraphs โ†’ **To**: 3-5 bullet points **Rule**: Each bullet = one key fact. No sub-bullets. ---- - ### 3. Minimize Examples -**From**: Full implementations -**To**: Smallest working example (<10 lines) - -**Example**: -```markdown -BEFORE (50 lines): -import React, { useState, useEffect } from 'react' -import axios from 'axios' - -function UserProfile({ userId }) { - const [user, setUser] = useState(null) - const [loading, setLoading] = useState(true) - const [error, setError] = useState(null) - - useEffect(() => { - const fetchUser = async () => { - try { - setLoading(true) - const response = await axios.get(`/api/users/${userId}`) - setUser(response.data) - setError(null) - } catch (err) { - setError(err.message) - setUser(null) - } finally { - setLoading(false) - } - } - - fetchUser() - }, [userId]) - - if (loading) return
Loading...
- if (error) return
Error: {error}
- if (!user) return
No user found
- - return ( -
-

{user.name}

-

{user.email}

-
- ) -} - -AFTER (8 lines): -```js -const [count, setCount] = useState(0) - -useEffect(() => { - document.title = `Count: ${count}` -}, [count]) // Re-run when count changes - -return -``` - -**Rule**: Show the simplest case that demonstrates the concept. Link to full examples. - ---- +**From**: Full implementations โ†’ **To**: Smallest working example (<10 lines) +**Rule**: Show the simplest case. Link to full examples. ### 4. Replace Repetition with References -**From**: Same info repeated in multiple places -**To**: Define once, reference with links - -**Example**: -```markdown -BEFORE: -# File A -Authentication uses JWT tokens. JWT tokens are JSON Web Tokens that... - -# File B -For auth, we use JWT tokens. JWT tokens are JSON Web Tokens that... - -# File C -The JWT token system (JSON Web Tokens) allows us to... - -AFTER: -# concepts/jwt.md -"JWT (JSON Web Token) is a stateless authentication method..." - -# Other files -See concepts/jwt.md for details. -``` - +**From**: Same info repeated โ†’ **To**: Define once, reference with links **Rule**: Say it once in concepts/, reference everywhere else. ---- - ### 5. Convert Prose to Tables -**From**: Paragraphs listing things -**To**: Scannable tables - -**Example**: -```markdown -BEFORE: -"There are several important lifecycle methods. componentDidMount runs -after mounting, componentDidUpdate runs after updates, componentWillUnmount -runs before unmounting..." - -AFTER: -| Method | When It Runs | -|--------|--------------| -| componentDidMount | After mount | -| componentDidUpdate | After update | -| componentWillUnmount | Before unmount | -``` - +**From**: Paragraphs listing things โ†’ **To**: Scannable tables **Rule**: If listing >3 items, use a table or bullets. --- ## Compaction Checklist -Before finalizing a context file: - - [ ] Core concept is 1-3 sentences? - [ ] Key points are 3-5 bullets (no sub-bullets)? - [ ] Example is <10 lines of code? - [ ] No repeated explanations? - [ ] Reference link added for deep dive? -- [ ] File is <200 lines total? +- [ ] File is under line limit? - [ ] Can be scanned in <30 seconds? -If any "no", compress further. - --- -## Common Bloat Patterns +## Common Bloat Patterns to Remove -### Bloat: Over-Explaining -```markdown -โŒ "This is important because it allows you to manage state in a more -efficient way, which can lead to better performance and cleaner code..." - -โœ… "Manages state efficiently" -``` - -### Bloat: Historical Context -```markdown -โŒ "Before React 16.8, we used class components. Then hooks were -introduced to solve several problems with classes..." - -โœ… Skip history unless critical. Just explain current approach. -``` - -### Bloat: Multiple Examples -```markdown -โŒ Example 1: useState with counter - Example 2: useState with string - Example 3: useState with object - Example 4: useState with array... - -โœ… Show ONE simple example. Link to more. -``` - -### Bloat: Implementation Details -```markdown -โŒ "The internal implementation uses a fiber architecture with a -reconciliation algorithm that diffs the virtual DOM..." - -โœ… Skip internal details. Just show how to use it. -``` +| Bloat Type | โŒ Avoid | โœ… Use Instead | +|------------|---------|---------------| +| Over-Explaining | "This is important because it allows you to manage state in a more efficient way..." | "Manages state efficiently" | +| Historical Context | "Before React 16.8, we used class components..." | Skip history unless critical | +| Multiple Examples | Example 1, 2, 3, 4... | ONE simple example + link | +| Implementation Details | "The internal implementation uses a fiber architecture..." | Skip internals, show usage | --- ## Target Line Counts -| File Type | Target Lines | Max Lines | -|-----------|--------------|-----------| +| File Type | Target | Max | +|-----------|--------|-----| | Concept | 40-60 | 100 | | Example | 30-50 | 80 | | Guide | 60-100 | 150 | | Lookup | 20-40 | 100 | | Error | 50-80 | 150 | -| README | 40-60 | 100 | **Philosophy**: If you hit max lines, split into multiple files or reference external docs. @@ -264,35 +81,21 @@ reconciliation algorithm that diffs the virtual DOM..." Every context file must be scannable in <30 seconds. - - If a developer can't grasp the core idea in 30 seconds: - - File is too verbose - - Concept is not well explained - - Needs more compression -**Test**: Give file to someone unfamiliar. Can they explain it back in 30 seconds? +**Test**: Can someone unfamiliar explain it back in 30 seconds? --- -## Compression Examples +## Quick Example -### Before: 150 lines -```markdown -# Authentication System +**Before (150 lines)**: Long authentication system explanation with edge cases, examples, etc. -Our authentication system is built on JSON Web Tokens (JWT), which -is a standard for securely transmitting information between parties... - -[100+ more lines of explanation, edge cases, examples, etc.] -``` - -### After: 45 lines +**After (45 lines)**: ```markdown # Concept: Authentication -**Core Idea**: JWT-based stateless auth. Token in httpOnly cookie, -verified on every request. +**Core Idea**: JWT-based stateless auth. Token in httpOnly cookie, verified on every request. **Key Points**: - Token has userId + role claims @@ -314,6 +117,6 @@ res.cookie('auth', token, { httpOnly: true }) ## Related -- mvi-principle.md - What MVI is -- harvest.md - When to compact (during extraction) +- mvi.md - MVI principle +- harvest.md - When to compact - templates.md - Standard formats diff --git a/.opencode/context/core/context-system/guides/creation.md b/.opencode/context/core/context-system/guides/creation.md index 869f54a..73034be 100644 --- a/.opencode/context/core/context-system/guides/creation.md +++ b/.opencode/context/core/context-system/guides/creation.md @@ -1,402 +1,173 @@ + + # Context File Creation Standards **Purpose**: Ensure all context files follow the same format and structure -**Last Updated**: 2026-01-06 +**Last Updated**: 2026-02-15 --- ## Critical Rules - - Files MUST be <200 lines. No exceptions. - - - - All files MUST follow MVI: 1-3 sentence core, 3-5 key points, minimal example, reference link. - - - - Files MUST be in correct function folder: concepts/, examples/, guides/, lookup/, or errors/. - - - - MUST update category README.md navigation when creating files. - + Files MUST be under line limits (see below) + All files MUST follow MVI principle + Files MUST be in correct folder + MUST update navigation.md when creating files --- ## Creation Workflow - - - Ask: Is this a concept, example, guide, lookup, or error? - โ†’ Place in correct folder - - - - Use standard template for file type (see templates.md) - - - - - Core: 1-3 sentences - - Key points: 3-5 bullets - - Example: <10 lines - - Reference: Link to docs - - - - Ensure file <200 lines. If not, split or reference external. - - - - Link to related concepts/, examples/, guides/, errors/ - - - - MUST show full preview before writing ANY files: +### 1. Determine Function +Ask: Is this a concept, example, guide, lookup, or error? +โ†’ Place in correct folder - ``` - โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” - Preview: File Creation Plan - โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” +### 2. Apply Template +Use standard template for file type (see templates.md) - CREATE file: - {category}/{function}/{filename}.md ({line_count} lines) +### 3. Apply MVI +- Core: 1-3 sentences +- Key points: 3-5 bullets +- Example: <10 lines +- Reference: Link to docs - Content preview: - โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” - โ”‚ # {Type}: {Name} โ”‚ - โ”‚ โ”‚ - โ”‚ **Purpose**: {1 sentence} โ”‚ - โ”‚ **Last Updated**: {date} โ”‚ - โ”‚ โ”‚ - โ”‚ ## Core Concept โ”‚ - โ”‚ {1-3 sentences} โ”‚ - โ”‚ โ”‚ - โ”‚ ## Key Points โ”‚ - โ”‚ {3-5 bullets} โ”‚ - โ”‚ ... โ”‚ - โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ +### 4. Validate Size +Ensure file under limit. If not, split or reference external. - UPDATE navigation: - {category}/navigation.md - + | [{filename}.md]({function}/{filename}.md) | {desc} | {priority} | +### 5. Add Cross-References +Link to related concepts/, examples/, guides/, errors/ - Validation: - โœ“ {line_count} lines (limit: {max_lines} for {type}) - โœ“ MVI format applied - โœ“ Correct folder: {function}/ - โœ“ Cross-references: {count} links added - - Approve? [y/n/edit]: _ - ``` - - If file already exists at target path: - ``` - โš ๏ธ File already exists: {category}/{function}/{filename}.md - - Options: - 1. Cancel (keep existing) - 2. Show diff (compare existing vs new) - 3. Overwrite (replace existing) - 4. Rename new file to {filename}-v2.md - - Choose [1/2/3/4]: _ - ``` - - - - Only after approval: - 1. Write file to disk - 2. Update navigation.md - 3. Show confirmation: - - ``` - โœ… Created: {category}/{function}/{filename}.md ({line_count} lines) - โœ… Updated: {category}/navigation.md - ``` - - - - - [ ] <200 lines? - - [ ] MVI format? - - [ ] Correct folder? - - [ ] navigation.md updated? - - [ ] Cross-refs added? - - +### 6. Update Navigation +Add entry to navigation.md in parent directory --- ## File Naming Conventions -### Concepts -**Format**: `{topic}.md` -**Examples**: -- `authentication.md` -- `state-management.md` -- `mvi-principle.md` +| Type | Format | Example | +|------|--------|---------| +| Concept | `{concept-name}.md` | `authentication.md` | +| Example | `{example-name}.md` | `jwt-example.md` | +| Guide | `{action-name}.md` | `creating-agents.md` | +| Lookup | `{reference-name}.md` | `commands.md` | +| Error | `{error-category}.md` | `auth-errors.md` | -**Rule**: Lowercase, hyphenated, describes the concept +**Rules**: +- Use kebab-case (lowercase with hyphens) +- Be descriptive but concise +- Avoid redundant category in name (not `concept-authentication.md`) --- -### Examples -**Format**: `{what-it-demonstrates}.md` -**Examples**: -- `jwt-auth-example.md` -- `react-hooks-example.md` -- `api-call-example.md` +## Standard Metadata (Frontmatter) -**Rule**: End with `-example.md`, describes what it shows - ---- - -### Guides -**Format**: `{action-being-done}.md` -**Examples**: -- `setting-up-auth.md` -- `deploying-api.md` -- `migrating-to-v2.md` - -**Rule**: Gerund form (verbs ending in -ing), describes the task - ---- - -### Lookup -**Format**: `{what-is-referenced}.md` -**Examples**: -- `cli-commands.md` -- `file-locations.md` -- `api-endpoints.md` - -**Rule**: Plural noun, describes the reference type - ---- - -### Errors -**Format**: `{framework-or-topic}-errors.md` -**Examples**: -- `react-errors.md` -- `nextjs-build-errors.md` -- `auth-errors.md` - -**Rule**: End with `-errors.md`, group by framework/topic (NOT one file per error) - ---- - -## Standard Metadata - -Every context file MUST start with: - -```markdown -# {Type}: {Name} - -**Purpose**: [1 sentence describing what this file contains] - -**Last Updated**: {YYYY-MM-DD} - ---- +```html + ``` -**Example**: -```markdown -# Concept: JWT Authentication +**Priority levels**: critical, high, medium, low -**Purpose**: Stateless authentication using signed JSON Web Tokens - -**Last Updated**: 2026-01-06 - ---- -``` +**When to use**: +- critical: Core system files, always needed +- high: Frequently referenced, important patterns +- medium: Useful but not essential +- low: Nice-to-have, rarely needed --- -## Priority Assignment +## File Size Limits -When adding files to README.md, assign priority: +| File Type | Max Lines | +|-----------|-----------| +| Concept | 100 | +| Example | 80 | +| Guide | 150 | +| Lookup | 100 | +| Error | 150 | -| Priority | When to Use | -|----------|-------------| -| **critical** | Must understand to work on project. Core concepts. | -| **high** | Commonly used. Important patterns. | -| **medium** | Occasionally needed. Reference material. | -| **low** | Rarely used. Edge cases. | - -**Example**: -```markdown -### Concepts -| File | Description | Priority | -|------|-------------|----------| -| [auth.md](concepts/auth.md) | Authentication system | critical | -| [caching.md](concepts/caching.md) | Cache strategy | high | -| [logging.md](concepts/logging.md) | Logging patterns | medium | -``` +**Enforcement**: Strict. If over limit, split into multiple files or reference external docs. --- ## Cross-Reference Guidelines -### When to Link +**Format**: `See {type}/{filename}.md for {what}` -Link to related files when: -- Concept uses another concept -- Example demonstrates a concept -- Guide references concepts/examples -- Error relates to specific concept +**Examples**: +- `See concepts/authentication.md for JWT details` +- `See examples/jwt-example.md for working code` +- `See errors/auth-errors.md for troubleshooting` -### How to Link - -**Format**: `**Related**: type/file.md` - -**Example**: -```markdown -**Related**: -- concepts/authentication.md -- examples/jwt-auth-example.md -- errors/auth-errors.md -``` - -**Rule**: Use relative paths from current location +**Best practices**: +- Link to related concepts +- Link to examples from guides +- Link to errors from guides +- Create bidirectional links when relevant --- -## README.md Update Process +## Navigation Update Process -When creating a new file: +When creating a file, update parent `navigation.md`: -1. **Open category README.md** -2. **Find correct section** (Concepts/Examples/Guides/Lookup/Errors) -3. **Add table row**: - ```markdown - | [file.md](folder/file.md) | Description | priority | - ``` -4. **Sort by priority** (critical โ†’ high โ†’ medium โ†’ low) -5. **Update "Last Updated"** date at top +```markdown +| File | Description | Priority | +|------|-------------|----------| +| new-file.md | Brief description | high | +``` + +**Keep navigation**: +- Alphabetical within priority groups +- Grouped by priority (critical โ†’ high โ†’ medium โ†’ low) +- Descriptions <10 words --- ## Validation Before Commit - - - - [ ] File is <200 lines? - - [ ] Follows MVI format (1-3 sentences, 3-5 points, example, reference)? - - [ ] In correct function folder (concepts/examples/guides/lookup/errors)? - - [ ] Has standard metadata (Purpose, Last Updated)? - - [ ] Added to navigation.md navigation? - - [ ] Priority assigned (critical/high/medium/low)? - - [ ] Cross-references added? - - [ ] Scannable in <30 seconds? - - [ ] No duplication of existing content? - - - -**If any checkbox is unchecked, fix before committing.** +- [ ] File under line limit? +- [ ] MVI format applied? +- [ ] Frontmatter added? +- [ ] In correct folder? +- [ ] Navigation.md updated? +- [ ] Cross-references added? +- [ ] Can be scanned in <30 seconds? --- ## Common Creation Mistakes -### โŒ Mistake 1: Wrong Folder -``` -development/authentication.md โŒ (flat structure) - -development/concepts/authentication.md โœ… (function-based) -``` - -### โŒ Mistake 2: Too Verbose -```markdown -# Concept: JWT - -[500 lines of explanation, examples, edge cases...] โŒ - -# Concept: JWT - -**Core Idea**: Stateless auth with signed tokens (1-3 sentences) โœ… -``` - -### โŒ Mistake 3: Missing README Update -``` -Created: concepts/new-topic.md -README.md: Not updated โŒ - -Created: concepts/new-topic.md -README.md: Updated with navigation entry โœ… -``` - -### โŒ Mistake 4: One Error Per File -``` -errors/jwt-expired-error.md -errors/jwt-invalid-error.md -errors/jwt-missing-error.md โŒ (too granular) - -errors/auth-errors.md โœ… (grouped by topic) -``` - ---- - -## File Size Enforcement - - - If file exceeds line limit: - - 1. First: Apply more compression (see compact.md) - 2. If still too large: Split into multiple files - 3. If logically can't split: Move details to external docs, keep summary - - DO NOT exceed 200 lines under any circumstance. - - -**Example**: -```markdown -If concepts/authentication.md hits 250 lines: - -Option 1: Compress (apply MVI more strictly) -Option 2: Split: - - concepts/authentication.md (core) - - concepts/jwt-tokens.md (specific type) - - concepts/oauth.md (another type) -Option 3: Reference external: - - Keep 100-line summary in concepts/authentication.md - - Link to https://docs.company.com/auth (full details) -``` +| Mistake | Fix | +|---------|-----| +| File too long | Split into multiple files or compress | +| Missing frontmatter | Add HTML comment at top | +| Wrong folder | Move to correct function folder | +| No cross-references | Add links to related files | +| Verbose explanations | Apply MVI compression | +| Missing from navigation | Update navigation.md | --- ## Template Selection -| File Type | Template | Max Lines | -|-----------|----------|-----------| -| Concept | templates.md โ†’ Concept Template | 100 | -| Example | templates.md โ†’ Example Template | 80 | -| Guide | templates.md โ†’ Guide Template | 150 | -| Lookup | templates.md โ†’ Lookup Template | 100 | -| Error | templates.md โ†’ Error Template | 150 | -| README | templates.md โ†’ README Template | 100 | +| File Type | Template | Use When | +|-----------|----------|----------| +| Concept | Concept template | Explaining what something is | +| Example | Example template | Showing working code | +| Guide | Guide template | Step-by-step instructions | +| Lookup | Lookup template | Quick reference data | +| Error | Error template | Troubleshooting issues | ---- - -## Quality Standards - -Every context file must be: - -1. **Minimal** - <200 lines, no bloat -2. **Scannable** - Can grasp in <30 seconds -3. **Functional** - In correct function folder -4. **Referenced** - Cross-links to related files -5. **Discoverable** - Listed in README.md -6. **Accurate** - Facts only, no speculation -7. **Current** - Last Updated date maintained +See templates.md for full templates. --- ## Related -- templates.md - Standard file formats -- mvi-principle.md - What to include -- compact.md - How to minimize -- structure.md - Where files go +- templates.md - File templates +- mvi.md - MVI principle +- compact.md - Compression techniques +- structure.md - Directory structure diff --git a/.opencode/context/core/context-system/guides/navigation-design-basics.md b/.opencode/context/core/context-system/guides/navigation-design-basics.md index c5c134c..4c20a92 100644 --- a/.opencode/context/core/context-system/guides/navigation-design-basics.md +++ b/.opencode/context/core/context-system/guides/navigation-design-basics.md @@ -1,3 +1,5 @@ + + # Guide: Designing Navigation Files **Purpose**: How to create token-efficient, scannable navigation files diff --git a/.opencode/context/core/context-system/guides/navigation-templates.md b/.opencode/context/core/context-system/guides/navigation-templates.md index 1b802e5..f3baf34 100644 --- a/.opencode/context/core/context-system/guides/navigation-templates.md +++ b/.opencode/context/core/context-system/guides/navigation-templates.md @@ -1,3 +1,5 @@ + + # Navigation File Templates **Purpose**: Ready-to-use templates for navigation files diff --git a/.opencode/context/core/context-system/guides/navigation.md b/.opencode/context/core/context-system/guides/navigation.md new file mode 100644 index 0000000..913aa34 --- /dev/null +++ b/.opencode/context/core/context-system/guides/navigation.md @@ -0,0 +1,50 @@ + + +# Context System Guides + +**Purpose**: Step-by-step guides for working with the context system + +--- + +## Structure + +``` +guides/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ compact.md +โ”œโ”€โ”€ creation.md +โ”œโ”€โ”€ navigation-design-basics.md +โ”œโ”€โ”€ navigation-templates.md +โ”œโ”€โ”€ organizing-context.md +โ””โ”€โ”€ workflows.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Create context files** | `creation.md` | +| **Design navigation** | `navigation-design-basics.md` | +| **Use templates** | `navigation-templates.md` | +| **Organize context** | `organizing-context.md` | +| **Compact files** | `compact.md` | +| **Context workflows** | `workflows.md` | + +--- + +## By Type + +**Creation** โ†’ How to create new context files +**Navigation** โ†’ How to design navigation files +**Organization** โ†’ How to organize context structure +**Maintenance** โ†’ How to maintain and compact files + +--- + +## Related Context + +- **Context System** โ†’ `../navigation.md` +- **Operations** โ†’ `../operations/navigation.md` +- **Standards** โ†’ `../standards/navigation.md` diff --git a/.opencode/context/core/context-system/guides/organizing-context.md b/.opencode/context/core/context-system/guides/organizing-context.md index eba98cf..5393393 100644 --- a/.opencode/context/core/context-system/guides/organizing-context.md +++ b/.opencode/context/core/context-system/guides/organizing-context.md @@ -1,18 +1,10 @@ + + # Guide: Organizing Context by Concern **Purpose**: How to choose and apply the right organizational pattern -**Last Updated**: 2026-01-08 - ---- - -## Prerequisites - -- Understand context system principles (../context-system.md) -- Know your content domain -- Have content to organize - -**Estimated time**: 30-45 min per category +**Last Updated**: 2026-02-15 --- @@ -22,11 +14,14 @@ **Use for**: Repository-specific context **Structure**: Organize by what the information does -- `concepts/` - What it is -- `examples/` - Working code -- `guides/` - How to do it -- `lookup/` - Quick reference -- `errors/` - Troubleshooting +``` +{repo}/ +โ”œโ”€โ”€ concepts/ # What it is +โ”œโ”€โ”€ examples/ # Working code +โ”œโ”€โ”€ guides/ # How to do it +โ”œโ”€โ”€ lookup/ # Quick reference +โ””โ”€โ”€ errors/ # Troubleshooting +``` **Example**: `openagents-repo/` @@ -36,470 +31,106 @@ **Use for**: Multi-technology development context **Structure**: Organize by what you're doing (concern), then how (approach/tech) -- `{concern}/` - What you're working on - - `{approach}/` - How you're doing it - - `{tech}/` - What you're using +``` +{concern}/ +โ”œโ”€โ”€ {approach}/ # How you're doing it +โ””โ”€โ”€ {tech}/ # What you're using +``` -**Example**: `development/` +**Example**: `development/frontend/react/`, `ui/web/design/` --- ## Decision Tree -### Step 1: Is this repository-specific? - -**YES** โ†’ Use **Pattern A (Function-Based)** - -Examples: -- `openagents-repo/` - OpenAgents Control repository work -- `myproject-repo/` - Your project's repository - -**NO** โ†’ Continue to Step 2 +| Question | Answer | Use Pattern | +|----------|--------|-------------| +| Is this repository-specific? | YES | **Pattern A** (Function-Based) | +| Does content span multiple technologies? | YES | **Pattern B** (Concern-Based) | +| Single domain/technology? | YES | **Pattern A** (Function-Based) | --- -### Step 2: Does content span multiple technologies? - -**YES** โ†’ Use **Pattern B (Concern-Based)** - -Examples: -- `development/` - Frontend, backend, data, infrastructure -- `ui/` - Web, terminal, mobile (future) - -**NO** โ†’ Use **Pattern A (Function-Based)** - -Examples: -- `content/` - Copywriting frameworks (single domain) -- `product/` - Product management (single domain) - ---- - -### Step 3: Is there a natural hierarchy of concerns? - -**YES** โ†’ Use **Pattern B (Concern-Based)** - -Example hierarchy: -``` -development/ -โ”œโ”€โ”€ frontend/ # Concern -โ”‚ โ”œโ”€โ”€ react/ # Tech -โ”‚ โ””โ”€โ”€ vue/ # Tech -โ”œโ”€โ”€ backend/ # Concern -โ”‚ โ”œโ”€โ”€ api-patterns/ # Approach -โ”‚ โ””โ”€โ”€ nodejs/ # Tech -``` - -**NO** โ†’ Use **Pattern A (Function-Based)** - ---- - -## Pattern A: Function-Based Organization - -### When to Use - -โœ… Repository-specific context (e.g., `openagents-repo/`) -โœ… Single-domain content (e.g., `content/`, `product/`) -โœ… Content naturally groups by information type -โœ… Users need to find "how to do X" quickly - -### Structure - -``` -{category}/ -โ”œโ”€โ”€ navigation.md -โ”œโ”€โ”€ quick-start.md # Optional: orientation -โ”‚ -โ”œโ”€โ”€ core-concepts/ # Optional: foundational -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ””โ”€โ”€ {concept}.md -โ”‚ -โ”œโ”€โ”€ concepts/ # What it is -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ””โ”€โ”€ {concept}.md -โ”‚ -โ”œโ”€โ”€ examples/ # Working code -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ””โ”€โ”€ {example}.md -โ”‚ -โ”œโ”€โ”€ guides/ # How to do it -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ””โ”€โ”€ {guide}.md -โ”‚ -โ”œโ”€โ”€ lookup/ # Quick reference -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ””โ”€โ”€ {lookup}.md -โ”‚ -โ””โ”€โ”€ errors/ # Troubleshooting - โ”œโ”€โ”€ navigation.md - โ””โ”€โ”€ {error}.md -``` - -### Example: openagents-repo/ - -``` -openagents-repo/ -โ”œโ”€โ”€ navigation.md -โ”œโ”€โ”€ quick-start.md -โ”‚ -โ”œโ”€โ”€ core-concepts/ # Foundational (agents, evals, registry) -โ”œโ”€โ”€ concepts/ # Additional concepts -โ”œโ”€โ”€ guides/ # How to add agent, test, etc. -โ”œโ”€โ”€ lookup/ # Commands, file locations -โ”œโ”€โ”€ examples/ # Context bundles, prompts -โ””โ”€โ”€ errors/ # Tool permissions, validation -``` - -**Why this works**: -- Repository-specific (not general development) -- Users need "how to add agent" (guide) -- Users need "where is X file" (lookup) -- Users need "fix this error" (errors) - ---- - -## Pattern B: Concern-Based Organization - -### When to Use - -โœ… Multi-technology content (e.g., `development/`) -โœ… Content organized by "what you're doing" (concern) -โœ… Multiple approaches/technologies per concern -โœ… Need to support full-stack workflows - -### Structure - -``` -{category}/ -โ”œโ”€โ”€ navigation.md -โ”œโ”€โ”€ {concern}-navigation.md # Specialized (optional) -โ”‚ -โ”œโ”€โ”€ principles/ # Universal (optional) -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ””โ”€โ”€ {principle}.md -โ”‚ -โ”œโ”€โ”€ {concern}/ # What you're doing -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ”‚ -โ”‚ โ”œโ”€โ”€ {approach}/ # How (approach-based) -โ”‚ โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ”‚ โ””โ”€โ”€ {pattern}.md -โ”‚ โ”‚ -โ”‚ โ””โ”€โ”€ {tech}/ # How (tech-specific) -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ””โ”€โ”€ {pattern}.md -``` - -### Example: development/ - -``` -development/ -โ”œโ”€โ”€ navigation.md -โ”œโ”€โ”€ ui-navigation.md # Specialized -โ”œโ”€โ”€ backend-navigation.md # Specialized -โ”‚ -โ”œโ”€โ”€ principles/ # Universal -โ”‚ โ”œโ”€โ”€ clean-code.md -โ”‚ โ””โ”€โ”€ api-design.md -โ”‚ -โ”œโ”€โ”€ frontend/ # Concern: client-side -โ”‚ โ”œโ”€โ”€ react/ # Tech -โ”‚ โ”‚ โ”œโ”€โ”€ hooks-patterns.md -โ”‚ โ”‚ โ””โ”€โ”€ tanstack/ # Sub-tech -โ”‚ โ””โ”€โ”€ vue/ # Tech -โ”‚ -โ”œโ”€โ”€ backend/ # Concern: server-side -โ”‚ โ”œโ”€โ”€ api-patterns/ # Approach -โ”‚ โ”‚ โ”œโ”€โ”€ rest-design.md -โ”‚ โ”‚ โ””โ”€โ”€ graphql-design.md -โ”‚ โ”œโ”€โ”€ nodejs/ # Tech -โ”‚ โ””โ”€โ”€ authentication/ # Functional concern -โ”‚ -โ””โ”€โ”€ data/ # Concern: data layer - โ”œโ”€โ”€ sql-patterns/ # Approach - โ””โ”€โ”€ orm-patterns/ # Approach -``` - -**Why this works**: -- Multi-technology (React, Vue, Node, Python, etc.) -- Organized by concern (frontend, backend, data) -- Then by approach (REST, GraphQL) or tech (Node.js, React) -- Supports full-stack workflows - ---- - -## Hybrid Approach - -### When to Use - -โœ… Category has both repository-specific AND multi-tech content -โœ… Need flexibility for different subcategories - -### Structure - -``` -{category}/ -โ”œโ”€โ”€ navigation.md -โ”‚ -โ”œโ”€โ”€ {subcategory-A}/ # Function-based -โ”‚ โ”œโ”€โ”€ concepts/ -โ”‚ โ”œโ”€โ”€ guides/ -โ”‚ โ””โ”€โ”€ examples/ -โ”‚ -โ””โ”€โ”€ {subcategory-B}/ # Concern-based - โ”œโ”€โ”€ {concern}/ - โ”‚ โ”œโ”€โ”€ {approach}/ - โ”‚ โ””โ”€โ”€ {tech}/ -``` - -### Example: ui/ - -``` -ui/ -โ”œโ”€โ”€ navigation.md -โ”‚ -โ”œโ”€โ”€ web/ # Platform (concern-based) -โ”‚ โ”œโ”€โ”€ navigation.md -โ”‚ โ”œโ”€โ”€ animation-patterns.md -โ”‚ โ”œโ”€โ”€ ui-styling-standards.md -โ”‚ โ””โ”€โ”€ design/ -โ”‚ โ”œโ”€โ”€ concepts/ # Function-based within -โ”‚ โ””โ”€โ”€ examples/ -โ”‚ -โ””โ”€โ”€ terminal/ # Platform (concern-based) - โ””โ”€โ”€ navigation.md -``` - -**Why this works**: -- Top level: Platform-based (web, terminal, mobile) -- Within platform: Mix of flat files + function folders -- Flexible for different needs - ---- - -## Organizing by Concern vs Tech - -### Concern First, Then Tech - -**Use when**: Multiple technologies solve the same concern - -``` -backend/ -โ”œโ”€โ”€ api-patterns/ # Concern: API design -โ”‚ โ”œโ”€โ”€ rest-design.md # Approach -โ”‚ โ”œโ”€โ”€ graphql-design.md # Approach -โ”‚ โ””โ”€โ”€ grpc-patterns.md # Approach -โ”œโ”€โ”€ nodejs/ # Tech -โ””โ”€โ”€ python/ # Tech -``` - -**Why**: Principles (REST, GraphQL) are more important than implementation (Node, Python) - ---- - -### Tech First, Then Concern - -**Use when**: Technology dictates the approach - -``` -frontend/ -โ”œโ”€โ”€ react/ # Tech -โ”‚ โ”œโ”€โ”€ hooks-patterns.md # Concern: state -โ”‚ โ”œโ”€โ”€ component-architecture.md # Concern: structure -โ”‚ โ””โ”€โ”€ tanstack/ # Sub-tech -โ”‚ โ”œโ”€โ”€ query-patterns.md # Concern: data fetching -โ”‚ โ””โ”€โ”€ router-patterns.md # Concern: routing -โ””โ”€โ”€ vue/ # Tech -``` - -**Why**: React patterns differ significantly from Vue patterns - ---- - -## Specialized Navigation Files - -### When to Create - -โœ… Concern spans multiple subcategories -โœ… Common workflows cross category boundaries -โœ… Users need task-focused routes - -### Examples - -**ui-navigation.md** (in `development/`): -- Spans `development/frontend/` + `ui/web/` -- Task: "I need to build a UI" -- Routes to both code patterns and visual design - -**backend-navigation.md** (in `development/`): -- Covers `backend/api-patterns/`, `backend/nodejs/`, `backend/authentication/` -- Task: "I need to build an API" -- Routes to approach, tech, and functional concerns - -**fullstack-navigation.md** (in `development/`): -- Covers frontend + backend + data -- Task: "I need to build a full-stack app" -- Shows common tech stacks (MERN, T3, etc.) - ---- - -## Steps to Organize +## Quick Steps to Organize ### 1. Audit Existing Content - -List all files: -```bash -find .opencode/context/{category} -name "*.md" | sort -``` - -Categorize each file: -- What concern does it address? -- What approach/tech does it cover? -- What type of information? (concept, guide, example, etc.) - ---- +- List all files +- Identify natural groupings +- Note overlaps/duplicates ### 2. Choose Pattern - -Use decision tree above to choose: -- Pattern A (Function-Based) -- Pattern B (Concern-Based) -- Hybrid - ---- +- Use decision tree above +- Consider future growth +- Check existing patterns in `.opencode/context/` ### 3. Create Directory Structure - -**For Pattern A**: ```bash -mkdir -p {category}/{concepts,examples,guides,lookup,errors} +mkdir -p {category}/{subcategory} ``` -**For Pattern B**: -```bash -mkdir -p {category}/{concern}/{approach} -mkdir -p {category}/{concern}/{tech} -``` - ---- - ### 4. Move Files - -Move files to appropriate locations: -```bash -mv {category}/old-file.md {category}/{concern}/{tech}/new-file.md -``` - -Rename for clarity: -```bash -mv code.md code-quality.md -mv tests.md test-coverage.md -``` - ---- +- Move files to new structure +- Keep filenames descriptive +- Follow naming conventions ### 5. Create Navigation Files - -Create `navigation.md` at each level: -- Category level -- Subcategory level -- Specialized navigation (if needed) - -Follow navigation design guide (navigation-design.md) - ---- +- Add `navigation.md` to each directory +- Follow navigation template (see navigation-templates.md) +- Keep to 200-300 tokens ### 6. Update References - -Find and update all cross-references: -```bash -grep -r "old-path" .opencode/context/ -# Update to new paths -``` +- Update links in moved files +- Update parent navigation.md +- Test navigation paths --- -## Examples +## Pattern Examples -### Example 1: Organizing development/ - -**Before** (flat): -``` -development/ -โ”œโ”€โ”€ clean-code.md -โ”œโ”€โ”€ api-design.md -โ”œโ”€โ”€ react-patterns.md -โ”œโ”€โ”€ animation-patterns.md -โ”œโ”€โ”€ design-systems.md -``` - -**After** (concern-based): -``` -development/ -โ”œโ”€โ”€ navigation.md -โ”œโ”€โ”€ ui-navigation.md -โ”‚ -โ”œโ”€โ”€ principles/ -โ”‚ โ”œโ”€โ”€ clean-code.md -โ”‚ โ””โ”€โ”€ api-design.md -โ”‚ -โ””โ”€โ”€ frontend/ - โ””โ”€โ”€ react/ - โ””โ”€โ”€ react-patterns.md -``` - -**Moved to ui/**: -``` -ui/web/ -โ”œโ”€โ”€ animation-patterns.md -โ””โ”€โ”€ design-systems.md -``` - ---- - -### Example 2: Organizing openagents-repo/ - -**Before** (mixed): +### Function-Based (openagents-repo/) ``` openagents-repo/ -โ”œโ”€โ”€ README.md -โ”œโ”€โ”€ agents.md -โ”œโ”€โ”€ evals.md -โ”œโ”€โ”€ adding-agent.md -โ”œโ”€โ”€ testing-agent.md -โ”œโ”€โ”€ commands.md +โ”œโ”€โ”€ concepts/agents.md +โ”œโ”€โ”€ examples/subagent-example.md +โ”œโ”€โ”€ guides/creating-agents.md +โ”œโ”€โ”€ lookup/commands.md +โ””โ”€โ”€ errors/tool-errors.md ``` -**After** (function-based): +### Concern-Based (development/) ``` -openagents-repo/ -โ”œโ”€โ”€ navigation.md -โ”œโ”€โ”€ quick-start.md -โ”‚ -โ”œโ”€โ”€ core-concepts/ -โ”‚ โ”œโ”€โ”€ agent-architecture.md -โ”‚ โ””โ”€โ”€ eval-framework.md -โ”‚ -โ”œโ”€โ”€ guides/ -โ”‚ โ”œโ”€โ”€ adding-agent.md -โ”‚ โ””โ”€โ”€ testing-agent.md -โ”‚ -โ””โ”€โ”€ lookup/ - โ””โ”€โ”€ commands.md +development/ +โ”œโ”€โ”€ frontend/ +โ”‚ โ”œโ”€โ”€ react/ +โ”‚ โ””โ”€โ”€ vue/ +โ”œโ”€โ”€ backend/ +โ”‚ โ”œโ”€โ”€ node/ +โ”‚ โ””โ”€โ”€ python/ +โ””โ”€โ”€ data/ + โ””โ”€โ”€ postgres/ +``` + +### Hybrid (ui/) +``` +ui/ +โ”œโ”€โ”€ web/ +โ”‚ โ”œโ”€โ”€ design/ +โ”‚ โ”œโ”€โ”€ animation/ +โ”‚ โ””โ”€โ”€ react-patterns.md +โ””โ”€โ”€ terminal/ + โ””โ”€โ”€ cli-design.md ``` --- -## Verification +## Verification Checklist -After organizing: - -- [ ] Pattern chosen (A, B, or Hybrid)? -- [ ] Directory structure created? -- [ ] Files moved to appropriate locations? -- [ ] Files renamed for clarity? -- [ ] Navigation files created at each level? -- [ ] Cross-references updated? -- [ ] Token count for navigation files 200-300? +- [ ] Every directory has navigation.md? +- [ ] Navigation files follow template? +- [ ] All files have frontmatter? +- [ ] Links updated and working? +- [ ] Pattern is consistent? +- [ ] Files under line limits? --- @@ -507,15 +138,15 @@ After organizing: | Issue | Solution | |-------|----------| -| File fits multiple concerns | Choose primary concern, add cross-reference | -| Too many subcategories | Group by higher-level concern | -| Unclear where file goes | Ask: "What task does this support?" | -| Navigation too complex | Create specialized navigation file | +| File fits multiple categories | Choose primary purpose, reference from others | +| Too many files in one directory | Create subcategories | +| Unclear hierarchy | Use concern-based pattern | +| Navigation too complex | Simplify structure, use specialized navigation | --- ## Related -- `../context-system.md` - Core principles -- `navigation-design.md` - How to create navigation files -- `../examples/navigation-examples.md` - Good examples +- structure.md - Directory structure standards +- navigation-templates.md - Navigation file templates +- creation.md - Creating new context files diff --git a/.opencode/context/core/context-system/guides/workflows.md b/.opencode/context/core/context-system/guides/workflows.md index c124332..9f116d0 100644 --- a/.opencode/context/core/context-system/guides/workflows.md +++ b/.opencode/context/core/context-system/guides/workflows.md @@ -1,3 +1,5 @@ + + # Context Operation Workflows **Purpose**: Detailed interactive workflows for all context operations diff --git a/.opencode/context/core/context-system/navigation.md b/.opencode/context/core/context-system/navigation.md index b587385..df62df2 100644 --- a/.opencode/context/core/context-system/navigation.md +++ b/.opencode/context/core/context-system/navigation.md @@ -1,3 +1,5 @@ + + # Context System **Purpose**: Documentation for the context system architecture and operations @@ -9,12 +11,14 @@ ``` core/context-system/ โ”œโ”€โ”€ navigation.md (this file) -โ”œโ”€โ”€ operations/ -โ”‚ โ””โ”€โ”€ [operational guides] +โ”œโ”€โ”€ examples/ +โ”‚ โ””โ”€โ”€ navigation.md โ”œโ”€โ”€ guides/ -โ”‚ โ””โ”€โ”€ [how-to guides] +โ”‚ โ””โ”€โ”€ navigation.md +โ”œโ”€โ”€ operations/ +โ”‚ โ””โ”€โ”€ navigation.md โ”œโ”€โ”€ standards/ -โ”‚ โ””โ”€โ”€ [standards and templates] +โ”‚ โ””โ”€โ”€ navigation.md โ””โ”€โ”€ [overview files] ``` @@ -25,17 +29,19 @@ core/context-system/ | Task | Path | |------|------| | **Understand context system** | `../context-system.md` | -| **Operations & procedures** | `./operations/` | -| **Implementation guides** | `./guides/` | -| **Standards & templates** | `./standards/navigation.md` | -| **Migrate global โ†’ local** | `./operations/migrate.md` | +| **Operations & procedures** | `operations/navigation.md` | +| **Implementation guides** | `guides/navigation.md` | +| **Standards & templates** | `standards/navigation.md` | +| **Examples** | `examples/navigation.md` | +| **Migrate global โ†’ local** | `operations/migrate.md` | --- ## By Type -**Operations** โ†’ How to operate and maintain the context system +**Examples** โ†’ Working examples of navigation files **Guides** โ†’ Step-by-step guides for working with context +**Operations** โ†’ How to operate and maintain the context system **Standards** โ†’ Templates and standards for context files --- diff --git a/.opencode/context/core/context-system/operations/error.md b/.opencode/context/core/context-system/operations/error.md index 4f53a7e..871edf5 100644 --- a/.opencode/context/core/context-system/operations/error.md +++ b/.opencode/context/core/context-system/operations/error.md @@ -1,3 +1,5 @@ + + # Error Operation **Purpose**: Add recurring errors to knowledge base with deduplication diff --git a/.opencode/context/core/context-system/operations/extract.md b/.opencode/context/core/context-system/operations/extract.md index f2fae84..7b4663d 100644 --- a/.opencode/context/core/context-system/operations/extract.md +++ b/.opencode/context/core/context-system/operations/extract.md @@ -1,3 +1,5 @@ + + # Extract Operation **Purpose**: Extract context from docs, code, or URLs into organized context files diff --git a/.opencode/context/core/context-system/operations/harvest.md b/.opencode/context/core/context-system/operations/harvest.md index fe3db30..1497e41 100644 --- a/.opencode/context/core/context-system/operations/harvest.md +++ b/.opencode/context/core/context-system/operations/harvest.md @@ -1,3 +1,5 @@ + + # Context Harvest Operation **Purpose**: Extract knowledge from AI summaries โ†’ permanent context, then clean workspace diff --git a/.opencode/context/core/context-system/operations/migrate.md b/.opencode/context/core/context-system/operations/migrate.md index 51b1d0e..ff00f1a 100644 --- a/.opencode/context/core/context-system/operations/migrate.md +++ b/.opencode/context/core/context-system/operations/migrate.md @@ -1,3 +1,5 @@ + + # Context Migrate Operation **Purpose**: Copy context files from global (`~/.config/opencode/context/`) to local (`.opencode/context/`) so they're project-specific and git-committed. diff --git a/.opencode/context/core/context-system/operations/navigation.md b/.opencode/context/core/context-system/operations/navigation.md new file mode 100644 index 0000000..0998b90 --- /dev/null +++ b/.opencode/context/core/context-system/operations/navigation.md @@ -0,0 +1,50 @@ + + +# Context System Operations + +**Purpose**: Operational procedures for maintaining the context system + +--- + +## Structure + +``` +operations/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ error.md +โ”œโ”€โ”€ extract.md +โ”œโ”€โ”€ harvest.md +โ”œโ”€โ”€ migrate.md +โ”œโ”€โ”€ organize.md +โ””โ”€โ”€ update.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Extract context** | `extract.md` | +| **Harvest summaries** | `harvest.md` | +| **Organize files** | `organize.md` | +| **Update context** | `update.md` | +| **Migrate context** | `migrate.md` | +| **Add errors** | `error.md` | + +--- + +## By Type + +**Extraction** โ†’ Extract context from sources +**Harvesting** โ†’ Clean up and harvest summaries +**Organization** โ†’ Restructure context files +**Maintenance** โ†’ Update and migrate context + +--- + +## Related Context + +- **Context System** โ†’ `../navigation.md` +- **Guides** โ†’ `../guides/navigation.md` +- **Standards** โ†’ `../standards/navigation.md` diff --git a/.opencode/context/core/context-system/operations/organize.md b/.opencode/context/core/context-system/operations/organize.md index b526914..37f3311 100644 --- a/.opencode/context/core/context-system/operations/organize.md +++ b/.opencode/context/core/context-system/operations/organize.md @@ -1,3 +1,5 @@ + + # Organize Operation **Purpose**: Restructure flat context files into function-based folder structure diff --git a/.opencode/context/core/context-system/operations/update.md b/.opencode/context/core/context-system/operations/update.md index 5474334..b3f1a36 100644 --- a/.opencode/context/core/context-system/operations/update.md +++ b/.opencode/context/core/context-system/operations/update.md @@ -1,3 +1,5 @@ + + # Update Operation **Purpose**: Update context when APIs, frameworks, or contracts change diff --git a/.opencode/context/core/context-system/standards/codebase-references.md b/.opencode/context/core/context-system/standards/codebase-references.md index 3200424..d983787 100644 --- a/.opencode/context/core/context-system/standards/codebase-references.md +++ b/.opencode/context/core/context-system/standards/codebase-references.md @@ -1,3 +1,5 @@ + + # Codebase References **Purpose**: Link context files to actual code implementation diff --git a/.opencode/context/core/context-system/standards/mvi.md b/.opencode/context/core/context-system/standards/mvi.md index a1b3591..89af7f4 100644 --- a/.opencode/context/core/context-system/standards/mvi.md +++ b/.opencode/context/core/context-system/standards/mvi.md @@ -1,3 +1,5 @@ + + # MVI Principle (Minimal Viable Information) **Purpose**: Extract only core concepts, not verbose explanations diff --git a/.opencode/context/core/context-system/standards/navigation.md b/.opencode/context/core/context-system/standards/navigation.md new file mode 100644 index 0000000..9307643 --- /dev/null +++ b/.opencode/context/core/context-system/standards/navigation.md @@ -0,0 +1,48 @@ + + +# Context System Standards + +**Purpose**: Standards and templates for context files + +--- + +## Structure + +``` +standards/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ codebase-references.md +โ”œโ”€โ”€ frontmatter.md +โ”œโ”€โ”€ mvi.md +โ”œโ”€โ”€ structure.md +โ””โ”€โ”€ templates.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **MVI principle** | `mvi.md` | +| **Frontmatter format** | `frontmatter.md` | +| **File structure** | `structure.md` | +| **File templates** | `templates.md` | +| **Codebase references** | `codebase-references.md` | + +--- + +## By Type + +**Principles** โ†’ Core principles (MVI) +**Formats** โ†’ File formats and frontmatter +**Structure** โ†’ Directory and file structure +**Templates** โ†’ Ready-to-use templates + +--- + +## Related Context + +- **Context System** โ†’ `../navigation.md` +- **Guides** โ†’ `../guides/navigation.md` +- **Operations** โ†’ `../operations/navigation.md` diff --git a/.opencode/context/core/context-system/standards/structure.md b/.opencode/context/core/context-system/standards/structure.md index 779ac65..ca50487 100644 --- a/.opencode/context/core/context-system/standards/structure.md +++ b/.opencode/context/core/context-system/standards/structure.md @@ -1,3 +1,5 @@ + + # Context Structure **Purpose**: Function-based folder organization for easy discovery @@ -149,17 +151,17 @@ ### Concepts | File | Description | Priority | |------|-------------|----------| -| [auth.md](concepts/auth.md) | Authentication patterns | critical | +| concepts/auth.md | Authentication patterns | critical | ### Examples | File | Description | Priority | |------|-------------|----------| -| [jwt.md](examples/jwt.md) | JWT auth example | high | +| examples/jwt.md | JWT auth example | high | ### Errors | File | Description | Priority | |------|-------------|----------| -| [react.md](errors/react.md) | Common React errors | high | +| errors/react.md | Common React errors | high | --- diff --git a/.opencode/context/core/essential-patterns.md b/.opencode/context/core/essential-patterns.md index ad8081e..3b7725e 100644 --- a/.opencode/context/core/essential-patterns.md +++ b/.opencode/context/core/essential-patterns.md @@ -1,3 +1,5 @@ + + # Essential Patterns - Core Development Guidelines ## Quick Reference diff --git a/.opencode/context/core/guides/navigation.md b/.opencode/context/core/guides/navigation.md new file mode 100644 index 0000000..014b13f --- /dev/null +++ b/.opencode/context/core/guides/navigation.md @@ -0,0 +1,39 @@ + + +# Core Guides + +**Purpose**: General guides for core system operations + +--- + +## Structure + +``` +guides/ +โ”œโ”€โ”€ navigation.md (this file) +โ””โ”€โ”€ resuming-sessions.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Resume sessions** | `resuming-sessions.md` | +| **Context system guides** | `../context-system/guides/navigation.md` | +| **Task management guides** | `../task-management/guides/navigation.md` | + +--- + +## By Type + +**Session Management** โ†’ How to resume and manage sessions + +--- + +## Related Context + +- **Core Navigation** โ†’ `../navigation.md` +- **Context System** โ†’ `../context-system/navigation.md` +- **Task Management** โ†’ `../task-management/navigation.md` diff --git a/.opencode/context/core/guides/resuming-sessions.md b/.opencode/context/core/guides/resuming-sessions.md index 493c712..5e4ce2c 100644 --- a/.opencode/context/core/guides/resuming-sessions.md +++ b/.opencode/context/core/guides/resuming-sessions.md @@ -1,3 +1,5 @@ + + # Guide: Resuming Multi-Session Tasks **Purpose**: How to resume work from previous sessions using session context and task files diff --git a/.opencode/context/core/navigation.md b/.opencode/context/core/navigation.md index 56f4bb6..0201062 100644 --- a/.opencode/context/core/navigation.md +++ b/.opencode/context/core/navigation.md @@ -1,3 +1,5 @@ + + # Core Context Navigation **Purpose**: Universal standards and workflows for all development @@ -29,26 +31,31 @@ core/ โ”‚ โ””โ”€โ”€ design-iteration-overview.md โ”‚ โ”œโ”€โ”€ guides/ -โ”‚ โ””โ”€โ”€ resuming-sessions.md # NEW: Multi-session task resumption +โ”‚ โ”œโ”€โ”€ navigation.md +โ”‚ โ””โ”€โ”€ resuming-sessions.md โ”‚ -โ”œโ”€โ”€ task-management/ # JSON-driven task tracking +โ”œโ”€โ”€ task-management/ โ”‚ โ”œโ”€โ”€ navigation.md โ”‚ โ”œโ”€โ”€ standards/ -โ”‚ โ”‚ โ””โ”€โ”€ task-schema.md +โ”‚ โ”‚ โ””โ”€โ”€ navigation.md โ”‚ โ”œโ”€โ”€ guides/ -โ”‚ โ”‚ โ”œโ”€โ”€ splitting-tasks.md -โ”‚ โ”‚ โ””โ”€โ”€ managing-tasks.md +โ”‚ โ”‚ โ””โ”€โ”€ navigation.md โ”‚ โ””โ”€โ”€ lookup/ -โ”‚ โ””โ”€โ”€ task-commands.md +โ”‚ โ””โ”€โ”€ navigation.md โ”‚ โ”œโ”€โ”€ system/ โ”‚ โ””โ”€โ”€ context-guide.md โ”‚ โ””โ”€โ”€ context-system/ - โ”œโ”€โ”€ guides/ + โ”œโ”€โ”€ navigation.md โ”œโ”€โ”€ examples/ - โ”œโ”€โ”€ standards/ - โ””โ”€โ”€ operations/ + โ”‚ โ””โ”€โ”€ navigation.md + โ”œโ”€โ”€ guides/ + โ”‚ โ””โ”€โ”€ navigation.md + โ”œโ”€โ”€ operations/ + โ”‚ โ””โ”€โ”€ navigation.md + โ””โ”€โ”€ standards/ + โ””โ”€โ”€ navigation.md ``` --- diff --git a/.opencode/context/core/standards/navigation.md b/.opencode/context/core/standards/navigation.md index adfff0e..6831ab1 100644 --- a/.opencode/context/core/standards/navigation.md +++ b/.opencode/context/core/standards/navigation.md @@ -1,3 +1,5 @@ + + # Core Standards Navigation **Purpose**: Universal standards for all development work diff --git a/.opencode/context/core/system/context-guide.md b/.opencode/context/core/system/context-guide.md index b84434c..1d9ee13 100644 --- a/.opencode/context/core/system/context-guide.md +++ b/.opencode/context/core/system/context-guide.md @@ -1,3 +1,5 @@ + + # Context System Guide ## Quick Reference diff --git a/.opencode/context/core/system/context-paths.md b/.opencode/context/core/system/context-paths.md index 5eaa2ef..9d482bd 100644 --- a/.opencode/context/core/system/context-paths.md +++ b/.opencode/context/core/system/context-paths.md @@ -1,3 +1,5 @@ + + --- id: context-paths name: Context File Path Resolution diff --git a/.opencode/context/core/system/navigation.md b/.opencode/context/core/system/navigation.md index ddca186..9330782 100644 --- a/.opencode/context/core/system/navigation.md +++ b/.opencode/context/core/system/navigation.md @@ -1,3 +1,5 @@ + + # Core System **Purpose**: System guides and paths for core operations diff --git a/.opencode/context/core/task-management/guides/managing-tasks.md b/.opencode/context/core/task-management/guides/managing-tasks.md index 95e26a1..40e4831 100644 --- a/.opencode/context/core/task-management/guides/managing-tasks.md +++ b/.opencode/context/core/task-management/guides/managing-tasks.md @@ -1,3 +1,5 @@ + + # Guide: Managing Task Lifecycle **Purpose**: Step-by-step workflow for JSON-driven task management diff --git a/.opencode/context/core/task-management/guides/navigation.md b/.opencode/context/core/task-management/guides/navigation.md new file mode 100644 index 0000000..d4f6ab9 --- /dev/null +++ b/.opencode/context/core/task-management/guides/navigation.md @@ -0,0 +1,42 @@ + + +# Task Management Guides + +**Purpose**: Step-by-step guides for task management workflows + +--- + +## Structure + +``` +guides/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ managing-tasks.md +โ””โ”€โ”€ splitting-tasks.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Split features into tasks** | `splitting-tasks.md` | +| **Manage task lifecycle** | `managing-tasks.md` | +| **Task schema** | `../standards/task-schema.md` | +| **CLI commands** | `../lookup/task-commands.md` | + +--- + +## By Type + +**Decomposition** โ†’ How to split features into subtasks +**Workflow** โ†’ How to manage task lifecycle + +--- + +## Related Context + +- **Task Management** โ†’ `../navigation.md` +- **Standards** โ†’ `../standards/navigation.md` +- **Lookup** โ†’ `../lookup/navigation.md` diff --git a/.opencode/context/core/task-management/guides/splitting-tasks.md b/.opencode/context/core/task-management/guides/splitting-tasks.md index b5ca958..9f6083b 100644 --- a/.opencode/context/core/task-management/guides/splitting-tasks.md +++ b/.opencode/context/core/task-management/guides/splitting-tasks.md @@ -1,3 +1,5 @@ + + # Guide: Splitting Features into Tasks **Purpose**: How to decompose features into atomic subtasks @@ -79,7 +81,7 @@ Concrete files/endpoints: Don't embed descriptions. Reference paths: ```json "context_files": [ - ".opencode/context/development/backend/auth/jwt-patterns.md" + "(example: .opencode/context/development/backend/auth/jwt-patterns.md)" ] ``` diff --git a/.opencode/context/core/task-management/lookup/navigation.md b/.opencode/context/core/task-management/lookup/navigation.md new file mode 100644 index 0000000..5883e0f --- /dev/null +++ b/.opencode/context/core/task-management/lookup/navigation.md @@ -0,0 +1,39 @@ + + +# Task Management Lookup + +**Purpose**: Quick reference for task management commands and patterns + +--- + +## Structure + +``` +lookup/ +โ”œโ”€โ”€ navigation.md (this file) +โ””โ”€โ”€ task-commands.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **CLI commands** | `task-commands.md` | +| **Task schema** | `../standards/task-schema.md` | +| **Splitting guide** | `../guides/splitting-tasks.md` | + +--- + +## By Type + +**Commands** โ†’ CLI command reference + +--- + +## Related Context + +- **Task Management** โ†’ `../navigation.md` +- **Guides** โ†’ `../guides/navigation.md` +- **Standards** โ†’ `../standards/navigation.md` diff --git a/.opencode/context/core/task-management/lookup/task-commands.md b/.opencode/context/core/task-management/lookup/task-commands.md index ca6346f..28e717e 100644 --- a/.opencode/context/core/task-management/lookup/task-commands.md +++ b/.opencode/context/core/task-management/lookup/task-commands.md @@ -1,8 +1,10 @@ + + # Lookup: Task CLI Commands **Purpose**: Quick reference for task-cli.ts commands -**Last Updated**: 2026-01-11 +**Last Updated**: 2026-02-14 --- @@ -162,7 +164,41 @@ task-cli.ts validate my-feature --- +## Enhanced Schema Support + +The CLI fully supports the enhanced task schema (v2.0) with: +- **Line-number precision** - Context files with specific line ranges +- **Domain modeling** - bounded_context, module, vertical_slice fields +- **Contract tracking** - API/interface dependencies +- **Design artifacts** - Figma, wireframes, mockups +- **ADR references** - Architecture decision records +- **Prioritization** - RICE/WSJF scores + +All enhanced fields are optional and backward compatible. See `../standards/enhanced-task-schema.md` for details. + +--- + +## Planning Workflow Integration + +For multi-stage orchestration workflows, use these planning agents before task creation: + +| Agent | Purpose | Output | +|-------|---------|--------| +| **ArchitectureAnalyzer** | DDD bounded context identification | `.tmp/architecture/contexts.json` | +| **StoryMapper** | User journey and story mapping | `.tmp/story-maps/map.json` | +| **PrioritizationEngine** | RICE/WSJF scoring | `.tmp/backlog/prioritized.json` | +| **ContractManager** | API contract definition | `.tmp/contracts/{service}.json` | +| **ADRManager** | Architecture decision records | `docs/adr/` | + +These agents populate enhanced schema fields (bounded_context, contracts, related_adrs, rice_score, etc.) automatically. + +See `.opencode/context/core/workflows/multi-stage-orchestration.md` for the complete workflow. + +--- + ## Related -- `../standards/task-schema.md` - JSON schema reference +- `../standards/task-schema.md` - Base JSON schema reference +- `../standards/enhanced-task-schema.md` - Extended schema with advanced features - `../guides/managing-tasks.md` - Workflow guide +- `../workflows/multi-stage-orchestration.md` - Planning workflow diff --git a/.opencode/context/core/task-management/navigation.md b/.opencode/context/core/task-management/navigation.md index 2a26c0e..7c440b3 100644 --- a/.opencode/context/core/task-management/navigation.md +++ b/.opencode/context/core/task-management/navigation.md @@ -1,8 +1,10 @@ + + # Task Management Navigation **Purpose**: JSON-driven task breakdown and tracking system -**Last Updated**: 2026-01-11 +**Last Updated**: 2026-02-14 --- @@ -12,12 +14,13 @@ core/task-management/ โ”œโ”€โ”€ navigation.md โ”œโ”€โ”€ standards/ -โ”‚ โ””โ”€โ”€ task-schema.md # JSON schema reference +โ”‚ โ”œโ”€โ”€ task-schema.md # Base JSON schema (v1.0) +โ”‚ โ””โ”€โ”€ enhanced-task-schema.md # Extended schema (v2.0) - line precision, domain modeling, contracts โ”œโ”€โ”€ guides/ -โ”‚ โ”œโ”€โ”€ splitting-tasks.md # Task decomposition -โ”‚ โ””โ”€โ”€ managing-tasks.md # Workflow guide +โ”‚ โ”œโ”€โ”€ splitting-tasks.md # Task decomposition +โ”‚ โ””โ”€โ”€ managing-tasks.md # Workflow guide โ””โ”€โ”€ lookup/ - โ””โ”€โ”€ task-commands.md # CLI script reference + โ””โ”€โ”€ task-commands.md # CLI script reference ``` --- @@ -26,7 +29,8 @@ core/task-management/ | Task | Path | Priority | |------|------|----------| -| **Understand schemas** | `standards/task-schema.md` | โญโญโญโญโญ | +| **Understand base schema** | `standards/task-schema.md` | โญโญโญโญโญ | +| **Use enhanced features** | `standards/enhanced-task-schema.md` | โญโญโญโญ | | **Split a feature** | `guides/splitting-tasks.md` | โญโญโญโญโญ | | **Manage task lifecycle** | `guides/managing-tasks.md` | โญโญโญโญ | | **Use CLI commands** | `lookup/task-commands.md` | โญโญโญโญ | @@ -35,11 +39,17 @@ core/task-management/ ## Loading Strategy -### For Creating Tasks: -1. Load `standards/task-schema.md` (understand structure) +### For Creating Basic Tasks: +1. Load `standards/task-schema.md` (understand base structure) 2. Load `guides/splitting-tasks.md` (decomposition approach) 3. Reference `lookup/task-commands.md` (validate after creation) +### For Multi-Stage Orchestration: +1. Load `standards/enhanced-task-schema.md` (advanced features) +2. Load `standards/task-schema.md` (base structure reference) +3. Load `guides/splitting-tasks.md` (decomposition approach) +4. Reference planning agents: ArchitectureAnalyzer, StoryMapper, PrioritizationEngine, ContractManager, ADRManager + ### For Managing Tasks: 1. Load `guides/managing-tasks.md` (workflow) 2. Reference `lookup/task-commands.md` (CLI usage) @@ -51,4 +61,6 @@ core/task-management/ - **Active tasks** โ†’ `.tmp/tasks/{feature}/` (at project root) - **Completed tasks** โ†’ `.tmp/tasks/completed/{feature}/` - **TaskManager agent** โ†’ `.opencode/agent/subagents/core/task-manager.md` +- **Planning agents** โ†’ `.opencode/agent/subagents/planning/` (ArchitectureAnalyzer, StoryMapper, PrioritizationEngine, ContractManager, ADRManager) +- **Multi-stage workflow** โ†’ `../workflows/multi-stage-orchestration.md` - **Core navigation** โ†’ `../navigation.md` diff --git a/.opencode/context/core/task-management/standards/enhanced-task-schema.md b/.opencode/context/core/task-management/standards/enhanced-task-schema.md new file mode 100644 index 0000000..3d8e9ab --- /dev/null +++ b/.opencode/context/core/task-management/standards/enhanced-task-schema.md @@ -0,0 +1,781 @@ + + +# Enhanced Task JSON Schema + +**Purpose**: Extended JSON schema for multi-stage orchestration with line-number precision, domain modeling, and prioritization + +**Version**: 2.0 + +**Last Updated**: 2026-02-14 + +**Backward Compatible**: Yes (all new fields are optional) + +--- + +## Overview + +This schema extends the base task.json and subtask_NN.json schemas with: +- **Line-number precision** for context and reference files +- **Domain modeling** fields (bounded_context, module, vertical_slice) +- **Contract tracking** for API/interface dependencies +- **Design artifacts** linking +- **ADR references** for architectural decisions +- **Prioritization scores** (RICE, WSJF) +- **Release planning** (release_slice) + +All enhancements are **optional** and backward compatible with existing task files. + +--- + +## Enhanced task.json Schema + +### New Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `bounded_context` | string | No | DDD bounded context (e.g., "authentication", "billing") | +| `module` | string | No | Module/package name (e.g., "@app/auth", "payment-service") | +| `vertical_slice` | string | No | Feature slice identifier (e.g., "user-registration", "checkout-flow") | +| `contracts` | array | No | API/interface contracts this feature depends on or provides | +| `design_components` | array | No | Design artifacts (Figma URLs, wireframes, mockups) | +| `related_adrs` | array | No | Architecture Decision Records (ADR file paths or IDs) | +| `rice_score` | object | No | RICE prioritization (Reach, Impact, Confidence, Effort) | +| `wsjf_score` | object | No | WSJF prioritization (Business Value, Time Criticality, Risk Reduction, Job Size) | +| `release_slice` | string | No | Release identifier (e.g., "v1.2.0", "Q1-2026", "MVP") | + +### Enhanced context_files and reference_files Format + +**Old format** (still supported): +```json +"context_files": [ + ".opencode/context/core/standards/code-quality.md" +] +``` + +**New format** (line-number precision): +```json +"context_files": [ + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "1-50", + "reason": "Pure function patterns for service layer" + }, + { + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "120-145", + "reason": "JWT token validation rules" + } +] +``` + +**Backward Compatibility**: Both formats are valid. Agents should handle both: +- String format โ†’ read entire file +- Object format โ†’ read specified lines only + +--- + +## Enhanced subtask_NN.json Schema + +### New Fields + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `bounded_context` | string | No | Inherited from task.json or subtask-specific override | +| `module` | string | No | Module this subtask modifies | +| `vertical_slice` | string | No | Feature slice this subtask belongs to | +| `contracts` | array | No | Contracts this subtask implements or depends on | +| `design_components` | array | No | Design artifacts relevant to this subtask | +| `related_adrs` | array | No | ADRs relevant to this subtask | + +--- + +## TypeScript Interfaces + +```typescript +// Line-number precision for context files +interface ContextFileReference { + path: string; // File path (absolute or relative to project root) + lines?: string; // Line range: "10-50", "1-20,45-60", or omit for entire file + reason?: string; // Why this file/section is relevant (max 200 chars) +} + +// Contract definition +interface Contract { + type: 'api' | 'interface' | 'event' | 'schema'; + name: string; // Contract identifier (e.g., "UserAPI", "AuthEvent") + path?: string; // File path where contract is defined + status: 'draft' | 'defined' | 'implemented' | 'verified'; + description?: string; // Brief description (max 200 chars) +} + +// Design component reference +interface DesignComponent { + type: 'figma' | 'wireframe' | 'mockup' | 'prototype' | 'sketch'; + url?: string; // External URL (Figma, etc.) + path?: string; // Local file path + description?: string; // What this design covers (max 200 chars) +} + +// ADR reference +interface ADRReference { + id: string; // ADR identifier (e.g., "ADR-001", "auth-strategy") + path?: string; // File path to ADR document + title?: string; // ADR title + decision?: string; // Brief summary of decision (max 200 chars) +} + +// RICE prioritization +interface RICEScore { + reach: number; // How many users affected (per time period) + impact: number; // Impact score (0.25 = minimal, 0.5 = low, 1 = medium, 2 = high, 3 = massive) + confidence: number; // Confidence % (0-100) + effort: number; // Person-months of work + score?: number; // Calculated: (reach * impact * confidence) / effort +} + +// WSJF prioritization +interface WSJFScore { + business_value: number; // 1-10 scale + time_criticality: number; // 1-10 scale + risk_reduction: number; // 1-10 scale + job_size: number; // 1-10 scale (effort estimate) + score?: number; // Calculated: (business_value + time_criticality + risk_reduction) / job_size +} + +// Enhanced task.json +interface EnhancedTask { + // Base fields (from task-schema.md) + id: string; + name: string; + status: 'active' | 'completed' | 'blocked' | 'archived'; + objective: string; + context_files?: (string | ContextFileReference)[]; + reference_files?: (string | ContextFileReference)[]; + exit_criteria?: string[]; + subtask_count?: number; + completed_count?: number; + created_at: string; + completed_at?: string; + + // Enhanced fields + bounded_context?: string; + module?: string; + vertical_slice?: string; + contracts?: Contract[]; + design_components?: DesignComponent[]; + related_adrs?: ADRReference[]; + rice_score?: RICEScore; + wsjf_score?: WSJFScore; + release_slice?: string; +} + +// Enhanced subtask_NN.json +interface EnhancedSubtask { + // Base fields (from task-schema.md) + id: string; + seq: string; + title: string; + status: 'pending' | 'in_progress' | 'completed' | 'blocked'; + depends_on?: string[]; + parallel?: boolean; + context_files?: (string | ContextFileReference)[]; + reference_files?: (string | ContextFileReference)[]; + suggested_agent?: string; + acceptance_criteria?: string[]; + deliverables?: string[]; + agent_id?: string; + started_at?: string; + completed_at?: string; + completion_summary?: string; + + // Enhanced fields + bounded_context?: string; + module?: string; + vertical_slice?: string; + contracts?: Contract[]; + design_components?: DesignComponent[]; + related_adrs?: ADRReference[]; +} +``` + +--- + +## Field Examples + +### bounded_context + +**Purpose**: DDD bounded context for domain modeling + +```json +{ + "bounded_context": "authentication" +} +``` + +Common values: +- `"authentication"` - User identity and access +- `"billing"` - Payment and invoicing +- `"inventory"` - Product and stock management +- `"notification"` - Messaging and alerts +- `"analytics"` - Reporting and insights + +--- + +### module + +**Purpose**: Module or package name for code organization + +```json +{ + "module": "@app/auth" +} +``` + +Examples: +- `"@app/auth"` - Authentication module +- `"payment-service"` - Payment microservice +- `"ui-components"` - Shared UI library +- `"core/utils"` - Core utilities + +--- + +### vertical_slice + +**Purpose**: Feature slice identifier for vertical slice architecture + +```json +{ + "vertical_slice": "user-registration" +} +``` + +Examples: +- `"user-registration"` - Complete user signup flow +- `"checkout-flow"` - End-to-end checkout +- `"dashboard-overview"` - Dashboard feature +- `"report-generation"` - Report creation flow + +--- + +### contracts + +**Purpose**: Track API/interface dependencies and implementations + +```json +{ + "contracts": [ + { + "type": "api", + "name": "UserAPI", + "path": "src/api/user.contract.ts", + "status": "defined", + "description": "REST API for user CRUD operations" + }, + { + "type": "event", + "name": "UserCreatedEvent", + "status": "draft", + "description": "Event emitted when new user is created" + } + ] +} +``` + +Contract types: +- `"api"` - REST/GraphQL API endpoints +- `"interface"` - TypeScript/language interfaces +- `"event"` - Event bus messages +- `"schema"` - Database schemas, validation schemas + +Contract statuses: +- `"draft"` - Being designed +- `"defined"` - Specification complete +- `"implemented"` - Code written +- `"verified"` - Tests passing + +--- + +### design_components + +**Purpose**: Link design artifacts to implementation tasks + +```json +{ + "design_components": [ + { + "type": "figma", + "url": "https://figma.com/file/abc123/Login-Flow", + "description": "Login page mockups with responsive breakpoints" + }, + { + "type": "wireframe", + "path": "docs/design/checkout-wireframe.png", + "description": "Checkout flow wireframe" + } + ] +} +``` + +Component types: +- `"figma"` - Figma designs +- `"wireframe"` - Low-fidelity wireframes +- `"mockup"` - High-fidelity mockups +- `"prototype"` - Interactive prototypes +- `"sketch"` - Sketch files + +--- + +### related_adrs + +**Purpose**: Reference architectural decisions that govern implementation + +```json +{ + "related_adrs": [ + { + "id": "ADR-003", + "path": "docs/adr/003-jwt-authentication.md", + "title": "Use JWT for stateless authentication", + "decision": "Implement JWT with RS256 signing and 15-minute expiry" + }, + { + "id": "ADR-007", + "path": "docs/adr/007-database-choice.md", + "title": "PostgreSQL for primary database" + } + ] +} +``` + +--- + +### rice_score + +**Purpose**: RICE prioritization framework (Reach ร— Impact ร— Confidence / Effort) + +```json +{ + "rice_score": { + "reach": 5000, + "impact": 2, + "confidence": 80, + "effort": 3, + "score": 2666.67 + } +} +``` + +**Calculation**: `(5000 ร— 2 ร— 0.80) / 3 = 2666.67` + +Field definitions: +- `reach`: Number of users/customers affected per time period (e.g., per quarter) +- `impact`: 0.25 (minimal), 0.5 (low), 1 (medium), 2 (high), 3 (massive) +- `confidence`: Percentage (0-100) - how confident are you in reach/impact estimates? +- `effort`: Person-months of work +- `score`: Auto-calculated or manually entered + +--- + +### wsjf_score + +**Purpose**: WSJF prioritization (Weighted Shortest Job First) for SAFe/Agile + +```json +{ + "wsjf_score": { + "business_value": 8, + "time_criticality": 6, + "risk_reduction": 5, + "job_size": 3, + "score": 6.33 + } +} +``` + +**Calculation**: `(8 + 6 + 5) / 3 = 6.33` + +Field definitions (all on 1-10 scale): +- `business_value`: Direct business impact +- `time_criticality`: How time-sensitive is this? +- `risk_reduction`: Does this reduce risk/enable other work? +- `job_size`: Effort estimate (1 = tiny, 10 = huge) +- `score`: Auto-calculated or manually entered + +--- + +### release_slice + +**Purpose**: Group tasks into releases for planning + +```json +{ + "release_slice": "v1.2.0" +} +``` + +Examples: +- `"v1.2.0"` - Semantic version +- `"Q1-2026"` - Quarterly release +- `"MVP"` - Minimum viable product +- `"Phase-2"` - Project phase +- `"Sprint-15"` - Sprint identifier + +--- + +## Line-Number Precision Format + +### Purpose + +Reduce cognitive load by pointing agents to **exact sections** of large files instead of forcing them to read entire documents. + +### Format + +```json +{ + "path": "path/to/file.md", + "lines": "10-50", + "reason": "Why these lines matter" +} +``` + +### Line Range Syntax + +- `"10-50"` - Lines 10 through 50 (inclusive) +- `"1-20,45-60"` - Lines 1-20 AND 45-60 (multiple ranges) +- Omit `lines` field to read entire file + +### Examples + +**Single range**: +```json +{ + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-95", + "reason": "Pure function and immutability patterns" +} +``` + +**Multiple ranges**: +```json +{ + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "1-25,120-145,200-220", + "reason": "JWT validation rules and token refresh patterns" +} +``` + +**Entire file** (backward compatible): +```json +{ + "path": ".opencode/context/core/standards/code-quality.md", + "reason": "All coding standards" +} +``` + +**Legacy string format** (still supported): +```json +".opencode/context/core/standards/code-quality.md" +``` + +--- + +## Backward Compatibility Rules + +### Rule 1: All new fields are optional + +Existing task.json and subtask_NN.json files remain valid without any changes. + +### Rule 2: Mixed formats allowed + +You can mix old and new formats in the same file: + +```json +{ + "context_files": [ + ".opencode/context/core/standards/code-quality.md", + { + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "120-145", + "reason": "JWT validation" + } + ] +} +``` + +### Rule 3: Agent handling + +Agents MUST support both formats: + +```typescript +function loadContextFile(ref: string | ContextFileReference): string { + if (typeof ref === 'string') { + // Legacy format: read entire file + return readFile(ref); + } else { + // New format: read specified lines + const content = readFile(ref.path); + if (ref.lines) { + return extractLines(content, ref.lines); + } + return content; + } +} +``` + +### Rule 4: Gradual migration + +Projects can adopt enhanced fields incrementally: +1. Start with line-number precision for large files +2. Add domain modeling fields (bounded_context, module) when needed +3. Add prioritization scores when planning releases +4. Add contracts/ADRs when formalizing architecture + +--- + +## Complete Example + +### Enhanced task.json + +```json +{ + "id": "user-authentication", + "name": "User Authentication System", + "status": "active", + "objective": "Implement JWT-based authentication with refresh tokens and role-based access control", + "context_files": [ + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-95", + "reason": "Pure function patterns for auth service" + }, + { + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "120-145,200-220", + "reason": "JWT validation and token refresh patterns" + } + ], + "reference_files": [ + { + "path": "src/middleware/auth.middleware.ts", + "lines": "1-50", + "reason": "Existing auth middleware to extend" + }, + "package.json" + ], + "exit_criteria": [ + "All tests passing with >90% coverage", + "JWT tokens signed with RS256", + "Refresh token rotation implemented", + "Role-based access control working" + ], + "subtask_count": 5, + "completed_count": 0, + "created_at": "2026-02-14T10:00:00Z", + "bounded_context": "authentication", + "module": "@app/auth", + "vertical_slice": "user-login", + "contracts": [ + { + "type": "api", + "name": "AuthAPI", + "path": "src/api/auth.contract.ts", + "status": "defined", + "description": "REST endpoints for login, logout, refresh, verify" + }, + { + "type": "event", + "name": "UserAuthenticatedEvent", + "status": "draft", + "description": "Event emitted on successful authentication" + } + ], + "design_components": [ + { + "type": "figma", + "url": "https://figma.com/file/xyz789/Auth-Flows", + "description": "Login and registration UI mockups" + } + ], + "related_adrs": [ + { + "id": "ADR-003", + "path": "docs/adr/003-jwt-authentication.md", + "title": "Use JWT for stateless authentication", + "decision": "JWT with RS256, 15-min access tokens, 7-day refresh tokens" + } + ], + "rice_score": { + "reach": 10000, + "impact": 3, + "confidence": 90, + "effort": 4, + "score": 6750 + }, + "wsjf_score": { + "business_value": 9, + "time_criticality": 8, + "risk_reduction": 7, + "job_size": 4, + "score": 6 + }, + "release_slice": "v1.0.0" +} +``` + +### Enhanced subtask_NN.json + +```json +{ + "id": "user-authentication-02", + "seq": "02", + "title": "Implement JWT service with token generation and validation", + "status": "pending", + "depends_on": ["01"], + "parallel": false, + "context_files": [ + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-72", + "reason": "Pure function patterns" + }, + { + "path": ".opencode/context/core/standards/security-patterns.md", + "lines": "120-145", + "reason": "JWT signing and validation rules" + } + ], + "reference_files": [ + { + "path": "src/config/jwt.config.ts", + "reason": "JWT configuration constants" + } + ], + "suggested_agent": "CoderAgent", + "acceptance_criteria": [ + "JWT tokens signed with RS256 algorithm", + "Access tokens expire in 15 minutes", + "Refresh tokens expire in 7 days", + "Token validation includes signature and expiry checks", + "Unit tests cover all token operations", + "No secrets hardcoded in code" + ], + "deliverables": [ + "src/auth/jwt.service.ts", + "src/auth/jwt.service.test.ts" + ], + "bounded_context": "authentication", + "module": "@app/auth", + "contracts": [ + { + "type": "interface", + "name": "JWTService", + "path": "src/auth/jwt.service.ts", + "status": "implemented", + "description": "Interface for JWT operations (sign, verify, refresh)" + } + ], + "related_adrs": [ + { + "id": "ADR-003", + "path": "docs/adr/003-jwt-authentication.md" + } + ] +} +``` + +--- + +## Migration Guide + +### For TaskManager Agents + +When creating new tasks: + +1. **Use line-number precision for large files** (>100 lines): + ```json + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-95", + "reason": "Pure function patterns" + } + ``` + +2. **Add domain modeling fields** when known: + ```json + { + "bounded_context": "authentication", + "module": "@app/auth", + "vertical_slice": "user-login" + } + ``` + +3. **Link design artifacts** for UI tasks: + ```json + { + "design_components": [ + { + "type": "figma", + "url": "https://figma.com/...", + "description": "Login page mockups" + } + ] + } + ``` + +4. **Reference ADRs** for architectural decisions: + ```json + { + "related_adrs": [ + { + "id": "ADR-003", + "path": "docs/adr/003-jwt-authentication.md" + } + ] + } + ``` + +### For Working Agents (CoderAgent, etc.) + +When reading tasks: + +1. **Handle both context file formats**: + ```typescript + const contextFiles = task.context_files || []; + for (const ref of contextFiles) { + if (typeof ref === 'string') { + // Read entire file + const content = await readFile(ref); + } else { + // Read specified lines + const content = await readFileLines(ref.path, ref.lines); + console.log(`Reading ${ref.path} (${ref.lines}): ${ref.reason}`); + } + } + ``` + +2. **Use contract information** to understand dependencies: + ```typescript + const contracts = task.contracts || []; + const apiContracts = contracts.filter(c => c.type === 'api'); + // Load API contract definitions before implementing + ``` + +3. **Check ADRs** before making architectural decisions: + ```typescript + const adrs = task.related_adrs || []; + for (const adr of adrs) { + if (adr.path) { + const decision = await readFile(adr.path); + // Apply architectural constraints from ADR + } + } + ``` + +--- + +## Related + +- `task-schema.md` - Base schema (backward compatible foundation) +- `../guides/splitting-tasks.md` - How to decompose features +- `../guides/managing-tasks.md` - Lifecycle workflow +- `../lookup/task-commands.md` - CLI reference diff --git a/.opencode/context/core/task-management/standards/navigation.md b/.opencode/context/core/task-management/standards/navigation.md new file mode 100644 index 0000000..98e6f84 --- /dev/null +++ b/.opencode/context/core/task-management/standards/navigation.md @@ -0,0 +1,42 @@ + + +# Task Management Standards + +**Purpose**: JSON schemas and standards for task definitions + +--- + +## Structure + +``` +standards/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ task-schema.md +โ””โ”€โ”€ enhanced-task-schema.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Base schema (v1.0)** | `task-schema.md` | +| **Enhanced schema (v2.0)** | `enhanced-task-schema.md` | +| **Splitting guide** | `../guides/splitting-tasks.md` | +| **CLI commands** | `../lookup/task-commands.md` | + +--- + +## By Type + +**Base Schema** โ†’ Core task structure (v1.0) +**Enhanced Schema** โ†’ Advanced features (v2.0) - line precision, domain modeling, contracts + +--- + +## Related Context + +- **Task Management** โ†’ `../navigation.md` +- **Guides** โ†’ `../guides/navigation.md` +- **Lookup** โ†’ `../lookup/navigation.md` diff --git a/.opencode/context/core/task-management/standards/task-schema.md b/.opencode/context/core/task-management/standards/task-schema.md index a4e77c8..94581ad 100644 --- a/.opencode/context/core/task-management/standards/task-schema.md +++ b/.opencode/context/core/task-management/standards/task-schema.md @@ -1,8 +1,10 @@ + + # Standard: Task JSON Schema **Purpose**: JSON schema reference for task management files -**Last Updated**: 2026-01-11 +**Last Updated**: 2026-02-14 --- @@ -16,6 +18,17 @@ Location: `.tmp/tasks/{feature-slug}/` (at project root) --- +## Schema Versions + +This document describes the **base schema** (v1.0) that all task files must follow. + +For **enhanced features** (line-number precision, domain modeling, contracts, ADRs, prioritization): +- See `enhanced-task-schema.md` for extended fields and capabilities +- All enhanced fields are **optional** and backward compatible +- Use enhanced schema for multi-stage orchestration workflows + +--- + ## task.json Schema | Field | Type | Required | Description | @@ -132,8 +145,57 @@ These two fields serve fundamentally different purposes. **Never mix them.** --- +## Migration to Enhanced Schema + +The enhanced schema adds powerful features while maintaining full backward compatibility: + +### When to Use Enhanced Schema + +Use `enhanced-task-schema.md` when you need: +- **Line-number precision** - Point to specific sections of large files (reduces cognitive load) +- **Domain modeling** - Track bounded contexts, modules, vertical slices +- **Contract tracking** - Manage API/interface dependencies +- **Design artifacts** - Link Figma, wireframes, mockups +- **ADR references** - Connect architectural decisions to tasks +- **Prioritization** - RICE/WSJF scoring for release planning + +### Migration Path + +1. **No changes required** - Existing task files work as-is +2. **Gradual adoption** - Add enhanced fields incrementally: + - Start with line-number precision for large context files + - Add domain fields (bounded_context, module) when modeling architecture + - Add contracts when defining APIs + - Add prioritization scores when planning releases +3. **Mixed formats** - You can mix old and new formats in the same file + +### Example: Adding Line-Number Precision + +**Old format** (still valid): +```json +"context_files": [ + ".opencode/context/core/standards/code-quality.md" +] +``` + +**New format** (enhanced): +```json +"context_files": [ + { + "path": ".opencode/context/core/standards/code-quality.md", + "lines": "53-95", + "reason": "Pure function patterns for service layer" + } +] +``` + +Both formats work. Agents handle both automatically. + +--- + ## Related +- `enhanced-task-schema.md` - Extended schema with advanced features - `../guides/splitting-tasks.md` - How to decompose features - `../guides/managing-tasks.md` - Lifecycle workflow - `../lookup/task-commands.md` - CLI reference diff --git a/.opencode/context/core/visual-development.md b/.opencode/context/core/visual-development.md index 42a55b5..6f8a633 100644 --- a/.opencode/context/core/visual-development.md +++ b/.opencode/context/core/visual-development.md @@ -450,7 +450,7 @@ After receiving output: - **UI Design Workflow**: `.opencode/context/core/workflows/design-iteration-overview.md` - **Design Systems**: `.opencode/context/ui/web/design-systems.md` - **UI Styling Standards**: `.opencode/context/ui/web/ui-styling-standards.md` -- **Animation Patterns**: `.opencode/context/ui/web/animation-patterns.md` +- **Animation Patterns**: `.opencode/context/ui/web/animation-basics.md`, `.opencode/context/ui/web/animation-advanced.md` - **Subagent Invocation Guide**: `.opencode/context/openagents-repo/guides/subagent-invocation.md` - **Agent Capabilities**: `.opencode/context/openagents-repo/core-concepts/agents.md` diff --git a/.opencode/context/core/workflows/design-iteration-best-practices.md b/.opencode/context/core/workflows/design-iteration-best-practices.md index e129f83..c67c577 100644 --- a/.opencode/context/core/workflows/design-iteration-best-practices.md +++ b/.opencode/context/core/workflows/design-iteration-best-practices.md @@ -166,7 +166,7 @@ Before presenting each stage: - [Design Systems Context](../../ui/web/design-systems.md) - [UI Styling Standards](../../ui/web/ui-styling-standards.md) -- [Animation Patterns](../../ui/web/animation-patterns.md) +- [Animation Basics](../../ui/web/animation-basics.md) - [ASCII Art Generator](https://www.asciiart.eu/) - [WCAG Contrast Checker](https://webaim.org/resources/contrastchecker/) diff --git a/.opencode/context/core/workflows/design-iteration-stage-animation.md b/.opencode/context/core/workflows/design-iteration-stage-animation.md index d354a6d..af47f36 100644 --- a/.opencode/context/core/workflows/design-iteration-stage-animation.md +++ b/.opencode/context/core/workflows/design-iteration-stage-animation.md @@ -77,4 +77,4 @@ linkHover: 250ms ease-out [underline 0โ†’100%] - [Overview](./design-iteration-overview.md) - [Stage 2: Theme](./design-iteration-stage-theme.md) - [Stage 4: Implementation](./design-iteration-stage-implementation.md) -- [Animation Patterns](../../ui/web/animation-patterns.md) +- [Animation Basics](../../ui/web/animation-basics.md) diff --git a/.opencode/context/core/workflows/lightweight-context-handoff-example.md b/.opencode/context/core/workflows/lightweight-context-handoff-example.md new file mode 100644 index 0000000..8832d44 --- /dev/null +++ b/.opencode/context/core/workflows/lightweight-context-handoff-example.md @@ -0,0 +1,613 @@ + +# Lightweight Context Handoff - Orchestrator Example + +## Complete Feature Implementation Using Context Index + +This document shows a complete orchestrator workflow using the lightweight context handoff pattern for implementing a JWT authentication system. + +--- + +## Setup Phase + +### Step 1: Initialize Context Index + +```typescript +import { createContextIndex } from './.opencode/skill/task-management/scripts/context-index'; + +// Create lightweight index with initial context +const result = createContextIndex('auth-system', { + contextFiles: [ + '.opencode/context/core/standards/code-quality.md', + '(example: (example: .opencode/context/security/auth-patterns.md))', + '(example: (example: .opencode/context/architecture/ddd-patterns.md))', + '(example: (example: .opencode/context/core/story-mapping/guide.md))' + ], + referenceFiles: [ + 'src/auth/old-auth.ts', + 'src/middleware/auth.middleware.ts' + ] +}); + +// Result: .tmp/context-index/auth-system.json created +``` + +**What's in the index:** +```json +{ + "feature": "auth-system", + "created": "2026-02-15T10:00:00Z", + "updated": "2026-02-15T10:00:00Z", + "agents": {}, + "contextFiles": [ + ".opencode/context/core/standards/code-quality.md", + "(example: (example: .opencode/context/security/auth-patterns.md))", + "(example: (example: .opencode/context/architecture/ddd-patterns.md))", + "(example: (example: .opencode/context/core/story-mapping/guide.md))" + ], + "referenceFiles": [ + "src/auth/old-auth.ts", + "src/middleware/auth.middleware.ts" + ] +} +``` + +--- + +## Stage 1: Architecture Analysis + +### Step 2: Get Context for ArchitectureAnalyzer + +```typescript +import { getContextForAgent } from './.opencode/skill/task-management/scripts/context-index'; + +const archContext = getContextForAgent('auth-system', 'ArchitectureAnalyzer'); + +// Returns: +{ + feature: "auth-system", + agentType: "ArchitectureAnalyzer", + contextFiles: [ + "(example: .opencode/context/architecture/ddd-patterns.md)" + ], + referenceFiles: [ + "src/auth/old-auth.ts", + "src/middleware/auth.middleware.ts" + ], + agentOutputs: [], + metadata: {} +} +``` + +**Key Point:** ArchitectureAnalyzer gets ONLY: +- Architecture patterns context +- Reference files to analyze +- NO story mapping guide (not needed yet) +- NO previous agent outputs (it's first) + +### Step 3: Delegate to ArchitectureAnalyzer + +```typescript +task( + subagent_type="ArchitectureAnalyzer", + description="Analyze authentication system architecture", + prompt=` + Analyze the architecture for implementing JWT authentication. + + Context files to load: + - ${archContext.contextFiles[0]} + + Reference files to analyze: + - ${archContext.referenceFiles[0]} + - ${archContext.referenceFiles[1]} + + Identify: + - Bounded contexts + - Module boundaries + - Integration points + + Output: .tmp/architecture/auth-system/contexts.json + ` +); +``` + +### Step 4: ArchitectureAnalyzer Completes โ†’ Update Index + +```typescript +import { addAgentOutput } from './.opencode/skill/task-management/scripts/context-index'; + +// Read ArchitectureAnalyzer output +const archOutput = JSON.parse( + fs.readFileSync('.tmp/architecture/auth-system/contexts.json', 'utf-8') +); + +// Update index with output path and metadata +addAgentOutput( + 'auth-system', + 'ArchitectureAnalyzer', + '.tmp/architecture/auth-system/contexts.json', + { + boundedContext: archOutput.primary_context, // "authentication" + module: archOutput.module_name, // "auth-service" + complexity: archOutput.complexity // "medium" + } +); +``` + +**Index now contains:** +```json +{ + "feature": "auth-system", + "agents": { + "ArchitectureAnalyzer": { + "outputs": [".tmp/architecture/auth-system/contexts.json"], + "metadata": { + "boundedContext": "authentication", + "module": "auth-service", + "complexity": "medium" + }, + "timestamp": "2026-02-15T10:05:00Z" + } + }, + ... +} +``` + +--- + +## Stage 2: Story Mapping + +### Step 5: Get Context for StoryMapper + +```typescript +const storyContext = getContextForAgent('auth-system', 'StoryMapper'); + +// Returns: +{ + feature: "auth-system", + agentType: "StoryMapper", + contextFiles: [ + "(example: .opencode/context/core/story-mapping/guide.md)" + ], + referenceFiles: [], + agentOutputs: [ + ".tmp/architecture/auth-system/contexts.json" + ], + metadata: { + boundedContext: "authentication", + module: "auth-service", + complexity: "medium" + } +} +``` + +**Key Point:** StoryMapper gets: +- Story mapping guide (filtered from contextFiles) +- ArchitectureAnalyzer output path (NOT full content) +- Metadata from ArchitectureAnalyzer (small, useful data) +- NO reference files (doesn't need source code) + +### Step 6: Delegate to StoryMapper + +```typescript +task( + subagent_type="StoryMapper", + description="Create user story map for authentication", + prompt=` + Create a user story map for JWT authentication system. + + Context files to load: + - ${storyContext.contextFiles[0]} + + Previous agent outputs to read: + - ${storyContext.agentOutputs[0]} + + Metadata from ArchitectureAnalyzer: + - Bounded Context: ${storyContext.metadata.boundedContext} + - Module: ${storyContext.metadata.module} + + Create vertical slices for: + - User login + - Token refresh + - Logout + + Output: .tmp/story-maps/auth-system/map.json + ` +); +``` + +### Step 7: StoryMapper Completes โ†’ Update Index + +```typescript +const storyOutput = JSON.parse( + fs.readFileSync('.tmp/story-maps/auth-system/map.json', 'utf-8') +); + +addAgentOutput( + 'auth-system', + 'StoryMapper', + '.tmp/story-maps/auth-system/map.json', + { + verticalSlice: storyOutput.primary_slice, // "user-login" + storyCount: storyOutput.stories.length // 8 + } +); +``` + +--- + +## Stage 3: Prioritization + +### Step 8: Get Context for PrioritizationEngine + +```typescript +const prioContext = getContextForAgent('auth-system', 'PrioritizationEngine'); + +// Returns: +{ + feature: "auth-system", + agentType: "PrioritizationEngine", + contextFiles: [], // No prioritization context file in index + referenceFiles: [], + agentOutputs: [ + ".tmp/story-maps/auth-system/map.json" + ], + metadata: { + verticalSlice: "user-login", + storyCount: 8 + } +} +``` + +**Key Point:** PrioritizationEngine gets: +- StoryMapper output path (to read stories) +- Metadata from StoryMapper +- NO ArchitectureAnalyzer output (not needed) + +### Step 9: Delegate to PrioritizationEngine + +```typescript +task( + subagent_type="PrioritizationEngine", + description="Prioritize authentication stories", + prompt=` + Prioritize user stories for authentication system. + + Story map to read: + - ${prioContext.agentOutputs[0]} + + Metadata: + - Vertical Slice: ${prioContext.metadata.verticalSlice} + - Story Count: ${prioContext.metadata.storyCount} + + Calculate RICE and WSJF scores. + Assign to release slices. + + Output: .tmp/planning/auth-system/prioritized.json + ` +); +``` + +### Step 10: PrioritizationEngine Completes โ†’ Update Index + +```typescript +const prioOutput = JSON.parse( + fs.readFileSync('.tmp/planning/auth-system/prioritized.json', 'utf-8') +); + +addAgentOutput( + 'auth-system', + 'PrioritizationEngine', + '.tmp/planning/auth-system/prioritized.json', + { + releaseSlice: prioOutput.release_slice, // "v1.0.0" + avgRiceScore: prioOutput.avg_rice_score // 6750 + } +); +``` + +--- + +## Stage 4: Task Breakdown + +### Step 11: Get Context for TaskManager + +```typescript +const taskContext = getContextForAgent('auth-system', 'TaskManager'); + +// Returns: +{ + feature: "auth-system", + agentType: "TaskManager", + contextFiles: [ + ".opencode/context/core/standards/code-quality.md" + ], + referenceFiles: [], + agentOutputs: [ + ".tmp/architecture/auth-system/contexts.json", + ".tmp/story-maps/auth-system/map.json", + ".tmp/planning/auth-system/prioritized.json" + ], + metadata: { + ArchitectureAnalyzer: { + boundedContext: "authentication", + module: "auth-service" + }, + StoryMapper: { + verticalSlice: "user-login", + storyCount: 8 + }, + PrioritizationEngine: { + releaseSlice: "v1.0.0", + avgRiceScore: 6750 + } + } +} +``` + +**Key Point:** TaskManager gets: +- ALL previous agent outputs (needs full picture) +- Metadata from ALL agents (for task.json population) +- Coding standards (for subtask context_files) + +### Step 12: Delegate to TaskManager + +```typescript +task( + subagent_type="TaskManager", + description="Break down authentication into subtasks", + prompt=` + Create task breakdown for JWT authentication system. + + Context files to load: + - ${taskContext.contextFiles[0]} + + Previous agent outputs to read: + - ${taskContext.agentOutputs[0]} (Architecture) + - ${taskContext.agentOutputs[1]} (Stories) + - ${taskContext.agentOutputs[2]} (Priorities) + + Metadata from previous agents: + ${JSON.stringify(taskContext.metadata, null, 2)} + + Create task.json and subtask_NN.json files. + Use metadata to populate enhanced fields. + + Output: .tmp/tasks/auth-system/ + ` +); +``` + +### Step 13: TaskManager Completes โ†’ Update Index + +```typescript +addAgentOutput( + 'auth-system', + 'TaskManager', + '.tmp/tasks/auth-system/task.json', + { + subtaskCount: 5, + parallelTasks: 2 + } +); +``` + +--- + +## Stage 5: Implementation + +### Step 14: Get Context for CoderAgent + +```typescript +const coderContext = getContextForAgent('auth-system', 'CoderAgent'); + +// Returns: +{ + feature: "auth-system", + agentType: "CoderAgent", + contextFiles: [ + ".opencode/context/core/standards/code-quality.md", + "(example: .opencode/context/security/auth-patterns.md)" + ], + referenceFiles: [], + agentOutputs: [ + ".tmp/tasks/auth-system/task.json" + ], + metadata: {} +} +``` + +**Key Point:** CoderAgent gets: +- Coding standards and security patterns +- TaskManager output (task.json) +- NO architecture/story/priority outputs (not needed for coding) + +### Step 15: Delegate to CoderAgent (for each subtask) + +```typescript +// Read task.json to get subtask list +const taskJson = JSON.parse( + fs.readFileSync('.tmp/tasks/auth-system/task.json', 'utf-8') +); + +// For each subtask +for (let seq = 1; seq <= taskJson.subtask_count; seq++) { + const subtaskPath = `.tmp/tasks/auth-system/subtask_${seq.toString().padStart(2, '0')}.json`; + + task( + subagent_type="CoderAgent", + description=`Implement subtask ${seq}`, + prompt=` + Implement the subtask defined in: ${subtaskPath} + + Context files to load: + ${coderContext.contextFiles.map(f => `- ${f}`).join('\n')} + + Follow acceptance criteria exactly. + Run self-review before completion. + ` + ); +} +``` + +--- + +## Summary: What Each Agent Received + +### ArchitectureAnalyzer +``` +Context Files: 1 (architecture patterns) +Reference Files: 2 (existing code) +Agent Outputs: 0 +Total Files to Read: 3 +``` + +### StoryMapper +``` +Context Files: 1 (story mapping guide) +Reference Files: 0 +Agent Outputs: 1 (ArchitectureAnalyzer) +Total Files to Read: 2 +``` + +### PrioritizationEngine +``` +Context Files: 0 +Reference Files: 0 +Agent Outputs: 1 (StoryMapper) +Total Files to Read: 1 +``` + +### TaskManager +``` +Context Files: 1 (code quality standards) +Reference Files: 0 +Agent Outputs: 3 (all previous agents) +Total Files to Read: 4 +``` + +### CoderAgent +``` +Context Files: 2 (code quality + security) +Reference Files: 0 +Agent Outputs: 1 (TaskManager - subtask JSON) +Total Files to Read: 3 +``` + +--- + +## Comparison: With vs Without Context Index + +### WITHOUT Context Index (Session Context Pattern) + +**Every agent receives:** +``` +- Full session context.md (500+ lines) +- All context files (10+ files) +- All reference files +- All previous agent outputs +- Full decision history +- Full progress tracking + +Total: 15+ files, 5000+ lines per agent +``` + +### WITH Context Index (Lightweight Pattern) + +**Each agent receives:** +``` +ArchitectureAnalyzer: 3 files +StoryMapper: 2 files +PrioritizationEngine: 1 file +TaskManager: 4 files +CoderAgent: 3 files + +Average: 2.6 files per agent +``` + +**Reduction:** ~83% fewer files per agent + +--- + +## Benefits Demonstrated + +### 1. Minimal Context Per Agent +Each agent reads only what it needs, nothing more. + +### 2. Fast Handoffs +Orchestrator just passes file paths, not content. + +### 3. Clear Dependencies +Agent outputs are explicitly tracked and passed. + +### 4. Lightweight Index +Index stays small (~200 lines JSON) even with 5 agents. + +### 5. Scalable +Adding more agents doesn't bloat the index. + +### 6. Debuggable +Easy to trace: "Which agent produced this file?" + +--- + +## Code Template for Orchestrators + +```typescript +import { + createContextIndex, + addAgentOutput, + getContextForAgent +} from './.opencode/skill/task-management/scripts/context-index'; + +// 1. Initialize +createContextIndex(feature, { contextFiles, referenceFiles }); + +// 2. For each agent in pipeline +const agentTypes = [ + 'ArchitectureAnalyzer', + 'StoryMapper', + 'PrioritizationEngine', + 'TaskManager', + 'CoderAgent' +]; + +for (const agentType of agentTypes) { + // Get minimal context + const context = getContextForAgent(feature, agentType); + + // Delegate with minimal context + const result = task( + subagent_type=agentType, + description=`Execute ${agentType} for ${feature}`, + prompt=` + Context files: ${context.contextFiles.join(', ')} + Previous outputs: ${context.agentOutputs.join(', ')} + Metadata: ${JSON.stringify(context.metadata)} + + Your task: ... + ` + ); + + // Update index with output + addAgentOutput(feature, agentType, outputPath, metadata); +} +``` + +--- + +## When to Use This Pattern + +โœ… **Use Lightweight Context Index when:** +- Multi-agent orchestration (3+ agents) +- Each agent has a specific role +- Performance matters +- Context bloat is a problem +- Agents should be isolated + +โŒ **Don't use when:** +- Single agent session +- Human needs to review context +- Agents need full narrative history +- Interactive feedback loops + +**Alternative:** Use `session-context-manager.ts` for human-readable tracking alongside context-index for agent coordination. diff --git a/.opencode/context/core/workflows/lightweight-context-handoff.md b/.opencode/context/core/workflows/lightweight-context-handoff.md new file mode 100644 index 0000000..e313b35 --- /dev/null +++ b/.opencode/context/core/workflows/lightweight-context-handoff.md @@ -0,0 +1,651 @@ + +# Lightweight Context Handoff Pattern + +## Problem + +**Context Fragmentation in Multi-Agent Orchestration** + +- Orchestrator needs to track full context across all agents +- Subagents should only get what they need for their specific job +- Current `session-context-manager.ts` passes too much context (entire session state) +- Agents waste time reading irrelevant files +- Context bloat slows down execution + +## Solution + +**Lightweight Context Index** + +- Orchestrator maintains a lightweight "context index" (just file paths and metadata) +- Each subagent gets ONLY the specific files they need +- Orchestrator reads agent outputs and updates the index +- Index is a pointer system, not a content dump + +## Key Principle + +โœ… **DO THIS:** +``` +Orchestrator โ†’ Agent: "Here's the ONE file you need: .tmp/architecture/auth-system/contexts.json" +``` + +โŒ **NOT THIS:** +``` +Orchestrator โ†’ Agent: "Here's the entire session context with everything from all previous agents (5000 lines)" +``` + +--- + +## Architecture + +### Context Index Structure + +```typescript +{ + feature: "auth-system", + created: "2026-02-15T10:00:00Z", + updated: "2026-02-15T10:30:00Z", + agents: { + "ArchitectureAnalyzer": { + outputs: [".tmp/architecture/auth-system/contexts.json"], + metadata: { + boundedContext: "authentication", + module: "auth-service" + }, + timestamp: "2026-02-15T10:05:00Z" + }, + "StoryMapper": { + outputs: [".tmp/story-maps/auth-system/map.json"], + metadata: { + verticalSlice: "user-login" + }, + timestamp: "2026-02-15T10:15:00Z" + } + }, + contextFiles: [ + ".opencode/context/core/standards/code-quality.md", + "(example: .opencode/context/security/auth-patterns.md)" + ], + referenceFiles: [ + "src/auth/old-auth.ts" + ] +} +``` + +### What Gets Stored + +**Lightweight (paths and metadata only):** +- โœ… File paths to agent outputs +- โœ… Small metadata objects (boundedContext, module, etc.) +- โœ… Timestamps +- โœ… Context file paths +- โœ… Reference file paths + +**NOT stored (content stays in files):** +- โŒ Full file contents +- โŒ Large JSON blobs +- โŒ Entire session history +- โŒ Redundant context + +--- + +## API Reference + +### Core Functions + +#### `createContextIndex(feature, options)` + +Initialize a new context index for a feature. + +```typescript +import { createContextIndex } from './context-index'; + +const result = createContextIndex('auth-system', { + contextFiles: [ + '.opencode/context/core/standards/code-quality.md', + '(example: .opencode/context/security/auth-patterns.md)' + ], + referenceFiles: [ + 'src/auth/old-auth.ts' + ] +}); + +// Result: { success: true } +// Creates: .tmp/context-index/auth-system.json +``` + +#### `addAgentOutput(feature, agent, outputPath, metadata)` + +Track what each agent produced. + +```typescript +import { addAgentOutput } from './context-index'; + +// After ArchitectureAnalyzer completes +addAgentOutput( + 'auth-system', + 'ArchitectureAnalyzer', + '.tmp/architecture/auth-system/contexts.json', + { + boundedContext: 'authentication', + module: 'auth-service' + } +); + +// After StoryMapper completes +addAgentOutput( + 'auth-system', + 'StoryMapper', + '.tmp/story-maps/auth-system/map.json', + { + verticalSlice: 'user-login' + } +); +``` + +#### `getContextForAgent(feature, agentType)` + +Get ONLY the files needed for a specific agent type. + +```typescript +import { getContextForAgent } from './context-index'; + +// StoryMapper needs: ArchitectureAnalyzer output + story context +const result = getContextForAgent('auth-system', 'StoryMapper'); + +// Returns: +{ + success: true, + context: { + feature: "auth-system", + agentType: "StoryMapper", + contextFiles: [ + "(example: .opencode/context/core/story-mapping/guide.md)" + ], + referenceFiles: [], + agentOutputs: [ + ".tmp/architecture/auth-system/contexts.json" + ], + metadata: { + boundedContext: "authentication", + module: "auth-service" + } + } +} +``` + +#### `getFullContext(feature)` + +Orchestrator can see everything (for coordination). + +```typescript +import { getFullContext } from './context-index'; + +const result = getFullContext('auth-system'); + +// Returns complete index with all agent outputs +``` + +--- + +## Agent-Specific Context Rules + +Each agent type gets a minimal, focused context: + +### ArchitectureAnalyzer +**Needs:** +- Architecture patterns context files +- Reference files (existing code) + +**Gets:** +```typescript +{ + contextFiles: [ + "(example: .opencode/context/architecture/patterns.md)" + ], + referenceFiles: [ + "src/auth/old-auth.ts" + ], + agentOutputs: [], + metadata: {} +} +``` + +### StoryMapper +**Needs:** +- ArchitectureAnalyzer output +- Story mapping context files + +**Gets:** +```typescript +{ + contextFiles: [ + "(example: .opencode/context/core/story-mapping/guide.md)" + ], + referenceFiles: [], + agentOutputs: [ + ".tmp/architecture/auth-system/contexts.json" + ], + metadata: { + boundedContext: "authentication", + module: "auth-service" + } +} +``` + +### PrioritizationEngine +**Needs:** +- StoryMapper output +- Prioritization context files + +**Gets:** +```typescript +{ + contextFiles: [ + "(example: .opencode/context/core/prioritization/scoring.md)" + ], + referenceFiles: [], + agentOutputs: [ + ".tmp/story-maps/auth-system/map.json" + ], + metadata: { + verticalSlice: "user-login" + } +} +``` + +### TaskManager +**Needs:** +- ALL previous agent outputs +- Task management context files + +**Gets:** +```typescript +{ + contextFiles: [ + ".opencode/context/core/task-management/navigation.md", + ".opencode/context/core/standards/code-quality.md" + ], + referenceFiles: [], + agentOutputs: [ + ".tmp/architecture/auth-system/contexts.json", + ".tmp/story-maps/auth-system/map.json", + ".tmp/planning/prioritized.json" + ], + metadata: { + ArchitectureAnalyzer: { boundedContext: "authentication" }, + StoryMapper: { verticalSlice: "user-login" } + } +} +``` + +### CoderAgent +**Needs:** +- TaskManager output (subtask JSON) +- Coding standards + +**Gets:** +```typescript +{ + contextFiles: [ + ".opencode/context/core/standards/code-quality.md", + "(example: .opencode/context/security/auth-patterns.md)" + ], + referenceFiles: [], + agentOutputs: [ + ".tmp/tasks/auth-system/subtask_01.json" + ], + metadata: {} +} +``` + +--- + +## Orchestrator Workflow Example + +### Complete Feature Implementation Flow + +```typescript +import { + createContextIndex, + addAgentOutput, + getContextForAgent +} from './context-index'; + +// 1. Initialize context index +createContextIndex('auth-system', { + contextFiles: [ + '.opencode/context/core/standards/code-quality.md', + '(example: .opencode/context/security/auth-patterns.md)', + '(example: .opencode/context/architecture/patterns.md)' + ], + referenceFiles: [ + 'src/auth/old-auth.ts' + ] +}); + +// 2. Delegate to ArchitectureAnalyzer +const archContext = getContextForAgent('auth-system', 'ArchitectureAnalyzer'); +// Pass ONLY: archContext.contextFiles + archContext.referenceFiles + +// 3. ArchitectureAnalyzer completes โ†’ Read output and update index +addAgentOutput( + 'auth-system', + 'ArchitectureAnalyzer', + '.tmp/architecture/auth-system/contexts.json', + { boundedContext: 'authentication', module: 'auth-service' } +); + +// 4. Delegate to StoryMapper +const storyContext = getContextForAgent('auth-system', 'StoryMapper'); +// Pass ONLY: +// - storyContext.contextFiles (story mapping guide) +// - storyContext.agentOutputs (ArchitectureAnalyzer output path) + +// 5. StoryMapper completes โ†’ Update index +addAgentOutput( + 'auth-system', + 'StoryMapper', + '.tmp/story-maps/auth-system/map.json', + { verticalSlice: 'user-login' } +); + +// 6. Delegate to PrioritizationEngine +const prioContext = getContextForAgent('auth-system', 'PrioritizationEngine'); +// Pass ONLY: +// - prioContext.contextFiles (prioritization guide) +// - prioContext.agentOutputs (StoryMapper output path) + +// 7. Continue pattern through all agents... +``` + +### Key Pattern + +```typescript +// For each agent: +const context = getContextForAgent(feature, agentType); + +// Delegate with minimal context +task( + subagent_type=agentType, + description="...", + prompt=` + Context files to load: + ${context.contextFiles.map(f => `- ${f}`).join('\n')} + + Previous agent outputs to read: + ${context.agentOutputs.map(f => `- ${f}`).join('\n')} + + Metadata from previous agents: + ${JSON.stringify(context.metadata, null, 2)} + + Your task: ... + ` +); + +// After agent completes, update index +addAgentOutput(feature, agentType, outputPath, metadata); +``` + +--- + +## Comparison: Session Context vs Context Index + +### When to Use Session Context Manager + +**Use `session-context-manager.ts` when:** +- โœ… Single long-running session with one agent +- โœ… Need human-readable markdown summary +- โœ… Want to track decisions and progress narratively +- โœ… Session state needs to be reviewed by humans + +**Example:** Interactive feature development with user feedback loops + +### When to Use Context Index + +**Use `context-index.ts` when:** +- โœ… Multi-agent orchestration with delegation +- โœ… Need minimal context handoff between agents +- โœ… Want to avoid context bloat +- โœ… Agents should only see what they need +- โœ… Performance matters (large features) + +**Example:** Automated feature pipeline (Architecture โ†’ Stories โ†’ Tasks โ†’ Code) + +### Comparison Table + +| Feature | Session Context | Context Index | +|---------|----------------|---------------| +| **Format** | Markdown (human-readable) | JSON (machine-readable) | +| **Size** | Large (full content) | Small (paths only) | +| **Audience** | Humans + Agents | Agents only | +| **Context Passing** | Everything to everyone | Minimal per agent | +| **Use Case** | Interactive sessions | Automated pipelines | +| **Performance** | Slower (large files) | Faster (lightweight) | +| **Tracking** | Decisions, progress, narrative | Outputs, metadata, pointers | + +### Can You Use Both? + +**Yes!** They solve different problems: + +```typescript +// Create session context for human tracking +createSession('auth-system', 'Implement JWT authentication', { + contextFiles: [...], + exitCriteria: [...] +}); + +// Create context index for agent coordination +createContextIndex('auth-system', { + contextFiles: [...], + referenceFiles: [...] +}); + +// Session context = human-readable audit trail +// Context index = efficient agent coordination +``` + +--- + +## Benefits + +### For Orchestrator +- โœ… Lightweight tracking (just paths and metadata) +- โœ… Full visibility into all agent outputs +- โœ… Easy to coordinate dependencies +- โœ… Fast lookups + +### For Subagents +- โœ… Minimal context (only what they need) +- โœ… Faster execution (less reading) +- โœ… Clear dependencies (explicit output paths) +- โœ… No context bloat + +### For System +- โœ… Scalable (index stays small) +- โœ… Maintainable (clear separation of concerns) +- โœ… Debuggable (trace agent outputs) +- โœ… Composable (agents don't need to know about each other) + +--- + +## Anti-Patterns + +### โŒ Passing Entire Index to Agents + +```typescript +// BAD: Agent gets everything +const index = getFullContext('auth-system'); +task(subagent_type="StoryMapper", prompt=JSON.stringify(index)); +``` + +**Why bad:** Agent wastes time parsing irrelevant data + +### โŒ Embedding Content in Index + +```typescript +// BAD: Storing full file contents +addAgentOutput('auth-system', 'ArchitectureAnalyzer', outputPath, { + fullContent: fs.readFileSync(outputPath, 'utf-8') // DON'T DO THIS +}); +``` + +**Why bad:** Index becomes bloated, defeats the purpose + +### โŒ Skipping Index Updates + +```typescript +// BAD: Agent completes but orchestrator doesn't update index +task(subagent_type="ArchitectureAnalyzer", ...); +// ... agent completes ... +// (orchestrator forgets to call addAgentOutput) +``` + +**Why bad:** Next agent won't know about previous outputs + +### โŒ Using Index for Human Review + +```typescript +// BAD: Expecting humans to read JSON index +const index = getFullContext('auth-system'); +console.log("Review this:", JSON.stringify(index)); +``` + +**Why bad:** Index is for machines, use session-context for humans + +--- + +## Best Practices + +### 1. Update Index Immediately After Agent Completes + +```typescript +// Agent completes +const result = await task(subagent_type="ArchitectureAnalyzer", ...); + +// Immediately update index +addAgentOutput( + 'auth-system', + 'ArchitectureAnalyzer', + '.tmp/architecture/auth-system/contexts.json', + { boundedContext: 'authentication' } +); +``` + +### 2. Use Metadata for Small, Useful Data + +```typescript +// GOOD: Small metadata that helps next agent +addAgentOutput('auth-system', 'ArchitectureAnalyzer', outputPath, { + boundedContext: 'authentication', + module: 'auth-service', + complexity: 'medium' +}); + +// BAD: Large data that should stay in files +addAgentOutput('auth-system', 'ArchitectureAnalyzer', outputPath, { + fullAnalysis: { /* 1000 lines of JSON */ } +}); +``` + +### 3. Let Agents Read Their Own Inputs + +```typescript +// GOOD: Agent reads the file +const context = getContextForAgent('auth-system', 'StoryMapper'); +task( + subagent_type="StoryMapper", + prompt=`Read architecture analysis: ${context.agentOutputs[0]}` +); + +// BAD: Orchestrator reads and passes content +const archOutput = fs.readFileSync('.tmp/architecture/...', 'utf-8'); +task( + subagent_type="StoryMapper", + prompt=`Here's the full architecture: ${archOutput}` +); +``` + +### 4. Keep Context Files Focused + +```typescript +// GOOD: Only relevant context files +createContextIndex('auth-system', { + contextFiles: [ + '(example: .opencode/context/security/auth-patterns.md)', + '.opencode/context/core/standards/code-quality.md' + ] +}); + +// BAD: Every context file in the project +createContextIndex('auth-system', { + contextFiles: glob('.opencode/context/**/*.md') // Too much! +}); +``` + +--- + +## CLI Usage + +### Create Index + +```bash +npx ts-node context-index.ts create auth-system +# โœ… Context index created for: auth-system +# Location: .tmp/context-index/auth-system.json +``` + +### Add Agent Output + +```bash +npx ts-node context-index.ts add-output \ + auth-system \ + ArchitectureAnalyzer \ + .tmp/architecture/auth-system/contexts.json \ + '{"boundedContext":"authentication","module":"auth-service"}' +# โœ… Added ArchitectureAnalyzer output: .tmp/architecture/auth-system/contexts.json +``` + +### Get Context for Agent + +```bash +npx ts-node context-index.ts get-context auth-system StoryMapper +# { +# "feature": "auth-system", +# "agentType": "StoryMapper", +# "contextFiles": ["(example: .opencode/context/core/story-mapping/guide.md)"], +# "agentOutputs": [".tmp/architecture/auth-system/contexts.json"], +# "metadata": {"boundedContext":"authentication"} +# } +``` + +### Show Full Index + +```bash +npx ts-node context-index.ts show auth-system +# { +# "feature": "auth-system", +# "created": "2026-02-15T10:00:00Z", +# "agents": { ... } +# } +``` + +--- + +## Summary + +**Lightweight Context Handoff Pattern:** +- Orchestrator maintains lightweight index (paths + metadata) +- Each agent gets minimal, focused context +- Index stays small and fast +- Agents read only what they need +- Clear separation: index for coordination, files for content + +**Use this pattern when:** +- Multi-agent orchestration +- Performance matters +- Context bloat is a problem +- Agents should be isolated + +**Use session-context when:** +- Human-readable tracking needed +- Single-agent sessions +- Narrative progress tracking diff --git a/.opencode/context/core/workflows/multi-stage-orchestration.md b/.opencode/context/core/workflows/multi-stage-orchestration.md new file mode 100644 index 0000000..0e02f8d --- /dev/null +++ b/.opencode/context/core/workflows/multi-stage-orchestration.md @@ -0,0 +1,925 @@ + + +# Multi-Stage Orchestration Workflow + +## Quick Reference + +**Purpose**: End-to-end workflow for complex feature development from concept to release + +**8 Stages**: Architecture Decomposition โ†’ Story Mapping โ†’ Prioritization โ†’ Enhanced Task Breakdown โ†’ Contract Definition โ†’ Parallel Execution โ†’ Integration & Validation โ†’ Release & Learning + +**Key Agents**: OpenCoder (orchestrator), TaskManager, BatchExecutor, CoderAgent, ContextScout, ExternalScout + +**When to Use**: Complex features requiring multi-agent coordination, parallel execution, and systematic integration + +--- + +## Overview + +The Multi-Stage Orchestration Workflow is a comprehensive framework for managing complex software development from initial requirements through to release. It coordinates multiple specialized agents, enables parallel execution, and ensures systematic integration and validation. + +### Core Philosophy + +- **Decompose before building**: Break down complexity systematically +- **Plan before executing**: Define contracts and dependencies upfront +- **Parallelize when possible**: Execute independent work simultaneously +- **Validate continuously**: Integrate and test throughout the process +- **Learn and improve**: Capture insights for future iterations + +### Workflow Stages + +``` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ MULTI-STAGE ORCHESTRATION โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + +Stage 1: Architecture Decomposition + โ†“ (System boundaries defined) + +Stage 2: Story Mapping + โ†“ (User journeys mapped) + +Stage 3: Prioritization + โ†“ (Work sequenced) + +Stage 4: Enhanced Task Breakdown + โ†“ (Atomic tasks with dependencies) + +Stage 5: Contract Definition + โ†“ (Interfaces and integration points) + +Stage 6: Parallel Execution + โ†“ (Simultaneous implementation) + +Stage 7: Integration & Validation + โ†“ (Components verified together) + +Stage 8: Release & Learning + โ†“ (Deployed and insights captured) +``` + +--- + +## Stage 1: Architecture Decomposition + +**Goal**: Break down the system into logical components and define boundaries + +**Primary Agent**: OpenCoder (orchestrator) + +**Supporting Agents**: ContextScout (for architectural patterns) + +### Process + +1. **Analyze Requirements** + - Understand feature scope and objectives + - Identify technical constraints + - Review existing system architecture + +2. **Identify Components** + - Break system into logical modules + - Define component responsibilities + - Identify shared dependencies + +3. **Define Boundaries** + - Establish clear interfaces between components + - Identify integration points + - Map data flow between components + +4. **Document Architecture** + - Create architecture overview + - Document component relationships + - Define technical decisions + +### Outputs + +- Architecture overview document +- Component list with responsibilities +- System boundary definitions +- Integration point map + +### Transition Criteria + +- All major components identified +- Component boundaries clearly defined +- Integration points documented +- Technical approach validated + +--- + +## Stage 2: Story Mapping + +**Goal**: Map user journeys and translate into user stories + +**Primary Agent**: OpenCoder (orchestrator) + +**Supporting Agents**: ContextScout (for user journey patterns) + +### Process + +1. **Identify User Personas** + - Define who will use the system + - Understand user goals and needs + - Map user contexts + +2. **Map User Journeys** + - Document end-to-end user flows + - Identify key user actions + - Map touchpoints with system + +3. **Create User Stories** + - Write stories from user perspective + - Define acceptance criteria + - Prioritize by user value + +4. **Organize Story Map** + - Group stories by journey + - Sequence by user flow + - Identify story dependencies + +### Outputs + +- User persona definitions +- User journey maps +- User story backlog +- Story map visualization + +### Transition Criteria + +- All user journeys documented +- Stories written with acceptance criteria +- Stories organized by priority +- Dependencies identified + +--- + +## Stage 3: Prioritization + +**Goal**: Sequence work based on value, risk, and dependencies + +**Primary Agent**: OpenCoder (orchestrator) + +### Process + +1. **Assess Value** + - Rank stories by user value + - Identify must-have vs. nice-to-have + - Consider business priorities + +2. **Evaluate Risk** + - Identify technical risks + - Assess complexity + - Flag unknowns and uncertainties + +3. **Map Dependencies** + - Identify blocking dependencies + - Find parallel work opportunities + - Define critical path + +4. **Create Execution Plan** + - Sequence work into phases + - Group parallel work into batches + - Define milestones + +### Outputs + +- Prioritized story backlog +- Risk assessment matrix +- Dependency graph +- Phased execution plan + +### Transition Criteria + +- All stories prioritized +- Dependencies mapped +- Execution phases defined +- Critical path identified + +--- + +## Stage 4: Enhanced Task Breakdown + +**Goal**: Transform stories into atomic, executable tasks with clear dependencies + +**Primary Agent**: TaskManager + +**Supporting Agents**: ContextScout (for standards), ExternalScout (for library docs) + +### Process + +1. **Load Context** + - Read task management standards + - Check current task state + - Load project coding standards + +2. **Analyze Feature** + - Understand scope and objectives + - Identify technical risks + - Determine natural task boundaries + +3. **Create Task Plan** + - Break into atomic subtasks (1-2 hours each) + - Define acceptance criteria + - Specify deliverables + - Map dependencies + +4. **Generate Task JSON** + - Create `task.json` with feature metadata + - Create `subtask_NN.json` for each task + - Include context_files and reference_files + - Validate with task-cli.ts + +### Outputs + +- `.tmp/tasks/{feature}/task.json` +- `.tmp/tasks/{feature}/subtask_01.json` through `subtask_NN.json` +- Task dependency graph +- Parallel execution batches identified + +### Task JSON Structure + +```json +{ + "id": "feature-slug", + "name": "Feature Name", + "status": "active", + "objective": "Clear objective (max 200 chars)", + "context_files": ["standards paths"], + "reference_files": ["source file paths"], + "exit_criteria": ["completion criteria"], + "subtask_count": 10, + "completed_count": 0, + "created_at": "2026-02-14T00:00:00Z" +} +``` + +### Subtask JSON Structure + +```json +{ + "id": "feature-slug-01", + "seq": "01", + "title": "Task description", + "status": "pending", + "depends_on": [], + "parallel": true, + "suggested_agent": "CoderAgent", + "context_files": ["standards for this task"], + "reference_files": ["source files for this task"], + "acceptance_criteria": ["criterion 1", "criterion 2"], + "deliverables": ["file paths"], + "agent_id": null, + "started_at": null, + "completed_at": null, + "completion_summary": null +} +``` + +### Transition Criteria + +- All tasks defined with clear objectives +- Dependencies mapped +- Parallel batches identified +- Task JSON validated + +--- + +## Stage 5: Contract Definition + +**Goal**: Define interfaces and integration contracts before implementation + +**Primary Agent**: OpenCoder (orchestrator) + +**Supporting Agents**: CoderAgent (for contract implementation) + +### Process + +1. **Identify Integration Points** + - Map component interfaces + - Define API contracts + - Specify data structures + +2. **Define Contracts** + - Write TypeScript interfaces + - Document API endpoints + - Define data schemas + +3. **Create Contract Files** + - Generate type definitions + - Create interface specifications + - Document integration patterns + +4. **Validate Contracts** + - Review for completeness + - Check for conflicts + - Verify against architecture + +### Outputs + +- TypeScript interface files +- API contract specifications +- Data schema definitions +- Integration documentation + +### Contract Example + +```typescript +// contracts/user-service.ts +export interface UserService { + createUser(data: CreateUserData): Promise; + getUser(id: string): Promise; + updateUser(id: string, data: UpdateUserData): Promise; + deleteUser(id: string): Promise; +} + +export interface CreateUserData { + email: string; + name: string; + role: UserRole; +} + +export interface User { + id: string; + email: string; + name: string; + role: UserRole; + createdAt: Date; + updatedAt: Date; +} + +export type UserRole = 'admin' | 'user' | 'guest'; +``` + +### Transition Criteria + +- All integration points have contracts +- Contracts validated against architecture +- Type definitions complete +- Documentation written + +--- + +## Stage 6: Parallel Execution + +**Goal**: Execute independent tasks simultaneously to maximize throughput + +**Primary Agent**: BatchExecutor + +**Supporting Agents**: CoderAgent (for implementation), ContextScout, ExternalScout + +### Process + +1. **Identify Parallel Batches** + - Group tasks with `parallel: true` + - Verify no inter-dependencies + - Check for deliverable conflicts + +2. **Execute Batch** + - Delegate all tasks simultaneously to CoderAgent + - Each CoderAgent: + - Loads context + - Implements deliverables + - Runs self-review + - Marks task complete + +3. **Monitor Completion** + - Wait for all tasks in batch to complete + - Track individual task status + - Detect failures early + +4. **Verify Batch Completion** + - Check all tasks marked complete + - Validate deliverables exist + - Confirm acceptance criteria met + +### Batch Execution Flow + +``` +BatchExecutor receives: Batch 1 [tasks 01, 02, 03] + โ†“ + Validates parallel safety + โ†“ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚ โ”‚ โ”‚ โ”‚ + โ–ผ โ–ผ โ–ผ โ–ผ +CoderAgent CoderAgent CoderAgent +(Task 01) (Task 02) (Task 03) + โ”‚ โ”‚ โ”‚ + โ”‚ Implement โ”‚ Implement โ”‚ Implement + โ”‚ Self-reviewโ”‚ Self-reviewโ”‚ Self-review + โ”‚ Mark done โ”‚ Mark done โ”‚ Mark done + โ”‚ โ”‚ โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + All tasks complete + โ†“ + BatchExecutor verifies and reports +``` + +### CoderAgent Workflow (per task) + +1. **Load Context** (ContextScout if needed) +2. **Load Reference Files** (study existing patterns) +3. **Check External Packages** (ExternalScout if needed) +4. **Update Status** to `in_progress` +5. **Implement Deliverables** (following standards) +6. **Self-Review Loop**: + - Type & import validation + - Anti-pattern scan + - Acceptance criteria check + - External library verification +7. **Mark Complete** via task-cli.ts +8. **Report Completion** to BatchExecutor + +### Outputs + +- Implemented deliverables for all tasks in batch +- Updated task status (all marked complete) +- Self-review reports +- Batch completion summary + +### Transition Criteria + +- All tasks in batch completed +- Deliverables verified +- No failures or blocking issues +- Ready for next batch or integration + +--- + +## Stage 7: Integration & Validation + +**Goal**: Integrate components and validate system works as a whole + +**Primary Agent**: OpenCoder (orchestrator) + +**Supporting Agents**: CoderAgent (for integration code), TestEngineer (for validation) + +### Process + +1. **Integrate Components** + - Wire components together + - Implement integration points + - Connect to contracts + +2. **Run Integration Tests** + - Test component interactions + - Validate data flow + - Check error handling + +3. **Validate Against Requirements** + - Verify acceptance criteria + - Test user journeys + - Confirm feature completeness + +4. **Fix Integration Issues** + - Debug failures + - Resolve conflicts + - Refine interfaces if needed + +### Outputs + +- Integrated system +- Integration test results +- Validation report +- Issue resolution log + +### Transition Criteria + +- All components integrated +- Integration tests passing +- Acceptance criteria met +- System validated end-to-end + +--- + +## Stage 8: Release & Learning + +**Goal**: Deploy to production and capture insights for future iterations + +**Primary Agent**: OpenCoder (orchestrator) + +### Process + +1. **Prepare Release** + - Final validation + - Documentation review + - Deployment checklist + +2. **Deploy** + - Execute deployment + - Monitor for issues + - Verify production health + +3. **Capture Insights** + - Document what worked well + - Identify improvement areas + - Record technical decisions + - Update patterns and standards + +4. **Plan Next Iteration** + - Review backlog + - Prioritize next features + - Apply learnings + +### Outputs + +- Deployed feature +- Release notes +- Lessons learned document +- Updated standards/patterns + +### Transition Criteria + +- Feature deployed successfully +- Production validated +- Insights documented +- Team aligned on learnings + +--- + +## Agent Responsibilities + +### OpenCoder (Orchestrator) + +**Stages**: All (primary orchestrator) + +**Responsibilities**: +- Overall workflow coordination +- Stage transitions +- Decision making +- Progress tracking +- Issue resolution + +### TaskManager + +**Stages**: Stage 4 (Enhanced Task Breakdown) + +**Responsibilities**: +- Feature decomposition +- Task JSON generation +- Dependency mapping +- Parallel batch identification +- Task validation + +### BatchExecutor + +**Stages**: Stage 6 (Parallel Execution) + +**Responsibilities**: +- Parallel batch coordination +- Simultaneous task delegation +- Completion monitoring +- Batch status reporting + +### CoderAgent + +**Stages**: Stage 5 (Contract Definition), Stage 6 (Parallel Execution), Stage 7 (Integration) + +**Responsibilities**: +- Code implementation +- Self-review execution +- Deliverable creation +- Task completion marking + +### ContextScout + +**Stages**: All (supporting) + +**Responsibilities**: +- Context discovery +- Standards retrieval +- Pattern identification +- Documentation finding + +### ExternalScout + +**Stages**: Stage 4, Stage 6 (supporting) + +**Responsibilities**: +- External library documentation +- API reference retrieval +- Integration pattern discovery + +--- + +## Integration with Existing System + +### Task Management Integration + +**Location**: `.tmp/tasks/{feature}/` + +**Files**: +- `task.json` โ€” Feature metadata +- `subtask_NN.json` โ€” Individual task definitions + +**CLI**: `.opencode/skill/task-management/scripts/task-cli.ts` + +**Commands**: +- `status [feature]` โ€” Check task status +- `next [feature]` โ€” Get next eligible task +- `parallel [feature]` โ€” Show parallel-ready tasks +- `complete {feature} {seq} "summary"` โ€” Mark task complete +- `validate [feature]` โ€” Validate task JSON + +### Session Management Integration + +**Location**: `.tmp/sessions/{timestamp}-{feature}/` + +**Files**: +- `context.md` โ€” Session context bundle +- `progress.md` โ€” Progress tracking + +**Usage**: Context bundles passed to delegated agents + +### Context System Integration + +**Standards Location**: `.opencode/context/core/standards/` + +**Workflows Location**: `.opencode/context/core/workflows/` + +**Usage**: Referenced in task `context_files` arrays + +### Agent Configuration Integration + +**Location**: `.opencode/agent/subagents/core/` + +**Files**: +- `task-manager.md` โ€” TaskManager configuration +- `batch-executor.md` โ€” BatchExecutor configuration +- `coder-agent.md` โ€” CoderAgent configuration + +--- + +## Workflow Diagram + +``` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ ORCHESTRATION FLOW โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stage 1: Architecture Decomposition โ”‚ +โ”‚ Agent: OpenCoder + ContextScout โ”‚ +โ”‚ Output: Component boundaries, integration points โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stage 2: Story Mapping โ”‚ +โ”‚ Agent: OpenCoder โ”‚ +โ”‚ Output: User journeys, story backlog โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stage 3: Prioritization โ”‚ +โ”‚ Agent: OpenCoder โ”‚ +โ”‚ Output: Sequenced work, dependency graph, execution plan โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stage 4: Enhanced Task Breakdown โ”‚ +โ”‚ Agent: TaskManager + ContextScout + ExternalScout โ”‚ +โ”‚ Output: task.json, subtask_NN.json files, parallel batches โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stage 5: Contract Definition โ”‚ +โ”‚ Agent: OpenCoder + CoderAgent โ”‚ +โ”‚ Output: TypeScript interfaces, API contracts, schemas โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stage 6: Parallel Execution โ”‚ +โ”‚ Agent: BatchExecutor โ†’ CoderAgent (multiple simultaneous) โ”‚ +โ”‚ โ”‚ +โ”‚ Batch 1: [Task 01, 02, 03] โ”€โ”€โ†’ Execute in parallel โ”‚ +โ”‚ โ†“ โ”‚ +โ”‚ Batch 2: [Task 04, 05] โ”€โ”€โ†’ Execute in parallel โ”‚ +โ”‚ โ†“ โ”‚ +โ”‚ Batch 3: [Task 06] โ”€โ”€โ†’ Execute sequentially โ”‚ +โ”‚ โ”‚ +โ”‚ Output: Implemented deliverables, completed tasks โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stage 7: Integration & Validation โ”‚ +โ”‚ Agent: OpenCoder + CoderAgent + TestEngineer โ”‚ +โ”‚ Output: Integrated system, test results, validation report โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stage 8: Release & Learning โ”‚ +โ”‚ Agent: OpenCoder โ”‚ +โ”‚ Output: Deployed feature, insights, updated standards โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ +``` + +--- + +## Example: Authentication System + +### Stage 1: Architecture Decomposition + +**Components Identified**: +- User Service (user management) +- Auth Service (authentication logic) +- Token Service (JWT handling) +- Middleware (request validation) +- Database Layer (user storage) + +**Integration Points**: +- Auth Service โ†” User Service (user lookup) +- Auth Service โ†” Token Service (token generation) +- Middleware โ†” Token Service (token validation) + +### Stage 2: Story Mapping + +**User Stories**: +1. As a user, I want to register an account +2. As a user, I want to log in with email/password +3. As a user, I want to reset my password +4. As a user, I want to stay logged in (refresh tokens) +5. As an admin, I want to manage user roles + +### Stage 3: Prioritization + +**Phase 1** (Must-have): +- Story 1: Registration +- Story 2: Login + +**Phase 2** (Should-have): +- Story 4: Refresh tokens +- Story 3: Password reset + +**Phase 3** (Nice-to-have): +- Story 5: Role management + +### Stage 4: Enhanced Task Breakdown + +**Batch 1** (Parallel): +- Task 01: Setup project structure +- Task 02: Configure database schema +- Task 03: Install dependencies + +**Batch 2** (Parallel): +- Task 04: Implement User Service +- Task 05: Implement Token Service + +**Batch 3** (Sequential): +- Task 06: Implement Auth Service (depends on 04, 05) + +**Batch 4** (Parallel): +- Task 07: Create registration endpoint +- Task 08: Create login endpoint + +**Batch 5** (Sequential): +- Task 09: Integration tests (depends on all) + +### Stage 5: Contract Definition + +```typescript +// contracts/auth-service.ts +export interface AuthService { + register(data: RegisterData): Promise; + login(credentials: LoginCredentials): Promise; + refreshToken(token: string): Promise; +} + +export interface AuthResult { + success: boolean; + user?: User; + accessToken?: string; + refreshToken?: string; + error?: string; +} +``` + +### Stage 6: Parallel Execution + +**Batch 1 Execution**: +- BatchExecutor delegates tasks 01, 02, 03 to three CoderAgents +- All execute simultaneously +- All complete and mark status +- BatchExecutor verifies and reports + +**Batch 2 Execution**: +- BatchExecutor delegates tasks 04, 05 to two CoderAgents +- Both execute simultaneously +- Both complete and mark status +- BatchExecutor verifies and reports + +### Stage 7: Integration & Validation + +- Wire Auth Service to User Service and Token Service +- Test registration flow end-to-end +- Test login flow end-to-end +- Validate error handling +- Confirm all acceptance criteria met + +### Stage 8: Release & Learning + +- Deploy to production +- Monitor authentication metrics +- Document JWT implementation decisions +- Update security patterns based on learnings + +--- + +## Best Practices + +### Planning Phase (Stages 1-4) + +- **Invest time upfront**: Thorough planning prevents rework +- **Involve stakeholders**: Validate assumptions early +- **Document decisions**: Capture rationale for future reference +- **Identify risks early**: Address unknowns before implementation + +### Execution Phase (Stages 5-6) + +- **Define contracts first**: Prevents integration issues +- **Maximize parallelization**: Execute independent work simultaneously +- **Monitor progress**: Track batch completion actively +- **Fail fast**: Detect and address issues immediately + +### Validation Phase (Stage 7) + +- **Test continuously**: Don't wait until the end +- **Validate against requirements**: Ensure acceptance criteria met +- **Test integration points**: Focus on component interactions +- **Document issues**: Track and resolve systematically + +### Learning Phase (Stage 8) + +- **Capture insights immediately**: Don't wait for retrospectives +- **Update standards**: Apply learnings to improve future work +- **Share knowledge**: Document for team benefit +- **Iterate**: Use insights to improve next iteration + +--- + +## Common Patterns + +### Pattern 1: Foundation โ†’ Features โ†’ Integration + +1. Setup infrastructure (database, auth, logging) +2. Build core features in parallel +3. Integrate and validate + +### Pattern 2: Vertical Slices + +1. Implement one complete user journey +2. Validate end-to-end +3. Repeat for next journey + +### Pattern 3: Contract-First Development + +1. Define all interfaces upfront +2. Implement components independently +3. Integration is straightforward + +--- + +## Troubleshooting + +### Issue: Tasks blocked by dependencies + +**Solution**: Review dependency graph, identify if dependencies can be removed or if contracts can enable parallel work + +### Issue: Integration failures + +**Solution**: Verify contracts were followed, check for interface mismatches, validate data flow + +### Issue: Batch execution delays + +**Solution**: Check for hidden dependencies, verify tasks are truly independent, consider splitting into smaller batches + +### Issue: Acceptance criteria unclear + +**Solution**: Refine criteria in planning stage, involve stakeholders, make criteria binary (pass/fail) + +--- + +## Summary + +The Multi-Stage Orchestration Workflow provides a systematic approach to complex feature development: + +1. **Decompose** the system into manageable components +2. **Map** user journeys and create stories +3. **Prioritize** work based on value and risk +4. **Break down** into atomic, executable tasks +5. **Define** integration contracts upfront +6. **Execute** independent work in parallel +7. **Integrate** and validate continuously +8. **Release** and capture learnings + +By following this workflow, teams can: +- Reduce complexity through systematic decomposition +- Maximize throughput via parallel execution +- Minimize integration issues through contract-first development +- Improve continuously through structured learning + +**Key Success Factors**: +- Thorough planning before execution +- Clear contracts and interfaces +- Effective parallel coordination +- Continuous validation +- Systematic learning capture diff --git a/.opencode/context/core/workflows/navigation.md b/.opencode/context/core/workflows/navigation.md index 474634e..445591c 100644 --- a/.opencode/context/core/workflows/navigation.md +++ b/.opencode/context/core/workflows/navigation.md @@ -1,3 +1,5 @@ + + # Core Workflows Navigation **Purpose**: Process workflows for common development tasks diff --git a/.opencode/context/core/workflows/session-context-pattern.md b/.opencode/context/core/workflows/session-context-pattern.md new file mode 100644 index 0000000..b5bdef2 --- /dev/null +++ b/.opencode/context/core/workflows/session-context-pattern.md @@ -0,0 +1,611 @@ + +# Session Context Pattern + +## Problem + +**Context Fragmentation in Multi-Agent Orchestration** + +When orchestrating complex features across multiple agents (TaskManager โ†’ CoderAgent โ†’ TestEngineer), each agent is stateless and loses context between delegations: + +- **TaskManager** creates subtasks but doesn't know what ContextScout discovered +- **CoderAgent** doesn't see what ArchitectureAnalyzer decided +- **TestEngineer** doesn't know what files CoderAgent created +- **Orchestrator** has to manually pass context in every delegation + +This leads to: +- โŒ Repeated context discovery (inefficient) +- โŒ Inconsistent decisions (agents don't see previous choices) +- โŒ Lost architectural context (bounded contexts, contracts, ADRs) +- โŒ Manual context passing (error-prone, verbose) + +## Solution + +**Persistent Session Context File** + +Create a single `context.md` file that all agents read and update throughout the feature lifecycle: + +``` +.tmp/sessions/{session-id}/context.md +``` + +This file acts as the **shared memory** for the entire orchestration session. + +## Architecture + +### Session Lifecycle + +``` +1. Orchestrator creates session โ†’ context.md initialized +2. ContextScout updates โ†’ adds context_files +3. ArchitectureAnalyzer updates โ†’ adds bounded_context, module +4. TaskManager reads context โ†’ creates subtasks with full context +5. CoderAgent reads context โ†’ knows all decisions, files, contracts +6. TestEngineer reads context โ†’ knows what to test +7. Orchestrator marks complete โ†’ session archived +``` + +### Context.md Structure + +```markdown +# Task Context: {Feature Name} + +Session ID: {session-id} +Created: {timestamp} +Status: in_progress | completed | blocked + +## Current Request +{Original user request - what we're building} + +## Context Files to Load +- {Standards paths - coding conventions, patterns, security rules} + +## Reference Files +- {Source material - existing project files to look at} + +## Architecture +- Bounded Context: {DDD context from ArchitectureAnalyzer} +- Module: {Package/module name} +- Vertical Slice: {Feature slice from StoryMapper} + +## User Stories +- {Story 1 from StoryMapper} +- {Story 2} + +## Priorities +- RICE Score: {score from PrioritizationEngine} +- WSJF Score: {score} +- Release Slice: {v1.0.0, Q1-2026, MVP} + +## Contracts +- {type}: {name} ({status}) + Path: {contract file path} + +## Architectural Decision Records +- {ADR-ID}: {title} + Path: {adr file path} + +## Progress +Current Stage: {Stage N: Name} + +Completed Stages: +- {Stage 0: Context Loading} +- {Stage 1: Planning} + +Stage Outputs: +- {Stage 0}: + - {Output 1} + - {Output 2} + +## Key Decisions +- [{timestamp}] {decision} + Rationale: {why this choice was made} + +## Files Created +- {file path 1} +- {file path 2} + +## Exit Criteria +- [ ] {criterion 1} +- [ ] {criterion 2} +- [x] {completed criterion} +``` + +## When to Use + +### Use Session Context When: + +โœ… **Multi-agent orchestration** - Feature requires 3+ agents working sequentially +โœ… **Complex features** - Needs architecture analysis, contracts, ADRs +โœ… **Stateful workflows** - Later agents need to know what earlier agents did +โœ… **Context-heavy tasks** - Lots of standards, patterns, decisions to track + +### Don't Use Session Context When: + +โŒ **Single agent tasks** - Simple subtask execution (CoderAgent alone) +โŒ **Stateless operations** - Each task is independent +โŒ **Quick fixes** - Bug fixes, small updates + +## Usage by Agent Type + +### Orchestrator (MetaAgent) + +**Stage 0: Initialize Session** + +```typescript +import { createSession } from '.opencode/skill/task-management/scripts/session-context-manager'; + +const result = createSession(feature, request, { + contextFiles: [], // Will be populated by ContextScout + referenceFiles: [], + exitCriteria: [ + 'All subtasks completed', + 'Tests passing', + 'Documentation updated' + ] +}); + +const sessionId = result.sessionId; +// Pass sessionId to all subsequent agents +``` + +**Between Stages: Update Context** + +```typescript +import { updateSession, markStageComplete } from './session-context-manager'; + +// After ContextScout completes +updateSession(sessionId, { + contextFiles: [ + '.opencode/context/core/standards/code-quality.md', + '.opencode/context/core/standards/security-patterns.md' + ] +}); + +// After ArchitectureAnalyzer completes +updateSession(sessionId, { + architecture: { + boundedContext: 'authentication', + module: '@app/auth' + } +}); + +// Mark stage complete +markStageComplete(sessionId, 'Stage 1: Planning', [ + '.tmp/tasks/auth-system/task.json', + '.tmp/tasks/auth-system/subtask_01.json' +]); +``` + +**Final Stage: Complete Session** + +```typescript +updateSession(sessionId, { status: 'completed' }); +``` + +### TaskManager + +**Stage 0: Load Session Context** + +```typescript +import { loadSession } from '.opencode/skill/task-management/scripts/session-context-manager'; + +const result = loadSession(sessionId); +if (!result.success) { + throw new Error(`Session not found: ${sessionId}`); +} + +const session = result.session; + +// Use session context for task planning +const contextFiles = session.contextFiles; // Standards to follow +const referenceFiles = session.referenceFiles; // Source files to look at +const architecture = session.architecture; // Bounded context, module +const contracts = session.contracts; // API contracts +const adrs = session.adrs; // Architectural decisions +``` + +**Stage 2: Create Tasks with Full Context** + +```json +{ + "id": "auth-system", + "name": "Authentication System", + "context_files": ["...from session.contextFiles..."], + "reference_files": ["...from session.referenceFiles..."], + "bounded_context": "...from session.architecture.boundedContext...", + "module": "...from session.architecture.module...", + "contracts": ["...from session.contracts..."], + "related_adrs": ["...from session.adrs..."] +} +``` + +**Stage 3: Update Progress** + +```typescript +import { addDecision } from './session-context-manager'; + +addDecision(sessionId, { + decision: 'Split authentication into 3 subtasks: schema, service, middleware', + rationale: 'Each subtask is atomic (1-2 hours) and has clear dependencies' +}); +``` + +### CoderAgent + +**Before Coding: Load Session Context** + +```typescript +import { loadSession } from '.opencode/skill/task-management/scripts/session-context-manager'; + +const result = loadSession(sessionId); +const session = result.session; + +// Read context files (standards) +session.contextFiles.forEach(file => { + // Load coding standards, security patterns +}); + +// Read reference files (existing code) +session.referenceFiles.forEach(file => { + // Study existing patterns +}); + +// Check architectural constraints +const boundedContext = session.architecture?.boundedContext; +const contracts = session.contracts; // API contracts to implement +const adrs = session.adrs; // Architectural decisions to follow +``` + +**After Coding: Track Files Created** + +```typescript +import { addFile } from './session-context-manager'; + +addFile(sessionId, 'src/auth/jwt.service.ts'); +addFile(sessionId, 'src/auth/jwt.service.test.ts'); +``` + +### ContextScout + +**After Discovery: Update Session** + +```typescript +import { updateSession } from './session-context-manager'; + +updateSession(sessionId, { + contextFiles: [ + '.opencode/context/core/standards/code-quality.md', + '.opencode/context/core/standards/security-patterns.md', + '(example: .opencode/context/core/standards/naming-conventions.md)' + ], + referenceFiles: [ + 'src/middleware/auth.middleware.ts', + 'src/config/jwt.config.ts' + ] +}); +``` + +### ArchitectureAnalyzer + +**After Analysis: Update Session** + +```typescript +import { updateSession, addDecision } from './session-context-manager'; + +updateSession(sessionId, { + architecture: { + boundedContext: 'authentication', + module: '@app/auth', + verticalSlice: 'user-login' + } +}); + +addDecision(sessionId, { + decision: 'Place authentication in separate bounded context', + rationale: 'Auth is a core domain with clear boundaries, used by multiple features' +}); +``` + +### ContractManager + +**After Contract Definition: Update Session** + +```typescript +import { updateSession } from './session-context-manager'; + +updateSession(sessionId, { + contracts: [ + { + type: 'api', + name: 'AuthAPI', + path: 'src/api/auth.contract.ts', + status: 'defined' + }, + { + type: 'interface', + name: 'JWTService', + path: 'src/auth/jwt.service.ts', + status: 'draft' + } + ] +}); +``` + +## API Reference + +### createSession(feature, request, options) + +Initialize a new session with context.md file. + +**Parameters:** +- `feature` (string) - Feature name (kebab-case) +- `request` (string) - Original user request +- `options` (object) - Optional configuration + - `contextFiles` (string[]) - Standards paths + - `referenceFiles` (string[]) - Source file paths + - `exitCriteria` (string[]) - Completion criteria + - `architecture` (object) - Bounded context, module, vertical slice + - `stories` (string[]) - User stories + - `priorities` (object) - RICE/WSJF scores, release slice + - `contracts` (array) - API/interface contracts + - `adrs` (array) - Architectural decision records + +**Returns:** +```typescript +{ success: boolean; sessionId?: string; error?: string } +``` + +**Example:** +```typescript +const result = createSession('auth-system', 'Implement JWT authentication', { + exitCriteria: ['All tests passing', 'JWT tokens signed with RS256'] +}); +// result.sessionId = "auth-system-2026-02-15T10-30-00-000Z" +``` + +### loadSession(sessionId) + +Read session context from context.md. + +**Parameters:** +- `sessionId` (string) - Session identifier + +**Returns:** +```typescript +{ success: boolean; session?: SessionContext; error?: string } +``` + +**Example:** +```typescript +const result = loadSession('auth-system-2026-02-15T10-30-00-000Z'); +if (result.success) { + const contextFiles = result.session.contextFiles; + const architecture = result.session.architecture; +} +``` + +### updateSession(sessionId, updates) + +Append new information to session context. + +**Parameters:** +- `sessionId` (string) - Session identifier +- `updates` (object) - Fields to update + - `status` - 'in_progress' | 'completed' | 'blocked' + - `contextFiles` - Add standards paths (merged with existing) + - `referenceFiles` - Add source file paths (merged with existing) + - `architecture` - Update bounded context, module, vertical slice + - `stories` - Add user stories + - `priorities` - Update RICE/WSJF scores + - `contracts` - Add contracts + - `adrs` - Add ADRs + +**Returns:** +```typescript +{ success: boolean; error?: string } +``` + +**Example:** +```typescript +updateSession(sessionId, { + architecture: { + boundedContext: 'authentication', + module: '@app/auth' + }, + contracts: [ + { type: 'api', name: 'AuthAPI', path: 'src/api/auth.contract.ts', status: 'defined' } + ] +}); +``` + +### markStageComplete(sessionId, stage, outputs) + +Mark a workflow stage as complete and record outputs. + +**Parameters:** +- `sessionId` (string) - Session identifier +- `stage` (string) - Stage name (e.g., "Stage 1: Planning") +- `outputs` (string[]) - Files/artifacts created in this stage + +**Returns:** +```typescript +{ success: boolean; error?: string } +``` + +**Example:** +```typescript +markStageComplete(sessionId, 'Stage 1: Planning', [ + '.tmp/tasks/auth-system/task.json', + '.tmp/tasks/auth-system/subtask_01.json', + '.tmp/tasks/auth-system/subtask_02.json' +]); +``` + +### addDecision(sessionId, decision) + +Log a key decision with rationale. + +**Parameters:** +- `sessionId` (string) - Session identifier +- `decision` (object) + - `decision` (string) - What was decided + - `rationale` (string) - Why this choice was made + +**Returns:** +```typescript +{ success: boolean; error?: string } +``` + +**Example:** +```typescript +addDecision(sessionId, { + decision: 'Use RS256 for JWT signing instead of HS256', + rationale: 'RS256 (asymmetric) is more secure for distributed systems where tokens are verified by multiple services' +}); +``` + +### addFile(sessionId, filePath) + +Track a file created during the session. + +**Parameters:** +- `sessionId` (string) - Session identifier +- `filePath` (string) - Path to created file + +**Returns:** +```typescript +{ success: boolean; error?: string } +``` + +**Example:** +```typescript +addFile(sessionId, 'src/auth/jwt.service.ts'); +addFile(sessionId, 'src/auth/jwt.service.test.ts'); +``` + +### getSessionSummary(sessionId) + +Get current session state summary. + +**Parameters:** +- `sessionId` (string) - Session identifier + +**Returns:** +```typescript +{ + success: boolean; + summary?: { + sessionId: string; + feature: string; + status: string; + currentStage: string; + completedStages: number; + totalDecisions: number; + filesCreated: number; + exitCriteriaMet: number; + exitCriteriaTotal: number; + }; + error?: string; +} +``` + +**Example:** +```typescript +const result = getSessionSummary(sessionId); +console.log(`Progress: ${result.summary.completedStages} stages complete`); +console.log(`Files: ${result.summary.filesCreated} created`); +console.log(`Exit Criteria: ${result.summary.exitCriteriaMet}/${result.summary.exitCriteriaTotal}`); +``` + +## CLI Usage + +```bash +# Create session +npx ts-node session-context-manager.ts create auth-system "Implement JWT authentication" + +# Load session +npx ts-node session-context-manager.ts load auth-system-2026-02-15T10-30-00-000Z + +# Show summary +npx ts-node session-context-manager.ts summary auth-system-2026-02-15T10-30-00-000Z +``` + +## Benefits + +โœ… **No context loss** - All agents see the full picture +โœ… **Consistent decisions** - Architectural choices tracked and visible +โœ… **Efficient** - Context discovered once, used by all agents +โœ… **Auditable** - Complete history of decisions and progress +โœ… **Self-documenting** - context.md is human-readable +โœ… **Resumable** - Can pause and resume orchestration + +## Best Practices + +### 1. Initialize Early +Create session at the start of orchestration, before any agent work begins. + +### 2. Update After Each Stage +Every agent that completes work should update the session context. + +### 3. Read Before Acting +Every agent should load session context before starting work. + +### 4. Track Decisions +Use `addDecision()` for any architectural or design choice. + +### 5. Track Files +Use `addFile()` for every file created (helps with cleanup, rollback). + +### 6. Use Exit Criteria +Define clear, binary exit criteria at session creation. + +## Example: Full Orchestration Flow + +```typescript +// Orchestrator: Initialize +const { sessionId } = createSession('auth-system', 'Implement JWT authentication', { + exitCriteria: ['All tests passing', 'JWT tokens signed with RS256'] +}); + +// Stage 0: ContextScout discovers context +updateSession(sessionId, { + contextFiles: ['.opencode/context/core/standards/code-quality.md'], + referenceFiles: ['src/middleware/auth.middleware.ts'] +}); +markStageComplete(sessionId, 'Stage 0: Context Loading', []); + +// Stage 1: ArchitectureAnalyzer analyzes +updateSession(sessionId, { + architecture: { boundedContext: 'authentication', module: '@app/auth' } +}); +addDecision(sessionId, { + decision: 'Separate bounded context for auth', + rationale: 'Core domain with clear boundaries' +}); +markStageComplete(sessionId, 'Stage 1: Architecture Analysis', []); + +// Stage 2: TaskManager creates tasks +const { session } = loadSession(sessionId); +// Use session.contextFiles, session.architecture in task.json +markStageComplete(sessionId, 'Stage 2: Task Planning', [ + '.tmp/tasks/auth-system/task.json' +]); + +// Stage 3: CoderAgent implements +const { session } = loadSession(sessionId); +// Read session.contextFiles, session.contracts +addFile(sessionId, 'src/auth/jwt.service.ts'); +markStageComplete(sessionId, 'Stage 3: Implementation', [ + 'src/auth/jwt.service.ts' +]); + +// Stage 4: Complete +updateSession(sessionId, { status: 'completed' }); +``` + +## Related + +- `.opencode/skill/task-management/scripts/session-context-manager.ts` - Implementation +- `.opencode/context/core/task-management/standards/task-schema.md` - Task JSON schema +- `.opencode/context/core/workflows/task-delegation.md` - Multi-agent orchestration +- `.tmp/sessions/test-task-manager/context.md` - Example session context diff --git a/.opencode/context/data/README.md b/.opencode/context/data/README.md index c17825a..7d1232c 100644 --- a/.opencode/context/data/README.md +++ b/.opencode/context/data/README.md @@ -1,3 +1,5 @@ + + # Data Context This directory contains context files for data analysis, visualization, and statistical methods. diff --git a/.opencode/context/data/navigation.md b/.opencode/context/data/navigation.md index c17825a..5e5bc53 100644 --- a/.opencode/context/data/navigation.md +++ b/.opencode/context/data/navigation.md @@ -1,3 +1,5 @@ + + # Data Context This directory contains context files for data analysis, visualization, and statistical methods. diff --git a/.opencode/context/development/ai/mastra-ai/concepts/agents-tools.md b/.opencode/context/development/ai/mastra-ai/concepts/agents-tools.md index 53a5d53..63c64d7 100644 --- a/.opencode/context/development/ai/mastra-ai/concepts/agents-tools.md +++ b/.opencode/context/development/ai/mastra-ai/concepts/agents-tools.md @@ -1,3 +1,5 @@ + + # Concept: Mastra Agents & Tools **Purpose**: Reusable units of logic and LLM-powered entities. diff --git a/.opencode/context/development/ai/mastra-ai/concepts/core.md b/.opencode/context/development/ai/mastra-ai/concepts/core.md index ac8a230..4360d7a 100644 --- a/.opencode/context/development/ai/mastra-ai/concepts/core.md +++ b/.opencode/context/development/ai/mastra-ai/concepts/core.md @@ -1,3 +1,5 @@ + + # Concept: Mastra Core **Purpose**: Central orchestration layer for AI agents, workflows, and tools in this project. diff --git a/.opencode/context/development/ai/mastra-ai/concepts/evaluations.md b/.opencode/context/development/ai/mastra-ai/concepts/evaluations.md index c86c37c..2a2559f 100644 --- a/.opencode/context/development/ai/mastra-ai/concepts/evaluations.md +++ b/.opencode/context/development/ai/mastra-ai/concepts/evaluations.md @@ -1,3 +1,5 @@ + + # Concept: Mastra Evaluations **Purpose**: Quality assurance and scoring for LLM outputs. diff --git a/.opencode/context/development/ai/mastra-ai/concepts/navigation.md b/.opencode/context/development/ai/mastra-ai/concepts/navigation.md new file mode 100644 index 0000000..cff35c2 --- /dev/null +++ b/.opencode/context/development/ai/mastra-ai/concepts/navigation.md @@ -0,0 +1,49 @@ + + +# Mastra AI Concepts + +**Purpose**: Core concepts and architecture of Mastra AI framework + +--- + +## Structure + +``` +concepts/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ agents-tools.md +โ”œโ”€โ”€ core.md +โ”œโ”€โ”€ evaluations.md +โ”œโ”€โ”€ storage.md +โ””โ”€โ”€ workflows.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Core concepts** | `core.md` | +| **Agents & tools** | `agents-tools.md` | +| **Workflows** | `workflows.md` | +| **Storage** | `storage.md` | +| **Evaluations** | `evaluations.md` | + +--- + +## By Type + +**Core** โ†’ Fundamental Mastra concepts +**Agents** โ†’ Agent and tool architecture +**Workflows** โ†’ Workflow system concepts +**Storage** โ†’ Data persistence patterns +**Evaluations** โ†’ Testing and evaluation + +--- + +## Related Context + +- **Mastra AI** โ†’ `../navigation.md` +- **Guides** โ†’ `../guides/navigation.md` +- **Examples** โ†’ `../examples/navigation.md` diff --git a/.opencode/context/development/ai/mastra-ai/concepts/storage.md b/.opencode/context/development/ai/mastra-ai/concepts/storage.md index 5e9bf86..6818f4b 100644 --- a/.opencode/context/development/ai/mastra-ai/concepts/storage.md +++ b/.opencode/context/development/ai/mastra-ai/concepts/storage.md @@ -1,3 +1,5 @@ + + # Concept: Mastra Data Storage **Purpose**: Persistence layer for cases, documents, assessments, and observability. diff --git a/.opencode/context/development/ai/mastra-ai/concepts/workflows.md b/.opencode/context/development/ai/mastra-ai/concepts/workflows.md index 47d18bd..defae67 100644 --- a/.opencode/context/development/ai/mastra-ai/concepts/workflows.md +++ b/.opencode/context/development/ai/mastra-ai/concepts/workflows.md @@ -1,3 +1,5 @@ + + # Concept: Mastra Workflows **Purpose**: Linear and parallel execution chains for complex AI tasks. diff --git a/.opencode/context/development/ai/mastra-ai/errors/mastra-errors.md b/.opencode/context/development/ai/mastra-ai/errors/mastra-errors.md index b3ef768..1d6c8d0 100644 --- a/.opencode/context/development/ai/mastra-ai/errors/mastra-errors.md +++ b/.opencode/context/development/ai/mastra-ai/errors/mastra-errors.md @@ -1,3 +1,5 @@ + + # Errors: Mastra Implementation **Purpose**: Common errors, their causes, and recovery strategies. diff --git a/.opencode/context/development/ai/mastra-ai/errors/navigation.md b/.opencode/context/development/ai/mastra-ai/errors/navigation.md new file mode 100644 index 0000000..005bad5 --- /dev/null +++ b/.opencode/context/development/ai/mastra-ai/errors/navigation.md @@ -0,0 +1,39 @@ + + +# Mastra AI Errors + +**Purpose**: Common errors and troubleshooting for Mastra AI + +--- + +## Structure + +``` +errors/ +โ”œโ”€โ”€ navigation.md (this file) +โ””โ”€โ”€ mastra-errors.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Common errors** | `mastra-errors.md` | +| **Guides** | `../guides/navigation.md` | +| **Concepts** | `../concepts/navigation.md` | + +--- + +## By Type + +**Troubleshooting** โ†’ Common errors and solutions + +--- + +## Related Context + +- **Mastra AI** โ†’ `../navigation.md` +- **Guides** โ†’ `../guides/navigation.md` +- **Concepts** โ†’ `../concepts/navigation.md` diff --git a/.opencode/context/development/ai/mastra-ai/examples/navigation.md b/.opencode/context/development/ai/mastra-ai/examples/navigation.md new file mode 100644 index 0000000..ba1ceff --- /dev/null +++ b/.opencode/context/development/ai/mastra-ai/examples/navigation.md @@ -0,0 +1,39 @@ + + +# Mastra AI Examples + +**Purpose**: Working examples and code samples for Mastra AI + +--- + +## Structure + +``` +examples/ +โ”œโ”€โ”€ navigation.md (this file) +โ””โ”€โ”€ workflow-example.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Workflow example** | `workflow-example.md` | +| **Workflow concepts** | `../concepts/workflows.md` | +| **Workflow guide** | `../guides/workflow-step-structure.md` | + +--- + +## By Type + +**Workflows** โ†’ Workflow implementation examples + +--- + +## Related Context + +- **Mastra AI** โ†’ `../navigation.md` +- **Concepts** โ†’ `../concepts/navigation.md` +- **Guides** โ†’ `../guides/navigation.md` diff --git a/.opencode/context/development/ai/mastra-ai/examples/workflow-example.md b/.opencode/context/development/ai/mastra-ai/examples/workflow-example.md index e7070d0..6ba415f 100644 --- a/.opencode/context/development/ai/mastra-ai/examples/workflow-example.md +++ b/.opencode/context/development/ai/mastra-ai/examples/workflow-example.md @@ -1,3 +1,5 @@ + + # Example: Document Ingestion Workflow **Purpose**: Demonstrates a multi-step workflow with parallel processing. diff --git a/.opencode/context/development/ai/mastra-ai/guides/modular-building.md b/.opencode/context/development/ai/mastra-ai/guides/modular-building.md index 60d1cff..bd288bb 100644 --- a/.opencode/context/development/ai/mastra-ai/guides/modular-building.md +++ b/.opencode/context/development/ai/mastra-ai/guides/modular-building.md @@ -1,3 +1,5 @@ + + # Guide: Modular Mastra Building **Purpose**: Best practices for structuring a large-scale Mastra implementation. diff --git a/.opencode/context/development/ai/mastra-ai/guides/navigation.md b/.opencode/context/development/ai/mastra-ai/guides/navigation.md new file mode 100644 index 0000000..9ced55f --- /dev/null +++ b/.opencode/context/development/ai/mastra-ai/guides/navigation.md @@ -0,0 +1,44 @@ + + +# Mastra AI Guides + +**Purpose**: Step-by-step guides for building with Mastra AI + +--- + +## Structure + +``` +guides/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ modular-building.md +โ”œโ”€โ”€ testing.md +โ””โ”€โ”€ workflow-step-structure.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Build modular systems** | `modular-building.md` | +| **Test Mastra apps** | `testing.md` | +| **Structure workflows** | `workflow-step-structure.md` | +| **Workflow concepts** | `../concepts/workflows.md` | + +--- + +## By Type + +**Architecture** โ†’ Modular building patterns +**Testing** โ†’ Testing strategies +**Workflows** โ†’ Workflow design and structure + +--- + +## Related Context + +- **Mastra AI** โ†’ `../navigation.md` +- **Concepts** โ†’ `../concepts/navigation.md` +- **Examples** โ†’ `../examples/navigation.md` diff --git a/.opencode/context/development/ai/mastra-ai/guides/testing.md b/.opencode/context/development/ai/mastra-ai/guides/testing.md index 75141ee..f9f87a3 100644 --- a/.opencode/context/development/ai/mastra-ai/guides/testing.md +++ b/.opencode/context/development/ai/mastra-ai/guides/testing.md @@ -1,3 +1,5 @@ + + # Guide: Testing Mastra **Purpose**: How to run and validate Mastra components in this project. diff --git a/.opencode/context/development/ai/mastra-ai/guides/workflow-step-structure.md b/.opencode/context/development/ai/mastra-ai/guides/workflow-step-structure.md index 97fb59f..00432fd 100644 --- a/.opencode/context/development/ai/mastra-ai/guides/workflow-step-structure.md +++ b/.opencode/context/development/ai/mastra-ai/guides/workflow-step-structure.md @@ -1,3 +1,5 @@ + + # Guide: Workflow Step Structure **Purpose**: Standardized pattern for defining maintainable and testable workflow steps. diff --git a/.opencode/context/development/ai/mastra-ai/lookup/mastra-config.md b/.opencode/context/development/ai/mastra-ai/lookup/mastra-config.md index ab84c6e..b8830f2 100644 --- a/.opencode/context/development/ai/mastra-ai/lookup/mastra-config.md +++ b/.opencode/context/development/ai/mastra-ai/lookup/mastra-config.md @@ -1,3 +1,5 @@ + + # Lookup: Mastra Configuration **Purpose**: Quick reference for Mastra file locations and registration. diff --git a/.opencode/context/development/ai/mastra-ai/lookup/navigation.md b/.opencode/context/development/ai/mastra-ai/lookup/navigation.md new file mode 100644 index 0000000..fe342e5 --- /dev/null +++ b/.opencode/context/development/ai/mastra-ai/lookup/navigation.md @@ -0,0 +1,39 @@ + + +# Mastra AI Lookup + +**Purpose**: Quick reference for Mastra AI configuration and APIs + +--- + +## Structure + +``` +lookup/ +โ”œโ”€โ”€ navigation.md (this file) +โ””โ”€โ”€ mastra-config.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Configuration reference** | `mastra-config.md` | +| **Core concepts** | `../concepts/core.md` | +| **Guides** | `../guides/navigation.md` | + +--- + +## By Type + +**Configuration** โ†’ Config file reference and patterns + +--- + +## Related Context + +- **Mastra AI** โ†’ `../navigation.md` +- **Concepts** โ†’ `../concepts/navigation.md` +- **Guides** โ†’ `../guides/navigation.md` diff --git a/.opencode/context/development/ai/mastra-ai/navigation.md b/.opencode/context/development/ai/mastra-ai/navigation.md index e337dfc..c991b38 100644 --- a/.opencode/context/development/ai/mastra-ai/navigation.md +++ b/.opencode/context/development/ai/mastra-ai/navigation.md @@ -1,3 +1,5 @@ + + # MAStra AI Navigation **Purpose**: AI framework for building agents, workflows, and LLM integrations. @@ -10,9 +12,15 @@ mastra-ai/ โ”œโ”€โ”€ navigation.md โ”œโ”€โ”€ concepts/ +โ”‚ โ””โ”€โ”€ navigation.md โ”œโ”€โ”€ guides/ +โ”‚ โ””โ”€โ”€ navigation.md โ”œโ”€โ”€ examples/ +โ”‚ โ””โ”€โ”€ navigation.md +โ”œโ”€โ”€ errors/ +โ”‚ โ””โ”€โ”€ navigation.md โ””โ”€โ”€ lookup/ + โ””โ”€โ”€ navigation.md ``` --- @@ -21,13 +29,19 @@ mastra-ai/ | Task | Path | |------|------| -| **Agent Definition** | `concepts/agents.md` [future] | -| **Workflow Setup** | `guides/workflows.md` [future] | +| **Core concepts** | `concepts/navigation.md` | +| **Agents & tools** | `concepts/agents-tools.md` | +| **Workflows** | `concepts/workflows.md` | +| **Build modular systems** | `guides/modular-building.md` | +| **Test Mastra apps** | `guides/testing.md` | +| **Troubleshooting** | `errors/navigation.md` | --- ## By Function -**Concepts** โ†’ Agents, Tools, Workflows, RAG -**Guides** โ†’ Installation, Integration, Deployment -**Examples** โ†’ Basic Agent, Tool Calling +**Concepts** โ†’ Core concepts, agents, tools, workflows, storage, evaluations +**Guides** โ†’ Modular building, testing, workflow structure +**Examples** โ†’ Workflow implementations +**Errors** โ†’ Common errors and troubleshooting +**Lookup** โ†’ Configuration reference diff --git a/.opencode/context/development/ai/navigation.md b/.opencode/context/development/ai/navigation.md index 104e9ec..1637d98 100644 --- a/.opencode/context/development/ai/navigation.md +++ b/.opencode/context/development/ai/navigation.md @@ -1,3 +1,5 @@ + + # AI Navigation **Purpose**: AI frameworks, agent runtimes, and LLM integration patterns. diff --git a/.opencode/context/development/backend-navigation.md b/.opencode/context/development/backend-navigation.md index 6b44e81..477c5db 100644 --- a/.opencode/context/development/backend-navigation.md +++ b/.opencode/context/development/backend-navigation.md @@ -1,3 +1,5 @@ + + # Backend Development Navigation **Scope**: Server-side, APIs, databases, auth diff --git a/.opencode/context/development/backend/navigation.md b/.opencode/context/development/backend/navigation.md index 99a1664..c31f3ae 100644 --- a/.opencode/context/development/backend/navigation.md +++ b/.opencode/context/development/backend/navigation.md @@ -1,3 +1,5 @@ + + # Backend Development Navigation **Purpose**: Server-side development patterns diff --git a/.opencode/context/development/data/navigation.md b/.opencode/context/development/data/navigation.md index 0ad1122..8108d71 100644 --- a/.opencode/context/development/data/navigation.md +++ b/.opencode/context/development/data/navigation.md @@ -1,3 +1,5 @@ + + # Data Layer Navigation **Purpose**: Database and data access patterns diff --git a/.opencode/context/development/frameworks/navigation.md b/.opencode/context/development/frameworks/navigation.md index 5d347ae..4acdadf 100644 --- a/.opencode/context/development/frameworks/navigation.md +++ b/.opencode/context/development/frameworks/navigation.md @@ -1,3 +1,5 @@ + + # Frameworks Navigation **Purpose**: Full-stack and meta-frameworks that span multiple architectural layers. diff --git a/.opencode/context/development/frameworks/tanstack-start/navigation.md b/.opencode/context/development/frameworks/tanstack-start/navigation.md index 9a855b2..f4cfbd1 100644 --- a/.opencode/context/development/frameworks/tanstack-start/navigation.md +++ b/.opencode/context/development/frameworks/tanstack-start/navigation.md @@ -1,3 +1,5 @@ + + # Tanstack Start Navigation **Purpose**: Full-stack React framework patterns and workflows. diff --git a/.opencode/context/development/frontend/navigation.md b/.opencode/context/development/frontend/navigation.md index c525649..16f379e 100644 --- a/.opencode/context/development/frontend/navigation.md +++ b/.opencode/context/development/frontend/navigation.md @@ -1,3 +1,5 @@ + + # Frontend Development Navigation **Purpose**: Client-side development patterns diff --git a/.opencode/context/development/frontend/react/navigation.md b/.opencode/context/development/frontend/react/navigation.md index 114fee7..aafff47 100644 --- a/.opencode/context/development/frontend/react/navigation.md +++ b/.opencode/context/development/frontend/react/navigation.md @@ -1,3 +1,5 @@ + + # React Development **Purpose**: Modern React patterns, hooks, and component design @@ -8,7 +10,7 @@ | File | Description | Priority | |------|-------------|----------| -| [react-patterns.md](react-patterns.md) | React hooks, components, state management | high | +| _(No files yet)_ | | | --- diff --git a/.opencode/context/development/frontend/when-to-delegate.md b/.opencode/context/development/frontend/when-to-delegate.md index 838dc98..d6afaf4 100644 --- a/.opencode/context/development/frontend/when-to-delegate.md +++ b/.opencode/context/development/frontend/when-to-delegate.md @@ -116,7 +116,7 @@ task( prompt="Context to load: - .opencode/context/ui/web/design-systems.md - .opencode/context/ui/web/ui-styling-standards.md - - .opencode/context/ui/web/animation-patterns.md + - .opencode/context/ui/web/animation-basics.md Task: Create a landing page with: - Hero section with headline, subheadline, CTA button @@ -353,7 +353,7 @@ task( prompt="Context to load: - .opencode/context/ui/web/design-systems.md - .opencode/context/ui/web/ui-styling-standards.md - - .opencode/context/ui/web/animation-patterns.md + - .opencode/context/ui/web/animation-basics.md Task: Create a SaaS landing page with: - Hero section (headline, subheadline, CTA) diff --git a/.opencode/context/development/fullstack-navigation.md b/.opencode/context/development/fullstack-navigation.md index 8a44f8a..f350fb3 100644 --- a/.opencode/context/development/fullstack-navigation.md +++ b/.opencode/context/development/fullstack-navigation.md @@ -1,3 +1,5 @@ + + # Full-Stack Development Navigation **Scope**: End-to-end application development diff --git a/.opencode/context/development/infrastructure/navigation.md b/.opencode/context/development/infrastructure/navigation.md index 51226a4..7d763ef 100644 --- a/.opencode/context/development/infrastructure/navigation.md +++ b/.opencode/context/development/infrastructure/navigation.md @@ -1,3 +1,5 @@ + + # Infrastructure Navigation **Purpose**: DevOps and deployment patterns diff --git a/.opencode/context/development/integration/navigation.md b/.opencode/context/development/integration/navigation.md index 1bda196..ccc70dc 100644 --- a/.opencode/context/development/integration/navigation.md +++ b/.opencode/context/development/integration/navigation.md @@ -1,3 +1,5 @@ + + # Integration Navigation **Purpose**: Connecting systems and services diff --git a/.opencode/context/development/navigation.md b/.opencode/context/development/navigation.md index 25cc62b..a5c74b0 100644 --- a/.opencode/context/development/navigation.md +++ b/.opencode/context/development/navigation.md @@ -1,3 +1,5 @@ + + # Development Navigation **Purpose**: Software development across all stacks diff --git a/.opencode/context/development/principles/api-design.md b/.opencode/context/development/principles/api-design.md index 94c1585..81a8b7d 100644 --- a/.opencode/context/development/principles/api-design.md +++ b/.opencode/context/development/principles/api-design.md @@ -1,3 +1,5 @@ + + # API Design Patterns **Category**: development diff --git a/.opencode/context/development/principles/clean-code.md b/.opencode/context/development/principles/clean-code.md index 7189d05..42e24b8 100644 --- a/.opencode/context/development/principles/clean-code.md +++ b/.opencode/context/development/principles/clean-code.md @@ -1,3 +1,5 @@ + + # Clean Code Principles **Category**: development diff --git a/.opencode/context/development/principles/navigation.md b/.opencode/context/development/principles/navigation.md index 0834ccf..acaa09a 100644 --- a/.opencode/context/development/principles/navigation.md +++ b/.opencode/context/development/principles/navigation.md @@ -1,3 +1,5 @@ + + # Development Principles Navigation **Purpose**: Universal development principles (language-agnostic) diff --git a/.opencode/context/development/ui-navigation.md b/.opencode/context/development/ui-navigation.md index 371eebd..1fd09a6 100644 --- a/.opencode/context/development/ui-navigation.md +++ b/.opencode/context/development/ui-navigation.md @@ -1,3 +1,5 @@ + + # UI Development Navigation **Scope**: Frontend code + visual design diff --git a/.opencode/context/learning/README.md b/.opencode/context/learning/README.md index cfc88e0..215da2b 100644 --- a/.opencode/context/learning/README.md +++ b/.opencode/context/learning/README.md @@ -1,3 +1,5 @@ + + # Learning Context This directory contains context files for education, coaching, and teaching methodologies. diff --git a/.opencode/context/learning/navigation.md b/.opencode/context/learning/navigation.md index cfc88e0..153bd78 100644 --- a/.opencode/context/learning/navigation.md +++ b/.opencode/context/learning/navigation.md @@ -1,3 +1,5 @@ + + # Learning Context This directory contains context files for education, coaching, and teaching methodologies. diff --git a/.opencode/context/navigation.md b/.opencode/context/navigation.md index 7d7a5e5..460027e 100644 --- a/.opencode/context/navigation.md +++ b/.opencode/context/navigation.md @@ -1,3 +1,5 @@ + + # Context Navigation **New here?** โ†’ `openagents-repo/quick-start.md` diff --git a/.opencode/context/openagents-repo/blueprints/context-bundle-template.md b/.opencode/context/openagents-repo/blueprints/context-bundle-template.md index 990fdb7..49e37ca 100644 --- a/.opencode/context/openagents-repo/blueprints/context-bundle-template.md +++ b/.opencode/context/openagents-repo/blueprints/context-bundle-template.md @@ -1,3 +1,5 @@ + + --- description: "Template for creating context bundles when delegating tasks to subagents" type: "context" @@ -58,7 +60,7 @@ Status: in_progress - `.opencode/context/openagents-repo/core-concepts/categories.md` โ†’ How organization works **Guides** (Load for specific workflows): -- `.opencode/context/openagents-repo/guides/adding-agent.md` โ†’ Step-by-step agent creation +- `.opencode/context/openagents-repo/guides/adding-agent-basics.md` โ†’ Step-by-step agent creation - `.opencode/context/openagents-repo/guides/testing-agent.md` โ†’ Testing workflow - `.opencode/context/openagents-repo/guides/updating-registry.md` โ†’ Registry workflow - `.opencode/context/openagents-repo/guides/debugging.md` โ†’ Troubleshooting diff --git a/.opencode/context/openagents-repo/blueprints/navigation.md b/.opencode/context/openagents-repo/blueprints/navigation.md index e0571f3..b96734b 100644 --- a/.opencode/context/openagents-repo/blueprints/navigation.md +++ b/.opencode/context/openagents-repo/blueprints/navigation.md @@ -1,3 +1,5 @@ + + # OpenAgents Blueprints **Purpose**: Blueprint templates and patterns for OpenAgents Control diff --git a/.opencode/context/openagents-repo/concepts/agent-skills.md b/.opencode/context/openagents-repo/concepts/agent-skills.md index a54bfdd..b46fbed 100644 --- a/.opencode/context/openagents-repo/concepts/agent-skills.md +++ b/.opencode/context/openagents-repo/concepts/agent-skills.md @@ -1,3 +1,5 @@ + + # Agent Skills **Purpose**: Markdown files that teach Claude how to do specific tasks diff --git a/.opencode/context/openagents-repo/concepts/compatibility-layer.md b/.opencode/context/openagents-repo/concepts/compatibility-layer.md index 45e86b2..0342d69 100644 --- a/.opencode/context/openagents-repo/concepts/compatibility-layer.md +++ b/.opencode/context/openagents-repo/concepts/compatibility-layer.md @@ -1,3 +1,5 @@ + + # Concept: Compatibility Layer Architecture **Purpose**: Enable bidirectional translation between OpenAgents Control and other AI coding tools @@ -78,7 +80,7 @@ Tool-specific config files ```typescript // Load OAC agent -const agent = await AgentLoader.loadAgent('.opencode/agent/openagent.md') +const agent = await AgentLoader.loadAgent('.opencode/agent/core/openagent.md') // Get Claude adapter const adapter = AdapterRegistry.get('claude') diff --git a/.opencode/context/openagents-repo/concepts/hooks-system.md b/.opencode/context/openagents-repo/concepts/hooks-system.md index 195cced..8234041 100644 --- a/.opencode/context/openagents-repo/concepts/hooks-system.md +++ b/.opencode/context/openagents-repo/concepts/hooks-system.md @@ -1,3 +1,5 @@ + + # Hooks System **Purpose**: User-defined shell commands that execute at Claude Code lifecycle points diff --git a/.opencode/context/openagents-repo/concepts/navigation.md b/.opencode/context/openagents-repo/concepts/navigation.md index a982da5..ac82d8c 100644 --- a/.opencode/context/openagents-repo/concepts/navigation.md +++ b/.opencode/context/openagents-repo/concepts/navigation.md @@ -1,3 +1,5 @@ + + # OpenAgents Concepts **Purpose**: Core concepts and ideas for OpenAgents Control diff --git a/.opencode/context/openagents-repo/concepts/subagent-testing-modes.md b/.opencode/context/openagents-repo/concepts/subagent-testing-modes.md index 5a4a670..243b397 100644 --- a/.opencode/context/openagents-repo/concepts/subagent-testing-modes.md +++ b/.opencode/context/openagents-repo/concepts/subagent-testing-modes.md @@ -1,3 +1,5 @@ + + # Subagent Testing Modes **Purpose**: Understand the two ways to test subagents (standalone vs delegation) diff --git a/.opencode/context/openagents-repo/concepts/subagents-system.md b/.opencode/context/openagents-repo/concepts/subagents-system.md index 38078b9..f678e51 100644 --- a/.opencode/context/openagents-repo/concepts/subagents-system.md +++ b/.opencode/context/openagents-repo/concepts/subagents-system.md @@ -1,3 +1,5 @@ + + # Subagents System **Purpose**: Specialized AI assistants with own context window for task-specific workflows diff --git a/.opencode/context/openagents-repo/core-concepts/agent-metadata.md b/.opencode/context/openagents-repo/core-concepts/agent-metadata.md index a4cd00b..77d7e54 100644 --- a/.opencode/context/openagents-repo/core-concepts/agent-metadata.md +++ b/.opencode/context/openagents-repo/core-concepts/agent-metadata.md @@ -550,7 +550,7 @@ jq 'del(.components.agents[] | select(.id == "agent-id"))' registry.json > tmp.j - **OpenCode Agent Docs**: https://opencode.ai/docs/agents/ - **Registry System**: `.opencode/context/openagents-repo/core-concepts/registry.md` -- **Adding Agents**: `.opencode/context/openagents-repo/guides/adding-agent.md` +- **Adding Agents**: `.opencode/context/openagents-repo/guides/adding-agent-basics.md` - **Dependencies**: `.opencode/context/openagents-repo/quality/registry-dependencies.md` --- diff --git a/.opencode/context/openagents-repo/core-concepts/agents.md b/.opencode/context/openagents-repo/core-concepts/agents.md index f05982e..337b993 100644 --- a/.opencode/context/openagents-repo/core-concepts/agents.md +++ b/.opencode/context/openagents-repo/core-concepts/agents.md @@ -182,10 +182,10 @@ The system supports multiple path formats for backward compatibility: "core/openagent" โ†’ resolves to โ†’ ".opencode/agent/core/openagent.md" # Full category path -"development/frontend-specialist" โ†’ resolves to โ†’ ".opencode/agent/development/frontend-specialist.md" +"development/frontend-specialist" โ†’ resolves to โ†’ ".opencode/agent/subagents/development/frontend-specialist.md" # Subagent path -"TestEngineer" โ†’ resolves to โ†’ ".opencode/agent/TestEngineer.md" +"TestEngineer" โ†’ resolves to โ†’ ".opencode/agent/subagents/code/test-engineer.md" ``` ### Resolution Rules @@ -240,7 +240,7 @@ Loads: `.opencode/context/core/standards/code-quality.md` ``` -Loads: `.opencode/context/development/react-patterns.md` +Loads: `.opencode/context/ui/web/react-patterns.md` ### Multiple Contexts diff --git a/.opencode/context/openagents-repo/core-concepts/categories.md b/.opencode/context/openagents-repo/core-concepts/categories.md index 816b226..abad50a 100644 --- a/.opencode/context/openagents-repo/core-concepts/categories.md +++ b/.opencode/context/openagents-repo/core-concepts/categories.md @@ -183,7 +183,7 @@ The system resolves agent paths flexibly: "subagents/development/frontend-specialist" โ†’ ".opencode/agent/subagents/development/frontend-specialist.md" # Subagent path -"TestEngineer" โ†’ ".opencode/agent/TestEngineer.md" +"TestEngineer" โ†’ ".opencode/agent/subagents/code/test-engineer.md" ``` --- @@ -301,7 +301,7 @@ Agents load category context based on task: ``` -Loads: `.opencode/context/development/react-patterns.md` +Loads: `.opencode/context/ui/web/react-patterns.md` --- diff --git a/.opencode/context/openagents-repo/core-concepts/evals.md b/.opencode/context/openagents-repo/core-concepts/evals.md index 3134f38..6b5142e 100644 --- a/.opencode/context/openagents-repo/core-concepts/evals.md +++ b/.opencode/context/openagents-repo/core-concepts/evals.md @@ -1,3 +1,5 @@ + + # Core Concept: Eval Framework **Purpose**: Understanding how agent testing works diff --git a/.opencode/context/openagents-repo/core-concepts/navigation.md b/.opencode/context/openagents-repo/core-concepts/navigation.md index 02fbcc7..882d2a4 100644 --- a/.opencode/context/openagents-repo/core-concepts/navigation.md +++ b/.opencode/context/openagents-repo/core-concepts/navigation.md @@ -1,3 +1,5 @@ + + # OpenAgents Core Concepts **Purpose**: Deep-dive documentation on core OpenAgents Control concepts diff --git a/.opencode/context/openagents-repo/core-concepts/registry.md b/.opencode/context/openagents-repo/core-concepts/registry.md index 1d60a2d..f2580af 100644 --- a/.opencode/context/openagents-repo/core-concepts/registry.md +++ b/.opencode/context/openagents-repo/core-concepts/registry.md @@ -1,3 +1,5 @@ + + # Core Concept: Registry System **Purpose**: Understanding how component tracking and distribution works @@ -48,7 +50,7 @@ The registry is a centralized catalog (`registry.json`) that tracks all componen "id": "frontend-specialist", "name": "Frontend Specialist", "type": "agent", - "path": ".opencode/agent/development/frontend-specialist.md", + "path": ".opencode/agent/subagents/development/frontend-specialist.md", "description": "Expert in React, Vue, and modern CSS", "category": "development", "tags": ["react", "vue", "css", "frontend"], @@ -146,7 +148,7 @@ tags: ["tag1", "tag2"] # Optional ```bash # Example errors -ERROR: Path does not exist: .opencode/agent/core/missing.md +ERROR: Path does not exist: (example: .opencode/agent/core/missing.md) ERROR: Duplicate ID: frontend-specialist ERROR: Invalid category: invalid-category ERROR: Missing dependency: subagent:nonexistent diff --git a/.opencode/context/openagents-repo/errors/navigation.md b/.opencode/context/openagents-repo/errors/navigation.md index e0c4a47..9108716 100644 --- a/.opencode/context/openagents-repo/errors/navigation.md +++ b/.opencode/context/openagents-repo/errors/navigation.md @@ -1,3 +1,5 @@ + + # OpenAgents Errors **Purpose**: Common errors and troubleshooting for OpenAgents Control diff --git a/.opencode/context/openagents-repo/errors/skills-errors.md b/.opencode/context/openagents-repo/errors/skills-errors.md index 699c017..779d946 100644 --- a/.opencode/context/openagents-repo/errors/skills-errors.md +++ b/.opencode/context/openagents-repo/errors/skills-errors.md @@ -1,3 +1,5 @@ + + # Skills Troubleshooting **Purpose**: Common skill issues and solutions diff --git a/.opencode/context/openagents-repo/errors/tool-permission-errors.md b/.opencode/context/openagents-repo/errors/tool-permission-errors.md index 54c1d7e..1dc825a 100644 --- a/.opencode/context/openagents-repo/errors/tool-permission-errors.md +++ b/.opencode/context/openagents-repo/errors/tool-permission-errors.md @@ -1,3 +1,5 @@ + + # Tool Permission Errors **Purpose**: Diagnose and fix tool permission issues in agents @@ -222,4 +224,4 @@ After fixing tool permission: - `guides/testing-subagents.md` - How to test subagents - `examples/subagent-prompt-structure.md` - Prompt structure with tool emphasis -**Reference**: `.opencode/agent/ContextScout.md` (lines 14-28, tool configuration) +**Reference**: `.opencode/agent/subagents/core/contextscout.md` (tool configuration) diff --git a/.opencode/context/openagents-repo/examples/baseadapter-implementation.md b/.opencode/context/openagents-repo/examples/baseadapter-implementation.md index 69b9395..2c5b04f 100644 --- a/.opencode/context/openagents-repo/examples/baseadapter-implementation.md +++ b/.opencode/context/openagents-repo/examples/baseadapter-implementation.md @@ -1,3 +1,5 @@ + + # Example: BaseAdapter Implementation Pattern **Purpose**: Template method pattern for AI tool adapters diff --git a/.opencode/context/openagents-repo/examples/baseadapter-pattern.md b/.opencode/context/openagents-repo/examples/baseadapter-pattern.md index 8ca34cd..dad4035 100644 --- a/.opencode/context/openagents-repo/examples/baseadapter-pattern.md +++ b/.opencode/context/openagents-repo/examples/baseadapter-pattern.md @@ -1,3 +1,5 @@ + + # Example: BaseAdapter Implementation Pattern **Purpose**: Template Method pattern for AI coding tool adapters diff --git a/.opencode/context/openagents-repo/examples/context-bundle-example.md b/.opencode/context/openagents-repo/examples/context-bundle-example.md index b9db73c..96bee71 100644 --- a/.opencode/context/openagents-repo/examples/context-bundle-example.md +++ b/.opencode/context/openagents-repo/examples/context-bundle-example.md @@ -1,3 +1,5 @@ + + # Context Bundle Example: Create Data Analyst Agent Session: 20250121-143022-a4f2 @@ -35,7 +37,7 @@ Create a new data analyst agent for the OpenAgents Control repository. This agen - `.opencode/context/openagents-repo/core-concepts/categories.md` โ†’ How organization works **Guides** (Load for specific workflows): -- `.opencode/context/openagents-repo/guides/adding-agent.md` โ†’ Step-by-step agent creation +- `.opencode/context/openagents-repo/guides/adding-agent-basics.md` โ†’ Step-by-step agent creation - `.opencode/context/openagents-repo/guides/testing-agent.md` โ†’ Testing workflow - `.opencode/context/openagents-repo/guides/updating-registry.md` โ†’ Registry workflow @@ -165,7 +167,7 @@ Create a complete data analyst agent for the OpenAgents Control repository follo **Approach**: 1. **Load Context**: Read all context files listed above to understand: - How agents are structured (core-concepts/agents.md) - - How to add an agent (guides/adding-agent.md) + - How to add an agent (guides/adding-agent-basics.md) - Code standards (standards/code-quality.md) - Testing requirements (core-concepts/evals.md) diff --git a/.opencode/context/openagents-repo/examples/hooks/formatting-hook.md b/.opencode/context/openagents-repo/examples/hooks/formatting-hook.md index 2f0cbb4..3253c5e 100644 --- a/.opencode/context/openagents-repo/examples/hooks/formatting-hook.md +++ b/.opencode/context/openagents-repo/examples/hooks/formatting-hook.md @@ -1,3 +1,5 @@ + + # Code Formatting Hook **Purpose**: Auto-format files after Claude edits them diff --git a/.opencode/context/openagents-repo/examples/hooks/markdown-formatter.md b/.opencode/context/openagents-repo/examples/hooks/markdown-formatter.md index 3178e7e..5fb3def 100644 --- a/.opencode/context/openagents-repo/examples/hooks/markdown-formatter.md +++ b/.opencode/context/openagents-repo/examples/hooks/markdown-formatter.md @@ -1,3 +1,5 @@ + + # Markdown Formatter Hook **Purpose**: Auto-fix markdown formatting issues after file edits diff --git a/.opencode/context/openagents-repo/examples/hooks/navigation.md b/.opencode/context/openagents-repo/examples/hooks/navigation.md new file mode 100644 index 0000000..909d84a --- /dev/null +++ b/.opencode/context/openagents-repo/examples/hooks/navigation.md @@ -0,0 +1,43 @@ + + +# Hook Examples + +**Purpose**: Example hook implementations for OpenAgents Control + +--- + +## Structure + +``` +hooks/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ formatting-hook.md +โ”œโ”€โ”€ markdown-formatter.md +โ””โ”€โ”€ protection-hook.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Formatting hook** | `formatting-hook.md` | +| **Markdown formatter** | `markdown-formatter.md` | +| **Protection hook** | `protection-hook.md` | +| **Hook concepts** | `../../concepts/hooks.md` | + +--- + +## By Type + +**Formatting** โ†’ Output formatting hooks +**Protection** โ†’ Safety and validation hooks + +--- + +## Related Context + +- **Examples** โ†’ `../navigation.md` +- **Concepts** โ†’ `../../concepts/navigation.md` +- **Guides** โ†’ `../../guides/navigation.md` diff --git a/.opencode/context/openagents-repo/examples/hooks/protection-hook.md b/.opencode/context/openagents-repo/examples/hooks/protection-hook.md index d5a1d4c..8e30687 100644 --- a/.opencode/context/openagents-repo/examples/hooks/protection-hook.md +++ b/.opencode/context/openagents-repo/examples/hooks/protection-hook.md @@ -1,3 +1,5 @@ + + # File Protection Hook **Purpose**: Block edits to sensitive files diff --git a/.opencode/context/openagents-repo/examples/navigation.md b/.opencode/context/openagents-repo/examples/navigation.md index af1741e..9f09b92 100644 --- a/.opencode/context/openagents-repo/examples/navigation.md +++ b/.opencode/context/openagents-repo/examples/navigation.md @@ -1,3 +1,5 @@ + + # OpenAgents Examples **Purpose**: Example implementations and use cases for OpenAgents Control @@ -9,7 +11,12 @@ ``` openagents-repo/examples/ โ”œโ”€โ”€ navigation.md (this file) -โ””โ”€โ”€ [example files] +โ”œโ”€โ”€ hooks/ +โ”‚ โ””โ”€โ”€ navigation.md +โ”œโ”€โ”€ skills/ +โ”‚ โ””โ”€โ”€ navigation.md +โ””โ”€โ”€ subagents/ + โ””โ”€โ”€ navigation.md ``` --- @@ -18,7 +25,9 @@ openagents-repo/examples/ | Task | Path | |------|------| -| **View examples** | `./` | +| **Hook examples** | `hooks/navigation.md` | +| **Skill examples** | `skills/navigation.md` | +| **Subagent examples** | `subagents/navigation.md` | | **Guides** | `../guides/navigation.md` | | **Blueprints** | `../blueprints/navigation.md` | @@ -26,8 +35,9 @@ openagents-repo/examples/ ## By Type -**Examples** โ†’ Working examples of OpenAgents implementations -**Use Cases** โ†’ Real-world use cases and patterns +**Hooks** โ†’ Hook implementation examples +**Skills** โ†’ Skill implementation examples +**Subagents** โ†’ Subagent implementation examples --- diff --git a/.opencode/context/openagents-repo/examples/skills/multi-file-skill.md b/.opencode/context/openagents-repo/examples/skills/multi-file-skill.md index adbce42..2064546 100644 --- a/.opencode/context/openagents-repo/examples/skills/multi-file-skill.md +++ b/.opencode/context/openagents-repo/examples/skills/multi-file-skill.md @@ -1,3 +1,5 @@ + + # Multi-File Skill Structure **Purpose**: Example of a skill with supporting files and scripts @@ -38,8 +40,8 @@ with pdfplumber.open("doc.pdf") as pdf: text = pdf.pages[0].extract_text() ``` -For form filling, see [FORMS.md](FORMS.md). -For detailed API reference, see [REFERENCE.md](REFERENCE.md). +For form filling, see FORMS.md (example file). +For detailed API reference, see REFERENCE.md (example file). ## Requirements diff --git a/.opencode/context/openagents-repo/examples/skills/navigation.md b/.opencode/context/openagents-repo/examples/skills/navigation.md new file mode 100644 index 0000000..d977ef2 --- /dev/null +++ b/.opencode/context/openagents-repo/examples/skills/navigation.md @@ -0,0 +1,39 @@ + + +# Skill Examples + +**Purpose**: Example skill implementations for OpenAgents Control + +--- + +## Structure + +``` +skills/ +โ”œโ”€โ”€ navigation.md (this file) +โ””โ”€โ”€ multi-file-skill.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Multi-file skill** | `multi-file-skill.md` | +| **Skill concepts** | `../../concepts/skills.md` | +| **Skill guides** | `../../guides/navigation.md` | + +--- + +## By Type + +**Skills** โ†’ Working skill implementations + +--- + +## Related Context + +- **Examples** โ†’ `../navigation.md` +- **Concepts** โ†’ `../../concepts/navigation.md` +- **Guides** โ†’ `../../guides/navigation.md` diff --git a/.opencode/context/openagents-repo/examples/subagent-prompt-structure.md b/.opencode/context/openagents-repo/examples/subagent-prompt-structure.md index 44c33b6..7ea2518 100644 --- a/.opencode/context/openagents-repo/examples/subagent-prompt-structure.md +++ b/.opencode/context/openagents-repo/examples/subagent-prompt-structure.md @@ -1,3 +1,5 @@ + + # Subagent Prompt Structure (Optimized) **Purpose**: Template for well-structured subagent prompts with tool usage emphasis @@ -268,8 +270,8 @@ Before deploying optimized prompt: - **Result**: Test passed (was failing with 0 tool calls) **Files**: -- Optimized: `.opencode/agent/ContextScout.md` -- Backup: `.opencode/agent/ContextScout-original-backup.md` +- Optimized: `.opencode/agent/subagents/core/contextscout.md` +- Backup: (example: `.opencode/agent/ContextScout-original-backup.md`) --- diff --git a/.opencode/context/openagents-repo/examples/subagents/code-reviewer.md b/.opencode/context/openagents-repo/examples/subagents/code-reviewer.md index 645d49a..f296e49 100644 --- a/.opencode/context/openagents-repo/examples/subagents/code-reviewer.md +++ b/.opencode/context/openagents-repo/examples/subagents/code-reviewer.md @@ -1,3 +1,5 @@ + + # Code Reviewer Subagent **Purpose**: Read-only subagent example for code review diff --git a/.opencode/context/openagents-repo/examples/subagents/db-validator.md b/.opencode/context/openagents-repo/examples/subagents/db-validator.md index a6f5125..bdfd70a 100644 --- a/.opencode/context/openagents-repo/examples/subagents/db-validator.md +++ b/.opencode/context/openagents-repo/examples/subagents/db-validator.md @@ -1,3 +1,5 @@ + + # DB Query Validator Subagent **Purpose**: Subagent with conditional tool validation via hooks diff --git a/.opencode/context/openagents-repo/examples/subagents/debugger.md b/.opencode/context/openagents-repo/examples/subagents/debugger.md index 0b19da6..089ce53 100644 --- a/.opencode/context/openagents-repo/examples/subagents/debugger.md +++ b/.opencode/context/openagents-repo/examples/subagents/debugger.md @@ -1,3 +1,5 @@ + + # Debugger Subagent **Purpose**: Full-access subagent for debugging and fixing issues diff --git a/.opencode/context/openagents-repo/examples/subagents/navigation.md b/.opencode/context/openagents-repo/examples/subagents/navigation.md new file mode 100644 index 0000000..1ce2b18 --- /dev/null +++ b/.opencode/context/openagents-repo/examples/subagents/navigation.md @@ -0,0 +1,44 @@ + + +# Subagent Examples + +**Purpose**: Example subagent implementations for OpenAgents Control + +--- + +## Structure + +``` +subagents/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ code-reviewer.md +โ”œโ”€โ”€ db-validator.md +โ””โ”€โ”€ debugger.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Code reviewer** | `code-reviewer.md` | +| **DB validator** | `db-validator.md` | +| **Debugger** | `debugger.md` | +| **Subagent concepts** | `../../concepts/subagents.md` | + +--- + +## By Type + +**Code Quality** โ†’ Code review and validation +**Debugging** โ†’ Debugging and troubleshooting +**Data** โ†’ Database validation + +--- + +## Related Context + +- **Examples** โ†’ `../navigation.md` +- **Concepts** โ†’ `../../concepts/navigation.md` +- **Guides** โ†’ `../../guides/navigation.md` diff --git a/.opencode/context/openagents-repo/examples/zod-schema-migration.md b/.opencode/context/openagents-repo/examples/zod-schema-migration.md index 41bf8e7..3e36cc4 100644 --- a/.opencode/context/openagents-repo/examples/zod-schema-migration.md +++ b/.opencode/context/openagents-repo/examples/zod-schema-migration.md @@ -1,3 +1,5 @@ + + # Example: Zod Schema Migration Pattern **Purpose**: Migrate TypeScript definitions to runtime-validated Zod schemas diff --git a/.opencode/context/openagents-repo/features/navigation.md b/.opencode/context/openagents-repo/features/navigation.md new file mode 100644 index 0000000..0de8772 --- /dev/null +++ b/.opencode/context/openagents-repo/features/navigation.md @@ -0,0 +1,41 @@ + + +# OpenAgents Features + +**Purpose**: Feature documentation and refactoring guides + +--- + +## Structure + +``` +features/ +โ”œโ”€โ”€ navigation.md (this file) +โ”œโ”€โ”€ oac-package-refactor.md +โ”œโ”€โ”€ oac-refactor-feedback.md +โ””โ”€โ”€ oac-refactor-quickstart.md +``` + +--- + +## Quick Routes + +| Task | Path | +|------|------| +| **Package refactor** | `oac-package-refactor.md` | +| **Refactor feedback** | `oac-refactor-feedback.md` | +| **Refactor quickstart** | `oac-refactor-quickstart.md` | + +--- + +## By Type + +**Refactoring** โ†’ Package restructuring and improvements + +--- + +## Related Context + +- **OpenAgents** โ†’ `../navigation.md` +- **Concepts** โ†’ `../concepts/navigation.md` +- **Guides** โ†’ `../guides/navigation.md` diff --git a/.opencode/context/openagents-repo/features/oac-package-refactor.md b/.opencode/context/openagents-repo/features/oac-package-refactor.md new file mode 100644 index 0000000..d99adf3 --- /dev/null +++ b/.opencode/context/openagents-repo/features/oac-package-refactor.md @@ -0,0 +1,2340 @@ + + +# Feature: OAC Package Refactor + +**Purpose**: Transform OpenAgents Control into a flexible npm package with CLI tooling for multi-IDE support and community contributions + +**Status**: In Development +**Branch**: `feature/oac-package-refactor` +**Priority**: CRITICAL +**Version Target**: 1.0.0 + +--- + +## Vision + +Transform `@nextsystems/oac` from a simple installer into a comprehensive CLI package manager that: +- โœ… Manages agents, skills, and contexts across multiple IDEs (OpenCode, Cursor, Claude Code, Windsurf) +- โœ… Provides flexible configuration for agent behavior and permissions +- โœ… Supports community contributions via shadcn-like component registry +- โœ… Handles context files from multiple locations +- โœ… Enables version management and updates +- โœ… Maintains backward compatibility with existing workflows +- โœ… **CRITICAL**: User runs in project root, chooses local or global install, always confirms overwrites (unless YOLO mode) + +--- + +## Core Features + +### 1. Multi-IDE Support + +**Goal**: One configuration, multiple IDEs + +```bash +# Configure once +oac configure + +# Install for any IDE +oac install opencode +oac install cursor +oac install claude + +# Apply updates to all +oac update --all +``` + +**Implementation**: +- Use compatibility layer adapters for IDE-specific translation +- Maintain single source of truth in OAC format +- Auto-detect IDE configurations +- Handle IDE-specific limitations gracefully + +--- + +### 2. Flexible Configuration System + +**Goal**: User-controlled agent behavior and permissions + +**Configuration File**: `~/.config/oac/config.json` (global) or `.oac/config.json` (local/project) + +**CRITICAL BEHAVIOR**: +- User runs `oac` commands in their project root directory +- Always asks: "Install locally (this project) or globally?" +- Always confirms before overwriting files (unless `--yolo` flag) +- YOLO mode (`--yolo`): Auto-confirms all, reports changes at end +- Default mode: Interactive approval for every file conflict + +```json +{ + "version": "1.0.0", + "preferences": { + "defaultIDE": "opencode", + "installLocation": "local", + "autoUpdate": false, + "updateChannel": "stable", + "confirmOverwrites": true, + "yoloMode": false + }, + "ides": { + "opencode": { + "enabled": true, + "path": ".opencode", + "profile": "developer" + }, + "cursor": { + "enabled": false, + "path": ".cursor", + "profile": "developer" + } + }, + "agents": { + "behavior": { + "approvalGates": true, + "contextLoading": "lazy", + "delegationThreshold": 4 + }, + "permissions": { + "bash": "approve", + "write": "approve", + "edit": "approve", + "task": "approve" + } + }, + "context": { + "locations": [ + ".opencode/context", + ".claude/context", + "docs/context" + ], + "autoDiscover": true, + "cacheEnabled": true + } +} +``` + +**Commands**: +```bash +oac configure # Interactive wizard +oac configure set agents.permissions.bash auto +oac configure get ides.opencode.enabled +oac configure show +oac configure reset +``` + +--- + +### 3. User Approval & YOLO Mode (CRITICAL) + +**Goal**: User maintains full control over their project, with optional fast mode + +**Default Behavior: Interactive Approval** + +Every operation that modifies files asks for confirmation: + +```bash +# User runs in project root +cd ~/my-project +oac install opencode + +# OAC asks: +? Install location: + > Local (this project: ~/my-project/.opencode) + Global (~/.config/oac) + +# User selects "Local" + +# OAC shows what will be installed: +๐Ÿ“ฆ Installing OpenCode Developer Profile + + Will create/modify: + โœ“ .opencode/agent/core/openagent.md + โœ“ .opencode/agent/core/opencoder.md + โš  .opencode/agent/subagents/code/test-engineer.md (exists - will overwrite) + โœ“ .opencode/context/core/standards/code-quality.md + โœ“ .opencode/config.json + + Total: 15 files (2 new, 12 updated, 1 conflict) + +? Proceed with installation? (Y/n) + +# If conflicts exist: +โš  File exists: .opencode/agent/subagents/code/test-engineer.md + + Current: 245 lines, modified 2 days ago + New: 312 lines, version 0.8.0 + +? What would you like to do? + > Skip (keep existing) + Overwrite (replace with new) + Backup (save as .bak, install new) + Diff (show changes) + Skip all conflicts + Overwrite all conflicts +``` + +**YOLO Mode: Fast & Furious** + +Skip all confirmations, auto-resolve conflicts, report at end: + +```bash +# Enable YOLO mode +oac install opencode --yolo + +# Or set in config +oac configure set preferences.yoloMode true + +# YOLO mode behavior: +๐Ÿ“ฆ Installing OpenCode Developer Profile (YOLO MODE) + + โšก Auto-confirming all operations... + โœ“ Created .opencode/agent/core/openagent.md + โœ“ Created .opencode/agent/core/opencoder.md + โš  Overwrote .opencode/agent/subagents/code/test-engineer.md (backed up to .bak) + โœ“ Created .opencode/context/core/standards/code-quality.md + โœ“ Created .opencode/config.json + + โœ… Installation complete! + + ๐Ÿ“Š Summary: + - 13 files created + - 2 files overwritten (backups in .opencode/.backups/) + - 0 files skipped + - Total time: 1.2s + + โš  Review changes: git diff +``` + +**Conflict Resolution Strategies** + +```typescript +enum ConflictStrategy { + ASK = 'ask', // Ask user for each conflict (default) + SKIP = 'skip', // Skip all conflicts, keep existing + OVERWRITE = 'overwrite', // Overwrite all conflicts + BACKUP = 'backup', // Backup existing, install new + YOLO = 'yolo' // Auto-resolve (backup + overwrite) +} +``` + +**Configuration** + +```json +{ + "preferences": { + "confirmOverwrites": true, + "yoloMode": false, + "conflictStrategy": "ask", + "autoBackup": true, + "backupLocation": ".opencode/.backups" + } +} +``` + +**Commands with Approval Control** + +```bash +# Interactive (default) +oac install opencode +oac update +oac add agent:rust-specialist + +# YOLO mode (skip confirmations) +oac install opencode --yolo +oac update --yolo +oac add agent:rust-specialist --yolo + +# Force overwrite (no backups) +oac install opencode --force + +# Skip conflicts (keep existing) +oac install opencode --skip-existing + +# Dry run (show what would happen) +oac install opencode --dry-run +``` + +**Safety Features** + +- โœ… Always create backups before overwriting (unless `--force`) +- โœ… Show diff before overwriting +- โœ… Maintain backup history in `.opencode/.backups/` +- โœ… Git integration: detect uncommitted changes, warn user +- โœ… Rollback support: `oac rollback` to undo last operation +- โœ… Audit log: `.oac/audit.log` tracks all operations + +**Example: Full Interactive Flow** + +```bash +cd ~/my-awesome-project +oac install opencode + +# Step 1: Location +? Install location: + > Local (this project: ~/my-awesome-project/.opencode) + Global (~/.config/oac) + +# Step 2: Profile +? Select profile: + > developer (Full development setup) + essential (Minimal setup) + business (Content and product focus) + custom (Choose components) + +# Step 3: Review +๐Ÿ“ฆ Installing OpenCode Developer Profile + + Will install to: ~/my-awesome-project/.opencode + + Components: + - 2 core agents (openagent, opencoder) + - 8 subagents (tester, reviewer, coder-agent, ...) + - 7 commands (commit, test, context, ...) + - 15 context files + + Total size: ~2.5 MB + +? Proceed? (Y/n) y + +# Step 4: Conflict Resolution (if any) +โš  3 files already exist: + + 1. .opencode/agent/subagents/code/test-engineer.md + Current: 245 lines, modified 2 days ago + New: 312 lines, version 0.8.0 + +? Action: + > Backup and overwrite + Skip (keep existing) + Show diff + +# Step 5: Installation +โšก Installing... + โœ“ Created .opencode/agent/core/openagent.md + โœ“ Created .opencode/agent/core/opencoder.md + โš  Backed up .opencode/agent/subagents/code/test-engineer.md โ†’ .backups/TestEngineer.md.2026-02-14 + โœ“ Overwrote .opencode/agent/subagents/code/test-engineer.md + ... + +# Step 6: Summary +โœ… Installation complete! + +๐Ÿ“Š Summary: +- 13 files created +- 2 files updated +- 3 files backed up +- 0 files skipped + +๐Ÿ“ Installed to: ~/my-awesome-project/.opencode + +๐Ÿ” Next steps: + 1. Review changes: git diff + 2. Test setup: oac doctor + 3. Configure: oac configure + +๐Ÿ’ก Tip: Use 'oac --yolo' to skip confirmations next time +``` + +--- + +### 4. Community Component Registry (shadcn-like) + +**Goal**: Enable users to create and share custom agents, skills, and contexts + +**Registry Structure**: +```json +{ + "version": "1.0.0", + "official": { + "agents": [...], + "skills": [...], + "contexts": [...] + }, + "community": { + "agents": [ + { + "id": "rust-specialist", + "name": "Rust Specialist", + "author": "community-user", + "source": "https://github.com/user/oac-rust-specialist", + "version": "1.0.0", + "downloads": 1234, + "verified": false + } + ] + } +} +``` + +**Commands**: +```bash +# Add component from registry +oac add agent:rust-specialist + +# Add from GitHub URL +oac add https://github.com/user/oac-rust-specialist + +# Add from local path +oac add ./my-custom-agent + +# List available community components +oac browse agents +oac browse skills + +# Publish your component +oac publish ./my-agent --type agent + +# Search registry +oac search "rust" +``` + +**Component Package Format**: +``` +my-custom-agent/ +โ”œโ”€โ”€ oac.json # Component metadata +โ”œโ”€โ”€ agent.md # Agent prompt +โ”œโ”€โ”€ tests/ # Optional tests +โ”‚ โ””โ”€โ”€ smoke-test.yaml +โ”œโ”€โ”€ context/ # Optional context files +โ”‚ โ””โ”€โ”€ rust-patterns.md +โ””โ”€โ”€ README.md # Documentation +``` + +**oac.json Schema**: +```json +{ + "name": "rust-specialist", + "version": "1.0.0", + "type": "agent", + "description": "Expert in Rust programming", + "author": "username", + "license": "MIT", + "repository": "https://github.com/user/oac-rust-specialist", + "keywords": ["rust", "systems", "programming"], + "dependencies": { + "agents": [], + "skills": [], + "contexts": ["core/standards/code-quality"] + }, + "files": { + "agent": "agent.md", + "tests": "tests/", + "context": "context/" + } +} +``` + +--- + +### 4. Context Resolution System (CRITICAL) + +**Goal**: Intelligent context resolution for agents running locally or globally + +**The Problem**: +- Agents can run from **global install** (`~/.config/oac/`) or **local install** (`./opencode/`) +- Context files exist in **project-specific** locations AND **global** locations +- Need to resolve: "Which context file should the agent use?" +- User preferences (global) vs project requirements (local) + +**The Solution: Layered Context Resolution** + +#### Context Layers (Priority Order) + +``` +1. PROJECT OVERRIDE (./.oac/context/) [Highest Priority] + โ†“ User's project-specific overrides + +2. PROJECT CONTEXT (./.opencode/context/) + โ†“ Project-specific context files + +3. IDE CONTEXT (./.cursor/context/, ./.claude/context/) + โ†“ IDE-specific context (if different IDE) + +4. PROJECT DOCS (./docs/, ./docs/context/) + โ†“ Project documentation + +5. USER GLOBAL (~/.config/oac/context/) + โ†“ User's personal preferences/standards + +6. OAC GLOBAL (~/.config/oac/official/) [Lowest Priority] + โ†“ Official OAC context files +``` + +#### Resolution Algorithm + +```typescript +class ContextResolver { + async resolve(ref: string, options: ResolveOptions): Promise { + const { + agentLocation, // 'global' | 'local' + projectRoot, // Current working directory + preferLocal // User preference + } = options; + + // Build search paths based on agent location and preferences + const searchPaths = this.buildSearchPaths(agentLocation, projectRoot, preferLocal); + + // Search in priority order + for (const basePath of searchPaths) { + const fullPath = path.join(basePath, ref); + if (await fs.pathExists(fullPath)) { + return fullPath; + } + } + + return null; // Not found + } + + private buildSearchPaths( + agentLocation: 'global' | 'local', + projectRoot: string, + preferLocal: boolean + ): string[] { + const paths: string[] = []; + + // If agent is running locally OR user prefers local context + if (agentLocation === 'local' || preferLocal) { + // Prioritize project context + paths.push( + path.join(projectRoot, '.oac/context'), // Project override + path.join(projectRoot, '.opencode/context'), // Project context + path.join(projectRoot, '.cursor/context'), // IDE context + path.join(projectRoot, '.claude/context'), + path.join(projectRoot, 'docs/context'), // Project docs + path.join(projectRoot, 'docs') + ); + } + + // Always include global context (fallback) + paths.push( + path.join(os.homedir(), '.config/oac/context'), // User global + path.join(os.homedir(), '.config/oac/official') // OAC official + ); + + // If agent is running globally AND user prefers global + if (agentLocation === 'global' && !preferLocal) { + // Reverse priority: global first, then project + return [ + path.join(os.homedir(), '.config/oac/context'), + path.join(os.homedir(), '.config/oac/official'), + ...paths.slice(0, -2) // Add project paths after global + ]; + } + + return paths; + } +} +``` + +#### Configuration + +```json +{ + "context": { + "resolution": { + "preferLocal": true, // Prefer project context over global + "allowOverrides": true, // Allow .oac/context/ overrides + "fallbackToGlobal": true, // Fall back to global if not found locally + "cacheResolution": true // Cache resolved paths + }, + "locations": { + "project": [ + ".oac/context", // Project overrides (highest priority) + ".opencode/context", // Project context + ".cursor/context", // IDE-specific + ".claude/context", + "docs/context", // Project docs + "docs" + ], + "global": [ + "~/.config/oac/context", // User global context + "~/.config/oac/official" // OAC official context + ] + }, + "autoDiscover": true, + "validation": { + "warnOnMissing": true, + "errorOnMissing": false, + "suggestAlternatives": true + } + } +} +``` + +#### Example Scenarios + +**Scenario 1: Agent runs locally, context exists in project** + +```bash +# User is in project directory +cd ~/my-project + +# Agent runs locally +oac install opencode --local + +# Agent needs: 'core/standards/code-quality.md' +# Resolution: +# 1. Check: ~/my-project/.oac/context/core/standards/code-quality.md โŒ +# 2. Check: ~/my-project/.opencode/context/core/standards/code-quality.md โœ… +# โ†’ Uses project-specific context +``` + +**Scenario 2: Agent runs globally, no project context** + +```bash +# User is in project directory +cd ~/my-project + +# Agent runs from global install +oac install opencode --global + +# Agent needs: 'core/standards/code-quality.md' +# Resolution: +# 1. Check: ~/.config/oac/context/core/standards/code-quality.md โœ… +# โ†’ Uses global context +``` + +**Scenario 3: Project override** + +```bash +# User wants custom code quality standards for this project +mkdir -p ~/my-project/.oac/context/core/standards +cp ~/.config/oac/official/core/standards/code-quality.md \ + ~/my-project/.oac/context/core/standards/code-quality.md + +# Edit project-specific version +vim ~/my-project/.oac/context/core/standards/code-quality.md + +# Agent needs: 'core/standards/code-quality.md' +# Resolution: +# 1. Check: ~/my-project/.oac/context/core/standards/code-quality.md โœ… +# โ†’ Uses project override (highest priority) +``` + +**Scenario 4: Mixed context (project + global)** + +```bash +# Project has some context +~/my-project/.opencode/context/ + โ””โ”€โ”€ project/ + โ””โ”€โ”€ architecture.md + +# Global has standard context +~/.config/oac/official/ + โ””โ”€โ”€ core/ + โ””โ”€โ”€ standards/ + โ””โ”€โ”€ code-quality.md + +# Agent needs both: +# - 'project/architecture.md' โ†’ Found in project โœ… +# - 'core/standards/code-quality.md' โ†’ Falls back to global โœ… +``` + +#### Context Merging (Advanced) + +For certain context types, we can **merge** instead of override: + +```typescript +interface ContextMergeStrategy { + type: 'override' | 'merge' | 'append'; + mergeKey?: string; // For merge strategy +} + +// Example: Merge project and global standards +const merged = await contextResolver.resolveWithMerge( + 'core/standards/code-quality.md', + { + strategy: 'merge', + mergeKey: 'standards', // Merge 'standards' sections + preferLocal: true // Local takes precedence on conflicts + } +); + +// Result: +// - Global standards: base rules +// - Project standards: additional/override rules +// - Final: combined ruleset +``` + +#### CLI Commands for Context Management + +```bash +# Show context resolution for a reference +oac context resolve 'core/standards/code-quality.md' + โ†’ Resolved to: ~/my-project/.opencode/context/core/standards/code-quality.md + โ†’ Source: project + โ†’ Fallbacks checked: 2 + +# List all available context files +oac context list + --local # Project context only + --global # Global context only + --all # All (default) + --tree # Show as tree + +# Validate context references +oac context validate + โ†’ Checking 45 context references... + โœ“ 42 resolved + โš  3 missing (using fallbacks) + +# Create project override +oac context override 'core/standards/code-quality.md' + โ†’ Copied from: ~/.config/oac/official/core/standards/code-quality.md + โ†’ To: ~/my-project/.oac/context/core/standards/code-quality.md + โ†’ Edit this file to customize for your project + +# Show context sources +oac context sources + Project Context: + .oac/context/ (2 files) + .opencode/context/ (15 files) + docs/ (8 files) + + Global Context: + ~/.config/oac/context/ (5 files) + ~/.config/oac/official/ (42 files) + + Total: 72 context files + +# Sync global context to project +oac context sync --to-project + โ†’ Copying global context to project... + โœ“ Copied 42 files to .opencode/context/ + +# Sync project context to global +oac context sync --to-global + โ†’ Copying project context to global... + โš  This will affect all projects using global context + ? Proceed? (y/N) +``` + +#### Agent Context Loading + +Agents need to know where they're running from: + +```typescript +// In agent prompt or configuration +class AgentContext { + location: 'global' | 'local'; + projectRoot: string | null; + contextResolver: ContextResolver; + + async loadContext(ref: string): Promise { + const resolved = await this.contextResolver.resolve(ref, { + agentLocation: this.location, + projectRoot: this.projectRoot || process.cwd(), + preferLocal: true + }); + + if (!resolved) { + throw new Error(`Context not found: ${ref}`); + } + + return fs.readFile(resolved, 'utf-8'); + } +} +``` + +#### Environment Variables + +```bash +# Override context resolution behavior +OAC_CONTEXT_PREFER_LOCAL=true # Prefer project context +OAC_CONTEXT_PREFER_GLOBAL=true # Prefer global context +OAC_CONTEXT_PROJECT_ROOT=/path/to/project +OAC_CONTEXT_GLOBAL_ROOT=~/.config/oac +OAC_CONTEXT_CACHE_ENABLED=true +OAC_CONTEXT_VALIDATION=strict # strict | warn | off +``` + +#### Visual Representation + +``` +Agent Running Locally (in ~/my-project): +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Agent: openagent (local) โ”‚ +โ”‚ Working Dir: ~/my-project โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + Needs: 'core/standards/code-quality.md' + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Context Resolver โ”‚ +โ”‚ Mode: preferLocal = true โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + Search Priority: + 1. ~/my-project/.oac/context/... โŒ + 2. ~/my-project/.opencode/context/... โœ… FOUND + 3. (skip remaining) + โ†“ + Returns: ~/my-project/.opencode/context/core/standards/code-quality.md + + +Agent Running Globally: +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Agent: openagent (global) โ”‚ +โ”‚ Working Dir: ~/my-project โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + Needs: 'core/standards/code-quality.md' + โ†“ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Context Resolver โ”‚ +โ”‚ Mode: preferLocal = true (default) โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + Search Priority: + 1. ~/my-project/.oac/context/... โŒ + 2. ~/my-project/.opencode/context/... โŒ + 3. ~/.config/oac/context/... โŒ + 4. ~/.config/oac/official/... โœ… FOUND + โ†“ + Returns: ~/.config/oac/official/core/standards/code-quality.md +``` + +#### Best Practices + +**For Users**: +- โœ… Use global context for personal coding standards +- โœ… Use project context for project-specific requirements +- โœ… Use `.oac/context/` for temporary overrides +- โœ… Keep project context in version control +- โœ… Keep global context private (personal preferences) + +**For Projects**: +- โœ… Include essential context in `.opencode/context/` +- โœ… Document required context files in README +- โœ… Use `oac context validate` in CI/CD +- โœ… Provide `.oac/context/` examples for common overrides + +**For OAC**: +- โœ… Ship official context in `~/.config/oac/official/` +- โœ… Never modify user's global context without permission +- โœ… Warn when context is missing +- โœ… Suggest alternatives when context not found + +--- + +### 5. Version Management & Updates + +**Goal**: Keep agents and components up-to-date across all IDEs + +```bash +# Check for updates +oac update --check + +# Update all components +oac update + +# Update and apply to specific IDE +oac update --claude --global +oac update --opencode --local + +# Update specific component +oac update agent:openagent + +# Update from specific version +oac update --version 0.8.0 + +# Rollback to previous version +oac rollback agent:openagent +``` + +**Update Flow**: +1. Fetch latest registry from GitHub +2. Compare with local cache +3. Show available updates +4. Download updated components +5. Apply to configured IDEs +6. Validate installation + +--- + +### 5. Agent Customization & Personal Presets (CRITICAL) + +**Goal**: Allow users to view, customize, and save personal agent configurations + +**The Problem**: +- Users want to customize agent prompts for their workflow +- Users want to save personal presets +- Updates shouldn't overwrite customizations +- Need easy way to view and edit agent configs + +**The Solution: Multi-Layer Customization System** + +#### Layer 1: View Agent Configuration + +```bash +# View agent prompt and config +oac show agent:openagent + โ†’ Opens agent file in pager (less/bat) + โ†’ Shows: prompt, config, metadata + +# View in editor +oac edit agent:openagent + โ†’ Opens in $EDITOR (vim/vscode/etc.) + โ†’ Read-only by default (shows warning) + +# View config only +oac config show agent:openagent + โ†’ Shows just the configuration (YAML frontmatter) + +# Export agent +oac export agent:openagent --output ./my-openagent.md + โ†’ Exports to file for inspection +``` + +#### Layer 2: Create Personal Preset + +```bash +# Create personal preset (copy to user space) +oac customize agent:openagent + +? What would you like to customize? + > Create personal preset (recommended) + Edit in place (advanced) + Fork to new agent + +? Preset name: my-openagent +? Description: My customized OpenAgent with stricter approval gates + +โœ“ Created preset: ~/.config/oac/presets/agents/my-openagent.md +โœ“ Linked to: agent:openagent (base) + +๐Ÿ“ Edit your preset: + oac edit preset:my-openagent + +๐Ÿ’ก Use your preset: + oac use preset:my-openagent +``` + +**Preset Structure**: +``` +~/.config/oac/ +โ”œโ”€โ”€ presets/ +โ”‚ โ”œโ”€โ”€ agents/ +โ”‚ โ”‚ โ”œโ”€โ”€ my-openagent.md # User's custom version +โ”‚ โ”‚ โ”œโ”€โ”€ my-opencoder.md +โ”‚ โ”‚ โ””โ”€โ”€ strict-reviewer.md +โ”‚ โ”œโ”€โ”€ skills/ +โ”‚ โ”‚ โ””โ”€โ”€ my-git-workflow.md +โ”‚ โ””โ”€โ”€ .presets.json # Preset metadata +``` + +**Preset Metadata** (`.presets.json`): +```json +{ + "presets": { + "my-openagent": { + "type": "agent", + "base": "agent:openagent", + "baseVersion": "0.7.1", + "created": "2026-02-14T10:30:00Z", + "modified": "2026-02-14T15:45:00Z", + "customizations": [ + "Modified approval gates", + "Added custom context paths", + "Changed delegation threshold" + ], + "autoUpdate": false, + "updateStrategy": "manual" + } + } +} +``` + +#### Layer 3: Edit Personal Preset + +```bash +# Edit preset in default editor +oac edit preset:my-openagent + โ†’ Opens ~/.config/oac/presets/agents/my-openagent.md in $EDITOR + +# Edit with specific editor +oac edit preset:my-openagent --editor code + โ†’ Opens in VS Code + +# Interactive customization wizard +oac customize preset:my-openagent --interactive + +? What would you like to customize? + โœ“ Approval gates behavior + โœ“ Context loading strategy + โ˜ Delegation threshold + โ˜ Tool permissions + +? Approval gates: + > Always ask (current) + Auto-approve reads + YOLO mode by default + +? Context loading: + > Lazy (current) + Eager (load all upfront) + Manual (user specifies) + +โœ“ Updated preset: my-openagent +โœ“ Changes saved to ~/.config/oac/presets/agents/my-openagent.md +``` + +#### Layer 4: Use Personal Preset + +```bash +# Use preset instead of base agent +oac use preset:my-openagent + โ†’ Activates preset in current project + +# Use preset globally +oac use preset:my-openagent --global + โ†’ Sets as default for all projects + +# Use preset for specific IDE +oac use preset:my-openagent --ide opencode + โ†’ Applies to OpenCode only + +# List active presets +oac presets list --active + opencode: preset:my-openagent + cursor: agent:openagent (base) + claude: preset:strict-reviewer + +# Switch back to base +oac use agent:openagent + โ†’ Deactivates preset, uses base agent +``` + +#### Layer 5: Update Management (CRITICAL) + +**Problem**: Updates shouldn't overwrite user customizations + +**Solution**: Smart update strategy with user control + +```bash +# Check for updates to base agent +oac update --check + +๐Ÿ“ฆ Updates Available: + +agent:openagent (base for preset:my-openagent) + Current: 0.7.1 + Latest: 0.8.0 + + Changes: + - Added new context loading patterns + - Improved delegation logic + - Fixed approval gate bug + + โš ๏ธ You have a personal preset based on this agent + +? How would you like to update? + > Review changes first (recommended) + Update base, keep my customizations + Update base, merge my customizations + Skip this update + Auto-update base (don't ask again) + +# Review changes before updating +oac diff agent:openagent 0.7.1 0.8.0 + โ†’ Shows diff between versions + +# Update with merge strategy +oac update agent:openagent --merge-preset my-openagent + +โšก Updating agent:openagent (0.7.1 โ†’ 0.8.0) + +๐Ÿ“ Merging with preset:my-openagent... + +โœ“ Base agent updated +โš ๏ธ Conflicts detected in preset: + + Section: Approval Gates + Base (new): "Always ask before execution" + Your preset: "Auto-approve read operations" + +? Keep your customization? (Y/n) y + +โœ“ Preset updated with merge +โœ“ Backup saved: ~/.config/oac/presets/.backups/my-openagent.2026-02-14.md + +๐Ÿ“Š Summary: + - Base agent: Updated to 0.8.0 + - Your preset: Merged (3 conflicts resolved) + - Customizations: Preserved +``` + +**Update Strategies**: +```typescript +enum PresetUpdateStrategy { + MANUAL = 'manual', // User reviews every update + AUTO_BASE = 'auto-base', // Auto-update base, keep preset unchanged + AUTO_MERGE = 'auto-merge', // Auto-merge, prompt on conflicts + LOCKED = 'locked' // Never update base +} +``` + +**Configuration**: +```json +{ + "presets": { + "my-openagent": { + "updateStrategy": "manual", + "autoUpdate": false, + "mergeStrategy": { + "onConflict": "ask", // ask | keep-mine | keep-theirs + "backupOnMerge": true, + "maxBackups": 10 + } + } + } +} +``` + +#### Layer 6: Preset Sharing + +```bash +# Export preset for sharing +oac export preset:my-openagent --output ./my-openagent-preset.md + โ†’ Exports with metadata + +# Share preset with team +oac share preset:my-openagent + โ†’ Generates shareable link or file + +# Import preset from teammate +oac import preset ./teammate-preset.md + โ†’ Imports as new preset + +# Publish preset to community +oac publish preset:my-openagent --public + โ†’ Publishes to community registry (optional) +``` + +#### Layer 7: In-Place Editing (Advanced) + +**Warning**: Editing installed agents directly is risky + +```bash +# Edit installed agent (not recommended) +oac edit agent:openagent --in-place + +โš ๏ธ WARNING: Editing installed agent directly + + This will modify the installed agent file. + Updates will overwrite your changes. + + Recommended: Create a preset instead + oac customize agent:openagent + +? Are you sure you want to edit in-place? (y/N) n + +# Force in-place edit (advanced users) +oac edit agent:openagent --in-place --force + +โš ๏ธ Editing: .opencode/agent/core/openagent.md +โš ๏ธ Changes will be overwritten on update +โš ๏ธ Creating backup: (example: .opencode/.backups/openagent.md.2026-02-14) + +[Opens in editor] + +โœ“ Saved changes +โš ๏ธ Remember: Updates will overwrite this file +๐Ÿ’ก Tip: Create a preset to preserve customizations +``` + +#### CLI Commands Summary + +```bash +# View +oac show agent:openagent # View agent +oac config show agent:openagent # View config only +oac export agent:openagent # Export to file + +# Customize +oac customize agent:openagent # Create preset (wizard) +oac edit preset:my-openagent # Edit preset +oac customize preset:my-openagent --interactive # Interactive wizard + +# Use +oac use preset:my-openagent # Activate preset +oac use preset:my-openagent --global # Set as default +oac presets list # List presets +oac presets list --active # Show active presets + +# Update +oac update --check # Check for updates +oac diff agent:openagent 0.7.1 0.8.0 # Show changes +oac update agent:openagent --merge-preset my-openagent + +# Share +oac export preset:my-openagent # Export preset +oac import preset ./preset.md # Import preset +oac share preset:my-openagent # Share with team +oac publish preset:my-openagent # Publish to community + +# Advanced +oac edit agent:openagent --in-place # Edit installed agent (risky) +oac fork agent:openagent my-agent # Fork to new agent +``` + +#### Configuration Schema + +```json +{ + "presets": { + "enabled": true, + "location": "~/.config/oac/presets", + "defaultUpdateStrategy": "manual", + "backupOnEdit": true, + "maxBackups": 10, + "warnOnInPlaceEdit": true + }, + "customization": { + "allowInPlaceEdit": true, + "requireConfirmation": true, + "autoBackup": true, + "showDiffOnUpdate": true + } +} +``` + +#### Preset File Format + +```markdown +--- +# Preset Metadata +preset: + name: my-openagent + base: agent:openagent + baseVersion: 0.7.1 + type: agent + created: 2026-02-14T10:30:00Z + modified: 2026-02-14T15:45:00Z + +# Customizations +customizations: + - section: "Approval Gates" + description: "Auto-approve read operations" + - section: "Context Loading" + description: "Changed to eager loading" + +# Update Strategy +update: + strategy: manual + autoUpdate: false + mergeStrategy: ask +--- + +# My Custom OpenAgent + +[Your customized agent prompt here] + + +**Modified Behavior**: Auto-approve read operations (glob, read, grep) + + +[Rest of agent prompt...] +``` + +#### Visual Workflow + +``` +User wants to customize agent:openagent + โ†“ + oac customize agent:openagent + โ†“ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚ Create Personal Preset โ”‚ + โ”‚ โ”‚ + โ”‚ Name: my-openagent โ”‚ + โ”‚ Base: agent:openagent โ”‚ + โ”‚ Location: ~/.config/oac/ โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + Copy base agent to preset location + โ†“ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚ Edit Preset โ”‚ + โ”‚ โ”‚ + โ”‚ oac edit preset:my-openagentโ”‚ + โ”‚ [Opens in $EDITOR] โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + User makes changes, saves + โ†“ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚ Activate Preset โ”‚ + โ”‚ โ”‚ + โ”‚ oac use preset:my-openagent โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + Preset is now active + โ†“ + Base agent updates (0.7.1 โ†’ 0.8.0) + โ†“ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚ Update Check โ”‚ + โ”‚ โ”‚ + โ”‚ โš ๏ธ Preset based on updated โ”‚ + โ”‚ agent โ”‚ + โ”‚ โ”‚ + โ”‚ ? How to update? โ”‚ + โ”‚ > Review changes โ”‚ + โ”‚ Merge โ”‚ + โ”‚ Skip โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + User reviews diff + โ†“ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚ Merge Strategy โ”‚ + โ”‚ โ”‚ + โ”‚ Conflicts: โ”‚ + โ”‚ - Approval gates (yours) โ”‚ + โ”‚ - Context loading (theirs) โ”‚ + โ”‚ โ”‚ + โ”‚ ? Keep your changes? Y/n โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ†“ + Preset updated with merge + Backup created + Customizations preserved +``` + +#### Best Practices + +**For Users**: +- โœ… Always create presets instead of editing in-place +- โœ… Use descriptive preset names +- โœ… Document your customizations in preset metadata +- โœ… Review updates before merging +- โœ… Keep backups of important presets + +**For OAC**: +- โœ… Default to preset creation (safest) +- โœ… Warn loudly on in-place edits +- โœ… Always create backups before updates +- โœ… Show clear diffs before merging +- โœ… Preserve user customizations by default +- โœ… Make it easy to revert to base agent + +#### Edge Cases Handled + +1. **User edits in-place, then update arrives** + - Detect local modifications + - Warn user + - Offer to create preset from modifications + - Backup before overwriting + +2. **Preset based on old version, multiple updates behind** + - Show all changes since preset creation + - Offer step-by-step merge or bulk merge + - Highlight breaking changes + +3. **User has multiple presets for same base agent** + - Allow multiple presets + - Each preset tracks its own base version + - Update each independently + +4. **Preset conflicts with IDE limitations** + - Warn if preset won't work with IDE + - Suggest compatible alternatives + - Auto-adapt if possible + +5. **User deletes base agent but has preset** + - Preset becomes standalone + - Warn that updates won't work + - Offer to reinstall base + +--- + +### 6. IDE Feature Parity & Capacity Management (CRITICAL) + +**Goal**: Support different feature sets per IDE based on their capabilities + +**The Problem**: +- Different IDEs support different features +- OpenCode and Claude Code: Full feature support (agents, skills, context, plugins, tools) +- Cursor: Limited (single .cursorrules file, no skills/plugins) +- Windsurf: Partial support +- Need to gracefully handle unsupported features + +**Feature Support Matrix**: + +```typescript +interface IDECapabilities { + id: string; + name: string; + features: { + multipleAgents: boolean; + skills: boolean; + plugins: boolean; + tools: boolean; + contexts: boolean; + commands: boolean; + granularPermissions: boolean; + hooks: boolean; + }; + limits?: { + maxAgents?: number; + maxFileSize?: number; + maxContextFiles?: number; + }; +} + +const IDE_CAPABILITIES: Record = { + opencode: { + id: 'opencode', + name: 'OpenCode', + features: { + multipleAgents: true, + skills: true, + plugins: true, + tools: true, + contexts: true, + commands: true, + granularPermissions: true, + hooks: true + } + // No limits - full support + }, + + claude: { + id: 'claude', + name: 'Claude Code', + features: { + multipleAgents: true, + skills: true, + plugins: true, + tools: true, + contexts: true, + commands: false, + granularPermissions: false, + hooks: true + } + // Full support except commands and granular permissions + }, + + cursor: { + id: 'cursor', + name: 'Cursor IDE', + features: { + multipleAgents: false, // Single .cursorrules file + skills: false, + plugins: false, + tools: false, + contexts: true, // Embedded in .cursorrules + commands: false, + granularPermissions: false, + hooks: false + }, + limits: { + maxAgents: 1, // Merge all agents into one + maxFileSize: 100000 // ~100KB limit for .cursorrules + } + }, + + windsurf: { + id: 'windsurf', + name: 'Windsurf', + features: { + multipleAgents: true, + skills: false, + plugins: false, + tools: false, + contexts: true, + commands: false, + granularPermissions: false, + hooks: false + }, + limits: { + maxAgents: 10 + } + } +}; +``` + +**Feature Detection & Warnings**: + +```bash +# User tries to install skill for Cursor +oac install cursor --profile developer + +โš  Feature Compatibility Warning: + + IDE: Cursor + Profile: developer + + Unsupported features in this profile: + โŒ Skills (8 skills will be skipped) + โŒ Plugins (2 plugins will be skipped) + โŒ Commands (7 commands will be skipped) + โš  Multiple agents (2 agents will be merged into .cursorrules) + + Supported features: + โœ“ Agents (will merge into single .cursorrules) + โœ“ Contexts (will embed in .cursorrules) + +? How would you like to proceed? + > Continue with supported features only + Cancel installation + Show detailed compatibility report + Create custom profile for Cursor + +# Detailed compatibility report +oac compatibility cursor --profile developer + +IDE Compatibility Report: Cursor +Profile: developer + +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Feature โ”‚ Status โ”‚ Action โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ Agents (2) โ”‚ โš  Merge โ”‚ Combine into .cursorrules โ”‚ +โ”‚ Subagents (8) โ”‚ โš  Merge โ”‚ Combine into .cursorrules โ”‚ +โ”‚ Skills (8) โ”‚ โŒ Skip โ”‚ Not supported โ”‚ +โ”‚ Plugins (2) โ”‚ โŒ Skip โ”‚ Not supported โ”‚ +โ”‚ Commands (7) โ”‚ โŒ Skip โ”‚ Not supported โ”‚ +โ”‚ Contexts (15) โ”‚ โœ“ Embed โ”‚ Embed in .cursorrules โ”‚ +โ”‚ Tools (3) โ”‚ โŒ Skip โ”‚ Not supported โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + +Estimated .cursorrules size: 45KB (within 100KB limit) + +Recommendations: +โ€ข Use OpenCode or Claude Code for full feature support +โ€ข Create Cursor-specific profile with essential agents only +โ€ข Consider using oac create profile --for cursor +``` + +**Adaptive Installation**: + +```typescript +class AdaptiveInstaller { + async install(ide: string, profile: string, options: InstallOptions) { + const capabilities = IDE_CAPABILITIES[ide]; + const components = await this.loadProfile(profile); + + // Filter components based on IDE capabilities + const supported = this.filterByCapabilities(components, capabilities); + const unsupported = components.filter(c => !supported.includes(c)); + + // Warn user about unsupported features + if (unsupported.length > 0 && !options.yolo) { + const proceed = await this.warnUnsupportedFeatures( + ide, + supported, + unsupported, + capabilities + ); + + if (!proceed) { + return { cancelled: true }; + } + } + + // Apply transformations for IDE-specific limitations + const transformed = await this.transformForIDE(supported, capabilities); + + // Install + return this.installComponents(transformed, ide, options); + } + + private filterByCapabilities( + components: Component[], + capabilities: IDECapabilities + ): Component[] { + return components.filter(component => { + switch (component.type) { + case 'agent': + case 'subagent': + return capabilities.features.multipleAgents || + components.filter(c => c.type === 'agent').length === 1; + case 'skill': + return capabilities.features.skills; + case 'plugin': + return capabilities.features.plugins; + case 'tool': + return capabilities.features.tools; + case 'context': + return capabilities.features.contexts; + case 'command': + return capabilities.features.commands; + default: + return false; + } + }); + } + + private async transformForIDE( + components: Component[], + capabilities: IDECapabilities + ): Promise { + // Special handling for Cursor: merge all agents + if (capabilities.id === 'cursor') { + const agents = components.filter(c => c.type === 'agent' || c.type === 'subagent'); + const contexts = components.filter(c => c.type === 'context'); + + // Merge agents into single .cursorrules + const merged = await this.mergeAgentsForCursor(agents, contexts); + + return [merged]; + } + + return components; + } +} +``` + +**IDE-Specific Profiles**: + +```bash +# Create profile optimized for specific IDE +oac create profile --for cursor --name cursor-essentials + +? Select components for Cursor profile: + Agents (select up to 3 - will be merged): + โœ“ openagent + โœ“ opencoder + โœ“ frontend-specialist + + Contexts (will be embedded): + โœ“ core/standards/code-quality + โœ“ development/react-patterns + + โš  Skills, plugins, and commands are not supported by Cursor + +โœ“ Created profile: cursor-essentials +โœ“ Estimated .cursorrules size: 32KB +โœ“ Compatible with Cursor IDE + +# List IDE-specific profiles +oac profiles --for cursor + cursor-essentials + cursor-minimal + cursor-frontend + +# Install IDE-specific profile +oac install cursor --profile cursor-essentials +``` + +**Component Creation with IDE Support**: + +```bash +# Create component with IDE compatibility info +oac create agent rust-specialist + +? Which IDEs should support this agent? + โœ“ OpenCode (full support) + โœ“ Claude Code (full support) + โœ“ Cursor (will be merged with other agents) + โœ“ Windsurf (full support) + +? Agent size optimization: + > Standard (no optimization) + Compact (optimize for Cursor's file size limit) + Minimal (essential instructions only) + +โœ“ Created agent with multi-IDE support +โœ“ Estimated sizes: + - OpenCode: 15KB (standalone) + - Claude Code: 15KB (standalone) + - Cursor: +15KB (merged into .cursorrules) + - Windsurf: 15KB (standalone) +``` + +**Capacity Warnings**: + +```bash +# Installing too many components for Cursor +oac install cursor --profile developer + +โš  Capacity Warning: + + IDE: Cursor + Limit: 100KB for .cursorrules + + Current profile size: 125KB + โŒ Exceeds limit by 25KB + +? How would you like to proceed: + > Remove optional components (interactive) + Use compact mode (reduce file sizes) + Create custom profile + Cancel installation + +# Interactive component selection +? Select components to include (max 100KB): + + Core (required): + โœ“ openagent (12KB) + โœ“ opencoder (15KB) + + Specialists (optional): + โœ“ frontend-specialist (18KB) + โœ“ devops-specialist (16KB) + โ˜ data-analyst (14KB) + โ˜ copywriter (12KB) + + Contexts: + โœ“ core/standards (8KB) + โœ“ development/patterns (12KB) + + Current: 81KB / 100KB + Remaining: 19KB +``` + +**CLI Commands for IDE Management**: + +```bash +# Check IDE compatibility +oac compatibility + --profile # Check profile compatibility + --component # Check component compatibility + +# List supported IDEs +oac ides + --features # Show feature matrix + --limits # Show capacity limits + +# Show IDE capabilities +oac ide info + โ†’ Shows full feature support matrix + +# Optimize for IDE +oac optimize --for + โ†’ Optimizes current installation for IDE + โ†’ Removes unsupported features + โ†’ Compacts files if needed + +# Validate IDE installation +oac validate --ide + โ†’ Checks if installation is valid for IDE + โ†’ Warns about unsupported features + โ†’ Checks capacity limits +``` + +**Configuration**: + +```json +{ + "ides": { + "opencode": { + "enabled": true, + "path": ".opencode", + "profile": "developer", + "features": "all" + }, + "cursor": { + "enabled": true, + "path": ".cursor", + "profile": "cursor-essentials", + "features": "auto-detect", + "optimization": { + "mergeAgents": true, + "embedContexts": true, + "compactMode": true, + "maxFileSize": 100000 + } + }, + "claude": { + "enabled": true, + "path": ".claude", + "profile": "developer", + "features": "all" + } + }, + "compatibility": { + "warnUnsupported": true, + "autoOptimize": false, + "strictMode": false + } +} +``` + +**Best Practices**: + +**For Full Features** (OpenCode, Claude Code): +- โœ… Use standard profiles (developer, business, etc.) +- โœ… Install all component types +- โœ… No optimization needed + +**For Limited IDEs** (Cursor): +- โœ… Create IDE-specific profiles +- โœ… Keep agent count low (1-3 agents) +- โœ… Use compact mode +- โœ… Embed contexts instead of separate files +- โœ… Monitor file size limits + +**For All IDEs**: +- โœ… Check compatibility before installing: `oac compatibility ` +- โœ… Use `--dry-run` to preview changes +- โœ… Create custom profiles for specific needs +- โœ… Validate after installation: `oac validate --ide ` + +--- + +## CLI Commands Reference + +**CRITICAL**: All commands run in project root directory. User chooses local (project) or global install. + +### Installation & Setup + +```bash +# Initialize OAC in current directory (interactive) +oac init [profile] + --local # Force local install (./opencode) + --global # Force global install (~/.config/oac) + --yolo # Skip all confirmations + --dry-run # Show what would happen + +# Install for specific IDE (asks local/global) +oac install [ide] + --local # Install to current directory + --global # Install to global config + --profile # Use specific profile + --yolo # Auto-confirm all + --skip-existing # Skip conflicts, keep existing + --force # Overwrite all, no backups + --dry-run # Preview changes + +# Configure OAC settings +oac configure + set # Set config value + get # Get config value + show # Show all config + reset # Reset to defaults +``` + +### Component Management + +```bash +# Add component from registry (asks local/global) +oac add + --local # Add to current project + --global # Add to global config + --yolo # Auto-confirm + --dry-run # Preview + +# Remove component +oac remove + --local # Remove from current project + --global # Remove from global + --yolo # Auto-confirm + +# List installed components +oac list [--type] + --local # List local components + --global # List global components + --agents # List agents only + --skills # List skills only + --contexts # List contexts only + +# Search registry +oac search + --type # Filter by type + --verified # Verified only + +# Browse available components +oac browse [type] + --verified # Verified only + --community # Community only +``` + +### Updates & Sync + +```bash +# Update components (asks which to update) +oac update [options] + --check # Check for updates only + --all # Update all components + --local # Update local install + --global # Update global install + --claude # Apply to Claude Code + --opencode # Apply to OpenCode + --yolo # Auto-confirm all + --dry-run # Preview updates + +# Apply config to IDE (asks for confirmation) +oac apply [ide] + --all # Apply to all configured IDEs + --yolo # Auto-confirm + --force # Overwrite all + --dry-run # Preview + +# Sync across all IDEs +oac sync + --yolo # Auto-confirm + --dry-run # Preview +``` + +### Creation & Scaffolding (Interactive) + +```bash +# Interactive component creation wizard +oac create + ? What would you like to create? + > Agent + Skill + Context + Plugin + Command + Tool + + ? Component type: + > agent + subagent + + ? Name: rust-specialist + ? Description: Expert in Rust programming + ? Category: development + + โœ“ Created .opencode/agent/subagents/development/rust-specialist.md + โœ“ Created tests/smoke-test.yaml + โœ“ Added to registry + + Next steps: + 1. Edit agent prompt + 2. Add tests + 3. Test: oac test agent:rust-specialist + +# Create specific component types +oac create agent [name] + --category # Agent category + --template