---
description: Guards against unauthorized changes to the TimeSafari building
  architecture
alwaysApply: false
---

# Build Architecture Guard Directive

**Author**: Matthew Raymer
**Date**: 2025-08-22
**Status**: 🎯 **ACTIVE** - Build system protection guidelines

## Purpose

Protect the TimeSafari building architecture from unauthorized changes that
could break the multi-platform build pipeline, deployment processes, or
development workflow. This directive ensures all build system modifications
follow proper review, testing, and documentation procedures.

**Note**: Recent Android build system enhancements (2025-08-22) include sophisticated asset validation, platform-specific API routing, and automatic resource regeneration. These features require enhanced testing and validation procedures.

## Protected Architecture Components

### Core Build Infrastructure

- **Vite Configuration Files**: `vite.config.*.mts` files
- **Build Scripts**: All scripts in `scripts/` directory
- **Package Scripts**: `package.json` build-related scripts
- **Platform Configs**: `capacitor.config.ts`, `electron/`, `android/`,
  `ios/`
- **Docker Configuration**: `Dockerfile`, `docker-compose.yml`
- **Environment Files**: `.env.*`, `.nvmrc`, `.node-version`

### Android-Specific Build Validation

- **Asset Validation Scripts**: `validate_android_assets()` function and resource checking
- **Resource Generation**: `capacitor-assets` integration and verification
- **Platform-Specific IP Handling**: Android emulator vs physical device API routing
- **Build Mode Validation**: Development/test/production mode handling
- **Resource Fallback Logic**: Automatic regeneration of missing Android resources

### Critical Build Dependencies

- **Build Tools**: Vite, Capacitor, Electron, Android SDK, Xcode
- **Asset Management**: `capacitor-assets.config.json`, asset scripts
- **Testing Infrastructure**: Playwright, Jest, mobile test scripts
- **CI/CD Pipeline**: GitHub Actions, build validation scripts
- **Service Worker Assembly**: `sw_scripts/`, `sw_combine.js`, WASM copy steps

## Change Authorization Requirements

### Level 1: Minor Changes (Requires Review)

- Documentation updates to `BUILDING.md`
- Non-breaking script improvements
- Test additions or improvements
- Asset configuration updates

**Process**: Code review + basic testing

### Level 2: Moderate Changes (Requires Testing)

- New build script additions
- Environment variable changes
- Dependency version updates
- Platform-specific optimizations
- **Build script argument parsing**: New flag handling (--api-ip, --auto-run, --deploy)
- **Platform-specific environment overrides**: Android API server IP customization
- **Asset regeneration logic**: Automatic fallback for missing Android resources

**Process**: Code review + platform testing + documentation update

### Level 3: Major Changes (Requires ADR)

- Build system architecture changes
- New platform support
- Breaking changes to build scripts
- Major dependency migrations

**Process**: ADR creation + comprehensive testing + team review

## Prohibited Actions

### ❌ Never Allow Without ADR

- **Delete or rename** core build scripts
- **Modify** `package.json` build script names
- **Change** Vite configuration structure
- **Remove** platform-specific build targets
- **Alter** Docker build process
- **Modify** CI/CD pipeline without testing

### ❌ Never Allow Without Testing

- **Update** build dependencies
- **Change** environment configurations
- **Modify** asset generation scripts
- **Alter** test infrastructure
- **Update** platform SDK versions

## Required Validation Checklist

### Before Any Build System Change

- [ ] **Impact Assessment**: Which platforms are affected?
- [ ] **Testing Plan**: How will this be tested across platforms?
- [ ] **Rollback Plan**: How can this be reverted if it breaks?
- [ ] **Documentation**: Will `BUILDING.md` need updates?
- [ ] **Dependencies**: Are all required tools available?

### After Build System Change

- [ ] **Web Platform**: Does `npm run build:web:dev` work?
- [ ] **Mobile Platforms**: Do iOS/Android builds succeed?
- [ ] **Desktop Platform**: Does Electron build and run?
- [ ] **Tests Pass**: Do all build-related tests pass?
- [ ] **Documentation Updated**: Is `BUILDING.md` current?

## Specific Test Commands (Minimum Required)

### Web Platform

- **Development**: `npm run build:web:dev` - serve and load app
- **Production**: `npm run build:web:prod` - verify SW and WASM present

