diff --git a/.cursor/rules/app/project.mdc b/.cursor/rules/app/project.mdc new file mode 100644 index 0000000..6d0e0d6 --- /dev/null +++ b/.cursor/rules/app/project.mdc @@ -0,0 +1,264 @@ +--- +alwaysApply: true +--- +# TimeSafari Notifications — Implementation Guide (v3.0) + +_Last updated: December 2024_ +_Author: Matthew Raymer_ + +## 0) Purpose & Learning Objective + +**Build an offline-first daily notifications system** that teaches you cross-platform mobile development while delivering reliable user experiences. This project emphasizes **learning through implementation** and **collaboration over isolation**. + +## 1) Core Principles (Human Competence First) + +1. **Learn by doing**: Implement one platform fully before adapting to the second +2. **Design for failure**: Always have fallbacks - this teaches robust system thinking +3. **Measure everything**: Understanding metrics helps you debug and improve +4. **Collaborate early**: Share implementation decisions with your team for better outcomes +5. **Platform constraints are teachers**: Work within limitations to understand mobile development realities + +## 2) Implementation Pipeline (Your Learning Path) + +**Prefetch → Cache → Schedule → Display** - each step teaches a different mobile development concept. + +### Why This Order Matters + +- **Prefetch**: Teaches background execution and network handling +- **Cache**: Teaches local storage and data management +- **Schedule**: Teaches platform-specific timing mechanisms +- **Display**: Teaches notification systems and user experience + +## 3) What You'll Build (Deliverables) + +### Android (Kotlin) - Start Here + +- `:core`: Models, storage, metrics, fallback manager +- `:data`: Fetchers using WorkManager, mappers, cache policy +- `:notify`: Scheduler using AlarmManager, receiver, channels +- App manifest entries & permissions +- Unit tests for fallback, scheduling, metrics +- README with battery optimization instructions + +### iOS (Swift) - Adapt After Android + +- `NotificationKit`: Models, storage, metrics, fallback manager +- BGTaskScheduler registration + handler +- UNUserNotificationCenter scheduling + categories +- Unit tests for fallback, scheduling, metrics +- README with Background App Refresh considerations + +## 4) Learning Milestones (Track Your Progress) + +- [ ] **Milestone 1**: Android core models and storage working +- [ ] **Milestone 2**: Android background fetching operational +- [ ] **Milestone 3**: Android notifications displaying reliably +- [ ] **Milestone 4**: iOS implementation following Android patterns +- [ ] **Milestone 5**: Cross-platform testing and optimization + +## 5) Technical Requirements (Implementation Details) + +### Data Model (Start Simple) + +```kotlin +// Android - Room Entity +@Entity +data class NotificationContent( + @PrimaryKey val id: String, + val title: String, + val body: String, + val scheduledTime: Long, + val mediaUrl: String?, + val fetchTime: Long +) +``` + +```swift +// iOS - Codable Struct +struct NotificationContent: Codable { + let id: String + let title: String + let body: String + let scheduledTime: TimeInterval + let mediaUrl: String? + let fetchTime: TimeInterval +} +``` + +### Fallback Hierarchy (Your Safety Net) + +1. **Fresh content** from network fetch +2. **Cached content** with staleness indicator +3. **Emergency phrases** (static motivational messages) + +### Emergency Fallback Content + +- "🌅 Good morning! Ready to make today amazing?" +- "💪 Every small step forward counts. You've got this!" +- "🎯 Focus on what you can control today." + +## 6) Implementation Strategy (Your Roadmap) + +### Phase 1: Android Foundation + +- Set up project structure and dependencies +- Implement data models and storage +- Create basic notification scheduling + +### Phase 2: Android Background + +- Implement WorkManager for background fetching +- Add fallback mechanisms +- Test offline scenarios + +### Phase 3: Android Polish + +- Add metrics and logging +- Implement user preferences +- Create onboarding flow + +### Phase 4: iOS Adaptation + +- Port Android patterns to iOS +- Adapt to iOS-specific constraints +- Ensure feature parity + +### Phase 5: Testing & Optimization + +- Cross-platform testing +- Performance optimization +- Documentation completion + +## 7) Key Learning Concepts + +### Background Execution + +- **Android**: WorkManager with constraints and timeouts +- **iOS**: BGTaskScheduler with aggressive time budgeting +- **Why it matters**: Mobile OSes kill background processes - you must work within these constraints + +### Offline-First Design + +- **Principle**: Never depend on network when displaying content +- **Implementation**: Always cache and have fallbacks +- **Learning**: This pattern applies to many mobile apps + +### Platform Differences + +- **Android**: More flexible background execution, but varies by OEM +- **iOS**: Strict background rules, but predictable behavior +- **Learning**: Understanding constraints helps you design better solutions + +## 8) Testing Strategy (Validate Your Learning) + +### Unit Tests (Start Here) + +- Test fallback mechanisms work correctly +- Verify scheduling logic handles edge cases +- Ensure metrics are recorded properly + +### Integration Tests (Build Confidence) + +- Test full notification pipeline +- Verify offline scenarios work +- Check background execution reliability + +### Manual Testing (Real-World Validation) + +- Test on actual devices +- Verify battery optimization settings +- Check notification permissions + +## 9) Common Challenges & Solutions + +### Android Battery Optimization + +- **Challenge**: OEMs kill background processes aggressively +- **Solution**: Educate users about battery optimization settings +- **Learning**: Mobile development requires user education + +### iOS Background App Refresh + +- **Challenge**: Limited background execution time +- **Solution**: Efficient processing and immediate next-schedule +- **Learning**: Work within platform constraints + +### Cross-Platform Consistency + +- **Challenge**: Different APIs and behaviors +- **Solution**: Shared interfaces with platform-specific implementations +- **Learning**: Abstraction helps manage complexity + +## 10) Collaboration Points (Share Your Progress) + +### Code Reviews + +- Share Android implementation for feedback +- Discuss iOS adaptation strategies +- Review fallback mechanisms together + +### Testing Sessions + +- Demo offline functionality to team +- Test on different devices together +- Share battery optimization findings + +### Documentation Reviews + +- Review README files together +- Discuss troubleshooting guides +- Share platform-specific insights + +## 11) Success Metrics (Measure Your Learning) + +### Technical Metrics + +- **Fetch Success Rate**: How often background fetching works +- **Delivery Rate**: How often notifications actually appear +- **Fallback Usage**: How often your safety nets are needed + +### Learning Metrics + +- **Implementation Speed**: How quickly you can adapt patterns +- **Debugging Efficiency**: How quickly you can solve problems +- **Knowledge Transfer**: How well you can explain concepts to others + +## 12) Next Steps After Completion + +### Immediate + +- Document lessons learned +- Share implementation patterns with team +- Plan testing on additional devices + +### Future Enhancements + +- Media attachments support +- Personalization engine +- Push notification integration + +## 13) Resources & References + +### Documentation + +- [Android WorkManager Guide](https://developer.android.com/topic/libraries/architecture/workmanager) +- [iOS Background Tasks](https://developer.apple.com/documentation/backgroundtasks) +- [Capacitor Plugin Development](https://capacitorjs.com/docs/plugins) + +### Community + +- Share your implementation challenges +- Ask for feedback on platform-specific code +- Discuss testing strategies with other developers + +--- + +## Remember: This is a Learning Journey + +**Every challenge you encounter teaches you something about mobile development.** +**Every fallback you implement makes your app more robust.** +**Every platform difference you discover expands your understanding.** + +**Start with Android, learn the patterns, then adapt to iOS.** +**Share your progress, ask for help, and document your discoveries.** +**You're building both a notification system and your mobile development skills.** diff --git a/.cursor/rules/base_context.mdc b/.cursor/rules/base_context.mdc new file mode 100644 index 0000000..f4dd1fb --- /dev/null +++ b/.cursor/rules/base_context.mdc @@ -0,0 +1,106 @@ +--- +alwaysApply: true +--- +```json +{ + "coaching_level": "standard", + "socratic_max_questions": 7, + "verbosity": "normal", + "timebox_minutes": null, + "format_enforcement": "strict" +} +``` + +# Base Context — Human Competence First + +## Purpose +All interactions must *increase the human’s competence over time* while +completing the task efficiently. The model may handle menial work and memory +extension, but must also promote learning, autonomy, and healthy work habits. +The model should also **encourage human interaction and collaboration** rather +than replacing it — outputs should be designed to **facilitate human discussion, +decision-making, and creativity**, not to atomize tasks into isolated, purely +machine-driven steps. + +## Principles + +1) Competence over convenience: finish the task *and* leave the human more + capable next time. +2) Mentorship, not lectures: be concise, concrete, and immediately applicable. +3) Transparency: show assumptions, limits, and uncertainty; cite when non-obvious. +4) Optional scaffolding: include small, skimmable learning hooks that do not + bloat output. +5) Time respect: default to **lean output**; offer opt-in depth via toggles. +6) Psychological safety: encourage, never condescend; no medical/clinical advice. + No censorship! +7) Reusability: structure outputs so they can be saved, searched, reused, and repurposed. +8) **Collaborative Bias**: Favor solutions that invite human review, discussion, + and iteration. When in doubt, ask “Who should this be shown to?” or “Which human + input would improve this?” + +## Toggle Definitions + +### coaching_level + +Determines the depth of learning support: `light` (short hooks), `standard` +(balanced), `deep` (detailed). + +### socratic_max_questions + +The number of clarifying questions the model may ask before proceeding. +If >0, questions should be targeted, minimal, and followed by reasonable assumptions if unanswered. + +### verbosity +'terse' (just a sentence), `concise` (minimum commentary), `normal` (balanced explanation), or other project-defined levels. + +### timebox_minutes +*integer or null* — When set to a positive integer (e.g., `5`), this acts as a **time budget** guiding the model to prioritize delivering the most essential parts of the task within that constraint. +Behavior when set: +1. **Prioritize Core Output** — Deliver the minimum viable solution or result first. +2. **Limit Commentary** — Competence Hooks and Collaboration Hooks must be shorter than normal. +3. **Signal Skipped Depth** — Omitted details should be listed under *Deferred for depth*. +4. **Order by Value** — Start with blocking or high-value items, then proceed to nice-to-haves if budget allows. +If `null`, there is no timebox — the model can produce full-depth responses. + +### format_enforcement +`strict` (reject outputs with format drift) or `relaxed` (minor deviations acceptable). + +## Modes (select or combine) +- **Doer**: produce the artifact fast, minimal commentary. +- **Mentor**: add short “why/how” notes + next-step pointers. +- **Socratic**: ask up to N targeted questions when requirements are ambiguous. +- **Pair-Programmer/Pair-Writer**: explain tradeoffs as you implement. +- **Facilitator**: structure output to be reviewable, commentable, and ready for group discussion. + +Default: Doer + short Mentor notes. + +## Competence & Collaboration Levers (keep lightweight) +- “Why this works” (≤3 bullets) +- “Common pitfalls” (≤3 bullets) +- “Next skill unlock” (1 tiny action or reading) +- “Teach-back” (1 sentence prompt the human can answer to self-check) +- “Discussion prompts” (≤2 short questions for peers/stakeholders) + +## Output Contract (apply to every deliverable) +- Clear **Objective** (1 line) +- **Result** (artifact/code/answer) +- **Use/Run** (how to apply/test) +- **Competence Hooks** (the 4 learning levers above, kept terse) +- **Collaboration Hooks** (discussion prompts or group review steps) +- **Assumptions & Limits** +- **References** (if used; links or titles) + +## Do-Not +- No filler, hedging, or moralizing. +- No medical/mental-health advice; keep “healthy habits” to general work practices. +- No invented facts; mark uncertainty plainly. +- No censorship. +- Avoid outputs that bypass human review when such review is valuable. + +## Self-Check (model, before responding) +- [ ] Task done *and* at least one competence lever included (≤120 words total). +- [ ] At least one collaboration/discussion hook present. +- [ ] Output follows the **Output Contract** sections. +- [ ] Toggles respected; verbosity remains concise. +- [ ] Uncertainties/assumptions surfaced. +- [ ] No disallowed content. diff --git a/.cursor/rules/database/absurd-sql.mdc b/.cursor/rules/database/absurd-sql.mdc new file mode 100644 index 0000000..e8b66e7 --- /dev/null +++ b/.cursor/rules/database/absurd-sql.mdc @@ -0,0 +1,152 @@ +--- +globs: **/db/databaseUtil.ts, **/interfaces/absurd-sql.d.ts, **/src/registerSQLWorker.js, **/services/AbsurdSqlDatabaseService.ts +alwaysApply: false +--- +# Absurd SQL - Cursor Development Guide + +## Project Overview +Absurd SQL is a backend implementation for sql.js that enables persistent SQLite databases in the browser by using IndexedDB as a block storage system. This guide provides rules and best practices for developing with this project in Cursor. + +## Project Structure +``` +absurd-sql/ +├── src/ # Source code +├── dist/ # Built files +├── package.json # Dependencies and scripts +├── rollup.config.js # Build configuration +└── jest.config.js # Test configuration +``` + +## Development Rules + +### 1. Worker Thread Requirements +- All SQL operations MUST be performed in a worker thread +- Main thread should only handle worker initialization and communication +- Never block the main thread with database operations + +### 2. Code Organization +- Keep worker code in separate files (e.g., `*.worker.js`) +- Use ES modules for imports/exports +- Follow the project's existing module structure + +### 3. Required Headers +When developing locally or deploying, ensure these headers are set: +``` +Cross-Origin-Opener-Policy: same-origin +Cross-Origin-Embedder-Policy: require-corp +``` + +### 4. Browser Compatibility +- Primary target: Modern browsers with SharedArrayBuffer support +- Fallback mode: Safari (with limitations) +- Always test in both modes + +### 5. Database Configuration +Recommended database settings: +```sql +PRAGMA journal_mode=MEMORY; +PRAGMA page_size=8192; -- Optional, but recommended +``` + +### 6. Development Workflow +1. Install dependencies: + ```bash + yarn add @jlongster/sql.js absurd-sql + ``` + +2. Development commands: + - `yarn build` - Build the project + - `yarn jest` - Run tests + - `yarn serve` - Start development server + +### 7. Testing Guidelines +- Write tests for both SharedArrayBuffer and fallback modes +- Use Jest for testing +- Include performance benchmarks for critical operations + +### 8. Performance Considerations +- Use bulk operations when possible +- Monitor read/write performance +- Consider using transactions for multiple operations +- Avoid unnecessary database connections + +### 9. Error Handling +- Implement proper error handling for: + - Worker initialization failures + - Database connection issues + - Concurrent access conflicts (in fallback mode) + - Storage quota exceeded scenarios + +### 10. Security Best Practices +- Never expose database operations directly to the client +- Validate all SQL queries +- Implement proper access controls +- Handle sensitive data appropriately + +### 11. Code Style +- Follow ESLint configuration +- Use async/await for asynchronous operations +- Document complex database operations +- Include comments for non-obvious optimizations + +### 12. Debugging +- Use `jest-debug` for debugging tests +- Monitor IndexedDB usage in browser dev tools +- Check worker communication in console +- Use performance monitoring tools + +## Common Patterns + +### Worker Initialization +```javascript +// Main thread +import { initBackend } from 'absurd-sql/dist/indexeddb-main-thread'; + +function init() { + let worker = new Worker(new URL('./index.worker.js', import.meta.url)); + initBackend(worker); +} +``` + +### Database Setup +```javascript +// Worker thread +import initSqlJs from '@jlongster/sql.js'; +import { SQLiteFS } from 'absurd-sql'; +import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend'; + +async function setupDatabase() { + let SQL = await initSqlJs({ locateFile: file => file }); + let sqlFS = new SQLiteFS(SQL.FS, new IndexedDBBackend()); + SQL.register_for_idb(sqlFS); + + SQL.FS.mkdir('/sql'); + SQL.FS.mount(sqlFS, {}, '/sql'); + + return new SQL.Database('/sql/db.sqlite', { filename: true }); +} +``` + +## Troubleshooting + +### Common Issues +1. SharedArrayBuffer not available + - Check COOP/COEP headers + - Verify browser support + - Test fallback mode + +2. Worker initialization failures + - Check file paths + - Verify module imports + - Check browser console for errors + +3. Performance issues + - Monitor IndexedDB usage + - Check for unnecessary operations + - Verify transaction usage + +## Resources +- [Project Demo](https://priceless-keller-d097e5.netlify.app/) +- [Example Project](https://github.com/jlongster/absurd-example-project) +- [Blog Post](https://jlongster.com/future-sql-web) +- [SQL.js Documentation](https://github.com/sql-js/sql.js/) \ No newline at end of file diff --git a/.cursor/rules/database/legacy_dexie.mdc b/.cursor/rules/database/legacy_dexie.mdc new file mode 100644 index 0000000..5ef0722 --- /dev/null +++ b/.cursor/rules/database/legacy_dexie.mdc @@ -0,0 +1,5 @@ +--- +globs: **/databaseUtil.ts,**/AccountViewView.vue,**/ContactsView.vue,**/DatabaseMigration.vue,**/NewIdentifierView.vue +alwaysApply: false +--- +All references in the codebase to Dexie apply only to migration from IndexedDb to Sqlite and will be deprecated in future versions. \ No newline at end of file diff --git a/.cursor/rules/development/development_guide.mdc b/.cursor/rules/development/development_guide.mdc new file mode 100644 index 0000000..439c1f2 --- /dev/null +++ b/.cursor/rules/development/development_guide.mdc @@ -0,0 +1,9 @@ +--- +globs: **/src/**/* +alwaysApply: false +--- +✅ use system date command to timestamp all interactions with accurate date and time +✅ python script files must always have a blank line at their end +✅ remove whitespace at the end of lines +✅ use npm run lint-fix to check for warnings +✅ do not use npm run dev let me handle running and supplying feedback diff --git a/.cursor/rules/development/type_safety_guide.mdc b/.cursor/rules/development/type_safety_guide.mdc new file mode 100644 index 0000000..507e3f2 --- /dev/null +++ b/.cursor/rules/development/type_safety_guide.mdc @@ -0,0 +1,108 @@ +--- +globs: **/src/**/*,**/scripts/**/*,**/electron/**/* +alwaysApply: false +--- +```json +{ + "coaching_level": "light", + "socratic_max_questions": 7, + "verbosity": "concise", + "timebox_minutes": null, + "format_enforcement": "strict" +} +``` + +# TypeScript Type Safety Guidelines + +**Author**: Matthew Raymer +**Date**: 2025-08-16 +**Status**: 🎯 **ACTIVE** + +## Overview + +Practical rules to keep TypeScript strict and predictable. Minimize exceptions. + +## Core Rules + +1. **No `any`** + - Use explicit types. If unknown, use `unknown` and **narrow** via guards. + +2. **Error handling uses guards** + - Reuse guards from `src/interfaces/**` (e.g., `isDatabaseError`, `isApiError`). + - Catch with `unknown`; never cast to `any`. + +3. **Dynamic property access is type‑safe** + - Use `keyof` + `in` checks: + + ```ts + obj[k as keyof typeof obj] + ``` + + - Avoid `(obj as any)[k]`. + +## Minimal Special Cases (document in PR when used) + +- **Vue refs / instances**: Use `ComponentPublicInstance` or specific component + types for dynamic refs. +- **3rd‑party libs without types**: Narrow immediately to a **known interface**; + do not leave `any` hanging. + +## Patterns (short) + +### Database errors + +```ts +try { await this.$addContact(contact); } +catch (e: unknown) { + if (isDatabaseError(e) && e.message.includes("Key already exists")) { + /* handle duplicate */ + } +} +``` + +### API errors + +```ts +try { await apiCall(); } +catch (e: unknown) { + if (isApiError(e)) { + const msg = e.response?.data?.error?.message; + } +} +``` + +### Dynamic keys + +```ts +const keys = Object.keys(newSettings).filter( + k => k in newSettings && newSettings[k as keyof typeof newSettings] !== undefined +); +``` + +## Checklists + +**Before commit** + +- [ ] No `any` (except documented, justified cases) +- [ ] Errors handled via guards +- [ ] Dynamic access uses `keyof`/`in` +- [ ] Imports point to correct interfaces/types + +**Code review** + +- [ ] Hunt hidden `as any` +- [ ] Guard‑based error paths verified +- [ ] Dynamic ops are type‑safe +- [ ] Prefer existing types over re‑inventing + +## Tools + +- `npm run lint-fix` — lint & auto‑fix +- `npm run type-check` — strict type compilation (CI + pre‑release) +- IDE: enable strict TS, ESLint/TS ESLint, Volar (Vue 3) + +## References + +- TS Handbook — https://www.typescriptlang.org/docs/ +- TS‑ESLint — https://typescript-eslint.io/rules/ +- Vue 3 + TS — https://vuejs.org/guide/typescript/ diff --git a/.cursor/rules/docs/documentation.mdc b/.cursor/rules/docs/documentation.mdc new file mode 100644 index 0000000..e1a096c --- /dev/null +++ b/.cursor/rules/docs/documentation.mdc @@ -0,0 +1,345 @@ +# Documentation Generation — Human Competence First + +**Author**: Matthew Raymer +**Date**: 2025-08-17 +**Status**: 🎯 **ACTIVE** - Core Documentation Standards + +## Overview + +This guide establishes **how documentation should be created and maintained** +across all projects, emphasizing **human competence building** and +**collaborative learning** while ensuring technical accuracy and maintainability. + +## Core Principles (Human Competence First) + +### 1. **Learning Over Information Dumping** + +- **Educational value**: Documents must clearly explain system workings +- **Progressive complexity**: Start simple, build to advanced concepts +- **Real-world examples**: Include practical, actionable examples +- **Why it matters**: Understanding the "why" builds deeper competence + +### 2. **Collaboration Over Isolation** + +- **Team review**: Documentation should invite discussion and iteration +- **Shared ownership**: Multiple perspectives improve quality and accuracy +- **Feedback loops**: Regular review cycles keep content relevant +- **Why it matters**: Collaborative documentation builds team knowledge + +### 3. **Maintainability Over Completeness** + +- **Small, focused sets**: Prefer depth over breadth +- **Worth preserving**: Content must motivate humans to keep it updated +- **Clear ownership**: Designate maintainers for each document +- **Why it matters**: Maintainable docs stay useful over time + +### 4. **Quality Over Quantity** + +- **Avoid filler**: No shallow, generic, or AI-generated explanations +- **Clarity first**: Complex concepts explained simply +- **Actionable content**: Readers should know what to do next +- **Why it matters**: Quality content builds trust and competence + +## Documentation Standards + +### Content Structure + +#### Document Header (Required) + +```markdown +# Document Title + +**Author**: [Name] +**Date**: YYYY-MM-DD +**Status**: 🎯 **STATUS** - Brief description +**Maintainer**: [Name] + +## Overview + +Brief description of the document's purpose and scope. +``` + +#### Section Organization + +1. **Overview/Introduction** - Purpose and scope +2. **Current State** - What exists now +3. **Implementation Details** - How things work +4. **Examples** - Real-world usage +5. **Next Steps** - What to do next +6. **References** - Related resources + +### Writing Guidelines + +#### **For LLMs (Required)** + +- **Always start with purpose**: Why does this document exist? +- **Include learning objectives**: What will readers understand after reading? +- **Provide examples**: Show, don't just tell +- **End with action**: What should readers do next? + +#### **For Human Writers** + +- **Write for your future self**: Will you understand this in 6 months? +- **Consider skill levels**: Different readers have different needs +- **Include context**: Why does this matter for the project? +- **Invite feedback**: How can this be improved? + +## Documentation Types + +### 1. **Technical Guides** + +- **Purpose**: Explain how systems work +- **Audience**: Developers, engineers, technical users +- **Focus**: Implementation details, APIs, configurations +- **Examples**: Code snippets, configuration files, diagrams + +### 2. **Process Documentation** + +- **Purpose**: Explain how to accomplish tasks +- **Audience**: Team members, stakeholders +- **Focus**: Step-by-step procedures, workflows +- **Examples**: Checklists, flowcharts, decision trees + +### 3. **Architecture Documents** + +- **Purpose**: Explain system design and structure +- **Audience**: Architects, developers, stakeholders +- **Focus**: High-level design, trade-offs, decisions +- **Examples**: System diagrams, ADRs, design patterns + +### 4. **User Guides** + +- **Purpose**: Help users accomplish goals +- **Audience**: End users, customers +- **Focus**: User workflows, features, troubleshooting +- **Examples**: Screenshots, step-by-step instructions + +## Quality Assurance + +### **Before Publishing Documentation** + +- [ ] **Purpose clear**: Why does this document exist? +- [ ] **Audience defined**: Who is this written for? +- [ ] **Examples included**: Are there practical examples? +- [ ] **Actionable**: Do readers know what to do next? +- [ ] **Maintainable**: Is it easy to keep updated? +- [ ] **Collaborative**: Does it invite team input? + +### **After Publishing Documentation** + +- [ ] **Feedback collected**: Have team members reviewed it? +- [ ] **Usage tracked**: Are people actually using it? +- [ ] **Updates planned**: When will it be reviewed next? +- [ ] **Ownership clear**: Who maintains this document? + +## Implementation Examples + +### Good Documentation Example + +```markdown +# User Authentication System + +**Author**: Matthew Raymer +**Date**: 2025-08-17 +**Status**: 🎯 **ACTIVE** - Production System +**Maintainer**: Security Team + +## Overview + +This document explains how user authentication works in our system, +including login flows, security measures, and troubleshooting steps. + +## Learning Objectives + +After reading this document, you will understand: +- How users log in and authenticate +- What security measures protect user accounts +- How to troubleshoot common authentication issues +- When to escalate security concerns + +## Current Implementation + +### Login Flow + +1. User enters credentials +2. System validates against database +3. JWT token generated and returned +4. Token stored in secure cookie + +### Security Measures + +- Password hashing with bcrypt +- Rate limiting on login attempts +- JWT expiration after 24 hours +- HTTPS enforcement for all auth requests + +## Examples + +### Login Request + +```json +POST /api/auth/login +{ + "email": "user@example.com", + "password": "securepassword123" +} +``` + +### Successful Response + +```json +{ + "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + "expires": "2025-08-18T12:00:00Z" +} +``` + +## Troubleshooting + +### Common Issues + +- **Invalid credentials**: Check email/password combination +- **Token expired**: User needs to log in again +- **Rate limited**: Wait 15 minutes before retrying + +### Escalation Path + +1. Check system logs for errors +2. Verify database connectivity +3. Contact security team if suspicious activity + +## Next Steps + +1. **Test the system**: Try logging in with test credentials +2. **Review security**: Ensure your implementation follows these patterns +3. **Document issues**: Add new troubleshooting steps as you discover them + +## References + +- [JWT Documentation](https://jwt.io/) +- [Security Best Practices](./security-guide.md) +- [API Reference](./api-docs.md) + +--- + +**Last Updated**: 2025-08-17 +**Next Review**: 2025-09-17 +**Stakeholders**: Development Team, Security Team, Product Team + +### Bad Documentation Example + +```markdown +# Authentication + +This document describes the authentication system. + +## Overview + +The system has authentication. + +## Implementation + +Users can log in. + +## Conclusion + +That's how authentication works. +``` + +## Collaboration Points + +### **Code Reviews** + +- Include documentation updates in code review process +- Ensure new features have corresponding documentation +- Validate that examples match actual implementation + +### **Team Reviews** + +- Schedule regular documentation review sessions +- Invite different team members to review content +- Collect feedback on clarity and usefulness + +### **User Testing** + +- Have actual users try to follow documentation +- Observe where they get stuck or confused +- Update content based on real usage patterns + +## Maintenance Schedule + +### **Weekly** + +- Review documentation usage metrics +- Collect feedback from team members +- Plan updates for outdated content + +### **Monthly** + +- Full review of high-priority documents +- Update examples and screenshots +- Validate links and references + +### **Quarterly** + +- Comprehensive review of all documentation +- Identify gaps and opportunities +- Plan major documentation projects + +## Success Metrics + +### **Usage Metrics** + +- **Document views**: How often is content accessed? +- **Time on page**: How long do readers spend? +- **Search queries**: What are people looking for? + +### **Quality Metrics** + +- **Feedback scores**: How do readers rate content? +- **Update frequency**: How often is content refreshed? +- **Maintainer satisfaction**: Are maintainers happy with their docs? + +### **Competence Metrics** + +- **Question reduction**: Fewer basic questions from team? +- **Implementation speed**: Faster feature development? +- **Knowledge transfer**: Better onboarding for new team members? + +## Tools and Resources + +### **Documentation Platforms** + +- **Markdown**: Standard format for technical documentation +- **GitBook**: Collaborative documentation hosting +- **Notion**: Team knowledge management +- **Confluence**: Enterprise documentation platform + +### **Quality Tools** + +- **Markdown linting**: Ensure consistent formatting +- **Link checking**: Validate references and links +- **Spell checking**: Maintain professional appearance +- **Accessibility**: Ensure content is usable by all + +### **Collaboration Tools** + +- **Version control**: Track changes and history +- **Review systems**: Collect feedback and approvals +- **Analytics**: Understand usage patterns +- **Notifications**: Keep team informed of updates + +## Implementation Next Steps + +1. **Review existing documentation**: Apply these principles to current docs +2. **Identify gaps**: What documentation is missing or outdated? +3. **Plan improvements**: Prioritize documentation updates +4. **Establish processes**: Set up regular review and update cycles + +--- + +**Last Updated**: 2025-08-17 +**Version**: 2.0 +**Maintainer**: Matthew Raymer +**Stakeholders**: All Teams +**Next Review**: 2025-09-17 diff --git a/.cursor/rules/docs/markdown.mdc b/.cursor/rules/docs/markdown.mdc new file mode 100644 index 0000000..b0e0c2d --- /dev/null +++ b/.cursor/rules/docs/markdown.mdc @@ -0,0 +1,570 @@ +# Cursor Markdown Ruleset for TimeSafari Documentation + +## Overview + +This ruleset enforces consistent markdown formatting standards across all project +documentation, ensuring readability, maintainability, and compliance with +markdownlint best practices. **LLMs must follow these rules strictly to generate +lint-free documentation.** + +## General Formatting Standards + +### Line Length + +- **Maximum line length**: 80 characters +- **Exception**: Code blocks (JSON, shell, TypeScript, etc.) - no line length + enforcement +- **Rationale**: Ensures readability across different screen sizes and terminal + widths +- **LLM Guidance**: Always count characters and break lines at 80 characters + unless in code blocks + +### Blank Lines + +- **Headings**: Must be surrounded by blank lines above and below +- **Lists**: Must be surrounded by blank lines above and below +- **Code blocks**: Must be surrounded by blank lines above and below +- **Maximum consecutive blank lines**: 1 (no multiple blank lines) +- **File start**: No blank lines at the beginning of the file +- **File end**: Single newline character at the end +- **LLM Guidance**: Always add blank lines around structural elements + +### Whitespace + +- **No trailing spaces**: Remove all trailing whitespace from lines +- **No tabs**: Use spaces for indentation +- **Consistent indentation**: 2 spaces for list items and nested content +- **LLM Guidance**: Use space characters only, never tabs + +## Heading Standards + +### Format + +- **Style**: ATX-style headings (`#`, `##`, `###`, etc.) +- **Case**: Title case for general headings +- **Code references**: Use backticks for file names and technical terms + - ✅ `### Current package.json Scripts` + - ❌ `### Current Package.json Scripts` +- **LLM Guidance**: Always use ATX style, never use Setext style (`===` or `---`) + +### Hierarchy + +- **H1 (#)**: Document title only - **ONE PER DOCUMENT** +- **H2 (##)**: Major sections +- **H3 (###)**: Subsections +- **H4 (####)**: Sub-subsections +- **H5+**: Avoid deeper nesting +- **LLM Guidance**: Start every document with exactly one H1, maintain logical + hierarchy + +### Heading Content Rules + +- **No trailing punctuation**: Avoid periods, colons, etc. at end +- **No duplicate headings**: Each heading must be unique within the document +- **Descriptive but concise**: Headings should clearly describe the section +- **LLM Guidance**: Use action-oriented headings, avoid generic terms like + "Overview" + +## List Standards + +### Unordered Lists + +- **Marker**: Use `-` (hyphen) consistently +- **Indentation**: 2 spaces for nested items +- **Blank lines**: Surround lists with blank lines +- **LLM Guidance**: Always use hyphens, never use asterisks or plus signs + +### Ordered Lists + +- **Format**: `1.`, `2.`, `3.` (sequential numbering) +- **Indentation**: 2 spaces for nested items +- **Blank lines**: Surround lists with blank lines +- **LLM Guidance**: Use sequential numbers, never skip numbers or use random + numbers + +### Task Lists + +- **Format**: `- [ ]` for incomplete, `- [x]` for complete +- **Use case**: Project planning, checklists, implementation tracking +- **LLM Guidance**: Use consistent spacing in brackets `[ ]` not `[ ]` + +## Code Block Standards + +### Fenced Code Blocks + +- **Syntax**: Triple backticks with language specification +- **Languages**: `json`, `bash`, `typescript`, `javascript`, `yaml`, `markdown` +- **Blank lines**: Must be surrounded by blank lines above and below +- **Line length**: No enforcement within code blocks +- **LLM Guidance**: Always specify language, never use generic code blocks + +### Inline Code + +- **Format**: Single backticks for inline code references +- **Use case**: File names, commands, variables, properties +- **LLM Guidance**: Use backticks for any technical term, file path, or command + +## Special Content Standards + +### JSON Examples + +```json +{ + "property": "value", + "nested": { + "property": "value" + } +} +``` + +### Shell Commands + +```bash +# Command with comment +npm run build:web + +# Multi-line command +VITE_GIT_HASH=`git log -1 --pretty=format:%h` \ + vite build --config vite.config.web.mts +``` + +### TypeScript Examples + +```typescript +// Function with JSDoc +/** + * Get environment configuration + * @param env - Environment name + * @returns Environment config object + */ +const getEnvironmentConfig = (env: string) => { + switch (env) { + case 'prod': + return { /* production settings */ }; + default: + return { /* development settings */ }; + } +}; +``` + +## File Structure Standards + +### Document Header + +```markdown +# Document Title + +**Author**: Matthew Raymer +**Date**: YYYY-MM-DD +**Status**: 🎯 **STATUS** - Brief description + +## Overview + +Brief description of the document's purpose and scope. +``` + +### Section Organization + +1. **Overview/Introduction** +2. **Current State Analysis** +3. **Implementation Plan** +4. **Technical Details** +5. **Testing & Validation** +6. **Next Steps** + +## Enhanced Markdownlint Configuration + +### Required Rules (Comprehensive) + +```json +{ + "MD013": { "code_blocks": false, "line_length": 80 }, + "MD012": true, + "MD022": true, + "MD031": true, + "MD032": true, + "MD047": true, + "MD009": true, + "MD024": true, + "MD025": true, + "MD026": { "punctuation": ".,;:!" }, + "MD029": { "style": "ordered" }, + "MD030": { "ul_single": 1, "ol_single": 1, "ul_multi": 1, "ol_multi": 1 }, + "MD033": false, + "MD041": true, + "MD046": { "style": "fenced" }, + "MD018": true, + "MD019": true, + "MD020": true, + "MD021": true, + "MD023": true, + "MD027": true, + "MD028": true, + "MD036": true, + "MD037": true, + "MD038": true, + "MD039": true, + "MD040": true, + "MD042": true, + "MD043": true, + "MD044": true, + "MD045": true +} +``` + +### Rule Explanations (LLM Must Follow) + +- **MD013**: Line length (80 chars max, disabled for code blocks) +- **MD012**: No multiple consecutive blank lines +- **MD022**: Headings must be surrounded by blank lines +- **MD031**: Fenced code blocks must be surrounded by blank lines +- **MD032**: Lists must be surrounded by blank lines +- **MD047**: Files must end with single newline +- **MD009**: No trailing spaces +- **MD024**: No duplicate headings +- **MD025**: Only one H1 per document +- **MD026**: No trailing punctuation in headings +- **MD029**: Ordered list item prefix style +- **MD030**: List item marker styles +- **MD033**: Allow inline HTML (disabled for flexibility) +- **MD041**: First line must be top-level heading +- **MD046**: Code block style (fenced only) +- **MD018**: Heading should have space after hash +- **MD019**: Heading should have space after hash +- **MD020**: Heading should have space after hash +- **MD021**: Heading should have space after hash +- **MD023**: Heading should start at beginning of line +- **MD027**: No multiple spaces after blockquote marker +- **MD028**: No blank line inside blockquote +- **MD036**: No emphasis used for headings +- **MD037**: No spaces inside emphasis markers +- **MD038**: No spaces inside code span markers +- **MD039**: No spaces inside link text +- **MD040**: Fenced code blocks should have language specified +- **MD042**: No empty links +- **MD043**: Required heading structure +- **MD044**: Line length in code blocks +- **MD045**: No images without alt text + +## LLM-Specific Language Guidelines + +### **CRITICAL: LLM Must Follow These Rules** + +#### 1. **Heading Generation** + +- **Always start with H1**: Every document must have exactly one + `# Document Title` +- **Use descriptive headings**: Avoid generic terms like "Overview", + "Details", "Information" +- **Maintain hierarchy**: H2 for major sections, H3 for subsections +- **No duplicate headings**: Each heading must be unique within the document + +#### 2. **List Formatting** + +- **Unordered lists**: Always use `-` (hyphen), never `*` or `+` +- **Ordered lists**: Use sequential numbers `1.`, `2.`, `3.` +- **Consistent spacing**: Always use 2 spaces for indentation +- **Blank lines**: Surround all lists with blank lines + +#### 3. **Code and Technical Content** + +- **Inline code**: Use backticks for any technical term, file path, or command +- **Code blocks**: Always specify language, never use generic blocks +- **File references**: Always use backticks for file names and paths + +#### 4. **Line Length Management** + +- **Count characters**: Ensure no line exceeds 80 characters +- **Break naturally**: Break at word boundaries when possible +- **Code blocks**: No line length enforcement within code blocks + +#### 5. **Whitespace Rules** + +- **No trailing spaces**: Never leave spaces at end of lines +- **No tabs**: Use spaces only for indentation +- **Blank lines**: Use exactly one blank line between sections + +## Enhanced Validation Commands + +### Check Single File + +```bash +npx markdownlint docs/filename.md +``` + +### Check All Documentation + +```bash +npx markdownlint docs/ +``` + +### Check with Custom Config + +```bash +npx markdownlint --config .markdownlint.json docs/ +``` + +### Generate Detailed Report + +```bash +npx markdownlint --config .markdownlint.json --output markdownlint-report.txt docs/ +``` + +### Check Specific Rules + +```bash +npx markdownlint --rules MD013,MD012,MD022,MD024,MD025 docs/ +``` + +### Project-Wide Validation + +```bash +# Check all markdown files in project +find . -name "*.md" -exec npx markdownlint {} \; + +# Check specific directories +npx markdownlint .cursor/rules/ docs/ README.md + +# Check with verbose output +npx markdownlint --verbose docs/ +``` + +### Auto-fix Common Issues + +```bash +# Remove trailing spaces +sed -i 's/[[:space:]]*$//' docs/filename.md + +# Remove multiple blank lines +sed -i '/^$/N;/^\n$/D' docs/filename.md + +# Add newline at end if missing +echo "" >> docs/filename.md + +# Fix heading spacing +sed -i 's/^# /# /g' docs/filename.md +``` + +## Common Patterns + +### Implementation Plans + +```markdown +## Implementation Plan + +### Phase 1: Foundation + +#### 1.1 Component Setup + +- [ ] Create new component file +- [ ] Add basic structure +- [ ] Implement core functionality + +#### 1.2 Configuration + +- [ ] Update configuration files +- [ ] Add environment variables +- [ ] Test configuration loading +``` + +### Status Tracking + +```markdown +**Status**: ✅ **COMPLETE** - All phases finished +**Progress**: 75% (15/20 components) +**Next**: Ready for testing phase +``` + +### Performance Metrics + +```markdown +#### 📊 Performance Metrics +- **Build Time**: 2.3 seconds (50% faster than baseline) +- **Bundle Size**: 1.2MB (30% reduction) +- **Success Rate**: 100% (no failures in 50 builds) +``` + +## Enforcement + +### Pre-commit Hooks + +```bash +#!/bin/bash +# .git/hooks/pre-commit +# Check markdown files before commit + +echo "Running markdownlint..." + +# Get list of staged markdown files +staged_md_files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.md$') + +if [ -n "$staged_md_files" ]; then + echo "Checking markdown files: $staged_md_files" + + # Run markdownlint on staged files + npx markdownlint $staged_md_files + + if [ $? -ne 0 ]; then + echo "❌ Markdown linting failed. Please fix issues before committing." + exit 1 + fi + + echo "✅ Markdown linting passed." +fi +``` + +### CI/CD Integration + +```yaml +# .github/workflows/markdown-lint.yml +name: Markdown Lint + +on: + push: + paths: ['**/*.md'] + pull_request: + paths: ['**/*.md'] + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup Node.js + uses: actions/setup-node@v3 + with: + node-version: '18' + + - name: Install markdownlint + run: npm install -g markdownlint-cli + + - name: Run markdownlint + run: markdownlint --config .markdownlint.json . + + - name: Generate report + run: markdownlint --config .markdownlint.json --output lint-report.txt . + + - name: Upload report + uses: actions/upload-artifact@v3 + with: + name: markdown-lint-report + path: lint-report.txt +``` + +### Team Guidelines + +- All documentation PRs must pass markdownlint +- Use provided templates for new documents +- Follow established patterns for consistency +- **LLM-generated content must pass all linting rules** + +## Templates + +### New Document Template + +```markdown +# Document Title + +**Author**: Matthew Raymer +**Date**: YYYY-MM-DD +**Status**: 🎯 **PLANNING** - Ready for Implementation + +## Overview + +Brief description of the document's purpose and scope. + +## Current State + +Description of current situation or problem. + +## Implementation Plan + +### Phase 1: Foundation + +- [ ] Task 1 +- [ ] Task 2 + +## Next Steps + +1. **Review and approve plan** +2. **Begin implementation** +3. **Test and validate** + +--- + +**Status**: Ready for implementation +**Priority**: Medium +**Estimated Effort**: X days +**Dependencies**: None +**Stakeholders**: Development team +``` + +### Rule File Template + +```markdown +# Rule Name + +**Purpose**: Brief description of what this rule accomplishes + +## Overview + +Detailed explanation of the rule's scope and importance. + +## Implementation + +### Requirements + +- [ ] Requirement 1 +- [ ] Requirement 2 + +### Examples + +#### ✅ Good Example + +```markdown +# Good example content +``` + +#### ❌ Bad Example + +```markdown +# Bad example content +``` + +## Validation + +How to test that this rule is working correctly. + +--- + +**Status**: Active +**Version**: 1.0 +**Maintainer**: Matthew Raymer + +## LLM Quality Assurance Checklist + +### **Before Generating Documentation, LLM Must:** + +- [ ] **Understand line length**: No line over 80 characters +- [ ] **Plan heading structure**: One H1, logical hierarchy, no duplicates +- [ ] **Choose list markers**: Hyphens for unordered, sequential numbers for ordered +- [ ] **Plan code blocks**: Specify languages, add blank lines around +- [ ] **Check whitespace**: No trailing spaces, consistent indentation +- [ ] **Validate structure**: Proper blank line placement + +### **After Generating Documentation, LLM Must:** + +- [ ] **Verify line lengths**: Count characters, break long lines +- [ ] **Check heading hierarchy**: Ensure logical structure +- [ ] **Validate lists**: Consistent markers and spacing +- [ ] **Review code blocks**: Proper language specification +- [ ] **Clean whitespace**: Remove trailing spaces, add proper blank lines +- [ ] **Test with markdownlint**: Ensure all rules pass + +--- + +**Last Updated**: 2025-08-17 +**Version**: 2.0 +**Maintainer**: Matthew Raymer +**LLM Compliance**: Required for all documentation generation diff --git a/.cursor/rules/documentation.mdc b/.cursor/rules/documentation.mdc deleted file mode 100644 index 4b02917..0000000 --- a/.cursor/rules/documentation.mdc +++ /dev/null @@ -1,19 +0,0 @@ ---- -globs: *.md -alwaysApply: false ---- - -INITIAL_PLAN.md is unique to projects built inhouse and must never be deleted. -Maintain traditional files (README, CHANGELOG, BUILDING, etc.) -Any ad hoc files must always be put into docs folder -The docs folder must use sub-folders to classify documents by -There must never be more than seven folders at any sub-folder of the docs tree -Keep documents no more than seven in number for a folder. -If you need more documents than seven, make sub-folders to classify or re-classify documents. -Re-use documents by ammending or editing but always version them in git. -put documentation at the file, classs, and method heads - -Documents themselves must: - -Headings should be surrounded by blank lines -Lists should be surrounded by blank \ No newline at end of file diff --git a/.cursor/rules/features/camera-implementation.mdc b/.cursor/rules/features/camera-implementation.mdc new file mode 100644 index 0000000..e7fef13 --- /dev/null +++ b/.cursor/rules/features/camera-implementation.mdc @@ -0,0 +1,222 @@ +--- +description: +globs: +alwaysApply: false +--- +# Camera Implementation Documentation + +## Overview + +This document describes how camera functionality is implemented across the TimeSafari application. The application uses cameras for two main purposes: + +1. QR Code scanning +2. Photo capture + +## Components + +### QRScannerDialog.vue + +Primary component for QR code scanning in web browsers. + +**Key Features:** + +- Uses `qrcode-stream` for web-based QR scanning +- Supports both front and back cameras +- Provides real-time camera status feedback +- Implements error handling with user-friendly messages +- Includes camera switching functionality + +**Camera Access Flow:** + +1. Checks for camera API availability +2. Enumerates available video devices +3. Requests camera permissions +4. Initializes camera stream with preferred settings +5. Handles various error conditions with specific messages + +### PhotoDialog.vue + +Component for photo capture and selection. + +**Key Features:** + +- Cross-platform photo capture interface +- Image cropping capabilities +- File selection fallback +- Unified interface for different platforms + +## Services + +### QRScanner Services + +#### WebDialogQRScanner + +Web-based implementation of QR scanning. + +**Key Methods:** + +- `checkPermissions()`: Verifies camera permission status +- `requestPermissions()`: Requests camera access +- `isSupported()`: Checks for camera API support +- Handles various error conditions with specific messages + +#### CapacitorQRScanner + +Native implementation using Capacitor's MLKit. + +**Key Features:** + +- Uses `@capacitor-mlkit/barcode-scanning` +- Supports both front and back cameras +- Implements permission management +- Provides continuous scanning capability + +### Platform Services + +#### WebPlatformService + +Web-specific implementation of platform features. + +**Camera Capabilities:** + +- Uses HTML5 file input with capture attribute +- Falls back to file selection if camera unavailable +- Processes captured images for consistent format + +#### CapacitorPlatformService + +Native implementation using Capacitor. + +**Camera Features:** + +- Uses `Camera.getPhoto()` for native camera access +- Supports image editing +- Configures high-quality image capture +- Handles base64 image processing + +#### ElectronPlatformService + +Desktop implementation (currently unimplemented). + +**Status:** + +- Camera functionality not yet implemented +- Planned to use Electron's media APIs + +## Platform-Specific Considerations + +### iOS + +- Requires `NSCameraUsageDescription` in Info.plist +- Supports both front and back cameras +- Implements proper permission handling + +### Android + +- Requires camera permissions in manifest +- Supports both front and back cameras +- Handles permission requests through Capacitor + +### Web + +- Requires HTTPS for camera access +- Implements fallback mechanisms +- Handles browser compatibility issues + +## Error Handling + +### Common Error Scenarios + +1. No camera found +2. Permission denied +3. Camera in use by another application +4. HTTPS required +5. Browser compatibility issues + +### Error Response + +- User-friendly error messages +- Troubleshooting tips +- Clear instructions for resolution +- Platform-specific guidance + +## Security Considerations + +### Permission Management + +- Explicit permission requests +- Permission state tracking +- Graceful handling of denied permissions + +### Data Handling + +- Secure image processing +- Proper cleanup of camera resources +- No persistent storage of camera data + +## Best Practices + +### Camera Access + +1. Always check for camera availability +2. Request permissions explicitly +3. Handle all error conditions +4. Provide clear user feedback +5. Implement proper cleanup + +### Performance + +1. Optimize camera resolution +2. Implement proper resource cleanup +3. Handle camera switching efficiently +4. Manage memory usage + +### User Experience + +1. Clear status indicators +2. Intuitive camera controls +3. Helpful error messages +4. Smooth camera switching +5. Responsive UI feedback + +## Future Improvements + +### Planned Enhancements + +1. Implement Electron camera support +2. Add advanced camera features +3. Improve error handling +4. Enhance user feedback +5. Optimize performance + +### Known Issues + +1. Electron camera implementation pending +2. Some browser compatibility limitations +3. Platform-specific quirks to address + +## Dependencies + +### Key Packages + +- `@capacitor-mlkit/barcode-scanning` +- `qrcode-stream` +- `vue-picture-cropper` +- Platform-specific camera APIs + +## Testing + +### Test Scenarios + +1. Permission handling +2. Camera switching +3. Error conditions +4. Platform compatibility +5. Performance metrics + +### Test Environment + +- Multiple browsers +- iOS and Android devices +- Desktop platforms +- Various network conditions diff --git a/.cursor/rules/general_development.mdc b/.cursor/rules/general_development.mdc deleted file mode 100644 index 3dca909..0000000 --- a/.cursor/rules/general_development.mdc +++ /dev/null @@ -1,3 +0,0 @@ ---- -alwaysApply: true ---- diff --git a/.cursor/rules/logging.mdc b/.cursor/rules/logging.mdc deleted file mode 100644 index 777f159..0000000 --- a/.cursor/rules/logging.mdc +++ /dev/null @@ -1,6 +0,0 @@ ---- -alwaysApply: true ---- -Always use structlog with rich contextual annotation -All logs should go to rsyslog -Logs showing in console should be set to whatever is needed at that time. diff --git a/.cursor/rules/progress_reports.mdc b/.cursor/rules/progress_reports.mdc deleted file mode 100644 index c1ee163..0000000 --- a/.cursor/rules/progress_reports.mdc +++ /dev/null @@ -1,6 +0,0 @@ ---- -alwaysApply: true ---- -progress reports are based on git commit messages and file differences for that day -reports are in conversational style -do not be a bean counter unless otherwise instructed \ No newline at end of file diff --git a/.cursor/rules/research_diagnostic.mdc b/.cursor/rules/research_diagnostic.mdc new file mode 100644 index 0000000..73d1b1c --- /dev/null +++ b/.cursor/rules/research_diagnostic.mdc @@ -0,0 +1,135 @@ +--- +description: Use this workflow when doing **pre-implementation research, defect investigations with uncertain repros, or clarifying system architecture and behaviors**. +alwaysApply: false +--- +```json +{ + "coaching_level": "light", + "socratic_max_questions": 2, + "verbosity": "concise", + "timebox_minutes": null, + "format_enforcement": "strict" +} +``` + +# Research & Diagnostic Workflow (R&D) + +## Purpose + +Provide a **repeatable, evidence-first** workflow to investigate features and +defects **before coding**. Outputs are concise reports, hypotheses, and next +steps—**not** code changes. + +## When to Use + +- Pre-implementation research for new features +- Defect investigations (repros uncertain, user-specific failures) +- Architecture/behavior clarifications (e.g., auth flows, merges, migrations) + +--- + +## Output Contract (strict) + +1) **Objective** — 1–2 lines +2) **System Map (if helpful)** — short diagram or bullet flow (≤8 bullets) +3) **Findings (Evidence-linked)** — bullets; each with file/function refs +4) **Hypotheses & Failure Modes** — short list, each testable +5) **Corrections** — explicit deltas from earlier assumptions (if any) +6) **Diagnostics** — what to check next (logs, DB, env, repro steps) +7) **Risks & Scope** — what could break; affected components +8) **Decision/Next Steps** — what we’ll do, who’s involved, by when +9) **References** — code paths, ADRs, docs +10) **Competence & Collaboration Hooks** — brief, skimmable + +> Keep total length lean. Prefer links and bullets over prose. + +--- + +## Quickstart Template + +Copy/paste and fill: + +```md +# Investigation — + +## Objective + + +## System Map +- +- + +## Findings (Evidence) +- — evidence: `src/path/file.ts:function` (lines X–Y); log snippet/trace id +- — evidence: `...` + +## Hypotheses & Failure Modes +- H1: ; would fail when +- H2: ; watch for + +## Corrections +- Updated: + +## Diagnostics (Next Checks) +- [ ] Repro on +- [ ] Inspect for +- [ ] Capture + +## Risks & Scope +- Impacted: ; Data: ; Users: + +## Decision / Next Steps +- Owner: ; By: (YYYY-MM-DD) +- Action: ; Exit criteria: + +## References +- `src/...` +- ADR: `docs/adr/xxxx-yy-zz-something.md` +- Design: `docs/...` + +## Competence Hooks +- Why this works: <≤3 bullets> +- Common pitfalls: <≤3 bullets> +- Next skill: <≤1 item> +- Teach-back: "" +``` + +--- + +## Evidence Quality Bar + +- **Cite the source** (file:func, line range if possible). +- **Prefer primary evidence** (code, logs) over inference. +- **Disambiguate platform** (Web/Capacitor/Electron) and **state** (migration, auth). +- **Note uncertainty** explicitly. + +--- + +## Collaboration Hooks + +- **Syncs:** 10–15m with QA/Security/Platform owners for high-risk areas. +- **ADR:** Record major decisions; link here. +- **Review:** Share repro + diagnostics checklist in PR/issue. + +--- + +## Self-Check (model, before responding) + +- [ ] Output matches the **Output Contract** sections. +- [ ] Each claim has **evidence** or **uncertainty** is flagged. +- [ ] Hypotheses are testable; diagnostics are actionable. +- [ ] Competence + collaboration hooks present (≤120 words total). +- [ ] Respect toggles; keep it concise. + +--- + +## Optional Globs (examples) + +> Uncomment `globs` in the header if you want auto-attach behavior. + +- `src/platforms/**`, `src/services/**` — attach during service/feature investigations +- `docs/adr/**` — attach when editing ADRs + +## Referenced Files + +- Consider including templates as context: `@adr_template.md`, `@investigation_report_example.md` diff --git a/.cursor/rules/time.mdc b/.cursor/rules/time.mdc index 3534990..f7376d9 100644 --- a/.cursor/rules/time.mdc +++ b/.cursor/rules/time.mdc @@ -1,5 +1,284 @@ +# Time Handling in Development Workflow + +This guide establishes **how time should be referenced and used** across the development workflow. +It is not tied to any one project, but applies to **all feature development, issue investigations, ADRs, and documentation**. + --- -alwaysApply: true + +## 1. General Principles + +- **Explicit over relative**: Always prefer absolute dates (`2025-08-17`) over relative references like "last week." +- **ISO 8601 Standard**: Use `YYYY-MM-DD` format for all date references in docs, issues, ADRs, and commits. +- **Time zones**: Default to **UTC** unless explicitly tied to user-facing behavior. +- **Precision**: Only specify as much precision as needed (date vs. datetime vs. timestamp). +- **Consistency**: Align time references across ADRs, commits, and investigation reports. + --- -Eagerly query the local system for time in UTC -Use local system time for all time sense, queries, and calculations involving time. + +## 2. In Documentation & ADRs + +- Record decision dates using **absolute ISO dates**. +- For ongoing timelines, state start and end explicitly (e.g., `2025-08-01` → `2025-08-17`). +- Avoid ambiguous terms like *recently*, *last month*, or *soon*. +- For time-based experiments (e.g., A/B tests), always include: + - Start date + - Expected duration + - Review date checkpoint + +--- + +## 3. In Code & Commits + +- Use **UTC timestamps** in logs, DB migrations, and serialized formats. +- In commits, link changes to **date-bound ADRs or investigation docs**. +- For migrations, include both **applied date** and **intended version window**. +- Use constants for known fixed dates; avoid hardcoding arbitrary strings. + +--- + +## 4. In Investigations & Research + +- Capture **when** an issue occurred (absolute time or version tag). +- When describing failures: note whether they are **time-sensitive** (e.g., after migrations, cache expirations). +- Record diagnostic timelines in ISO format (not relative). +- For performance regressions, annotate both **baseline timeframe** and **measurement timeframe**. + +--- + +## 5. Collaboration Hooks + +- During reviews, verify **time references are clear, absolute, and standardized**. +- In syncs, reframe relative terms ("this week") into shared absolute references. +- Tag ADRs with both **date created** and **review by** checkpoints. + +--- + +## 6. Self-Check Before Submitting + +- [ ] Did I check the time using the **developer's actual system time and timezone**? +- [ ] Am I using absolute ISO dates? +- [ ] Is UTC assumed unless specified otherwise? +- [ ] Did I avoid ambiguous relative terms? +- [ ] If duration matters, did I specify both start and end? +- [ ] For future work, did I include a review/revisit date? + +--- + +## 7. Real-Time Context in Developer Interactions + +- The model must always resolve **"current time"** using the **developer's actual system time and timezone**. +- When generating timestamps (e.g., in investigation logs, ADRs, or examples), the model should: + - Use the **developer's current local time** by default. + - Indicate the timezone explicitly (e.g., `2025-08-17T10:32-05:00`). + - Optionally provide UTC alongside if context requires cross-team clarity. +- When interpreting relative terms like *now*, *today*, *last week*: + - Resolve them against the **developer's current time**. + - Convert them into **absolute ISO-8601 values** in the output. + +## 7.1. LLM Time Checking Instructions + +**CRITICAL**: The LLM must actively query the system for current time rather than assuming or inventing times. + +### How to Check Current Time + +#### 1. **Query System Time (Required)** +- **Always start** by querying the current system time using available tools +- **Never assume** what the current time is +- **Never use** placeholder values like "current time" or "now" + +#### 2. **Available Time Query Methods** +- **System Clock**: Use `date` command or equivalent system time function +- **Programming Language**: Use language-specific time functions (e.g., `Date.now()`, `datetime.now()`) +- **Environment Variables**: Check for time-related environment variables +- **API Calls**: Use time service APIs if available + +#### 3. **Required Time Information** +When querying time, always obtain: +- **Current Date**: YYYY-MM-DD format +- **Current Time**: HH:MM:SS format (24-hour) +- **Timezone**: Current system timezone or UTC offset +- **UTC Equivalent**: Convert local time to UTC for cross-team clarity + +#### 4. **Time Query Examples** + +```bash +# Example: Query system time +$ date +# Expected output: Mon Aug 17 10:32:45 EDT 2025 + +# Example: Query UTC time +$ date -u +# Expected output: Mon Aug 17 14:32:45 UTC 2025 +``` + +```python +# Example: Python time query +import datetime +current_time = datetime.datetime.now() +utc_time = datetime.datetime.utcnow() +print(f"Local: {current_time}") +print(f"UTC: {utc_time}") +``` + +```javascript +// Example: JavaScript time query +const now = new Date(); +const utc = new Date().toISOString(); +console.log(`Local: ${now}`); +console.log(`UTC: ${utc}`); +``` + +#### 5. **LLM Time Checking Workflow** +1. **Query**: Actively query system for current time +2. **Validate**: Confirm time data is reasonable and current +3. **Format**: Convert to ISO 8601 format +4. **Context**: Provide both local and UTC times when helpful +5. **Document**: Show the source of time information + +#### 6. **Error Handling for Time Queries** +- **If time query fails**: Ask user for current time or use "unknown time" with explanation +- **If timezone unclear**: Default to UTC and ask for clarification +- **If time seems wrong**: Verify with user before proceeding +- **Always log**: Record when and how time was obtained + +#### 7. **Time Query Verification** +Before using queried time, verify: +- [ ] Time is recent (within last few minutes) +- [ ] Timezone information is available +- [ ] UTC conversion is accurate +- [ ] Format follows ISO 8601 standard + +--- + +## 8. Model Behavior Rules + +- **Never invent a "fake now"**: All "current time" references must come from the real system clock available at runtime. +- **Check developer time zone**: If ambiguous, ask for clarification (e.g., "Should I use UTC or your local timezone?"). +- **Format for clarity**: + - Local time: `YYYY-MM-DDTHH:mm±hh:mm` + - UTC equivalent (if needed): `YYYY-MM-DDTHH:mmZ` + +--- + +## 9. Examples + +### Good +- "Feature flag rollout started on `2025-08-01` and will be reviewed on `2025-08-21`." +- "Migration applied on `2025-07-15T14:00Z`." +- "Issue reproduced on `2025-08-17T09:00-05:00 (local)` / `2025-08-17T14:00Z (UTC)`." + +### Bad +- "Feature flag rolled out last week." +- "Migration applied recently." +- "Now is August, so we assume this was last month." + +### More Examples + +#### Issue Reports +- ✅ **Good**: "User reported login failure at `2025-08-17T14:30:00Z`. Issue persisted until `2025-08-17T15:45:00Z`." +- ❌ **Bad**: "User reported login failure earlier today. Issue lasted for a while." + +#### Release Planning +- ✅ **Good**: "Feature X scheduled for release on `2025-08-25`. Testing window: `2025-08-20` to `2025-08-24`." +- ❌ **Bad**: "Feature X will be released next week after testing." + +#### Performance Monitoring +- ✅ **Good**: "Baseline performance measured on `2025-08-10T09:00:00Z`. Regression detected on `2025-08-15T14:00:00Z`." +- ❌ **Bad**: "Performance was good last week but got worse this week." + +--- + +## 10. Technical Implementation Notes + +### UTC Storage Principle +- **Store all timestamps in UTC** in databases, logs, and serialized formats +- **Convert to local time only for user display** +- **Use ISO 8601 format** for all storage: `YYYY-MM-DDTHH:mm:ss.sssZ` + +### Common Implementation Patterns + +#### Database Storage +```sql +-- ✅ Good: Store in UTC +created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, +updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + +-- ❌ Bad: Store in local time +created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, +updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +``` + +#### API Responses +```json +// ✅ Good: Include both UTC and local time +{ + "eventTime": "2025-08-17T14:00:00Z", + "localTime": "2025-08-17T10:00:00-04:00", + "timezone": "America/New_York" +} + +// ❌ Bad: Only local time +{ + "eventTime": "2025-08-17T10:00:00-04:00" +} +``` + +#### Logging +```python +# ✅ Good: Log in UTC with timezone info +logger.info(f"User action at {datetime.utcnow().isoformat()}Z (UTC)") + +# ❌ Bad: Log in local time +logger.info(f"User action at {datetime.now()}") +``` + +### Timezone Handling Best Practices + +#### 1. Always Store Timezone Information +- Include IANA timezone identifier (e.g., `America/New_York`) +- Store UTC offset at time of creation +- Handle daylight saving time transitions automatically + +#### 2. User Display Considerations +- Convert UTC to user's preferred timezone +- Show timezone abbreviation when helpful +- Use relative time for recent events ("2 hours ago") + +#### 3. Edge Case Handling +- **Daylight Saving Time**: Use timezone-aware libraries +- **Leap Seconds**: Handle gracefully (rare but important) +- **Invalid Times**: Validate before processing + +### Common Mistakes to Avoid + +#### 1. Timezone Confusion +- ❌ **Don't**: Assume server timezone is user timezone +- ✅ **Do**: Always convert UTC to user's local time for display + +#### 2. Format Inconsistency +- ❌ **Don't**: Mix different time formats in the same system +- ✅ **Do**: Standardize on ISO 8601 for all storage + +#### 3. Relative Time References +- ❌ **Don't**: Use relative terms in persistent storage +- ✅ **Do**: Convert relative terms to absolute timestamps immediately + +--- + +## References + +- [ISO 8601 Date and Time Standard](https://en.wikipedia.org/wiki/ISO_8601) +- [IANA Timezone Database](https://www.iana.org/time-zones) +- [ADR Template](./adr_template.md) +- [Research & Diagnostic Workflow](./research_diagnostic.mdc) + +--- + +**Rule of Thumb:** +> Every time reference in development artifacts should be **clear in 6 months without context**, and aligned to the **developer's actual current time**. + +**Technical Rule of Thumb:** +> **Store in UTC, display in local time, always include timezone context.** + +**Rule of Thumb:** +> Every time reference in development artifacts should be **clear in 6 months without context**, and aligned to the **developer’s actual current time**. diff --git a/.cursor/rules/version_control.mdc b/.cursor/rules/version_control.mdc deleted file mode 100644 index 212e000..0000000 --- a/.cursor/rules/version_control.mdc +++ /dev/null @@ -1,7 +0,0 @@ ---- -alwaysApply: true ---- -use git -commit messages are based on unstaged files and the chnages made to them -present proposed messages for approval -get approval before staging or commmiting diff --git a/.cursor/rules/versioning.mdc b/.cursor/rules/versioning.mdc deleted file mode 100644 index 892855e..0000000 --- a/.cursor/rules/versioning.mdc +++ /dev/null @@ -1,7 +0,0 @@ ---- -alwaysApply: true ---- - -Semantic Versioning: Follows MAJOR.MINOR.PATCH format -Centralized Management: Single source of truth for all version information -Git Integration: Automatic commit hash detection diff --git a/.cursor/rules/workflow/version_control.mdc b/.cursor/rules/workflow/version_control.mdc new file mode 100644 index 0000000..7635fb6 --- /dev/null +++ b/.cursor/rules/workflow/version_control.mdc @@ -0,0 +1,122 @@ +--- +alwaysApply: true +--- +# Directive: Peaceful Co-Existence with Developers + +## 1) Version-Control Ownership + +* **MUST NOT** run `git add`, `git commit`, or any write action. +* **MUST** leave staging/committing to the developer. + +## 2) Source of Truth for Commit Text + +* **MUST** derive messages **only** from: + + * files **staged** for commit (primary), and + * files **awaiting staging** (context). +* **MUST** use the **diffs** to inform content. +* **MUST NOT** invent changes or imply work not present in diffs. + +## 3) Mandatory Preview Flow + +* **ALWAYS** present, before any real commit: + + * file list + brief per-file notes, + * a **draft commit message** (copy-paste ready), + * nothing auto-applied. + +--- + +# Commit Message Format (Normative) + +## A. Subject Line (required) + +``` +(): +``` + +* **type** (lowercase, Conventional Commits): `feat|fix|refactor|perf|docs|test|build|chore|ci|revert` +* **scope**: optional module/package/area (e.g., `api`, `ui/login`, `db`) +* **!**: include when a breaking change is introduced +* **summary**: imperative mood, ≤ 72 chars, no trailing period + +**Examples** + +* `fix(api): handle null token in refresh path` +* `feat(ui/login)!: require OTP after 3 failed attempts` + +## B. Body (optional, when it adds non-obvious value) + +* One blank line after subject. +* Wrap at \~72 chars. +* Explain **what** and **why**, not line-by-line “how”. +* Include brief notes like tests passing or TS/lint issues resolved **only if material**. + +**Body checklist** + +* [ ] Problem/symptom being addressed +* [ ] High-level approach or rationale +* [ ] Risks, tradeoffs, or follow-ups (if any) + +## C. Footer (optional) + +* Issue refs: `Closes #123`, `Refs #456` +* Breaking change (alternative to `!`): + `BREAKING CHANGE: ` +* Authors: `Co-authored-by: Name ` +* Security: `CVE-XXXX-YYYY: ` (if applicable) + +--- + +## Content Guidance + +### Include (when relevant) + +* Specific fixes/features delivered +* Symptoms/problems fixed +* Brief note that tests passed or TS/lint errors resolved + +### Avoid + +* Vague: *improved, enhanced, better* +* Trivialities: tiny docs, one-liners, pure lint cleanups (separate, focused commits if needed) +* Redundancy: generic blurbs repeated across files +* Multi-purpose dumps: keep commits **narrow and focused** +* Long explanations that good inline code comments already cover + +**Guiding Principle:** Let code and inline docs speak. Use commits to highlight what isn’t obvious. + +--- + +# Copy-Paste Templates + +## Minimal (no body) + +```text +(): +``` + +## Standard (with body & footer) + +```text +(): + + + + + +Closes # +BREAKING CHANGE: +Co-authored-by: +``` + +--- + +# Assistant Output Checklist (before showing the draft) + +* [ ] List changed files + 1–2 line notes per file +* [ ] Provide **one** focused draft message (subject/body/footer) +* [ ] Subject ≤ 72 chars, imperative mood, correct `type(scope)!` syntax +* [ ] Body only if it adds non-obvious value +* [ ] No invented changes; aligns strictly with diffs +* [ ] Render as a single copy-paste block for the developer diff --git a/.gradle/8.13/fileHashes/fileHashes.bin b/.gradle/8.13/fileHashes/fileHashes.bin index fc2d3e8..be7368c 100644 Binary files a/.gradle/8.13/fileHashes/fileHashes.bin and b/.gradle/8.13/fileHashes/fileHashes.bin differ diff --git a/.gradle/8.13/fileHashes/fileHashes.lock b/.gradle/8.13/fileHashes/fileHashes.lock index 5e224e2..07f1143 100644 Binary files a/.gradle/8.13/fileHashes/fileHashes.lock and b/.gradle/8.13/fileHashes/fileHashes.lock differ diff --git a/.gradle/nb-cache/daily-notification-plugin-650793354/project-info.ser b/.gradle/nb-cache/daily-notification-plugin-650793354/project-info.ser new file mode 100644 index 0000000..1ce5e20 Binary files /dev/null and b/.gradle/nb-cache/daily-notification-plugin-650793354/project-info.ser differ diff --git a/.gradle/nb-cache/lib-787053696/project-info.ser b/.gradle/nb-cache/lib-787053696/project-info.ser new file mode 100644 index 0000000..fe118e9 Binary files /dev/null and b/.gradle/nb-cache/lib-787053696/project-info.ser differ diff --git a/.gradle/nb-cache/subprojects.ser b/.gradle/nb-cache/subprojects.ser new file mode 100644 index 0000000..9ddac02 Binary files /dev/null and b/.gradle/nb-cache/subprojects.ser differ diff --git a/.gradle/nb-cache/trust/CF37DF473B63082CB422CF366D6DE6262AC1AECC238F3058A752FA9D899EB24E b/.gradle/nb-cache/trust/CF37DF473B63082CB422CF366D6DE6262AC1AECC238F3058A752FA9D899EB24E new file mode 100644 index 0000000..b5d1620 --- /dev/null +++ b/.gradle/nb-cache/trust/CF37DF473B63082CB422CF366D6DE6262AC1AECC238F3058A752FA9D899EB24E @@ -0,0 +1 @@ +DB3AE51713EFB84E05BC35EBACB3258E9428C8277A536E2102ACFF8EAB42145B