diff --git a/.cursor/rules/adr_template.mdc b/.cursor/rules/adr_template.mdc new file mode 100644 index 00000000..ce75d9ab --- /dev/null +++ b/.cursor/rules/adr_template.mdc @@ -0,0 +1,65 @@ +# ADR Template + +## ADR-XXXX-YY-ZZ: [Short Title] + +**Date:** YYYY-MM-DD +**Status:** [PROPOSED | ACCEPTED | REJECTED | DEPRECATED | SUPERSEDED] +**Deciders:** [List of decision makers] +**Technical Story:** [Link to issue/PR if applicable] + +## Context + +[Describe the forces at play, including technological, political, social, and +project local. These forces are probably in tension, and should be called out as +such. The language in this section is value-neutral. It is simply describing facts.] + +## Decision + +[Describe our response to these forces. We will use the past tense ("We will...").] + +## Consequences + +### Positive +- [List positive consequences] + +### Negative +- [List negative consequences or trade-offs] + +### Neutral +- [List neutral consequences or notes] + +## Alternatives Considered + +- **Alternative 1:** [Description] - [Why rejected] +- **Alternative 2:** [Description] - [Why rejected] +- **Alternative 3:** [Description] - [Why rejected] + +## Implementation Notes + +[Any specific implementation details, migration steps, or technical considerations] + +## References + +- [Link to relevant documentation] +- [Link to related ADRs] +- [Link to external resources] + +## Related Decisions + +- [List related ADRs or decisions] + +--- + +## Usage Guidelines + +1. **Copy this template** for new ADRs +2. **Number sequentially** (ADR-001, ADR-002, etc.) +3. **Use descriptive titles** that clearly indicate the decision +4. **Include all stakeholders** in the deciders list +5. **Link to related issues** and documentation +6. **Update status** as decisions evolve +7. **Store in** `doc/architecture-decisions/` directory +description: +globs: +alwaysApply: false +--- diff --git a/.cursor/rules/app/architectural_decision_record.mdc b/.cursor/rules/app/architectural_decision_record.mdc new file mode 100644 index 00000000..91cd8e8d --- /dev/null +++ b/.cursor/rules/app/architectural_decision_record.mdc @@ -0,0 +1,352 @@ +--- +description: when you need to understand the system architecture or make changes that impact the system architecture +alwaysApply: false +--- +# TimeSafari Cross-Platform Architecture Guide + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Architecture guidelines + +## 1. Platform Support Matrix + +| Feature | Web (PWA) | Capacitor (Mobile) | Electron (Desktop) | +|---------|-----------|--------------------|-------------------| +| QR Code Scanning | WebInlineQRScanner | @capacitor-mlkit/barcode-scanning | Not Implemented | +| Deep Linking | URL Parameters | App URL Open Events | Not Implemented | +| File System | Limited (Browser API) | Capacitor Filesystem | Electron fs | +| Camera Access | MediaDevices API | Capacitor Camera | Not Implemented | +| Platform Detection | Web APIs | Capacitor.isNativePlatform() | process.env checks | + +## 2. Project Structure + +### Core Directories + +``` +src/ +β”œβ”€β”€ components/ # Vue components +β”œβ”€β”€ services/ # Platform services and business logic +β”œβ”€β”€ views/ # Page components +β”œβ”€β”€ router/ # Vue router configuration +β”œβ”€β”€ types/ # TypeScript type definitions +β”œβ”€β”€ utils/ # Utility functions +β”œβ”€β”€ lib/ # Core libraries +β”œβ”€β”€ platforms/ # Platform-specific implementations +β”œβ”€β”€ electron/ # Electron-specific code +β”œβ”€β”€ constants/ # Application constants +β”œβ”€β”€ db/ # Database related code +β”œβ”€β”€ interfaces/ # TypeScript interfaces +└── assets/ # Static assets +``` + +### Entry Points + +- `main.ts` β†’ Base entry +- `main.common.ts` β†’ Shared init +- `main.capacitor.ts` β†’ Mobile entry +- `main.electron.ts` β†’ Electron entry +- `main.web.ts` β†’ Web entry + +## 3. Service Architecture + +### Service Organization + +```tree +services/ +β”œβ”€β”€ QRScanner/ +β”‚ β”œβ”€β”€ WebInlineQRScanner.ts +β”‚ └── interfaces.ts +β”œβ”€β”€ platforms/ +β”‚ β”œβ”€β”€ WebPlatformService.ts +β”‚ β”œβ”€β”€ CapacitorPlatformService.ts +β”‚ └── ElectronPlatformService.ts +└── factory/ + └── PlatformServiceFactory.ts +``` + +### Factory Pattern + +Use a **singleton factory** to select platform services via +`process.env.VITE_PLATFORM`. + +## 4. Feature Guidelines + +### QR Code Scanning + +- Define `QRScannerService` interface. +- Implement platform-specific classes (`WebInlineQRScanner`, Capacitor, + etc). +- Provide `addListener` and `onStream` hooks for composability. + +### Deep Linking + +- URL format: `timesafari://[/][?query=value]` +- Web: `router.beforeEach` β†’ parse query +- Capacitor: `App.addListener("appUrlOpen", …)` + +## 5. Build Process + +- `vite.config.common.mts` β†’ shared config +- Platform configs: `vite.config.web.mts`, `.capacitor.mts`, + `.electron.mts` +- Use `process.env.VITE_PLATFORM` for conditional loading. + +```bash +npm run build:web +npm run build:capacitor +npm run build:electron +``` + +## 6. Testing Strategy + +- **Unit tests** for services. +- **Playwright** for Web + Capacitor: + - `playwright.config-local.ts` includes web + Pixel 5. +- **Electron tests**: add `spectron` or Playwright-Electron. +- Mark tests with platform tags: + + ```ts + test.skip(!process.env.MOBILE_TEST, "Mobile-only test"); + ``` + +> πŸ”— **Human Hook:** Before merging new tests, hold a short sync (≀15 +> min) with QA to align on coverage and flaky test risks. + +## 7. Error Handling + +- Global Vue error handler β†’ logs with component name. +- Platform-specific wrappers log API errors with platform prefix + (`[Capacitor API Error]`, etc). +- Use structured logging (not `console.log`). + +## 8. Best Practices + +- Keep platform code **isolated** in `platforms/`. +- Always define a **shared interface** first. +- Use feature detection, not platform detection, when possible. +- Dependency injection for services β†’ improves testability. +- Maintain **Competence Hooks** in PRs (2–3 prompts for dev + discussion). + +## 9. Dependency Management + +- Key deps: `@capacitor/core`, `electron`, `vue`. +- Use conditional `import()` for platform-specific libs. + +## 10. Security Considerations + +- **Permissions**: Always check + request gracefully. +- **Storage**: Secure storage for sensitive data; encrypt when possible. +- **Audits**: Schedule quarterly security reviews. + +## 11. ADR Process + +- All major architecture choices β†’ log in `doc/adr/`. +- Use ADR template with Context, Decision, Consequences, Status. +- Link related ADRs in PR descriptions. + +> πŸ”— **Human Hook:** When proposing a new ADR, schedule a 30-min +> design sync for discussion, not just async review. + +## 12. Collaboration Hooks + +- **QR features**: Sync with Security before merging β†’ permissions & + privacy. +- **New platform builds**: Demo in team meeting β†’ confirm UX + differences. +- **Critical ADRs**: Present in guild or architecture review. + +## Self-Check + +- [ ] Does this feature implement a shared interface? +- [ ] Are fallbacks + errors handled gracefully? +- [ ] Have relevant ADRs been updated/linked? +- [ ] Did I add competence hooks or prompts for the team? +- [ ] Was human interaction (sync/review/demo) scheduled? + +--- + +**Status**: Active architecture guidelines +**Priority**: High +**Estimated Effort**: Ongoing reference +**Dependencies**: Vue 3, Capacitor, Electron, Vite +**Stakeholders**: Development team, Architecture team + +- [ ] Are fallbacks + errors handled gracefully? +- [ ] Have relevant ADRs been updated/linked? +- [ ] Did I add competence hooks or prompts for the team? +- [ ] Was human interaction (sync/review/demo) scheduled? +# TimeSafari Cross-Platform Architecture Guide + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Architecture guidelines + +## 1. Platform Support Matrix + +| Feature | Web (PWA) | Capacitor (Mobile) | Electron (Desktop) | +|---------|-----------|--------------------|-------------------| +| QR Code Scanning | WebInlineQRScanner | @capacitor-mlkit/barcode-scanning | Not Implemented | +| Deep Linking | URL Parameters | App URL Open Events | Not Implemented | +| File System | Limited (Browser API) | Capacitor Filesystem | Electron fs | +| Camera Access | MediaDevices API | Capacitor Camera | Not Implemented | +| Platform Detection | Web APIs | Capacitor.isNativePlatform() | process.env checks | + +## 2. Project Structure + +### Core Directories + +``` +src/ +β”œβ”€β”€ components/ # Vue components +β”œβ”€β”€ services/ # Platform services and business logic +β”œβ”€β”€ views/ # Page components +β”œβ”€β”€ router/ # Vue router configuration +β”œβ”€β”€ types/ # TypeScript type definitions +β”œβ”€β”€ utils/ # Utility functions +β”œβ”€β”€ lib/ # Core libraries +β”œβ”€β”€ platforms/ # Platform-specific implementations +β”œβ”€β”€ electron/ # Electron-specific code +β”œβ”€β”€ constants/ # Application constants +β”œβ”€β”€ db/ # Database related code +β”œβ”€β”€ interfaces/ # TypeScript interfaces +└── assets/ # Static assets +``` + +### Entry Points + +- `main.ts` β†’ Base entry +- `main.common.ts` β†’ Shared init +- `main.capacitor.ts` β†’ Mobile entry +- `main.electron.ts` β†’ Electron entry +- `main.web.ts` β†’ Web entry + +## 3. Service Architecture + +### Service Organization + +```tree +services/ +β”œβ”€β”€ QRScanner/ +β”‚ β”œβ”€β”€ WebInlineQRScanner.ts +β”‚ └── interfaces.ts +β”œβ”€β”€ platforms/ +β”‚ β”œβ”€β”€ WebPlatformService.ts +β”‚ β”œβ”€β”€ CapacitorPlatformService.ts +β”‚ └── ElectronPlatformService.ts +└── factory/ + └── PlatformServiceFactory.ts +``` + +### Factory Pattern + +Use a **singleton factory** to select platform services via +`process.env.VITE_PLATFORM`. + +## 4. Feature Guidelines + +### QR Code Scanning + +- Define `QRScannerService` interface. +- Implement platform-specific classes (`WebInlineQRScanner`, Capacitor, + etc). +- Provide `addListener` and `onStream` hooks for composability. + +### Deep Linking + +- URL format: `timesafari://[/][?query=value]` +- Web: `router.beforeEach` β†’ parse query +- Capacitor: `App.addListener("appUrlOpen", …)` + +## 5. Build Process + +- `vite.config.common.mts` β†’ shared config +- Platform configs: `vite.config.web.mts`, `.capacitor.mts`, + `.electron.mts` +- Use `process.env.VITE_PLATFORM` for conditional loading. + +```bash +npm run build:web +npm run build:capacitor +npm run build:electron +``` + +## 6. Testing Strategy + +- **Unit tests** for services. +- **Playwright** for Web + Capacitor: + - `playwright.config-local.ts` includes web + Pixel 5. +- **Electron tests**: add `spectron` or Playwright-Electron. +- Mark tests with platform tags: + + ```ts + test.skip(!process.env.MOBILE_TEST, "Mobile-only test"); + ``` + +> πŸ”— **Human Hook:** Before merging new tests, hold a short sync (≀15 +> min) with QA to align on coverage and flaky test risks. + +## 7. Error Handling + +- Global Vue error handler β†’ logs with component name. +- Platform-specific wrappers log API errors with platform prefix + (`[Capacitor API Error]`, etc). +- Use structured logging (not `console.log`). + +## 8. Best Practices + +- Keep platform code **isolated** in `platforms/`. +- Always define a **shared interface** first. +- Use feature detection, not platform detection, when possible. +- Dependency injection for services β†’ improves testability. +- Maintain **Competence Hooks** in PRs (2–3 prompts for dev + discussion). + +## 9. Dependency Management + +- Key deps: `@capacitor/core`, `electron`, `vue`. +- Use conditional `import()` for platform-specific libs. + +## 10. Security Considerations + +- **Permissions**: Always check + request gracefully. +- **Storage**: Secure storage for sensitive data; encrypt when possible. +- **Audits**: Schedule quarterly security reviews. + +## 11. ADR Process + +- All major architecture choices β†’ log in `doc/adr/`. +- Use ADR template with Context, Decision, Consequences, Status. +- Link related ADRs in PR descriptions. + +> πŸ”— **Human Hook:** When proposing a new ADR, schedule a 30-min +> design sync for discussion, not just async review. + +## 12. Collaboration Hooks + +- **QR features**: Sync with Security before merging β†’ permissions & + privacy. +- **New platform builds**: Demo in team meeting β†’ confirm UX + differences. +- **Critical ADRs**: Present in guild or architecture review. + +## Self-Check + +- [ ] Does this feature implement a shared interface? +- [ ] Are fallbacks + errors handled gracefully? +- [ ] Have relevant ADRs been updated/linked? +- [ ] Did I add competence hooks or prompts for the team? +- [ ] Was human interaction (sync/review/demo) scheduled? + +--- + +**Status**: Active architecture guidelines +**Priority**: High +**Estimated Effort**: Ongoing reference +**Dependencies**: Vue 3, Capacitor, Electron, Vite +**Stakeholders**: Development team, Architecture team + +- [ ] Are fallbacks + errors handled gracefully? +- [ ] Have relevant ADRs been updated/linked? +- [ ] Did I add competence hooks or prompts for the team? +- [ ] Was human interaction (sync/review/demo) scheduled? diff --git a/.cursor/rules/app/timesafari.mdc b/.cursor/rules/app/timesafari.mdc new file mode 100644 index 00000000..ccc37996 --- /dev/null +++ b/.cursor/rules/app/timesafari.mdc @@ -0,0 +1,181 @@ +# Time Safari Context + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Core application context + +## Project Overview + +Time Safari is an application designed to foster community building through +gifts, gratitude, and collaborative projects. The app makes it easy and +intuitive for users of any age and capability to recognize contributions, +build trust networks, and organize collective action. It is built on services +that preserve privacy and data sovereignty. + +## Core Goals + +1. **Connect**: Make it easy, rewarding, and non-threatening for people to + connect with others who have similar interests, and to initiate activities + together. + +2. **Reveal**: Widely advertise the great support and rewards that are being + given and accepted freely, especially non-monetary ones, showing the impact + gifts make in people's lives. + +## Technical Foundation + +### Architecture + +- **Privacy-preserving claims architecture** via endorser.ch +- **Decentralized Identifiers (DIDs)**: User identities based on + public/private key pairs stored on devices +- **Cryptographic Verification**: All claims and confirmations are + cryptographically signed +- **User-Controlled Visibility**: Users explicitly control who can see their + identifiers and data +- **Cross-Platform**: Web (PWA), Mobile (Capacitor), Desktop (Electron) + +### Current Database State + +- **Database**: SQLite via Absurd SQL (browser) and native SQLite + (mobile/desktop) +- **Legacy Support**: IndexedDB (Dexie) for backward compatibility +- **Status**: Modern database architecture fully implemented + +### Core Technologies + +- **Frontend**: Vue 3 + TypeScript + vue-facing-decorator +- **Styling**: TailwindCSS +- **Build**: Vite with platform-specific configs +- **Testing**: Playwright E2E, Jest unit tests +- **Database**: SQLite (Absurd SQL in browser), IndexedDB (legacy) +- **State**: Pinia stores +- **Platform Services**: Abstracted behind interfaces with factory pattern + +## Development Principles + +### Code Organization + +- **Platform Services**: Abstract platform-specific code behind interfaces +- **Service Factory**: Use `PlatformServiceFactory` for platform selection +- **Type Safety**: Strict TypeScript, no `any` types, use type guards +- **Modern Architecture**: Use current platform service patterns + +### Architecture Patterns + +- **Dependency Injection**: Services injected via mixins and factory pattern +- **Interface Segregation**: Small, focused interfaces over large ones +- **Composition over Inheritance**: Prefer mixins and composition +- **Single Responsibility**: Each component/service has one clear purpose + +### Testing Strategy + +- **E2E**: Playwright for critical user journeys +- **Unit**: Jest with F.I.R.S.T. principles +- **Platform Coverage**: Web + Capacitor (Pixel 5) in CI +- **Quality Assurance**: Comprehensive testing and validation + +## Current Development Focus + +### Active Development + +- **Feature Development**: Build new functionality using modern platform + services +- **Performance Optimization**: Improve app performance and user experience +- **Platform Enhancement**: Leverage platform-specific capabilities +- **Code Quality**: Maintain high standards and best practices + +### Development Metrics + +- **Code Quality**: High standards maintained across all platforms +- **Performance**: Optimized for all target devices +- **Testing**: Comprehensive coverage maintained +- **User Experience**: Focus on intuitive, accessible interfaces + +## Platform-Specific Considerations + +### Web (PWA) + +- **QR Scanning**: WebInlineQRScanner +- **Deep Linking**: URL parameters +- **File System**: Limited browser APIs +- **Build**: `npm run build:web` (development build) + +### Mobile (Capacitor) + +- **QR Scanning**: @capacitor-mlkit/barcode-scanning +- **Deep Linking**: App URL open events +- **File System**: Capacitor Filesystem +- **Build**: `npm run build:capacitor` + +### Desktop (Electron) + +- **File System**: Node.js fs +- **Build**: `npm run build:electron` +- **Distribution**: AppImage, DEB, DMG packages + +## Development Workflow + +### Build Commands + +```bash +# Web (development) +npm run build:web + +# Mobile +npm run build:capacitor +npm run build:native + +# Desktop +npm run build:electron +npm run build:electron:appimage +npm run build:electron:deb +npm run build:electron:dmg +``` + +### Testing Commands + +```bash +# Web E2E +npm run test:web + +# Mobile +npm run test:mobile +npm run test:android +npm run test:ios + +# Type checking +npm run type-check +npm run lint-fix +``` + +## Key Constraints + +1. **Privacy First**: User identifiers remain private except when explicitly + shared +2. **Platform Compatibility**: Features must work across all target platforms +3. **Performance**: Must remain performant on older/simpler devices +4. **Modern Architecture**: New features should use current platform services +5. **Offline Capability**: Key functionality should work offline when feasible + +## Use Cases to Support + +1. **Community Building**: Tools for finding others with shared interests +2. **Project Coordination**: Easy proposal and collaboration on projects +3. **Reputation Building**: Showcasing contributions and reliability +4. **Governance**: Facilitating decision-making and collective governance + +## Resources + +- **Testing**: `docs/migration-testing/` +- **Architecture**: `docs/architecture-decisions.md` +- **Build Context**: `docs/build-modernization-context.md` + +--- + +## Status: Active application context + +- **Priority**: Critical +- **Estimated Effort**: Ongoing reference +- **Dependencies**: Vue 3, TypeScript, SQLite, Capacitor, Electron +- **Stakeholders**: Development team, Product team diff --git a/.cursor/rules/architectural_decision_record.mdc b/.cursor/rules/architectural_decision_record.mdc deleted file mode 100644 index fdc53c60..00000000 --- a/.cursor/rules/architectural_decision_record.mdc +++ /dev/null @@ -1,287 +0,0 @@ ---- -description: -globs: -alwaysApply: true ---- -# TimeSafari Cross-Platform Architecture Guide - -## 1. Platform Support Matrix - -| Feature | Web (PWA) | Capacitor (Mobile) | Electron (Desktop) | -|---------|-----------|-------------------|-------------------| -| QR Code Scanning | WebInlineQRScanner | @capacitor-mlkit/barcode-scanning | Not Implemented | -| Deep Linking | URL Parameters | App URL Open Events | Not Implemented | -| File System | Limited (Browser API) | Capacitor Filesystem | Electron fs | -| Camera Access | MediaDevices API | Capacitor Camera | Not Implemented | -| Platform Detection | Web APIs | Capacitor.isNativePlatform() | process.env checks | - -## 2. Project Structure - -### 2.1 Core Directories -``` -src/ -β”œβ”€β”€ components/ # Vue components -β”œβ”€β”€ services/ # Platform services and business logic -β”œβ”€β”€ views/ # Page components -β”œβ”€β”€ router/ # Vue router configuration -β”œβ”€β”€ types/ # TypeScript type definitions -β”œβ”€β”€ utils/ # Utility functions -β”œβ”€β”€ lib/ # Core libraries -β”œβ”€β”€ platforms/ # Platform-specific implementations -β”œβ”€β”€ electron/ # Electron-specific code -β”œβ”€β”€ constants/ # Application constants -β”œβ”€β”€ db/ # Database related code -β”œβ”€β”€ interfaces/ # TypeScript interfaces and type definitions -└── assets/ # Static assets -``` - -### 2.2 Entry Points -``` -src/ -β”œβ”€β”€ main.ts # Base entry -β”œβ”€β”€ main.common.ts # Shared initialization -β”œβ”€β”€ main.capacitor.ts # Mobile entry -β”œβ”€β”€ main.electron.ts # Electron entry -└── main.web.ts # Web/PWA entry -``` - -### 2.3 Build Configurations -``` -root/ -β”œβ”€β”€ vite.config.common.mts # Shared config -β”œβ”€β”€ vite.config.capacitor.mts # Mobile build -β”œβ”€β”€ vite.config.electron.mts # Electron build -└── vite.config.web.mts # Web/PWA build -``` - -## 3. Service Architecture - -### 3.1 Service Organization -``` -services/ -β”œβ”€β”€ QRScanner/ # QR code scanning service -β”‚ β”œβ”€β”€ WebInlineQRScanner.ts -β”‚ └── interfaces.ts -β”œβ”€β”€ platforms/ # Platform-specific services -β”‚ β”œβ”€β”€ WebPlatformService.ts -β”‚ β”œβ”€β”€ CapacitorPlatformService.ts -β”‚ └── ElectronPlatformService.ts -└── factory/ # Service factories - └── PlatformServiceFactory.ts -``` - -### 3.2 Service Factory Pattern -```typescript -// PlatformServiceFactory.ts -export class PlatformServiceFactory { - private static instance: PlatformService | null = null; - - public static getInstance(): PlatformService { - if (!PlatformServiceFactory.instance) { - const platform = process.env.VITE_PLATFORM || "web"; - PlatformServiceFactory.instance = createPlatformService(platform); - } - return PlatformServiceFactory.instance; - } -} -``` - -## 4. Feature Implementation Guidelines - -### 4.1 QR Code Scanning - -1. **Service Interface** -```typescript -interface QRScannerService { - checkPermissions(): Promise; - requestPermissions(): Promise; - isSupported(): Promise; - startScan(): Promise; - stopScan(): Promise; - addListener(listener: ScanListener): void; - onStream(callback: (stream: MediaStream | null) => void): void; - cleanup(): Promise; -} -``` - -2. **Platform-Specific Implementation** -```typescript -// WebInlineQRScanner.ts -export class WebInlineQRScanner implements QRScannerService { - private scanListener: ScanListener | null = null; - private isScanning = false; - private stream: MediaStream | null = null; - private events = new EventEmitter(); - - // Implementation of interface methods -} -``` - -### 4.2 Deep Linking - -1. **URL Structure** -```typescript -// Format: timesafari://[/][?queryParam1=value1] -interface DeepLinkParams { - route: string; - params?: Record; - query?: Record; -} -``` - -2. **Platform Handlers** -```typescript -// Capacitor -App.addListener("appUrlOpen", handleDeepLink); - -// Web -router.beforeEach((to, from, next) => { - handleWebDeepLink(to.query); -}); -``` - -## 5. Build Process - -### 5.1 Environment Configuration -```typescript -// vite.config.common.mts -export function createBuildConfig(mode: string) { - return { - define: { - 'process.env.VITE_PLATFORM': JSON.stringify(mode), - // PWA is automatically enabled for web platforms via build configuration - __IS_MOBILE__: JSON.stringify(isCapacitor), - __USE_QR_READER__: JSON.stringify(!isCapacitor) - } - }; -} -``` - -### 5.2 Platform-Specific Builds - -```bash -# Build commands from package.json -"build:web": "vite build --config vite.config.web.mts", -"build:capacitor": "vite build --config vite.config.capacitor.mts", -"build:electron": "vite build --config vite.config.electron.mts" -``` - -## 6. Testing Strategy - -### 6.1 Test Configuration -```typescript -// playwright.config-local.ts -const config: PlaywrightTestConfig = { - projects: [ - { - name: 'web', - use: { browserName: 'chromium' } - }, - { - name: 'mobile', - use: { ...devices['Pixel 5'] } - } - ] -}; -``` - -### 6.2 Platform-Specific Tests -```typescript -test('QR scanning works on mobile', async ({ page }) => { - test.skip(!process.env.MOBILE_TEST, 'Mobile-only test'); - // Test implementation -}); -``` - -## 7. Error Handling - -### 7.1 Global Error Handler -```typescript -function setupGlobalErrorHandler(app: VueApp) { - app.config.errorHandler = (err, instance, info) => { - logger.error("[App Error]", { - error: err, - info, - component: instance?.$options.name - }); - }; -} -``` - -### 7.2 Platform-Specific Error Handling -```typescript -// API error handling for Capacitor -if (process.env.VITE_PLATFORM === 'capacitor') { - logger.error(`[Capacitor API Error] ${endpoint}:`, { - message: error.message, - status: error.response?.status - }); -} -``` - -## 8. Best Practices - -### 8.1 Code Organization -- Use platform-specific directories for unique implementations -- Share common code through service interfaces -- Implement feature detection before using platform capabilities -- Keep platform-specific code isolated in dedicated directories -- Use TypeScript interfaces for cross-platform compatibility - -### 8.2 Platform Detection -```typescript -const platformService = PlatformServiceFactory.getInstance(); -const capabilities = platformService.getCapabilities(); - -if (capabilities.hasCamera) { - // Implement camera features -} -``` - -### 8.3 Feature Implementation -1. Define platform-agnostic interface -2. Create platform-specific implementations -3. Use factory pattern for instantiation -4. Implement graceful fallbacks -5. Add comprehensive error handling -6. Use dependency injection for better testability - -## 9. Dependency Management - -### 9.1 Platform-Specific Dependencies -```json -{ - "dependencies": { - "@capacitor/core": "^6.2.0", - "electron": "^33.2.1", - "vue": "^3.4.0" - } -} -``` - -### 9.2 Conditional Loading -```typescript -if (process.env.VITE_PLATFORM === 'capacitor') { - await import('@capacitor/core'); -} -``` - -## 10. Security Considerations - -### 10.1 Permission Handling -```typescript -async checkPermissions(): Promise { - if (platformService.isCapacitor()) { - return await checkNativePermissions(); - } - return await checkWebPermissions(); -} -``` - -### 10.2 Data Storage -- Use secure storage mechanisms for sensitive data -- Implement proper encryption for stored data -- Follow platform-specific security guidelines -- Regular security audits and updates - -This document should be updated as new features are added or platform-specific implementations change. Regular reviews ensure it remains current with the codebase. diff --git a/.cursor/rules/asset_configuration.mdc b/.cursor/rules/asset_configuration.mdc new file mode 100644 index 00000000..aa493fe9 --- /dev/null +++ b/.cursor/rules/asset_configuration.mdc @@ -0,0 +1,61 @@ +--- +description: when doing anything with capacitor assets +alwaysApply: false +--- +# Asset Configuration Directive + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Asset management guidelines + +*Scope: Assets Only (icons, splashes, image pipelines) β€” not overall build +orchestration* + +## Intent + +- Version **asset configuration files** (optionally dev-time generated). +- **Do not** version platform asset outputs (Android/iOS/Electron); generate + them **at build-time** with standard tools. +- Keep existing per-platform build scripts unchanged. + +## Source of Truth + +- **Preferred (Capacitor default):** `resources/` as the single master source. +- **Alternative:** `assets/` is acceptable **only** if `capacitor-assets` is + explicitly configured to read from it. +- **Never** maintain both `resources/` and `assets/` as parallel sources. + Migrate and delete the redundant folder. + +## Config Files + +- Live under: `config/assets/` (committed). +- Examples: + - `config/assets/capacitor-assets.config.json` (or the path the tool + expects) + - `config/assets/android.assets.json` + - `config/assets/ios.assets.json` + - `config/assets/common.assets.yaml` (optional shared layer) +- **Dev-time generation allowed** for these configs; **build-time + generation is forbidden**. + +## Build-Time Behavior + +- Build generates platform assets (not configs) using the standard chain: + +```bash +npm run build:capacitor # web build via Vite (.mts) +npx cap sync +npx capacitor-assets generate # produces platform assets; not committed +# then platform-specific build steps +``` + +--- + +**Status**: Active asset management directive +**Priority**: Medium +**Estimated Effort**: Ongoing reference +**Dependencies**: capacitor-assets toolchain +**Stakeholders**: Development team, Build team + + npx capacitor-assets generate # produces platform assets; not committed + # then platform-specific build steps diff --git a/.cursor/rules/base_context.mdc b/.cursor/rules/base_context.mdc new file mode 100644 index 00000000..4585c232 --- /dev/null +++ b/.cursor/rules/base_context.mdc @@ -0,0 +1,154 @@ +--- +alwaysApply: true +--- +```json +{ + "coaching_level": "standard", + "socratic_max_questions": 7, + "verbosity": "normal", + "timebox_minutes": null, + "format_enforcement": "strict" +} +``` + +# Base Context β€” Human Competence First + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Core interaction guidelines + +## 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. + +## Related Rulesets + +- **software_development.mdc**: For software-specific development practices +- **research_diagnostic.mdc**: For investigation and research workflows + +## 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. + +--- + +**Status**: Active core guidelines +**Priority**: Critical +**Estimated Effort**: Ongoing reference +**Dependencies**: None (base ruleset) +**Stakeholders**: All AI interactions + +- [ ] Uncertainties/assumptions surfaced. +- [ ] No disallowed content. diff --git a/.cursor/rules/absurd-sql.mdc b/.cursor/rules/database/absurd-sql.mdc similarity index 80% rename from .cursor/rules/absurd-sql.mdc rename to .cursor/rules/database/absurd-sql.mdc index 56729c2a..954fd8f7 100644 --- a/.cursor/rules/absurd-sql.mdc +++ b/.cursor/rules/database/absurd-sql.mdc @@ -1,14 +1,23 @@ --- -description: -globs: -alwaysApply: true +globs: **/db/databaseUtil.ts, **/interfaces/absurd-sql.d.ts, **/src/registerSQLWorker.js, **/ +services/AbsurdSqlDatabaseService.ts +alwaysApply: false --- # Absurd SQL - Cursor Development Guide +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Database development guidelines + ## 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. + +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 @@ -21,36 +30,45 @@ absurd-sql/ ## 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 ``` @@ -61,17 +79,20 @@ PRAGMA page_size=8192; -- Optional, but recommended - `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 @@ -79,18 +100,21 @@ PRAGMA page_size=8192; -- Optional, but recommended - 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 @@ -99,6 +123,7 @@ PRAGMA page_size=8192; -- Optional, but recommended ## Common Patterns ### Worker Initialization + ```javascript // Main thread import { initBackend } from 'absurd-sql/dist/indexeddb-main-thread'; @@ -110,6 +135,7 @@ function init() { ``` ### Database Setup + ```javascript // Worker thread import initSqlJs from '@jlongster/sql.js'; @@ -131,6 +157,7 @@ async function setupDatabase() { ## Troubleshooting ### Common Issues + 1. SharedArrayBuffer not available - Check COOP/COEP headers - Verify browser support @@ -147,7 +174,20 @@ async function setupDatabase() { - 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/) + +--- + +**Status**: Active database development guidelines +**Priority**: High +**Estimated Effort**: Ongoing reference +**Dependencies**: Absurd SQL, SQL.js, IndexedDB +**Stakeholders**: Development team, Database team - [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 +- [SQL.js Documentation](https://github.com/sql-js/sql.js/) diff --git a/.cursor/rules/database/legacy_dexie.mdc b/.cursor/rules/database/legacy_dexie.mdc new file mode 100644 index 00000000..ac02aaba --- /dev/null +++ b/.cursor/rules/database/legacy_dexie.mdc @@ -0,0 +1,8 @@ +--- +globs: **/databaseUtil.ts,**/AccountViewView.vue,**/ContactsView.vue,**/DatabaseMigration.vue,**/NewIdentifierView.vue +alwaysApply: false +--- +# What to do with Dexie + +All references in the codebase to Dexie apply only to migration from IndexedDb to +Sqlite and will be deprecated in future versions. diff --git a/.cursor/rules/development_guide.mdc b/.cursor/rules/development/development_guide.mdc similarity index 82% rename from .cursor/rules/development_guide.mdc rename to .cursor/rules/development/development_guide.mdc index cc43b000..439c1f26 100644 --- a/.cursor/rules/development_guide.mdc +++ b/.cursor/rules/development/development_guide.mdc @@ -1,7 +1,6 @@ --- -description: rules used while developing -globs: -alwaysApply: true +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 diff --git a/.cursor/rules/development/type_safety_guide.mdc b/.cursor/rules/development/type_safety_guide.mdc new file mode 100644 index 00000000..9c23938a --- /dev/null +++ b/.cursor/rules/development/type_safety_guide.mdc @@ -0,0 +1,139 @@ +--- +description: when dealing with types and Typesript +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-19 +**Status**: 🎯 **ACTIVE** - Type safety enforcement + +## 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]`. + +## Type Safety Enforcement + +### Core Type Safety Rules + +- **No `any` Types**: Use explicit types or `unknown` with proper type guards +- **Error Handling Uses Guards**: Implement and reuse type guards from `src/interfaces/**` +- **Dynamic Property Access**: Use `keyof` + `in` checks for type-safe property access + +### Type Guard Patterns +- **API Errors**: Use `isApiError(error)` guards for API error handling +- **Database Errors**: Use `isDatabaseError(error)` guards for database operations +- **Axios Errors**: Implement `isAxiosError(error)` guards for HTTP error handling + +### Implementation Guidelines +- **Avoid Type Assertions**: Replace `as any` with proper type guards and interfaces +- **Narrow Types Properly**: Use type guards to narrow `unknown` types safely +- **Document Type Decisions**: Explain complex type structures and their purpose + +## 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/ + +--- + +**Status**: Active type safety guidelines +**Priority**: High +**Estimated Effort**: Ongoing reference +**Dependencies**: TypeScript, ESLint, Vue 3 +**Stakeholders**: Development team + +- 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/documentation.mdc b/.cursor/rules/docs/documentation.mdc similarity index 100% rename from .cursor/rules/documentation.mdc rename to .cursor/rules/docs/documentation.mdc diff --git a/.cursor/rules/markdown.mdc b/.cursor/rules/docs/markdown.mdc similarity index 100% rename from .cursor/rules/markdown.mdc rename to .cursor/rules/docs/markdown.mdc diff --git a/.cursor/rules/camera-implementation.mdc b/.cursor/rules/features/camera-implementation.mdc similarity index 96% rename from .cursor/rules/camera-implementation.mdc rename to .cursor/rules/features/camera-implementation.mdc index e7fef13c..afeb0e28 100644 --- a/.cursor/rules/camera-implementation.mdc +++ b/.cursor/rules/features/camera-implementation.mdc @@ -1,13 +1,13 @@ --- -description: -globs: +description: when dealing with cameras in the application 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: +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 @@ -219,4 +219,4 @@ Desktop implementation (currently unimplemented). - Multiple browsers - iOS and Android devices - Desktop platforms -- Various network conditions +- Various network conditions diff --git a/.cursor/rules/investigation_report_example.mdc b/.cursor/rules/investigation_report_example.mdc new file mode 100644 index 00000000..ca3a7d36 --- /dev/null +++ b/.cursor/rules/investigation_report_example.mdc @@ -0,0 +1,117 @@ +# Investigation Report Example + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Investigation methodology example + +## Investigation β€” Registration Dialog Test Flakiness + +## Objective + +Identify root cause of flaky tests related to registration dialogs in contact +import scenarios. + +## System Map + +- User action β†’ ContactInputForm β†’ ContactsView.addContact() β†’ + handleRegistrationPrompt() +- setTimeout(1000ms) β†’ Modal dialog β†’ User response β†’ Registration API call +- Test execution β†’ Wait for dialog β†’ Assert dialog content β†’ Click response + button + +## Findings (Evidence) + +- **1-second timeout causes flakiness** β€” evidence: + `src/views/ContactsView.vue:971-1000`; setTimeout(..., 1000) in + handleRegistrationPrompt() +- **Import flow bypasses dialogs** β€” evidence: + `src/views/ContactImportView.vue:500-520`; importContacts() calls + $insertContact() directly, no handleRegistrationPrompt() +- **Dialog only appears in direct add flow** β€” evidence: + `src/views/ContactsView.vue:774-800`; addContact() calls + handleRegistrationPrompt() after database insert + +## Hypotheses & Failure Modes + +- H1: 1-second timeout makes dialog appearance unpredictable; would fail when + tests run faster than 1000ms +- H2: Test environment timing differs from development; watch for CI vs local + test differences + +## Corrections + +- Updated: "Multiple dialogs interfere with imports" β†’ "Import flow never + triggers dialogs - they only appear in direct contact addition" +- Updated: "Complex batch registration needed" β†’ "Simple timeout removal and + test mode flag sufficient" + +## Diagnostics (Next Checks) + +- [ ] Repro on CI environment vs local +- [ ] Measure actual dialog appearance timing +- [ ] Test with setTimeout removed +- [ ] Verify import flow doesn't call handleRegistrationPrompt + +## Risks & Scope + +- Impacted: Contact addition tests, registration workflow tests; Data: None; + Users: Test suite reliability + +## Decision / Next Steps + +- Owner: Development Team; By: 2025-01-28 +- Action: Remove 1-second timeout + add test mode flag; Exit criteria: Tests + pass consistently + +## References + +- `src/views/ContactsView.vue:971-1000` +- `src/views/ContactImportView.vue:500-520` +- `src/views/ContactsView.vue:774-800` + +## Competence Hooks + +- Why this works: Code path tracing revealed separate execution flows, + evidence disproved initial assumptions +- Common pitfalls: Assuming related functionality without tracing execution + paths, over-engineering solutions to imaginary problems +- Next skill: Learn to trace code execution before proposing architectural + changes +- Teach-back: "What evidence shows that contact imports bypass registration + dialogs?" + +## Key Learning Points + +### Evidence-First Approach + +This investigation demonstrates the importance of: + +1. **Tracing actual code execution** rather than making assumptions +2. **Citing specific evidence** with file:line references +3. **Validating problem scope** before proposing solutions +4. **Considering simpler alternatives** before complex architectural changes + +### Code Path Tracing Value + +By tracing the execution paths, we discovered: + +- Import flow and direct add flow are completely separate +- The "multiple dialog interference" problem didn't exist +- A simple timeout removal would solve the actual issue + +### Prevention of Over-Engineering + +The investigation prevented: + +- Unnecessary database schema changes +- Complex batch registration systems +- Migration scripts for non-existent problems +- Architectural changes based on assumptions + +--- + +**Status**: Active investigation methodology +**Priority**: High +**Estimated Effort**: Ongoing reference +**Dependencies**: software_development.mdc +**Stakeholders**: Development team, QA team diff --git a/.cursor/rules/legacy_dexie.mdc b/.cursor/rules/legacy_dexie.mdc deleted file mode 100644 index 82de6cca..00000000 --- a/.cursor/rules/legacy_dexie.mdc +++ /dev/null @@ -1,6 +0,0 @@ ---- -description: -globs: -alwaysApply: true ---- -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/logging_standards.mdc b/.cursor/rules/logging_standards.mdc new file mode 100644 index 00000000..2b9d6507 --- /dev/null +++ b/.cursor/rules/logging_standards.mdc @@ -0,0 +1,222 @@ +# Agent Contract β€” TimeSafari Logging (Unified, MANDATORY) + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Mandatory logging standards + +## Overview + +This document defines unified logging standards for the TimeSafari project, +ensuring consistent, rest-parameter logging style using the project logger. +No `console.*` methods are allowed in production code. + +## Scope and Goals + +**Scope**: Applies to all diffs and generated code in this workspace unless +explicitly exempted below. + +**Goal**: One consistent, rest-parameter logging style using the project +logger; no `console.*` in production code. + +## Non‑Negotiables (DO THIS) + +- You **MUST** use the project logger; **DO NOT** use any `console.*` + methods. +- Import exactly as: + - `import { logger } from '@/utils/logger'` + - If `@` alias is unavailable, compute the correct relative path (do not + fail). +- Call signatures use **rest parameters**: `logger.info(message, ...args)` +- Prefer primitives/IDs and small objects in `...args`; **never build a + throwaway object** just to "wrap context". +- Production defaults: Web = `warn+`, Electron = `error`, Dev/Capacitor = + `info+` (override via `VITE_LOG_LEVEL`). +- **Database persistence**: `info|warn|error` are persisted; `debug` is not. + Use `logger.toDb(msg, level?)` for DB-only. + +## Available Logger API (Authoritative) + +- `logger.debug(message, ...args)` β€” verbose internals, timings, input/output + shapes +- `logger.log(message, ...args)` β€” synonym of `info` for general info +- `logger.info(message, ...args)` β€” lifecycle, state changes, success paths +- `logger.warn(message, ...args)` β€” recoverable issues, retries, degraded mode +- `logger.error(message, ...args)` β€” failures, thrown exceptions, aborts +- `logger.toDb(message, level?)` β€” DB-only entry (default level = `info`) +- `logger.toConsoleAndDb(message, isError)` β€” console + DB (use sparingly) +- `logger.withContext(componentName)` β€” returns a scoped logger + +## Level Guidelines (Use These Heuristics) + +### DEBUG + +Use for method entry/exit, computed values, filters, loops, retries, and +external call payload sizes. + +```typescript +logger.debug('[HomeView] reloadFeedOnChange() called'); +logger.debug('[HomeView] Current filter settings', + settings.filterFeedByVisible, + settings.filterFeedByNearby, + settings.searchBoxes?.length ?? 0); +logger.debug('[FeedFilters] Toggling nearby filter', + this.isNearby, this.settingChanged, this.activeDid); +``` + +**Avoid**: Vague messages (`'Processing data'`). + +### INFO + +Use for user-visible lifecycle and completed operations. + +```typescript +logger.info('[StartView] Component mounted', process.env.VITE_PLATFORM); +logger.info('[StartView] User selected new seed generation'); +logger.info('[SearchAreaView] Search box stored', + searchBox.name, searchBox.bbox); +logger.info('[ContactQRScanShowView] Contact registration OK', + contact.did); +``` + +**Avoid**: Diagnostic details that belong in `debug`. + +### WARN + +Use for recoverable issues, fallbacks, unexpected-but-handled conditions. + +```typescript +logger.warn('[ContactQRScanShowView] Invalid scan result – no value', + resultType); +logger.warn('[ContactQRScanShowView] Invalid QR format – no JWT in URL'); +logger.warn('[ContactQRScanShowView] JWT missing "own" field'); +``` + +**Avoid**: Hard failures (those are `error`). + +### ERROR + +Use for unrecoverable failures, data integrity issues, and thrown +exceptions. + +```typescript +logger.error('[HomeView Settings] initializeIdentity() failed', err); +logger.error('[StartView] Failed to load initialization data', error); +logger.error('[ContactQRScanShowView] Error processing contact QR', + error, rawValue); +``` + +**Avoid**: Expected user cancels (use `info`/`debug`). + +## Context Hygiene (Consistent, Minimal, Helpful) + +- **Component context**: Prefer scoped logger. + +```typescript +const log = logger.withContext('UserService'); +log.info('User created', userId); +log.error('Failed to create user', error); +``` + +If not using `withContext`, prefix message with `[ComponentName]`. + +- **Emojis**: Optional and minimal for visual scanning. Recommended set: + - Start/finish: πŸš€ / βœ… + - Retry/loop: πŸ”„ + - External call: πŸ“‘ + - Data/metrics: πŸ“Š + - Inspection: πŸ” + +- **Sensitive data**: Never log secrets (tokens, keys, passwords) or + payloads >10KB. Prefer IDs over objects; redact/hash when needed. + +## Migration β€” Auto‑Rewrites (Apply Every Time) + +- Exact transforms: + - `console.debug(...)` β†’ `logger.debug(...)` + - `console.log(...)` β†’ `logger.log(...)` (or `logger.info(...)` when + clearly stateful) + - `console.info(...)` β†’ `logger.info(...)` + - `console.warn(...)` β†’ `logger.warn(...)` + - `console.error(...)` β†’ `logger.error(...)` + +- Multi-arg handling: + - First arg becomes `message` (stringify safely if non-string). + - Remaining args map 1:1 to `...args`: + `console.info(msg, a, b)` β†’ `logger.info(String(msg), a, b)` + +- Sole `Error`: + - `console.error(err)` β†’ `logger.error(err.message, err)` + +- **Object-wrapping cleanup**: Replace `{{ userId, meta }}` wrappers with + separate args: + `logger.info('User signed in', userId, meta)` + +## DB Logging Rules + +- `debug` **never** persists automatically. +- `info|warn|error` persist automatically. +- For DB-only events (no console), call `logger.toDb('Message', + 'info'|'warn'|'error')`. + +## Exceptions (Tightly Scoped) + +Allowed paths (still prefer logger): + +- `**/*.test.*`, `**/*.spec.*` +- `scripts/dev/**`, `scripts/migrate/**` + +To intentionally keep `console.*`, add a pragma on the previous line: + +```typescript +// cursor:allow-console reason="short justification" +console.log('temporary output'); +``` + +Without the pragma, rewrite to `logger.*`. + +## CI & Diff Enforcement + +- Do not introduce `console.*` anywhere outside allowed, pragma'd spots. +- If an import is missing, insert it and resolve alias/relative path + correctly. +- Enforce rest-parameter call shape in reviews; replace object-wrapped + context. +- Ensure environment log level rules remain intact (`VITE_LOG_LEVEL` + respected). + +## Quick Before/After + +### **Before** + +```typescript +console.log('User signed in', user.id, meta); +console.error('Failed to update profile', err); +console.info('Filter toggled', this.hasVisibleDid); +``` + +### **After** + +```typescript +import { logger } from '@/utils/logger'; + +logger.info('User signed in', user.id, meta); +logger.error('Failed to update profile', err); +logger.debug('[FeedFilters] Filter toggled', this.hasVisibleDid); +``` + +## Checklist (for every PR) + +- [ ] No `console.*` (or properly pragma'd in the allowed locations) +- [ ] Correct import path for `logger` +- [ ] Rest-parameter call shape (`message, ...args`) +- [ ] Right level chosen (debug/info/warn/error) +- [ ] No secrets / oversized payloads / throwaway context objects +- [ ] Component context provided (scoped logger or `[Component]` prefix) + +--- + +**Status**: Active and enforced +**Priority**: Critical +**Estimated Effort**: Ongoing reference +**Dependencies**: TimeSafari logger utility +**Stakeholders**: Development team, Code review team diff --git a/.cursor/rules/research_diagnostic.mdc b/.cursor/rules/research_diagnostic.mdc new file mode 100644 index 00000000..d82c9097 --- /dev/null +++ b/.cursor/rules/research_diagnostic.mdc @@ -0,0 +1,174 @@ +--- +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) + +--- + +## Enhanced with Software Development Ruleset + +When investigating software issues, also apply: + +- **Code Path Tracing**: Required for technical investigations +- **Evidence Validation**: Ensure claims are code-backed +- **Solution Complexity Assessment**: Justify architectural changes + +--- + +## 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. + +--- + +## Code Path Tracing (Required for Software Investigations) + +Before proposing solutions, trace the actual execution path: + +- [ ] **Entry Points**: Identify where the flow begins (user action, API call, etc.) +- [ ] **Component Flow**: Map which components/methods are involved +- [ ] **Data Path**: Track how data moves through the system +- [ ] **Exit Points**: Confirm where the flow ends and what results +- [ ] **Evidence Collection**: Gather specific code citations for each step + +--- + +## 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. + +--- + +## Integration with Other Rulesets + +### With software_development.mdc + +- **Enhanced Evidence Validation**: Use code path tracing for technical investigations +- **Architecture Assessment**: Apply complexity justification to proposed solutions +- **Impact Analysis**: Assess effects on existing systems before recommendations + +### With base_context.mdc + +- **Competence Building**: Focus on technical investigation skills +- **Collaboration**: Structure outputs for team review and discussion + +--- + +## 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. +- [ ] **Code path traced** (for software investigations). +- [ ] **Evidence validated** against actual code execution. + +--- + +## 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.mdc`, `@investigation_report_example.mdc` diff --git a/.cursor/rules/software_development.mdc b/.cursor/rules/software_development.mdc new file mode 100644 index 00000000..2f7c2c71 --- /dev/null +++ b/.cursor/rules/software_development.mdc @@ -0,0 +1,225 @@ + +# Software Development Ruleset + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Core development guidelines + +## Purpose + +Specialized guidelines for software development tasks including code review, +debugging, architecture decisions, and testing. + +## Core Principles + +### 1. Evidence-First Development + +- **Code Citations Required**: Always cite specific file:line references when + making claims +- **Execution Path Tracing**: Trace actual code execution before proposing + architectural changes +- **Assumption Validation**: Flag assumptions as "assumed" vs "evidence-based" + +### 2. Code Review Standards + +- **Trace Before Proposing**: Always trace execution paths before suggesting + changes +- **Evidence Over Inference**: Prefer code citations over logical deductions +- **Scope Validation**: Confirm the actual scope of problems before proposing + solutions + +### 3. Problem-Solution Validation + +- **Problem Scope**: Does the solution address the actual problem? +- **Evidence Alignment**: Does the solution match the evidence? +- **Complexity Justification**: Is added complexity justified by real needs? +- **Alternative Analysis**: What simpler solutions were considered? + +### 4. Dependency Management & Environment Validation + +- **Pre-build Validation**: Always validate critical dependencies before executing + build scripts +- **Environment Consistency**: Ensure team members have identical development + environments +- **Dependency Verification**: Check that required packages are installed and + accessible +- **Path Resolution**: Use `npx` for local dependencies to avoid PATH issues + +## Required Workflows + +### Before Proposing Changes + +- [ ] **Code Path Tracing**: Map execution flow from entry to exit +- [ ] **Evidence Collection**: Gather specific code citations and logs +- [ ] **Assumption Surfacing**: Identify what's proven vs. inferred +- [ ] **Scope Validation**: Confirm the actual extent of the problem +- [ ] **Dependency Validation**: Verify all required dependencies are available + and accessible + +### During Solution Design + +- [ ] **Evidence Alignment**: Ensure solution addresses proven problems +- [ ] **Complexity Assessment**: Justify any added complexity +- [ ] **Alternative Evaluation**: Consider simpler approaches first +- [ ] **Impact Analysis**: Assess effects on existing systems +- [ ] **Environment Impact**: Assess how changes affect team member setups + +## Software-Specific Competence Hooks + +### Evidence Validation + +- **"What code path proves this claim?"** +- **"How does data actually flow through the system?"** +- **"What am I assuming vs. what can I prove?"** + +### Code Tracing + +- **"What's the execution path from user action to system response?"** +- **"Which components actually interact in this scenario?"** +- **"Where does the data originate and where does it end up?"** + +### Architecture Decisions + +- **"What evidence shows this change is necessary?"** +- **"What simpler solution could achieve the same goal?"** +- **"How does this change affect the existing system architecture?"** + +### Dependency & Environment Management + +- **"What dependencies does this feature require and are they properly + declared?"** +- **"How will this change affect team member development environments?"** +- **"What validation can we add to catch dependency issues early?"** + +## Dependency Management Best Practices + +### Pre-build Validation + +- **Check Critical Dependencies**: Validate essential tools before executing build + scripts +- **Use npx for Local Dependencies**: Prefer `npx tsx` over direct `tsx` to + avoid PATH issues +- **Environment Consistency**: Ensure all team members have identical dependency + versions + +### Common Pitfalls + +- **Missing npm install**: Team members cloning without running `npm install` +- **PATH Issues**: Direct command execution vs. npm script execution differences +- **Version Mismatches**: Different Node.js/npm versions across team members + +### Validation Strategies + +- **Dependency Check Scripts**: Implement pre-build validation for critical + dependencies +- **Environment Requirements**: Document and enforce minimum Node.js/npm versions +- **Onboarding Checklist**: Standardize team member setup procedures + +### Error Messages and Guidance + +- **Specific Error Context**: Provide clear guidance when dependency issues occur +- **Actionable Solutions**: Direct users to specific commands (`npm install`, + `npm run check:dependencies`) +- **Environment Diagnostics**: Implement comprehensive environment validation + tools + +### Build Script Enhancements + +- **Early Validation**: Check dependencies before starting build processes +- **Graceful Degradation**: Continue builds when possible but warn about issues +- **Helpful Tips**: Remind users about dependency management best practices + +## Integration with Other Rulesets + +### With base_context.mdc + +- Inherits generic competence principles +- Adds software-specific evidence requirements +- Maintains collaboration and learning focus + +### With research_diagnostic.mdc + +- Enhances investigation with code path tracing +- Adds evidence validation to diagnostic workflow +- Strengthens problem identification accuracy + +## Usage Guidelines + +### When to Use This Ruleset + +- Code reviews and architectural decisions +- Bug investigation and debugging +- Performance optimization +- Feature implementation planning +- Testing strategy development + +### When to Combine with Others + +- **base_context + software_development**: General development tasks +- **research_diagnostic + software_development**: Technical investigations +- **All three**: Complex architectural decisions or major refactoring + +## Self-Check (model, before responding) + +- [ ] Code path traced and documented +- [ ] Evidence cited with specific file:line references +- [ ] Assumptions clearly flagged as proven vs. inferred +- [ ] Solution complexity justified by evidence +- [ ] Simpler alternatives considered and documented +- [ ] Impact on existing systems assessed +- [ ] Dependencies validated and accessible +- [ ] Environment impact assessed for team members +- [ ] Pre-build validation implemented where appropriate + +## Additional Core Principles + +### 4. Dependency Management & Environment Validation +- **Pre-build Validation**: Always validate critical dependencies before executing build scripts +- **Environment Consistency**: Ensure team members have identical development environments +- **Dependency Verification**: Check that required packages are installed and accessible +- **Path Resolution**: Use `npx` for local dependencies to avoid PATH issues + +## Additional Required Workflows + +### Dependency Validation (Before Proposing Changes) +- [ ] **Dependency Validation**: Verify all required dependencies are available and accessible + +### Environment Impact Assessment (During Solution Design) +- [ ] **Environment Impact**: Assess how changes affect team member setups + +## Additional Competence Hooks + +### Dependency & Environment Management +- **"What dependencies does this feature require and are they properly declared?"** +- **"How will this change affect team member development environments?"** +- **"What validation can we add to catch dependency issues early?"** + +## Dependency Management Best Practices + +### Pre-build Validation +- **Check Critical Dependencies**: Validate essential tools before executing build scripts +- **Use npx for Local Dependencies**: Prefer `npx tsx` over direct `tsx` to avoid PATH issues +- **Environment Consistency**: Ensure all team members have identical dependency versions + +### Common Pitfalls +- **Missing npm install**: Team members cloning without running `npm install` +- **PATH Issues**: Direct command execution vs. npm script execution differences +- **Version Mismatches**: Different Node.js/npm versions across team members + +### Validation Strategies +- **Dependency Check Scripts**: Implement pre-build validation for critical dependencies +- **Environment Requirements**: Document and enforce minimum Node.js/npm versions +- **Onboarding Checklist**: Standardize team member setup procedures + +### Error Messages and Guidance +- **Specific Error Context**: Provide clear guidance when dependency issues occur +- **Actionable Solutions**: Direct users to specific commands (`npm install`, `npm run check:dependencies`) +- **Environment Diagnostics**: Implement comprehensive environment validation tools + +### Build Script Enhancements +- **Early Validation**: Check dependencies before starting build processes +- **Graceful Degradation**: Continue builds when possible but warn about issues +- **Helpful Tips**: Remind users about dependency management best practices + +- **Narrow Types Properly**: Use type guards to narrow `unknown` types safely +- **Document Type Decisions**: Explain complex type structures and their purpose diff --git a/.cursor/rules/time.mdc b/.cursor/rules/time.mdc new file mode 100644 index 00000000..61c962bb --- /dev/null +++ b/.cursor/rules/time.mdc @@ -0,0 +1,329 @@ +--- +alwaysApply: true +--- +# Time Handling in Development Workflow + +**Author**: Matthew Raymer +**Date**: 2025-08-17 +**Status**: 🎯 **ACTIVE** - Production Ready + +## Overview + +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**. + +## 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. + +## 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 + +## 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. + +## 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**. + +## 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. + +## 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? + +## 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. + +## 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 + +## 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` + +## 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." + +## 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.** + +--- + +**Status**: Active +**Version**: 1.0 +**Maintainer**: Matthew Raymer +**Next Review**: 2025-09-17 diff --git a/.cursor/rules/timesafari.mdc b/.cursor/rules/timesafari.mdc deleted file mode 100644 index c32804be..00000000 --- a/.cursor/rules/timesafari.mdc +++ /dev/null @@ -1,316 +0,0 @@ ---- -description: -globs: -alwaysApply: true ---- -# Time Safari Context - -## Project Overview - -Time Safari is an application designed to foster community building through gifts, -gratitude, and collaborative projects. The app should make it extremely easy and -intuitive for users of any age and capability to recognize contributions, build -trust networks, and organize collective action. It is built on services that -preserve privacy and data sovereignty. - -The ultimate goals of Time Safari are two-fold: - -1. **Connect** Make it easy, rewarding, and non-threatening for people to -connect with others who have similar interests, and to initiate activities -together. This helps people accomplish and learn from other individuals in -less-structured environments; moreover, it helps them discover who they want -to continue to support and with whom they want to maintain relationships. - -2. **Reveal** Widely advertise the great support and rewards that are being -given and accepted freely, especially non-monetary ones. Using visuals and text, -display the kind of impact that gifts are making in the lives of others. Also -show useful and engaging reports of project statistics and personal accomplishments. - - -## Core Approaches - -Time Safari should help everyday users build meaningful connections and organize -collective efforts by: - -1. **Recognizing Contributions**: Creating permanent, verifiable records of gifts -and contributions people give to each other and their communities. - -2. **Facilitating Collaboration**: Making it ridiculously easy for people to ask -for or propose help on projects and interests that matter to them. - -3. **Building Trust Networks**: Enabling users to maintain their network and activity -visibility. Developing reputation through verified contributions and references, -which can be selectively shown to others outside the network. - -4. **Preserving Privacy**: Ensuring personal identifiers are only shared with -explicitly authorized contacts, allowing private individuals including children -to participate safely. - -5. **Engaging Content**: Displaying people's records in compelling stories, and -highlighting those projects that are lifting people's lives long-term, both in -physical support and in emotional-spiritual-creative thriving. - - -## Technical Foundation - -This application is built on a privacy-preserving claims architecture (via -endorser.ch) with these key characteristics: - -- **Decentralized Identifiers (DIDs)**: User identities are based on public/private -key pairs stored on their devices -- **Cryptographic Verification**: All claims and confirmations are -cryptographically signed -- **User-Controlled Visibility**: Users explicitly control who can see their -identifiers and data -- **Merkle-Chained Claims**: Claims are cryptographically chained for verification -and integrity -- **Native and Web App**: Works on Capacitor (iOS, Android), Desktop (Electron -and CEFPython), and web browsers - -## User Journey - -The typical progression of usage follows these stages: - -1. **Gratitude & Recognition**: Users begin by expressing and recording gratitude -for gifts received, building a foundation of acknowledgment. - -2. **Project Proposals**: Users propose projects and ideas, reaching out to connect -with others who share similar interests. - -3. **Action Triggers**: Offers of help serve as triggers and motivations to execute -proposed projects, moving from ideas to action. - -## Context for LLM Development - -When developing new functionality for Time Safari, consider these design principles: - -1. **Accessibility First**: Features should be usable by non-technical users with -minimal learning curve. - -2. **Privacy by Design**: All features must respect user privacy and data sovereignty. - -3. **Progressive Enhancement**: Core functionality should work across all devices, -with richer experiences where supported. - -4. **Voluntary Collaboration**: The system should enable but never coerce participation. - -5. **Trust Building**: Features should help build verifiable trust between users. - -6. **Network Effects**: Consider how features scale as more users join the platform. - -7. **Low Resource Requirements**: The system should be lightweight enough to run -on inexpensive devices users already own. - -## Use Cases to Support - -LLM development should focus on enhancing these key use cases: - -1. **Community Building**: Tools that help people find others with shared -interests and values. - -2. **Project Coordination**: Features that make it easy to propose collaborative -projects and to submit suggestions and offers to existing ones. - -3. **Reputation Building**: Methods for users to showcase their contributions -and reliability, in contexts where they explicitly reveal that information. - -4. **Governance Experimentation**: Features that facilitate decision-making and -collective governance. - -## Constraints - -When developing new features, be mindful of these constraints: - -1. **Privacy Preservation**: User identifiers must remain private except when -explicitly shared. - -2. **Platform Limitations**: Features must work within the constraints of the target -app platforms, while aiming to leverage the best platform technology available. - -3. **Endorser API Limitations**: Backend features are constrained by the endorser.ch -API capabilities. - -4. **Performance on Low-End Devices**: The application should remain performant -on older/simpler devices. - -5. **Offline-First When Possible**: Key functionality should work offline when feasible. - -## Project Technologies - -- Typescript using ES6 classes using vue-facing-decorator -- TailwindCSS -- Vite Build Tool -- Playwright E2E testing -- IndexDB -- Camera, Image uploads, QR Code reader, ... - -## Mobile Features - -- Deep Linking -- Local Notifications via a custom Capacitor plugin - -## Project Architecture - -- The application must work on web browser, PWA (Progressive Web Application), - desktop via Electron, and mobile via Capacitor -- Building for each platform is managed via Vite - -## Core Development Principles - -### DRY development - -- **Code Reuse** - - Extract common functionality into utility functions - - Create reusable components for UI patterns - - Implement service classes for shared business logic - - Use mixins for cross-cutting concerns - - Leverage TypeScript interfaces for shared type definitions - -- **Component Patterns** - - Create base components for common UI elements - - Implement higher-order components for shared behavior - - Use slot patterns for flexible component composition - - Create composable services for business logic - - Implement factory patterns for component creation - -- **State Management** - - Centralize state in Pinia stores - - Use computed properties for derived state - - Implement shared state selectors - - Create reusable state mutations - - Use action creators for common operations - -- **Error Handling** - - Implement centralized error handling - - Create reusable error components - - Use error boundary components - - Implement consistent error logging - - Create error type definitions - -- **Type Definitions** - - Create shared interfaces for common data structures - - Use type aliases for complex types - - Implement generic types for reusable components - - Create utility types for common patterns - - Use discriminated unions for state management - -- **API Integration** - - Create reusable API client classes - - Implement request/response interceptors - - Use consistent error handling patterns - - Create type-safe API endpoints - - Implement caching strategies - -- **Platform Services** - - Abstract platform-specific code behind interfaces - - Create platform-agnostic service layers - - Implement feature detection - - Use dependency injection for services - - Create service factories - -- **Testing** - - Create reusable test utilities - - Implement test factories - - Use shared test configurations - - Create reusable test helpers - - Implement consistent test patterns - - F.I.R.S.T. (for Unit Tests) - F – Fast - I – Independent - R – Repeatable - S – Self-validating - T – Timely - -### SOLID Principles - -- **Single Responsibility**: Each class/component should have only one reason to - change - - Components should focus on one specific feature (e.g., QR scanning, DID management) - - Services should handle one type of functionality (e.g., platform services, - crypto services) - - Utilities should provide focused helper functions - -- **Open/Closed**: Software entities should be open for extension but closed for - modification - - Use interfaces for service definitions - - Implement plugin architecture for platform-specific features - - Allow component behavior extension through props and events - -- **Liskov Substitution**: Objects should be replaceable with their subtypes - - Platform services should work consistently across web/mobile - - Authentication providers should be interchangeable - - Storage implementations should be swappable - -- **Interface Segregation**: Clients shouldn't depend on interfaces they don't use - - Break down large service interfaces into smaller, focused ones - - Component props should be minimal and purposeful - - Event emissions should be specific and targeted - -- **Dependency Inversion**: High-level modules shouldn't depend on low-level modules - - Use dependency injection for services - - Abstract platform-specific code behind interfaces - - Implement factory patterns for component creation - -### Law of Demeter - -- Components should only communicate with immediate dependencies -- Avoid chaining method calls (e.g., `this.service.getUser().getProfile().getName()`) -- Use mediator patterns for complex component interactions -- Implement facade patterns for subsystem access -- Keep component communication through defined events and props - -### Composition over Inheritance - -- Prefer building components through composition -- Use mixins for shared functionality -- Implement feature toggles through props -- Create higher-order components for common patterns -- Use service composition for complex features - -### Interface Segregation - -- Define clear interfaces for services -- Keep component APIs minimal and focused -- Split large interfaces into smaller, specific ones -- Use TypeScript interfaces for type definitions -- Implement role-based interfaces for different use cases - -### Fail Fast - -- Validate inputs early in the process -- Use TypeScript strict mode -- Implement comprehensive error handling -- Add runtime checks for critical operations -- Use assertions for development-time validation - -### Principle of Least Astonishment - -- Follow Vue.js conventions consistently -- Use familiar naming patterns -- Implement predictable component behaviors -- Maintain consistent error handling -- Keep UI interactions intuitive - -### Information Hiding - -- Encapsulate implementation details -- Use private class members -- Implement proper access modifiers -- Hide complex logic behind simple interfaces -- Use TypeScript's access modifiers effectively - -### Single Source of Truth - -- Use Pinia for state management -- Maintain one source for user data -- Centralize configuration management -- Use computed properties for derived state -- Implement proper state synchronization - -### Principle of Least Privilege - -- Implement proper access control -- Use minimal required permissions -- Follow privacy-by-design principles -- Restrict component access to necessary data -- Implement proper authentication/authorization diff --git a/.cursor/rules/version_control.mdc b/.cursor/rules/version_control.mdc deleted file mode 100644 index 7635fb6b..00000000 --- a/.cursor/rules/version_control.mdc +++ /dev/null @@ -1,122 +0,0 @@ ---- -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/.cursor/rules/workflow/version_control.mdc b/.cursor/rules/workflow/version_control.mdc new file mode 100644 index 00000000..6e619f5c --- /dev/null +++ b/.cursor/rules/workflow/version_control.mdc @@ -0,0 +1,335 @@ +--- +description: interacting with git +alwaysApply: false +--- +# Directive: Peaceful Co-Existence with Developers + +**Author**: Matthew Raymer +**Date**: 2025-08-19 +**Status**: 🎯 **ACTIVE** - Version control guidelines + +## 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. + +## 4) Version Synchronization Requirements + +- **MUST** check for version changes in `package.json` before committing +- **MUST** ensure `CHANGELOG.md` is updated when `package.json` version + changes +- **MUST** validate version format consistency between both files +- **MUST** include version bump commits in changelog with proper semantic + versioning + +### Version Sync Checklist (Before Commit) + +- [ ] `package.json` version matches latest `CHANGELOG.md` entry +- [ ] New version follows semantic versioning + (MAJOR.MINOR.PATCH[-PRERELEASE]) +- [ ] Changelog entry includes all significant changes since last version +- [ ] Version bump commit message follows `build(version): bump to X.Y.Z` + format +- [ ] Breaking changes properly documented with migration notes +- [ ] Alert developer in chat message that version has been updated + +### Version Change Detection + +- **Check for version changes** in staged/unstaged `package.json` +- **Alert developer** if version changed but changelog not updated +- **Suggest changelog update** with proper format and content +- **Validate semantic versioning** compliance + +### Implementation Notes + +- **Version Detection**: Compare `package.json` version field with latest + changelog entry +- **Semantic Validation**: Ensure version follows `X.Y.Z[-PRERELEASE]` + format +- **Changelog Format**: Follow [Keep a Changelog](https://keepachangelog.com/) + standards +- **Breaking Changes**: Use `!` in commit message and `BREAKING CHANGE:` + in changelog +- **Pre-release Versions**: Include beta/alpha/rc suffixes in both files + consistently + +## 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 + +--- + +**Status**: Active version control guidelines +**Priority**: High +**Estimated Effort**: Ongoing reference +**Dependencies**: git, package.json, CHANGELOG.md +**Stakeholders**: Development team, AI assistants + +- [ ] No invented changes; aligns strictly with diffs +- [ ] Render as a single copy-paste block for the developer + +## 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. + +## 4) Version Synchronization Requirements + +- **MUST** check for version changes in `package.json` before committing +- **MUST** ensure `CHANGELOG.md` is updated when `package.json` version + changes +- **MUST** validate version format consistency between both files +- **MUST** include version bump commits in changelog with proper semantic + versioning + +### Version Sync Checklist (Before Commit) + +- [ ] `package.json` version matches latest `CHANGELOG.md` entry +- [ ] New version follows semantic versioning + (MAJOR.MINOR.PATCH[-PRERELEASE]) +- [ ] Changelog entry includes all significant changes since last version +- [ ] Version bump commit message follows `build(version): bump to X.Y.Z` + format +- [ ] Breaking changes properly documented with migration notes +- [ ] Alert developer in chat message that version has been updated + +### Version Change Detection + +- **Check for version changes** in staged/unstaged `package.json` +- **Alert developer** if version changed but changelog not updated +- **Suggest changelog update** with proper format and content +- **Validate semantic versioning** compliance + +### Implementation Notes + +- **Version Detection**: Compare `package.json` version field with latest + changelog entry +- **Semantic Validation**: Ensure version follows `X.Y.Z[-PRERELEASE]` + format +- **Changelog Format**: Follow [Keep a Changelog](https://keepachangelog.com/) + standards +- **Breaking Changes**: Use `!` in commit message and `BREAKING CHANGE:` + in changelog +- **Pre-release Versions**: Include beta/alpha/rc suffixes in both files + consistently + +## 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 + +--- + +**Status**: Active version control guidelines +**Priority**: High +**Estimated Effort**: Ongoing reference +**Dependencies**: git, package.json, CHANGELOG.md +**Stakeholders**: Development team, AI assistants + +* [ ] No invented changes; aligns strictly with diffs +* [ ] Render as a single copy-paste block for the developer diff --git a/.env.test b/.env.test index 5776e66c..dd3d755c 100644 --- a/.env.test +++ b/.env.test @@ -7,7 +7,7 @@ VITE_LOG_LEVEL=info TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.app # This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not - production). +# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not production). VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch diff --git a/.eslintrc.js b/.eslintrc.js index fcd19ebe..43e7fbd5 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -30,7 +30,7 @@ module.exports = { }], "no-console": process.env.NODE_ENV === "production" ? "error" : "warn", "no-debugger": process.env.NODE_ENV === "production" ? "error" : "warn", - "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/no-explicit-any": "error", "@typescript-eslint/explicit-function-return-type": "off", "@typescript-eslint/no-unnecessary-type-constraint": "off", "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }] diff --git a/.github/workflows/asset-validation.yml b/.github/workflows/asset-validation.yml new file mode 100644 index 00000000..72cd2be0 --- /dev/null +++ b/.github/workflows/asset-validation.yml @@ -0,0 +1,142 @@ +name: Asset Validation & CI Safeguards + +on: + pull_request: + paths: + - 'resources/**' + - 'config/assets/**' + - 'capacitor-assets.config.json' + - 'capacitor.config.ts' + - 'capacitor.config.json' + push: + branches: [main, develop] + paths: + - 'resources/**' + - 'config/assets/**' + - 'capacitor-assets.config.json' + - 'capacitor.config.ts' + - 'capacitor.config.json' + +jobs: + asset-validation: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Validate asset configuration + run: npm run assets:validate + + - name: Check for committed platform assets (Android) + run: | + if git ls-files -z android/app/src/main/res | grep -E '(AppIcon.*\.png|Splash.*\.png|mipmap-.*/ic_launcher.*\.png)' > /dev/null; then + echo "❌ Android platform assets found in VCS - these should be generated at build-time" + git ls-files -z android/app/src/main/res | grep -E '(AppIcon.*\.png|Splash.*\.png|mipmap-.*/ic_launcher.*\.png)' + exit 1 + fi + echo "βœ… No Android platform assets committed" + + - name: Check for committed platform assets (iOS) + run: | + if git ls-files -z ios/App/App/Assets.xcassets | grep -E '(AppIcon.*\.png|Splash.*\.png)' > /dev/null; then + echo "❌ iOS platform assets found in VCS - these should be generated at build-time" + git ls-files -z ios/App/App/Assets.xcassets | grep -E '(AppIcon.*\.png|Splash.*\.png)' + exit 1 + fi + echo "βœ… No iOS platform assets committed" + + - name: Test asset generation + run: | + echo "πŸ§ͺ Testing asset generation workflow..." + npm run build:capacitor + npx cap sync + npx capacitor-assets generate --dry-run || npx capacitor-assets generate + echo "βœ… Asset generation test completed" + + - name: Verify clean tree after build + run: | + if [ -n "$(git status --porcelain)" ]; then + echo "❌ Dirty tree after build - asset configs were modified" + git status + git diff + exit 1 + fi + echo "βœ… Build completed with clean tree" + + schema-validation: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Validate schema compliance + run: | + echo "πŸ” Validating schema compliance..." + node -e " + const fs = require('fs'); + const config = JSON.parse(fs.readFileSync('capacitor-assets.config.json', 'utf8')); + const schema = JSON.parse(fs.readFileSync('config/assets/schema.json', 'utf8')); + + // Basic schema validation + if (!config.icon || !config.splash) { + throw new Error('Missing required sections: icon and splash'); + } + + if (!config.icon.source || !config.splash.source) { + throw new Error('Missing required source fields'); + } + + if (!/^resources\/.*\.(png|svg)$/.test(config.icon.source)) { + throw new Error('Icon source must be in resources/ directory'); + } + + if (!/^resources\/.*\.(png|svg)$/.test(config.splash.source)) { + throw new Error('Splash source must be in resources/ directory'); + } + + console.log('βœ… Schema validation passed'); + " + + - name: Check source file existence + run: | + echo "πŸ“ Checking source file existence..." + node -e " + const fs = require('fs'); + const config = JSON.parse(fs.readFileSync('capacitor-assets.config.json', 'utf8')); + + const requiredFiles = [ + config.icon.source, + config.splash.source + ]; + + if (config.splash.darkSource) { + requiredFiles.push(config.splash.darkSource); + } + + const missingFiles = requiredFiles.filter(file => !fs.existsSync(file)); + + if (missingFiles.length > 0) { + console.error('❌ Missing source files:', missingFiles); + process.exit(1); + } + + console.log('βœ… All source files exist'); + " diff --git a/.gitignore b/.gitignore index a9f37e49..4202ef2a 100644 --- a/.gitignore +++ b/.gitignore @@ -56,6 +56,10 @@ icons *.log +# Build outputs +dist/ +build/ + # Generated Android assets and resources (should be generated during build) android/app/src/main/assets/public/ @@ -64,6 +68,14 @@ android/app/src/main/res/drawable*/ android/app/src/main/res/mipmap*/ android/app/src/main/res/values/ic_launcher_background.xml +# Android generated assets (deny-listed in CI) +android/app/src/main/res/mipmap-*/ic_launcher*.png +android/app/src/main/res/drawable*/splash*.png + +# iOS generated assets (deny-listed in CI) +ios/App/App/Assets.xcassets/**/AppIcon*.png +ios/App/App/Assets.xcassets/**/Splash*.png + # Keep these Android configuration files in version control: # - android/app/src/main/assets/capacitor.plugins.json # - android/app/src/main/res/values/strings.xml diff --git a/.node-version b/.node-version new file mode 100644 index 00000000..a9d08739 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +18.19.0 diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000..a9d08739 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +18.19.0 diff --git a/BUILDING.md b/BUILDING.md index e1e94fcd..e5abf069 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -1017,47 +1017,27 @@ If you need to build manually or want to understand the individual steps: export GEM_PATH=$shortened_path ``` -1. Build the web assets & update ios: +1. Bump the version in package.json, then here. - ```bash - rm -rf dist - npm run build:web - npm run build:capacitor - npx cap sync ios - ``` - - - If that fails with "Could not find..." then look at the "gem_path" instructions above. - -3. Copy the assets: - - ```bash - # It makes no sense why capacitor-assets will not run without these but it actually changes the contents. - mkdir -p ios/App/App/Assets.xcassets/AppIcon.appiconset - echo '{"images":[]}' > ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json - mkdir -p ios/App/App/Assets.xcassets/Splash.imageset - echo '{"images":[]}' > ios/App/App/Assets.xcassets/Splash.imageset/Contents.json - npx capacitor-assets generate --ios ``` - -4. Bump the version to match Android & package.json: - - ``` - cd ios/App && xcrun agvtool new-version 39 && perl -p -i -e "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 1.0.6;/g" App.xcodeproj/project.pbxproj && cd - + cd ios/App && xcrun agvtool new-version 40 && perl -p -i -e "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 1.0.7;/g" App.xcodeproj/project.pbxproj && cd - # Unfortunately this edits Info.plist directly. #xcrun agvtool new-marketing-version 0.4.5 ``` -5. Open the project in Xcode: +2. Build. - ```bash - npx cap open ios - ``` + Here's prod. Also available: test, dev + + ```bash + npm run build:ios:prod + ``` -6. Use Xcode to build and run on simulator or device. +3.1. Use Xcode to build and run on simulator or device. * Select Product -> Destination with some Simulator version. Then click the run arrow. -7. Release +3.2. Use Xcode to release. * Someday: Under "General" we want to rename a bunch of things to "Time Safari" * Choose Product -> Destination -> Any iOS Device @@ -1125,35 +1105,28 @@ The recommended way to build for Android is using the automated build script: #### Manual Build Process -1. Build the web assets: - - ```bash - rm -rf dist - npm run build:web - npm run build:capacitor - ``` - -2. Update Android project with latest build: +1. Bump the version in package.json, then here: android/app/build.gradle - ```bash - npx cap sync android - ``` + ```bash + perl -p -i -e 's/versionCode .*/versionCode 40/g' android/app/build.gradle + perl -p -i -e 's/versionName .*/versionName "1.0.7"/g' android/app/build.gradle + ``` -3. Copy the assets +2. Build. - ```bash - npx capacitor-assets generate --android - ``` + Here's prod. Also available: test, dev -4. Bump version to match iOS & package.json: android/app/build.gradle + ```bash + npm run build:android:prod + ``` -5. Open the project in Android Studio: +3. Open the project in Android Studio: ```bash npx cap open android ``` -6. Use Android Studio to build and run on emulator or device. +4. Use Android Studio to build and run on emulator or device. ## Android Build from the console @@ -1186,9 +1159,9 @@ cd - At play.google.com/console: -- Go to the Testing Track (eg. Closed). +- Go to Production or the Closed Testing and either Create Track or Manage Track. - Click "Create new release". -- Upload the `aab` file. +- Upload the `aab` file from: app/build/outputs/bundle/release/app-release.aab - Hit "Next". - Save, go to "Publishing Overview" as prompted, and click "Send changes for review". diff --git a/CHANGELOG.md b/CHANGELOG.md index cf28e788..19209fb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,12 +5,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [1.0.3] - 2025.07.12 -### Changed -- Photo is pinned to profile mode +## [1.0.7] - 2025.08.18 ### Fixed -- Deep link URLs (and other prod settings) -- Error in BVC begin view +- Deep link for onboard-meeting-members + ## [1.0.6] - 2025.08.09 ### Fixed diff --git a/README.md b/README.md index 6992ba09..fc954fd5 100644 --- a/README.md +++ b/README.md @@ -136,11 +136,77 @@ const apiUrl = `${APP_SERVER}/api/claim/123`; See [TESTING.md](test-playwright/TESTING.md) for detailed test instructions. -## Icons +## Asset Management -Application icons are in the `assets` directory, processed by the `capacitor-assets` command. +TimeSafari uses a standardized asset configuration system for consistent +icon and splash screen generation across all platforms. -To add a Font Awesome icon, add to fontawesome.ts and reference with `font-awesome` element and `icon` attribute with the hyphenated name. +### Asset Sources + +- **Single source of truth**: `resources/` directory (Capacitor default) +- **Source files**: `icon.png`, `splash.png`, `splash_dark.png` +- **Format**: PNG or SVG files for optimal quality + +### Asset Generation + +- **Configuration**: `config/assets/capacitor-assets.config.json` +- **Schema validation**: `config/assets/schema.json` +- **Build-time generation**: Platform assets generated via `capacitor-assets` +- **No VCS commits**: Generated assets are never committed to version control + +### Development Commands + +```bash +# Generate/update asset configurations +npm run assets:config + +# Validate asset configurations +npm run assets:validate + +# Clean generated platform assets (local dev only) +npm run assets:clean + +# Build with asset generation +npm run build:native +``` + +### Environment Setup & Dependencies + +Before building the application, ensure your development environment is properly +configured: + +```bash +# Install all dependencies (required first time and after updates) +npm install + +# Validate your development environment +npm run check:dependencies + +# Check prerequisites for testing +npm run test:prerequisites +``` + +**Common Issues & Solutions**: + +- **"tsx: command not found"**: Run `npm install` to install devDependencies +- **"capacitor-assets: command not found"**: Ensure `@capacitor/assets` is installed +- **Build failures**: Run `npm run check:dependencies` to diagnose environment issues + +**Required Versions**: +- Node.js: 18+ (LTS recommended) +- npm: 8+ (comes with Node.js) +- Platform-specific tools: Android Studio, Xcode (for mobile builds) + +### Platform Support + +- **Android**: Adaptive icons with foreground/background, monochrome support +- **iOS**: LaunchScreen storyboard preferred, splash assets when needed +- **Web**: PWA icons generated during build to `dist/` (not committed) + +### Font Awesome Icons + +To add a Font Awesome icon, add to `fontawesome.ts` and reference with +`font-awesome` element and `icon` attribute with the hyphenated name. ## Other diff --git a/android/app/build.gradle b/android/app/build.gradle index a92af2db..57c34006 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -31,8 +31,8 @@ android { applicationId "app.timesafari.app" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 39 - versionName "1.0.6" + versionCode 40 + versionName "1.0.7" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" aaptOptions { // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. diff --git a/android/app/src/main/assets/capacitor.config.json b/android/app/src/main/assets/capacitor.config.json index 594ebca3..04ab8d0c 100644 --- a/android/app/src/main/assets/capacitor.config.json +++ b/android/app/src/main/assets/capacitor.config.json @@ -29,7 +29,7 @@ "splashFullScreen": true, "splashImmersive": true }, - "CapacitorSQLite": { + "CapSQLite": { "iosDatabaseLocation": "Library/CapacitorDatabase", "iosIsEncryption": false, "iosBiometric": { diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..79f802e1 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,7 @@ + + + #3F51B5 + #303F9F + #FF4081 + #FFFFFF + diff --git a/android/build.gradle b/android/build.gradle index 858b0bc0..4bd6375d 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -7,7 +7,7 @@ buildscript { mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:8.12.0' + classpath 'com.android.tools.build:gradle:8.12.1' classpath 'com.google.gms:google-services:4.4.0' // NOTE: Do not place your application dependencies here; they belong diff --git a/assets/README.md b/assets/README.md deleted file mode 100644 index b9272ff0..00000000 --- a/assets/README.md +++ /dev/null @@ -1,2 +0,0 @@ - -Application icons are here. They are processed for android & ios by the `capacitor-assets` command, as indicated in the BUILDING.md file. diff --git a/capacitor-assets.config.json b/capacitor-assets.config.json index d56533f4..92bd0414 100644 --- a/capacitor-assets.config.json +++ b/capacitor-assets.config.json @@ -1,36 +1,32 @@ { "icon": { - "ios": { - "source": "resources/ios/icon/icon.png", - "target": "ios/App/App/Assets.xcassets/AppIcon.appiconset" - }, "android": { - "source": "resources/android/icon/icon.png", + "adaptive": { + "background": "#121212", + "foreground": "resources/icon.png", + "monochrome": "resources/icon.png" + }, "target": "android/app/src/main/res" }, + "ios": { + "padding": 0, + "target": "ios/App/App/Assets.xcassets/AppIcon.appiconset" + }, + "source": "resources/icon.png", "web": { - "source": "resources/web/icon/icon.png", "target": "public/img/icons" } }, "splash": { - "ios": { - "source": "resources/ios/splash/splash.png", - "target": "ios/App/App/Assets.xcassets/Splash.imageset" - }, "android": { - "source": "resources/android/splash/splash.png", + "scale": "cover", "target": "android/app/src/main/res" - } - }, - "splashDark": { + }, + "darkSource": "resources/splash_dark.png", "ios": { - "source": "resources/ios/splash/splash_dark.png", - "target": "ios/App/App/Assets.xcassets/SplashDark.imageset" + "target": "ios/App/App/Assets.xcassets", + "useStoryBoard": true }, - "android": { - "source": "resources/android/splash/splash_dark.png", - "target": "android/app/src/main/res" - } + "source": "resources/splash.png" } -} \ No newline at end of file +} diff --git a/capacitor.config.ts b/capacitor.config.ts new file mode 100644 index 00000000..24ef38c6 --- /dev/null +++ b/capacitor.config.ts @@ -0,0 +1,116 @@ +import { CapacitorConfig } from '@capacitor/cli'; + +const config: CapacitorConfig = { + appId: 'app.timesafari', + appName: 'TimeSafari', + webDir: 'dist', + server: { + cleartext: true + }, + plugins: { + App: { + appUrlOpen: { + handlers: [ + { + url: 'timesafari://*', + autoVerify: true + } + ] + } + }, + SplashScreen: { + launchShowDuration: 3000, + launchAutoHide: true, + backgroundColor: '#ffffff', + androidSplashResourceName: 'splash', + androidScaleType: 'CENTER_CROP', + showSpinner: false, + androidSpinnerStyle: 'large', + iosSpinnerStyle: 'small', + spinnerColor: '#999999', + splashFullScreen: true, + splashImmersive: true + }, + CapSQLite: { + iosDatabaseLocation: 'Library/CapacitorDatabase', + iosIsEncryption: false, + iosBiometric: { + biometricAuth: false, + biometricTitle: 'Biometric login for TimeSafari' + }, + androidIsEncryption: false, + androidBiometric: { + biometricAuth: false, + biometricTitle: 'Biometric login for TimeSafari' + }, + electronIsEncryption: false + } + }, + ios: { + contentInset: 'never', + allowsLinkPreview: true, + scrollEnabled: true, + limitsNavigationsToAppBoundDomains: true, + backgroundColor: '#ffffff', + allowNavigation: [ + '*.timesafari.app', + '*.jsdelivr.net', + 'api.endorser.ch' + ] + }, + android: { + allowMixedContent: true, + captureInput: true, + webContentsDebuggingEnabled: false, + allowNavigation: [ + '*.timesafari.app', + '*.jsdelivr.net', + 'api.endorser.ch', + '10.0.2.2:3000' + ] + }, + electron: { + deepLinking: { + schemes: ['timesafari'] + }, + buildOptions: { + appId: 'app.timesafari', + productName: 'TimeSafari', + directories: { + output: 'dist-electron-packages' + }, + files: [ + 'dist/**/*', + 'electron/**/*' + ], + mac: { + category: 'public.app-category.productivity', + target: [ + { + target: 'dmg', + arch: ['x64', 'arm64'] + } + ] + }, + win: { + target: [ + { + target: 'nsis', + arch: ['x64'] + } + ] + }, + linux: { + target: [ + { + target: 'AppImage', + arch: ['x64'] + } + ], + category: 'Utility' + } + } + } +}; + +export default config; diff --git a/config/assets/capacitor-assets.config.json b/config/assets/capacitor-assets.config.json new file mode 100644 index 00000000..92bd0414 --- /dev/null +++ b/config/assets/capacitor-assets.config.json @@ -0,0 +1,32 @@ +{ + "icon": { + "android": { + "adaptive": { + "background": "#121212", + "foreground": "resources/icon.png", + "monochrome": "resources/icon.png" + }, + "target": "android/app/src/main/res" + }, + "ios": { + "padding": 0, + "target": "ios/App/App/Assets.xcassets/AppIcon.appiconset" + }, + "source": "resources/icon.png", + "web": { + "target": "public/img/icons" + } + }, + "splash": { + "android": { + "scale": "cover", + "target": "android/app/src/main/res" + }, + "darkSource": "resources/splash_dark.png", + "ios": { + "target": "ios/App/App/Assets.xcassets", + "useStoryBoard": true + }, + "source": "resources/splash.png" + } +} diff --git a/config/assets/schema.json b/config/assets/schema.json new file mode 100644 index 00000000..89e76c0c --- /dev/null +++ b/config/assets/schema.json @@ -0,0 +1,119 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Capacitor Assets Configuration Schema", + "description": "Schema for validating capacitor-assets configuration files", + "type": "object", + "properties": { + "icon": { + "type": "object", + "properties": { + "source": { + "type": "string", + "pattern": "^resources/.*\\.(png|svg)$", + "description": "Source icon file path relative to project root" + }, + "android": { + "type": "object", + "properties": { + "adaptive": { + "type": "object", + "properties": { + "foreground": { + "type": "string", + "pattern": "^resources/.*\\.(png|svg)$", + "description": "Foreground icon for Android adaptive icons" + }, + "background": { + "type": ["string", "object"], + "description": "Background color or image for adaptive icons" + }, + "monochrome": { + "type": "string", + "pattern": "^resources/.*\\.(png|svg)$", + "description": "Monochrome icon for Android 13+" + } + }, + "required": ["foreground", "background"] + }, + "target": { + "type": "string", + "description": "Android target directory for generated icons" + } + } + }, + "ios": { + "type": "object", + "properties": { + "padding": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Padding ratio for iOS icons" + }, + "target": { + "type": "string", + "description": "iOS target directory for generated icons" + } + } + }, + "web": { + "type": "object", + "properties": { + "target": { + "type": "string", + "description": "Web target directory for generated icons" + } + } + } + }, + "required": ["source"], + "additionalProperties": false + }, + "splash": { + "type": "object", + "properties": { + "source": { + "type": "string", + "pattern": "^resources/.*\\.(png|svg)$", + "description": "Source splash screen file" + }, + "darkSource": { + "type": "string", + "pattern": "^resources/.*\\.(png|svg)$", + "description": "Dark mode splash screen file" + }, + "android": { + "type": "object", + "properties": { + "scale": { + "type": "string", + "enum": ["cover", "contain", "fill"], + "description": "Android splash screen scaling mode" + }, + "target": { + "type": "string", + "description": "Android target directory for splash screens" + } + } + }, + "ios": { + "type": "object", + "properties": { + "useStoryBoard": { + "type": "boolean", + "description": "Use LaunchScreen storyboard instead of splash assets" + }, + "target": { + "type": "string", + "description": "iOS target directory for splash screens" + } + } + } + }, + "required": ["source"], + "additionalProperties": false + } + }, + "required": ["icon", "splash"], + "additionalProperties": false +} diff --git a/doc/asset-migration-plan.md b/doc/asset-migration-plan.md new file mode 100644 index 00000000..3a05353c --- /dev/null +++ b/doc/asset-migration-plan.md @@ -0,0 +1,214 @@ +# TimeSafari Asset Configuration Migration Plan + +**Author**: Matthew Raymer +**Date**: 2025-08-14 +**Status**: 🎯 **IMPLEMENTATION** - Ready for Execution + +## Overview + +This document outlines the migration from the current mixed asset management +system to a standardized, single-source asset configuration approach using +`capacitor-assets` as the standard generator. + +## Current State Analysis + +### Asset Sources (Duplicated) + +- **`assets/` directory**: Contains `icon.png`, `splash.png`, `splash_dark.png` +- **`resources/` directory**: Contains identical files in platform-specific subdirectories +- **Result**: Duplicate storage, confusion about source of truth + +### Asset Generation (Manual) + +- **Custom scripts**: `generate-icons.sh`, `generate-ios-assets.sh`, `generate-android-icons.sh` +- **Bypass capacitor-assets**: Manual ImageMagick-based generation +- **Inconsistent outputs**: Different generation methods for each platform + +### Configuration (Scattered) + +- **`capacitor-assets.config.json`**: Basic configuration at root +- **Platform-specific configs**: Mixed in various build scripts +- **No validation**: No schema or consistency checks + +## Target State + +### Single Source of Truth + +- **`resources/` directory**: Capacitor default location for source assets +- **Eliminate duplication**: Remove `assets/` directory after migration +- **Standardized paths**: All tools read from `resources/` + +### Standardized Generation + +- **`capacitor-assets`**: Single tool for all platform asset generation +- **Build-time generation**: Assets generated during build, not committed +- **Deterministic outputs**: Same inputs β†’ same outputs every time + +### Centralized Configuration + +- **`config/assets/`**: All asset-related configuration files +- **Schema validation**: JSON schema for configuration validation +- **CI safeguards**: Automated validation and compliance checks + +## Migration Steps + +### Phase 1: Foundation Setup βœ… + +- [x] Create `config/assets/` directory structure +- [x] Create asset configuration schema (`schema.json`) +- [x] Create enhanced capacitor-assets configuration +- [x] Convert `capacitor.config.json` to `capacitor.config.ts` +- [x] Pin Node.js version (`.nvmrc`, `.node-version`) +- [x] Create dev-time asset configuration generator +- [x] Create asset configuration validator +- [x] Add npm scripts for asset management +- [x] Update `.gitignore` with proper asset exclusions +- [x] Create CI workflow for asset validation + +### Phase 2: Validation & Testing + +- [ ] Run `npm run assets:config` to generate new configuration +- [ ] Run `npm run assets:validate` to verify configuration +- [ ] Test `npm run build:native` workflow +- [ ] Verify CI workflow passes all checks +- [ ] Confirm no platform assets are committed to VCS + +### Phase 3: Cleanup & Removal + +- [ ] Remove `assets/` directory (after validation) +- [ ] Remove manual asset generation scripts +- [ ] Remove asset checking scripts +- [ ] Update documentation references +- [ ] Final validation of clean state + +## Implementation Details + +### File Structure + +``` +resources/ # Image sources ONLY + icon.png + splash.png + splash_dark.png + +config/assets/ # Versioned config & schema + capacitor-assets.config.json + schema.json + +scripts/ + assets-config.js # Dev-time config generator + assets-validator.js # Schema validator +``` + +### Configuration Schema + +The schema enforces: +- Source files must be in `resources/` directory +- Required fields for icon and splash sections +- Android adaptive icon support (foreground/background/monochrome) +- iOS LaunchScreen preferences +- Target directory validation + +### CI Safeguards + +- **Schema validation**: Configuration must comply with schema +- **Source file validation**: All referenced files must exist +- **Platform asset denial**: Reject commits with generated assets +- **Clean tree enforcement**: Build must not modify committed configs + +## Testing Strategy + +### Local Validation + +```bash +# Generate configuration +npm run assets:config + +# Validate configuration +npm run assets:validate + +# Test build workflow +npm run build:native + +# Clean generated assets +npm run assets:clean +``` + +### CI Validation + +- **Asset validation workflow**: Runs on asset-related changes +- **Schema compliance**: Ensures configuration follows schema +- **Source file existence**: Verifies all referenced files exist +- **Platform asset detection**: Prevents committed generated assets +- **Build tree verification**: Ensures clean tree after build + +## Risk Mitigation + +### Data Loss Prevention + +- **Backup branch**: Create backup before removing `assets/` +- **Validation checks**: Multiple validation steps before removal +- **Gradual migration**: Phase-by-phase approach with rollback capability + +### Build Continuity + +- **Per-platform scripts unchanged**: All existing build orchestration preserved +- **Standard toolchain**: Uses capacitor-assets, not custom scripts +- **Fallback support**: Manual scripts remain until migration complete + +### Configuration Consistency + +- **Schema enforcement**: JSON schema prevents invalid configurations +- **CI validation**: Automated checks catch configuration issues +- **Documentation updates**: Clear guidance for future changes + +## Success Criteria + +### Technical Requirements + +- [ ] Single source of truth in `resources/` directory +- [ ] All platform assets generated via `capacitor-assets` +- [ ] No manual asset generation scripts +- [ ] Configuration validation passes all checks +- [ ] CI workflow enforces asset policies + +### Quality Metrics + +- [ ] Zero duplicate asset sources +- [ ] 100% configuration schema compliance +- [ ] No platform assets committed to VCS +- [ ] Clean build tree after asset generation +- [ ] Deterministic asset outputs + +### User Experience + +- [ ] Clear asset management documentation +- [ ] Simple development commands +- [ ] Consistent asset generation across platforms +- [ ] Reduced confusion about asset sources + +## Next Steps + +1. **Execute Phase 2**: Run validation and testing steps +2. **Verify CI workflow**: Ensure all checks pass +3. **Execute Phase 3**: Remove duplicate assets and scripts +4. **Update documentation**: Finalize README and BUILDING.md +5. **Team training**: Ensure all developers understand new workflow + +## Rollback Plan + +If issues arise during migration: + +1. **Restore backup branch**: `git checkout backup-before-asset-migration` +2. **Revert configuration changes**: Remove new config files +3. **Restore manual scripts**: Re-enable previous asset generation +4. **Investigate issues**: Identify and resolve root causes +5. **Plan revised migration**: Adjust approach based on lessons learned + +--- + +**Status**: Ready for Phase 2 execution +**Priority**: High +**Estimated Effort**: 2-3 hours +**Dependencies**: CI workflow validation +**Stakeholders**: Development team diff --git a/doc/debug-hook-guide.md b/doc/debug-hook-guide.md new file mode 100644 index 00000000..956a21e7 --- /dev/null +++ b/doc/debug-hook-guide.md @@ -0,0 +1,182 @@ +# TimeSafari Debug Hook Guide + +**Complete Guide for Team Members** + +**Date**: 2025-01-27 +**Author**: Matthew Raymer +**Status**: βœ… **ACTIVE** - Ready for production use + +## 🎯 Overview + +A pre-commit hook that automatically detects and prevents debug code from reaching protected branches (master, main, production, release, stable). This ensures production code remains clean while allowing free development on feature branches. + +## πŸš€ Quick Installation + +**From within the TimeSafari repository:** + +```bash +./scripts/install-debug-hook.sh +``` + +This automatically installs, updates, and verifies the hook in your current +repository. **Note**: Hooks are not automatically installed - you must run this +script deliberately to enable debug code checking. + +## πŸ”§ Manual Installation + +**Copy files manually:** + +```bash +cp scripts/git-hooks/pre-commit /path/to/your/repo/.git/hooks/ +cp scripts/git-hooks/debug-checker.config /path/to/your/repo/.git/hooks/ +chmod +x /path/to/your/repo/.git/hooks/pre-commit +``` + +## πŸ“‹ What Gets Installed + +- **`pre-commit`** - Main hook script (executable) +- **`debug-checker.config`** - Configuration file +- **`README.md`** - Documentation and troubleshooting + +**Note**: Hooks are stored in `scripts/git-hooks/` and must be deliberately +installed by each developer. They are not automatically active. + +## 🎯 How It Works + +1. **Deliberate Installation**: Hooks must be explicitly installed by each + developer +2. **Branch Detection**: Only runs on protected branches +3. **File Filtering**: Automatically skips tests, scripts, and documentation +4. **Pattern Matching**: Detects debug code using regex patterns +5. **Commit Prevention**: Blocks commits containing debug code + +## πŸ”’ Installation Philosophy + +**Why deliberate installation?** + +- **Developer choice**: Each developer decides whether to use the hook +- **No forced behavior**: Hooks don't interfere with existing workflows +- **Local control**: Hooks are installed locally, not globally +- **Easy removal**: Can be uninstalled at any time +- **Team flexibility**: Some developers may prefer different tools + +## 🌿 Branch Behavior + +- **Protected branches** (master, main, production, release, stable): Hook runs automatically +- **Feature branches**: Hook is skipped, allowing free development with debug code + +## πŸ” Debug Patterns Detected + +- **Console statements**: `console.log`, `console.debug`, `console.error` +- **Template debug**: `Debug:`, `debug:` in Vue templates +- **Debug constants**: `DEBUG_`, `debug_` variables +- **HTML debug**: `" 1 + +echo -e "\n${BLUE}Test Case 7: Debug attribute (should fail)${NC}" +run_test "Debug attribute" "
content
" 1 + +echo -e "\n${BLUE}Test Case 8: Test file (should be skipped)${NC}" +run_test "Test file" "console.log('this should be skipped')" 0 + +# Test branch detection +echo -e "\n${BLUE}Testing branch detection...${NC}" +cd "$TEST_DIR" +git init > /dev/null 2>&1 +git checkout -b feature-branch > /dev/null 2>&1 +echo "console.log('debug')" > test.vue +git add test.vue > /dev/null 2>&1 + +if bash ../../.git/hooks/pre-commit > hook_output.txt 2>&1; then + echo -e " ${GREEN}βœ… PASS${NC} - Hook skipped on feature branch" +else + echo -e " ${RED}❌ FAIL${NC} - Hook should have been skipped on feature branch" + echo -e " ${YELLOW}Hook output:${NC}" + cat hook_output.txt +fi + +rm -rf .git +rm -f hook_output.txt + +echo -e "\n${GREEN}πŸŽ‰ All tests completed!${NC}" +echo -e "\n${BLUE}To test manually:${NC}" +echo "1. Make changes to a file with debug code" +echo "2. Stage the file: git add " +echo "3. Try to commit: git commit -m 'test'" +echo "4. The hook should prevent the commit if debug code is found" diff --git a/scripts/type-safety-check.sh b/scripts/type-safety-check.sh new file mode 100755 index 00000000..399343df --- /dev/null +++ b/scripts/type-safety-check.sh @@ -0,0 +1,103 @@ +#!/bin/bash + +# Type Safety Pre-commit Check Script +# This script ensures type safety before commits by running linting and type checking + +set -e + +echo "πŸ” Running Type Safety Pre-commit Checks..." + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Function to print colored output +print_status() { + echo -e "${GREEN}βœ… $1${NC}" +} + +print_warning() { + echo -e "${YELLOW}⚠️ $1${NC}" +} + +print_error() { + echo -e "${RED}❌ $1${NC}" +} + +# Check if we're in the right directory +if [ ! -f "package.json" ]; then + print_error "Must run from project root directory" + exit 1 +fi + +# Step 1: Run ESLint with TypeScript rules +print_status "Running ESLint TypeScript checks..." +if npm run lint > /dev/null 2>&1; then + print_status "ESLint passed - no type safety issues found" +else + print_error "ESLint failed - type safety issues detected" + echo "" + echo "Running lint with details..." + npm run lint + echo "" + print_error "Please fix the above type safety issues before committing" + exit 1 +fi + +# Step 2: Run TypeScript type checking +print_status "Running TypeScript type checking..." +if npm run type-check > /dev/null 2>&1; then + print_status "TypeScript compilation passed" +else + print_error "TypeScript compilation failed" + echo "" + echo "Running type check with details..." + npm run type-check + echo "" + print_error "Please fix the above TypeScript errors before committing" + exit 1 +fi + +# Step 3: Check for any remaining 'any' types +print_status "Scanning for any remaining 'any' types..." +ANY_COUNT=$(grep -r "any" src/ --include="*.ts" --include="*.vue" | grep -v "// eslint-disable" | grep -v "eslint-disable-next-line" | wc -l) + +if [ "$ANY_COUNT" -eq 0 ]; then + print_status "No 'any' types found in source code" +else + print_warning "Found $ANY_COUNT instances of 'any' type usage" + echo "" + echo "Instances found:" + grep -r "any" src/ --include="*.ts" --include="*.vue" | grep -v "// eslint-disable" | grep -v "eslint-disable-next-line" || true + echo "" + print_error "Please replace 'any' types with proper TypeScript types before committing" + exit 1 +fi + +# Step 4: Verify database migration status +print_status "Checking database migration status..." +if grep -r "databaseUtil" src/ --include="*.ts" --include="*.vue" > /dev/null 2>&1; then + print_warning "Found databaseUtil imports - ensure migration is complete" + echo "" + echo "Files with databaseUtil imports:" + grep -r "databaseUtil" src/ --include="*.ts" --include="*.vue" | head -5 || true + echo "" + print_warning "Consider completing database migration to PlatformServiceMixin" +else + print_status "No databaseUtil imports found - migration appears complete" +fi + +# All checks passed +echo "" +print_status "All type safety checks passed! πŸŽ‰" +print_status "Your code is ready for commit" +echo "" +echo "πŸ“š Remember to follow the Type Safety Guidelines:" +echo " - docs/typescript-type-safety-guidelines.md" +echo " - Use proper error handling patterns" +echo " - Leverage existing type definitions" +echo " - Run 'npm run lint-fix' for automatic fixes" + +exit 0 diff --git a/src/assets/icons.json b/src/assets/icons.json deleted file mode 100644 index 434421e6..00000000 --- a/src/assets/icons.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "warning": { - "fillRule": "evenodd", - "d": "M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z", - "clipRule": "evenodd" - }, - "spinner": { - "d": "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" - }, - "chart": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" - }, - "plus": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M12 4v16m8-8H4" - }, - "settings": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" - }, - "settingsDot": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M15 12a3 3 0 11-6 0 3 3 0 016 0z" - }, - "lock": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" - }, - "download": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" - }, - "check": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" - }, - "edit": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" - }, - "trash": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" - }, - "plusCircle": { - "strokeLinecap": "round", - "strokeLinejoin": "round", - "strokeWidth": "2", - "d": "M12 6v6m0 0v6m0-6h6m-6 0H6" - }, - "info": { - "fillRule": "evenodd", - "d": "M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z", - "clipRule": "evenodd" - } -} \ No newline at end of file diff --git a/src/components/ActivityListItem.vue b/src/components/ActivityListItem.vue index c68281da..39dfcffa 100644 --- a/src/components/ActivityListItem.vue +++ b/src/components/ActivityListItem.vue @@ -288,8 +288,7 @@ export default class ActivityListItem extends Vue { } get fetchAmount(): string { - const claim = - (this.record.fullClaim as any)?.claim || this.record.fullClaim; + const claim = this.record.fullClaim; const amount = claim.object?.amountOfThisGood ? this.displayAmount(claim.object.unitCode, claim.object.amountOfThisGood) @@ -299,8 +298,7 @@ export default class ActivityListItem extends Vue { } get description(): string { - const claim = - (this.record.fullClaim as any)?.claim || this.record.fullClaim; + const claim = this.record.fullClaim; return `${claim?.description || ""}`; } diff --git a/src/components/DataExportSection.vue b/src/components/DataExportSection.vue index a21be7b2..61bf4753 100644 --- a/src/components/DataExportSection.vue +++ b/src/components/DataExportSection.vue @@ -171,6 +171,8 @@ export default class DataExportSection extends Vue { * @throws {Error} If export fails */ public async exportDatabase(): Promise { + // Note that similar code is in ContactsView.vue exportContactData() + if (this.isExporting) { return; // Prevent multiple simultaneous exports } diff --git a/src/components/FeedFilters.vue b/src/components/FeedFilters.vue index e0ab2f9e..956685e9 100644 --- a/src/components/FeedFilters.vue +++ b/src/components/FeedFilters.vue @@ -101,6 +101,7 @@ import { import { Router } from "vue-router"; import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin"; +import { logger } from "@/utils/logger"; @Component({ components: { @@ -119,11 +120,13 @@ export default class FeedFilters extends Vue { isNearby = false; settingChanged = false; visible = false; + activeDid = ""; - async open(onCloseIfChanged: () => void) { + async open(onCloseIfChanged: () => void, activeDid: string) { this.onCloseIfChanged = onCloseIfChanged; + this.activeDid = activeDid; - const settings = await this.$settings(); + const settings = await this.$accountSettings(activeDid); this.hasVisibleDid = !!settings.filterFeedByVisible; this.isNearby = !!settings.filterFeedByNearby; if (settings.searchBoxes && settings.searchBoxes.length > 0) { @@ -137,6 +140,7 @@ export default class FeedFilters extends Vue { async toggleHasVisibleDid() { this.settingChanged = true; this.hasVisibleDid = !this.hasVisibleDid; + await this.$updateSettings({ filterFeedByVisible: this.hasVisibleDid, }); @@ -145,9 +149,18 @@ export default class FeedFilters extends Vue { async toggleNearby() { this.settingChanged = true; this.isNearby = !this.isNearby; + + logger.debug("[FeedFilters] πŸ”„ Toggling nearby filter:", { + newValue: this.isNearby, + settingChanged: this.settingChanged, + activeDid: this.activeDid, + }); + await this.$updateSettings({ filterFeedByNearby: this.isNearby, }); + + logger.debug("[FeedFilters] βœ… Nearby filter updated in settings"); } async clearAll() { @@ -179,13 +192,20 @@ export default class FeedFilters extends Vue { } close() { + logger.debug("[FeedFilters] πŸšͺ Closing dialog:", { + settingChanged: this.settingChanged, + hasCallback: !!this.onCloseIfChanged, + }); + if (this.settingChanged) { + logger.debug("[FeedFilters] πŸ”„ Settings changed, calling callback"); this.onCloseIfChanged(); } this.visible = false; } done() { + logger.debug("[FeedFilters] βœ… Done button clicked"); this.close(); } } diff --git a/src/components/GiftedDialog.vue b/src/components/GiftedDialog.vue index 83a8b93d..0b9cd16a 100644 --- a/src/components/GiftedDialog.vue +++ b/src/components/GiftedDialog.vue @@ -622,7 +622,10 @@ export default class GiftedDialog extends Vue { * Handle edit entity request from GiftDetailsStep * @param data - Object containing entityType and currentEntity */ - handleEditEntity(data: { entityType: string; currentEntity: any }) { + handleEditEntity(data: { + entityType: string; + currentEntity: { did: string; name: string }; + }) { this.goBackToStep1(data.entityType); } diff --git a/src/components/IconRenderer.vue b/src/components/IconRenderer.vue deleted file mode 100644 index 83a0b14c..00000000 --- a/src/components/IconRenderer.vue +++ /dev/null @@ -1,90 +0,0 @@ - - - diff --git a/src/components/UsageLimitsSection.vue b/src/components/UsageLimitsSection.vue index 4eb9d8ef..ed53393d 100644 --- a/src/components/UsageLimitsSection.vue +++ b/src/components/UsageLimitsSection.vue @@ -83,6 +83,7 @@