From 86e9aa75c1b7a4997c68049d01ae5a80b13bb470 Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Tue, 19 Aug 2025 03:47:57 +0000 Subject: [PATCH 1/9] fix(types): resolve TypeScript any type violations - Replace any types in ProfileService with AxiosErrorResponse interface - Add type-safe error URL extraction method - Fix Leaflet icon type assertion using Record - Enhance AxiosErrorResponse interface with missing properties - Maintain existing functionality while improving type safety Closes typing violations in ProfileService.ts and AccountViewView.vue --- src/interfaces/common.ts | 6 ++- src/services/ProfileService.ts | 55 +++++++++++++++------------ src/views/AccountViewView.vue | 69 +++++++++++++++++++++------------- 3 files changed, 78 insertions(+), 52 deletions(-) diff --git a/src/interfaces/common.ts b/src/interfaces/common.ts index 9267cf70..b2e68d1f 100644 --- a/src/interfaces/common.ts +++ b/src/interfaces/common.ts @@ -60,9 +60,13 @@ export interface AxiosErrorResponse { [key: string]: unknown; }; status?: number; + statusText?: string; config?: unknown; }; - config?: unknown; + config?: { + url?: string; + [key: string]: unknown; + }; [key: string]: unknown; } diff --git a/src/services/ProfileService.ts b/src/services/ProfileService.ts index bdb27f46..26dbe9f3 100644 --- a/src/services/ProfileService.ts +++ b/src/services/ProfileService.ts @@ -10,6 +10,7 @@ import { getHeaders, errorStringForLog } from "@/libs/endorserServer"; import { handleApiError } from "./api"; import { logger } from "@/utils/logger"; import { ACCOUNT_VIEW_CONSTANTS } from "@/constants/accountView"; +import { AxiosErrorResponse } from "@/interfaces/common"; /** * Profile data interface @@ -124,36 +125,29 @@ export class ProfileService { async deleteProfile(activeDid: string): Promise { try { const headers = await getHeaders(activeDid); - logger.debug("Attempting to delete profile for DID:", activeDid); - logger.debug("Using partner API server:", this.partnerApiServer); - logger.debug("Request headers:", headers); - - const url = `${this.partnerApiServer}/api/partner/userProfile`; - logger.debug("DELETE request URL:", url); - - const response = await this.axios.delete(url, { headers }); + const response = await this.axios.delete( + `${this.partnerApiServer}/api/partner/userProfile`, + { headers }, + ); - if (response.status === 200 || response.status === 204) { - logger.debug("Profile deleted successfully"); + if (response.status === 204 || response.status === 200) { + logger.info("Profile deleted successfully"); return true; } else { - logger.error("Unexpected response status when deleting profile:", { - status: response.status, - statusText: response.statusText, - data: response.data - }); - throw new Error(`Profile not deleted - HTTP ${response.status}: ${response.statusText}`); + throw new Error( + `Profile not deleted - HTTP ${response.status}: ${response.statusText}`, + ); } } catch (error) { if (this.isApiError(error) && error.response) { - const response = error.response as any; // Type assertion for error response + const response = error.response; logger.error("API error deleting profile:", { status: response.status, statusText: response.statusText, data: response.data, - url: (error as any).config?.url + url: this.getErrorUrl(error), }); - + // Handle specific HTTP status codes if (response.status === 204) { logger.debug("Profile deleted successfully (204 No Content)"); @@ -163,7 +157,9 @@ export class ProfileService { return true; // Consider this a success if profile doesn't exist } else if (response.status === 400) { logger.error("Bad request when deleting profile:", response.data); - throw new Error(`Profile deletion failed: ${response.data?.message || 'Bad request'}`); + throw new Error( + `Profile deletion failed: ${response.data?.error?.message || "Bad request"}`, + ); } else if (response.status === 401) { logger.error("Unauthorized to delete profile"); throw new Error("You are not authorized to delete this profile"); @@ -172,7 +168,7 @@ export class ProfileService { throw new Error("You are not allowed to delete this profile"); } } - + logger.error("Error deleting profile:", errorStringForLog(error)); handleApiError(error as AxiosError, "/api/partner/userProfile"); return false; @@ -242,13 +238,22 @@ export class ProfileService { } /** - * Type guard for API errors + * Type guard for API errors with proper typing */ - private isApiError( - error: unknown, - ): error is { response?: { status?: number } } { + private isApiError(error: unknown): error is AxiosErrorResponse { return typeof error === "object" && error !== null && "response" in error; } + + /** + * Extract error URL safely from error object + */ + private getErrorUrl(error: unknown): string | undefined { + if (this.isApiError(error) && error.config) { + const config = error.config as { url?: string }; + return config.url; + } + return undefined; + } } /** diff --git a/src/views/AccountViewView.vue b/src/views/AccountViewView.vue index 1c38a8bb..5be23edf 100644 --- a/src/views/AccountViewView.vue +++ b/src/views/AccountViewView.vue @@ -174,16 +174,18 @@ :aria-busy="loadingProfile || savingProfile" > -
- - - (Debug: {{ isMapReady ? 'Map Ready' : 'Map Loading' }}) -
+
+ + + (Debug: {{ isMapReady ? "Map Ready" : "Map Loading" }}) +

The location you choose will be shared with the world until you remove @@ -918,15 +920,21 @@ export default class AccountViewView extends Vue { created() { this.notify = createNotifyHelpers(this.$notify); - + // Fix Leaflet icon issues in modern bundlers // This prevents the "Cannot read properties of undefined (reading 'Default')" error if (L.Icon.Default) { - delete (L.Icon.Default.prototype as any)._getIconUrl; + // Type-safe way to handle Leaflet icon prototype + const iconDefault = L.Icon.Default.prototype as Record; + if ("_getIconUrl" in iconDefault) { + delete iconDefault._getIconUrl; + } L.Icon.Default.mergeOptions({ - iconRetinaUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon-2x.png', - iconUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon.png', - shadowUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-shadow.png', + iconRetinaUrl: + "https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon-2x.png", + iconUrl: "https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon.png", + shadowUrl: + "https://unpkg.com/leaflet@1.7.1/dist/images/marker-shadow.png", }); } } @@ -955,7 +963,7 @@ export default class AccountViewView extends Vue { this.userProfileLatitude = profile.latitude; this.userProfileLongitude = profile.longitude; this.includeUserProfileLocation = profile.includeLocation; - + // Initialize map ready state if location is included if (profile.includeLocation) { this.isMapReady = false; // Will be set to true when map is ready @@ -1543,12 +1551,18 @@ export default class AccountViewView extends Vue { try { logger.debug("Map ready event fired, map object:", map); // doing this here instead of on the l-map element avoids a recentering after a drag then zoom at startup - const zoom = this.userProfileLatitude && this.userProfileLongitude ? 12 : 2; + const zoom = + this.userProfileLatitude && this.userProfileLongitude ? 12 : 2; const lat = this.userProfileLatitude || 0; const lng = this.userProfileLongitude || 0; map.setView([lat, lng], zoom); this.isMapReady = true; - logger.debug("Map ready state set to true, coordinates:", [lat, lng], "zoom:", zoom); + logger.debug( + "Map ready state set to true, coordinates:", + [lat, lng], + "zoom:", + zoom, + ); } catch (error) { logger.error("Error in onMapReady:", error); this.isMapReady = true; // Set to true even on error to prevent infinite loading @@ -1560,7 +1574,7 @@ export default class AccountViewView extends Vue { // Check if map ref is available const mapRef = this.$refs.profileMap; logger.debug("Map ref:", mapRef); - + // Try to set map ready after component is mounted setTimeout(() => { this.isMapReady = true; @@ -1597,9 +1611,9 @@ export default class AccountViewView extends Vue { longitude: this.userProfileLongitude, includeLocation: this.includeUserProfileLocation, }; - + logger.debug("Saving profile data:", profileData); - + const success = await this.profileService.saveProfile( this.activeDid, profileData, @@ -1628,7 +1642,7 @@ export default class AccountViewView extends Vue { this.userProfileLatitude = updated.latitude; this.userProfileLongitude = updated.longitude; this.includeUserProfileLocation = updated.includeLocation; - + // Reset map ready state when toggling location if (!updated.includeLocation) { this.isMapReady = false; @@ -1679,7 +1693,7 @@ export default class AccountViewView extends Vue { } } catch (error) { logger.error("Error in deleteProfile component method:", error); - + // Show more specific error message if available if (error instanceof Error) { this.notify.error(error.message); @@ -1710,7 +1724,10 @@ export default class AccountViewView extends Vue { onLocationCheckboxChange(): void { try { - logger.debug("Location checkbox changed, new value:", this.includeUserProfileLocation); + logger.debug( + "Location checkbox changed, new value:", + this.includeUserProfileLocation, + ); if (!this.includeUserProfileLocation) { // Location checkbox was unchecked, clean up map state this.isMapReady = false; @@ -1721,7 +1738,7 @@ export default class AccountViewView extends Vue { // Location checkbox was checked, start map initialization timeout this.isMapReady = false; logger.debug("Location checked, starting map initialization timeout"); - + // Try to set map ready after a short delay to allow Vue to render setTimeout(() => { if (!this.isMapReady) { @@ -1729,7 +1746,7 @@ export default class AccountViewView extends Vue { this.isMapReady = true; } }, 1000); // 1 second delay - + this.handleMapInitFailure(); } } catch (error) { From ab23d491457ef422a83d8de5871765af1523349f Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Tue, 19 Aug 2025 03:48:53 +0000 Subject: [PATCH 2/9] docs(rules): enhance development guidelines with type safety and dependency management - Add comprehensive Type Safety Enforcement section with core rules and patterns - Include Type Guard Patterns for API, Database, and Axios error handling - Add Implementation Guidelines for avoiding type assertions and proper type narrowing - Enhance software development ruleset with dependency management best practices - Add pre-build validation workflows and environment impact assessment - Include dependency validation strategies and common pitfalls guidance - Add build script enhancement recommendations for early validation Improves development workflow consistency and type safety enforcement --- .../rules/development/type_safety_guide.mdc | 17 +++ .cursor/rules/software_development.mdc | 118 +++++++----------- 2 files changed, 59 insertions(+), 76 deletions(-) diff --git a/.cursor/rules/development/type_safety_guide.mdc b/.cursor/rules/development/type_safety_guide.mdc index 507e3f23..6dba1416 100644 --- a/.cursor/rules/development/type_safety_guide.mdc +++ b/.cursor/rules/development/type_safety_guide.mdc @@ -40,6 +40,23 @@ Practical rules to keep TypeScript strict and predictable. Minimize exceptions. - 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 diff --git a/.cursor/rules/software_development.mdc b/.cursor/rules/software_development.mdc index f84bd5a2..745317cd 100644 --- a/.cursor/rules/software_development.mdc +++ b/.cursor/rules/software_development.mdc @@ -1,6 +1,3 @@ ---- -alwaysApply: true ---- # Software Development Ruleset @@ -89,90 +86,59 @@ Specialized guidelines for software development tasks including code review, deb - [ ] Solution complexity justified by evidence - [ ] Simpler alternatives considered and documented - [ ] Impact on existing systems assessed -# Software Development Ruleset +- [ ] Dependencies validated and accessible +- [ ] Environment impact assessed for team members +- [ ] Pre-build validation implemented where appropriate -## Purpose -Specialized guidelines for software development tasks including code review, debugging, architecture decisions, and testing. +## Additional Core Principles -## 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 -### 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" +## Additional Required Workflows -### 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 +### Dependency Validation (Before Proposing Changes) +- [ ] **Dependency Validation**: Verify all required dependencies are available and accessible -### 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? +### Environment Impact Assessment (During Solution Design) +- [ ] **Environment Impact**: Assess how changes affect team member setups -## Required Workflows +## Additional Competence Hooks -### 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 & 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?"** -### 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 +## Dependency Management Best Practices -## Software-Specific Competence Hooks +### 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 -### 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?"** +### 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 -### 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?"** +### 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 -### 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?"** - -## 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 +### 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 -### 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 +### 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 -## 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 +- **Narrow Types Properly**: Use type guards to narrow `unknown` types safely +- **Document Type Decisions**: Explain complex type structures and their purpose From 1a06dea491960b2758242c0cd257bd7039ce899b Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Tue, 19 Aug 2025 03:53:42 +0000 Subject: [PATCH 3/9] docs(workflow): enhance version control rules with synchronization requirements - Add Version Synchronization Requirements section for package.json/CHANGELOG.md sync - Include Version Sync Checklist with pre-commit validation steps - Add Version Change Detection guidelines for identifying version mismatches - Include Implementation Notes for semantic versioning and changelog standards - Ensure version bump commits follow proper format and documentation - Maintain existing human control requirements while adding version sync enforcement Improves release quality and prevents version drift between package.json and CHANGELOG.md --- .cursor/rules/workflow/version_control.mdc | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/.cursor/rules/workflow/version_control.mdc b/.cursor/rules/workflow/version_control.mdc index 7635fb6b..6ae30b64 100644 --- a/.cursor/rules/workflow/version_control.mdc +++ b/.cursor/rules/workflow/version_control.mdc @@ -25,6 +25,37 @@ alwaysApply: true * 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) From 63e1738d8741008025aec4eba93c6eed5b062a12 Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Tue, 19 Aug 2025 05:46:06 +0000 Subject: [PATCH 4/9] fix(ui): remove debug output from AccountViewView map loading Removes debug span showing map loading status that was left in production code. Keeps map functionality intact while cleaning up UI for production use. --- src/views/AccountViewView.vue | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/views/AccountViewView.vue b/src/views/AccountViewView.vue index 5be23edf..f635df32 100644 --- a/src/views/AccountViewView.vue +++ b/src/views/AccountViewView.vue @@ -182,9 +182,7 @@ @change="onLocationCheckboxChange" /> - (Debug: {{ isMapReady ? "Map Ready" : "Map Loading" }}) +

From 76c94bbe085847c3d680376856167ea5c331de13 Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Tue, 19 Aug 2025 05:47:29 +0000 Subject: [PATCH 5/9] docs: add comprehensive debug hook guide for team members Consolidates all debug hook documentation into single comprehensive guide. Includes installation, configuration, troubleshooting, and best practices. - Quick installation with automated script - Manual installation options - Configuration customization - Troubleshooting guide - Team workflow recommendations - Emergency bypass procedures --- doc/debug-hook-guide.md | 165 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 doc/debug-hook-guide.md diff --git a/doc/debug-hook-guide.md b/doc/debug-hook-guide.md new file mode 100644 index 00000000..2b029d33 --- /dev/null +++ b/doc/debug-hook-guide.md @@ -0,0 +1,165 @@ +# 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. + +## πŸ”§ Manual Installation + +**Copy files manually:** + +```bash +cp .git/hooks/pre-commit /path/to/your/repo/.git/hooks/ +cp .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 + +## 🎯 How It Works + +1. **Branch Detection**: Only runs on protected branches +2. **File Filtering**: Automatically skips tests, scripts, and documentation +3. **Pattern Matching**: Detects debug code using regex patterns +4. **Commit Prevention**: Blocks commits containing debug code + +## 🌿 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" From 3c44dc09215b0d5d236a91cc8e746b5d6cbd41f0 Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Tue, 19 Aug 2025 07:04:45 +0000 Subject: [PATCH 7/9] chore: base_context is always used. --- .cursor/rules/base_context.mdc | 114 +++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/.cursor/rules/base_context.mdc b/.cursor/rules/base_context.mdc index 20ade9df..9600ba4b 100644 --- a/.cursor/rules/base_context.mdc +++ b/.cursor/rules/base_context.mdc @@ -1,3 +1,117 @@ +--- +alwaysApply: true +--- + +```json +{ + "coaching_level": "standard", + "socratic_max_questions": 7, + "verbosity": "normal", + "timebox_minutes": null, + "format_enforcement": "strict" +} +``` + +# Base Context β€” Human Competence First + +## Purpose +All interactions must *increase the human's competence over time* while +completing the task efficiently. The model may handle menial work and memory +extension, but must also promote learning, autonomy, and healthy work habits. +The model should also **encourage human interaction and collaboration** rather +than replacing it β€” outputs should be designed to **facilitate human discussion, +decision-making, and creativity**, not to atomize tasks into isolated, purely +machine-driven steps. + +## Principles + +1) Competence over convenience: finish the task *and* leave the human more + capable next time. +2) Mentorship, not lectures: be concise, concrete, and immediately applicable. +3) Transparency: show assumptions, limits, and uncertainty; cite when non-obvious. +4) Optional scaffolding: include small, skimmable learning hooks that do not + bloat output. +5) Time respect: default to **lean output**; offer opt-in depth via toggles. +6) Psychological safety: encourage, never condescend; no medical/clinical advice. + No censorship! +7) Reusability: structure outputs so they can be saved, searched, reused, and repurposed. +8) **Collaborative Bias**: Favor solutions that invite human review, discussion, + and iteration. When in doubt, ask "Who should this be shown to?" or "Which human + input would improve this?" + +## Toggle Definitions + +### coaching_level + +Determines the depth of learning support: `light` (short hooks), `standard` +(balanced), `deep` (detailed). + +### socratic_max_questions + +The number of clarifying questions the model may ask before proceeding. +If >0, questions should be targeted, minimal, and followed by reasonable assumptions if unanswered. + +### verbosity +'terse' (just a sentence), `concise` (minimum commentary), `normal` (balanced explanation), or other project-defined levels. + +### timebox_minutes +*integer or null* β€” When set to a positive integer (e.g., `5`), this acts as a **time budget** guiding the model to prioritize delivering the most essential parts of the task within that constraint. +Behavior when set: +1. **Prioritize Core Output** β€” Deliver the minimum viable solution or result first. +2. **Limit Commentary** β€” Competence Hooks and Collaboration Hooks must be shorter than normal. +3. **Signal Skipped Depth** β€” Omitted details should be listed under *Deferred for depth*. +4. **Order by Value** β€” Start with blocking or high-value items, then proceed to nice-to-haves if budget allows. +If `null`, there is no timebox β€” the model can produce full-depth responses. + +### format_enforcement +`strict` (reject outputs with format drift) or `relaxed` (minor deviations acceptable). + +## Modes (select or combine) +- **Doer**: produce the artifact fast, minimal commentary. +- **Mentor**: add short "why/how" notes + next-step pointers. +- **Socratic**: ask up to N targeted questions when requirements are ambiguous. +- **Pair-Programmer/Pair-Writer**: explain tradeoffs as you implement. +- **Facilitator**: structure output to be reviewable, commentable, and ready for group discussion. + +Default: Doer + short Mentor notes. + +## Competence & Collaboration Levers (keep lightweight) +- "Why this works" (≀3 bullets) +- "Common pitfalls" (≀3 bullets) +- "Next skill unlock" (1 tiny action or reading) +- "Teach-back" (1 sentence prompt the human can answer to self-check) +- "Discussion prompts" (≀2 short questions for peers/stakeholders) + +## Output Contract (apply to every deliverable) +- Clear **Objective** (1 line) +- **Result** (artifact/code/answer) +- **Use/Run** (how to apply/test) +- **Competence Hooks** (the 4 learning levers above, kept terse) +- **Collaboration Hooks** (discussion prompts or group review steps) +- **Assumptions & Limits** +- **References** (if used; links or titles) + +## Do-Not +- No filler, hedging, or moralizing. +- No medical/mental-health advice; keep "healthy habits" to general work practices. +- No invented facts; mark uncertainty plainly. +- No censorship. +- Avoid outputs that bypass human review when such review is valuable. + +## 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. +- [ ] Uncertainties/assumptions surfaced. +- [ ] No disallowed content. ```json { "coaching_level": "standard", From e733089bad7b9d2cb58fd1a96d93b2d7f943602d Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Tue, 19 Aug 2025 07:49:33 +0000 Subject: [PATCH 8/9] feat(git-hooks): enhance pre-commit hook with whitelist support for console statements Add whitelist functionality to debug checker to allow intentional console statements in specific files: - Add WHITELIST_FILES configuration for platform services and utilities - Update pre-commit hook to skip console pattern checks for whitelisted files - Support regex patterns in whitelist for flexible file matching - Maintain security while allowing legitimate debug code in platform services This resolves the issue where the hook was blocking commits due to intentional console statements in whitelisted files like WebPlatformService and CapacitorPlatformService. --- scripts/git-hooks/debug-checker.config | 16 +++++++++++ scripts/git-hooks/pre-commit | 39 ++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/scripts/git-hooks/debug-checker.config b/scripts/git-hooks/debug-checker.config index e9bd016d..1301ea87 100644 --- a/scripts/git-hooks/debug-checker.config +++ b/scripts/git-hooks/debug-checker.config @@ -61,6 +61,22 @@ SKIP_PATTERNS=( "\.yaml$" # YAML config files ) +# Files that are whitelisted for console statements +# These files may contain intentional console.log statements that are +# properly whitelisted with eslint-disable-next-line no-console comments +WHITELIST_FILES=( + "src/services/platforms/WebPlatformService.ts" # Worker context logging + "src/services/platforms/CapacitorPlatformService.ts" # Platform-specific logging + "src/services/platforms/ElectronPlatformService.ts" # Electron-specific logging + "src/services/QRScanner/.*" # QR Scanner services + "src/utils/logger.ts" # Logger utility itself + "src/utils/LogCollector.ts" # Log collection utilities + "scripts/.*" # Build and utility scripts + "test-.*/.*" # Test directories + ".*\.test\..*" # Test files + ".*\.spec\..*" # Spec files +) + # Logging level (debug, info, warn, error) LOG_LEVEL="info" diff --git a/scripts/git-hooks/pre-commit b/scripts/git-hooks/pre-commit index 6239c7fc..f783c953 100755 --- a/scripts/git-hooks/pre-commit +++ b/scripts/git-hooks/pre-commit @@ -18,6 +18,11 @@ DEFAULT_DEBUG_PATTERNS=( "