### Mobile Platforms

- **Android**: `npm run build:android:test` or `:prod` - confirm assets copied
- **iOS**: `npm run build:ios:test` or `:prod` - verify build succeeds

### Android Platform (Enhanced)
- **Development Mode**: `npm run build:android --dev` - verify 10.0.2.2 API routing
- **Custom IP Mode**: `npm run build:android --dev --api-ip 192.168.1.100` - verify custom IP
- **Asset Validation**: `npm run build:android --assets` - verify resource generation
- **Deploy Mode**: `npm run build:android --deploy` - verify device deployment

### Desktop Platform

- **Electron**: `npm run build:electron:dev` and packaging for target OS
- **Verify**: Single-instance behavior and app boot

### Auto-run (if affected)

- **Test Mode**: `npm run auto-run:test` and platform variants
- **Production Mode**: `npm run auto-run:prod` and platform variants

### Clean and Rebuild

- Run relevant `clean:*` scripts and ensure re-build works

## Emergency Procedures

### Build System Broken

1. **Immediate**: Revert to last known working commit
2. **Investigation**: Create issue with full error details
3. **Testing**: Verify all platforms work after revert
4. **Documentation**: Update `BUILDING.md` with failure notes

### Platform-Specific Failure

1. **Isolate**: Identify which platform is affected
2. **Test Others**: Verify other platforms still work
3. **Rollback**: Revert platform-specific changes
4. **Investigation**: Debug in isolated environment

## Integration Points

### With Version Control

- **Branch Protection**: Require reviews for build script changes
- **Commit Messages**: Must reference ADR for major changes
- **Testing**: All build changes must pass CI/CD pipeline

### With Documentation

- **BUILDING.md**: Must be updated for any script changes
- **README.md**: Must reflect new build requirements
- **CHANGELOG.md**: Must document breaking build changes

### With Testing

- **Pre-commit**: Run basic build validation
- **CI/CD**: Full platform build testing
- **Manual Testing**: Human verification of critical paths

## Risk Matrix & Required Validation

### Environment Handling

- **Trigger**: Change to `.env.*` loading / variable names
- **Validation**: Prove `dev/test/prod` builds; show environment echo in logs

### Script Flow

- **Trigger**: Reorder steps (prebuild → build → package), new flags
- **Validation**: Dry-run + normal run, show exit codes & timing

### Platform Packaging

- **Trigger**: Electron NSIS/DMG/AppImage, Android/iOS bundle
- **Validation**: Produce installer/artifact and open it; verify single-instance,
  icons, signing

### Service Worker / WASM

- **Trigger**: `sw_combine.js`, WASM copy path
- **Validation**: Verify combined SW exists and is injected; page loads offline;
  WASM present

### Docker

- **Trigger**: New base image, build args
- **Validation**: Build image locally; run container; list produced `/dist`

### Android Asset Management
- **Trigger**: Changes to `validate_android_assets()` function or resource paths
- **Validation**: Run `npm run build:android --assets` and verify all mipmap/drawable resources
- **Risk**: Missing splash screens or app icons causing build failures

### Android API Routing
- **Trigger**: Changes to Android-specific API server IP logic
- **Validation**: Test both emulator (10.0.2.2) and custom IP modes
- **Risk**: API connectivity failures on different device types

### Signing/Notarization

- **Trigger**: Cert path/profiles
- **Validation**: Show signing logs + verify on target OS

## PR Template (Paste into Description)

- [ ] **Level**: L1 / L2 / L3 + justification
- [ ] **Files & platforms touched**:
- [ ] **Risk triggers & mitigations**:
- [ ] **Commands run (paste logs)**:
- [ ] **Artifacts (names + sha256)**:
- [ ] **Docs updated (sections/links)**:
- [ ] **Rollback steps verified**:
- [ ] **CI**: Jobs passing and artifacts uploaded

## Rollback Playbook

### Immediate Rollback

1. `git revert` or `git reset --hard <prev>`; restore prior `scripts/` or config
   files
2. Rebuild affected targets; verify old behavior returns
3. Post-mortem notes → update this guard and `BUILDING.md` if gaps found

### Rollback Verification

- **Web**: `npm run build:web:dev` and `npm run build:web:prod`
- **Mobile**: `npm run build:android:test` and `npm run build:ios:test`
- **Desktop**: `npm run build:electron:dev` and packaging commands
- **Clean**: Run relevant `clean:*` scripts and verify re-build works

### Android-Specific Rollback Verification
- **Asset Generation**: `npm run build:android --assets` - verify resources regenerate
- **API Routing**: Test both `--dev` and `--dev --api-ip <custom>` modes
- **Resource Validation**: Check `android/app/src/main/res/` for all required assets
- **Build Modes**: Verify development, test, and production modes all work
- **Resource Fallback**: Confirm missing resources trigger automatic regeneration

## ADR Trigger List

Raise an ADR when you propose any of:

- **New build stage** or reorder of canonical stages
- **Replacement of packager** / packaging format
- **New environment model** or secure secret handling scheme
- **New service worker assembly** strategy or cache policy
- **New Docker base** or multi-stage pipeline
- **Relocation of build outputs** or directory conventions
- **New Android build modes** or argument parsing logic
- **Changes to asset validation** or resource generation strategy
- **Modifications to platform-specific API routing** (Android emulator vs physical)
- **New Android deployment strategies** or device management

**ADR must include**: motivation, alternatives, risks, validation plan, rollback,
  doc diffs.

## Competence Hooks

### Why This Works

- **Prevents Build Failures**: Catches issues before they reach production
- **Maintains Consistency**: Ensures all platforms build identically
- **Reduces Debugging Time**: Prevents build system regressions

### Common Pitfalls

- **Silent Failures**: Changes that work on one platform but break others
- **Dependency Conflicts**: Updates that create version incompatibilities
- **Documentation Drift**: Build scripts that don't match documentation

### Next Skill Unlock

- Learn to test build changes across all platforms simultaneously

### Teach-back

- "What three platforms must I test before committing a build script change?"

## Collaboration Hooks

### Team Review Requirements

- **Platform Owners**: iOS, Android, Electron, Web specialists
- **DevOps**: CI/CD pipeline maintainers
- **QA**: Testing infrastructure owners

### Discussion Prompts

- "Which platforms will be affected by this build change?"
- "How can we test this change without breaking existing builds?"
- "What's our rollback plan if this change fails?"

## Self-Check (Before Allowing Changes)

- [ ] **Authorization Level**: Is this change appropriate for the level?
- [ ] **Testing Plan**: Is there a comprehensive testing strategy?
- [ ] **Documentation**: Will BUILDING.md be updated?
- [ ] **Rollback**: Is there a safe rollback mechanism?
- [ ] **Team Review**: Have appropriate stakeholders been consulted?
- [ ] **CI/CD**: Will this pass the build pipeline?

## Continuous Improvement & Feedback

### Feedback Collection

The Build Architecture Guard system includes feedback mechanisms to continuously improve its effectiveness:

- **User Feedback**: Script includes feedback prompts for guard improvements
- **Pattern Analysis**: Monitor which file patterns trigger false positives/negatives
- **Documentation Gaps**: Track which changes lack proper documentation
- **Testing Effectiveness**: Measure how often guard catches actual issues

### Feedback Integration Process

1. **Collect Feedback**: Monitor guard execution logs and user reports
2. **Analyze Patterns**: Identify common false positives or missed patterns
3. **Update Rules**: Modify `build_architecture_guard.mdc` based on feedback
4. **Enhance Script**: Update `build-arch-guard.sh` with new validations
5. **Test Changes**: Verify guard improvements don't introduce new issues
6. **Document Updates**: Update guard documentation with new patterns

### Feedback Categories

- **False Positives**: Files flagged as sensitive that shouldn't be
- **False Negatives**: Sensitive files that weren't caught
- **Missing Patterns**: New file types that should be protected
- **Overly Strict**: Patterns that are too restrictive
- **Documentation Gaps**: Missing guidance for specific change types
- **Testing Improvements**: Better validation procedures

### Feedback Reporting

When reporting guard issues, include:
- **File patterns** that triggered false positives/negatives
- **Build system changes** that weren't properly caught
- **Documentation gaps** in current guard rules
- **Testing procedures** that could be improved
- **User experience** issues with guard enforcement

---

**Status**: Active build system protection
**Priority**: Critical
**Estimated Effort**: Ongoing vigilance
**Dependencies**: All build system components
**Stakeholders**: Development team, DevOps, Platform owners
**Next Review**: 2025-09-22
