---
name: build-output-path-standardization
description: Standardize build output paths across all projects in the monorepo for consistent artifact organization, easier cleanup, and predictable deployment
status: open
priority: high
effort: S
estimated_hours: 2-3 days
dependencies: [nx-advanced-configuration-guide]
created: 2025-10-02
updated: 2025-10-02
source: P1.7 Audit Issue - Build Output Path Standardization
---

# PRD: Build Output Path Standardization

## Overview

Establish and implement standardized build output paths for all applications, libraries, and tools across the BuzzTrail NX monorepo workspace. This ensures consistent artifact organization, simplifies deployment pipelines, enables efficient cleanup, and aligns with NX best practices.

**Key Objectives**:
1. **Define standard output paths** for all project types
2. **Configure NX targets** for consistent builds
3. **Simplify deployment** with predictable artifact locations
4. **Enable efficient cleanup** with centralized dist/ directory
5. **Document build conventions** for all developers

## Business Value

### Problem Statement

**Current Issues**:
- **Inconsistent Paths**: Build outputs scattered across workspace
  - Some: `dist/apps/{app}/`
  - Others: `apps/{app}/dist/`
  - Mixed: `{app}/build/`, `{app}/out/`
- **Deployment Confusion**: CI/CD scripts hardcode different paths
- **Cleanup Difficulty**: `.gitignore` has many patterns for build outputs
- **Cache Inefficiency**: NX cache confused by inconsistent outputs
- **Developer Friction**: "Where did my build go?"

**Developer Pain Points**:
- "Where are the build artifacts?" - Unpredictable locations
- "How do I clean builds?" - No single command
- "Why is my build cached?" - Output path mismatches
- "Deployment failed" - Wrong path in CI/CD
- "Git shows build files" - `.gitignore` incomplete

### Expected Outcomes

- **Predictable Paths**: All builds in `dist/{project-type}/{project-name}/`
- **Simplified Deployment**: Single pattern for all CI/CD scripts
- **Easy Cleanup**: `rm -rf dist/` clears all builds
- **Better Caching**: NX cache works correctly with standard paths
- **Clean Git**: Comprehensive `.gitignore` for dist/

## Current State Analysis

### Existing Build Outputs (Need Audit)

| Project | Current Output | Issues |
|---------|----------------|--------|
| extension | `dist/apps/extension/` | ✅ Standard NX pattern |
| chatbot | `apps/chatbot/dist/` | ❌ Non-standard location |
| fake-tavus-server | `dist/apps/fake-tavus-server/` | ✅ Standard NX pattern |
| @buzztrail/shared-database | `dist/libs/shared/database/` | ✅ Standard NX pattern |

**Analysis Needed**: Complete audit of all 25+ projects to identify violations.

### NX Default Patterns

```json
// NX default outputPath in project.json
{
  "targets": {
    "build": {
      "options": {
        "outputPath": "dist/apps/{project-name}"  // Apps
        "outputPath": "dist/libs/{lib-path}"      // Libs
      }
    }
  }
}
```

## Requirements

### Functional Requirements

#### FR1: Output Path Standards

**FR1.1**: Standard output paths by project type

**Applications**:
```
dist/apps/{app-name}/
├── index.html          (web apps)
├── main.js             (bundled output)
├── assets/             (static assets)
└── manifest.json       (extensions)
```

**Libraries**:
```
dist/libs/{lib-category}/{lib-name}/
├── index.js            (CJS output)
├── index.mjs           (ESM output)
├── index.d.ts          (type definitions)
└── package.json        (publishable metadata)
```

**Tools/Scripts**:
```
dist/tools/{tool-name}/
└── {tool}.js           (compiled script)
```

**E2E Tests**:
```
dist/apps/{app-name}-e2e/
├── videos/             (test recordings)
├── screenshots/        (failure screenshots)
└── reports/            (test reports)
```

**FR1.2**: Output path format rules
- **Root Directory**: Always `dist/` at workspace root
- **Project Type**: Second level indicates type (`apps/`, `libs/`, `tools/`)
- **Project Path**: Mirrors source structure (e.g., `libs/shared/database/`)
- **No Nesting**: No additional `dist/` or `build/` subdirectories
- **Consistent Naming**: Match project name exactly

**Examples**:
```
✅ GOOD:
dist/apps/extension/
dist/apps/chatbot/
dist/libs/shared/database/
dist/libs/ui/components/
dist/tools/readme-validator/

❌ BAD:
apps/extension/dist/          (wrong location)
dist/extension/               (missing apps/)
dist/apps/extension/build/    (extra nesting)
dist/applications/extension/  (wrong type name)
build/apps/extension/         (wrong root)
```

**FR1.3**: Special output configurations

**Production vs Development**:
```json
{
  "targets": {
    "build": {
      "configurations": {
        "development": {
          "outputPath": "dist/apps/{app-name}"
        },
        "production": {
          "outputPath": "dist/apps/{app-name}"  // Same path, different contents
        }
      }
    }
  }
}
```

**Multiple Build Formats** (for libraries):
```
dist/libs/{lib}/
├── esm/
│   ├── index.js
│   └── package.json  (type: "module")
├── cjs/
│   ├── index.js
│   └── package.json  (type: "commonjs")
└── types/
    └── index.d.ts
```

#### FR2: NX Configuration Patterns

**FR2.1**: Project.json build target configuration

**Application Template**:
```json
{
  "name": "{app-name}",
  "targets": {
    "build": {
      "executor": "@nx/vite:build",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/apps/{app-name}",
        "reportCompressedSize": false
      },
      "configurations": {
        "production": {
          "sourcemap": false,
          "minify": true
        },
        "development": {
          "sourcemap": true,
          "minify": false
        }
      }
    }
  }
}
```

**Library Template**:
```json
{
  "name": "{lib-name}",
  "targets": {
    "build": {
      "executor": "@nx/vite:build",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/libs/{lib-category}/{lib-name}",
        "format": ["esm", "cjs"],
        "declaration": true
      }
    }
  }
}
```

**FR2.2**: Output path tokens
- **{projectRoot}**: Source directory (e.g., `apps/extension/`)
- **{projectName}**: Project name (e.g., `extension`)
- **{workspaceRoot}**: Workspace root (monorepo root)
- **{options.outputPath}**: Configured output path

**Usage**:
```json
{
  "outputs": [
    "{options.outputPath}",                    // Standard output
    "{workspaceRoot}/dist/{projectName}"       // Alternative syntax
  ]
}
```

**FR2.3**: NX cache configuration
```json
// nx.json
{
  "targetDefaults": {
    "build": {
      "outputs": ["{workspaceRoot}/dist"],
      "cache": true
    }
  }
}
```

#### FR3: Cleanup & Maintenance

**FR3.1**: Cleanup strategies

**Global Cleanup** (all projects):
```bash
# Remove all build outputs
rm -rf dist/

# NX command (clears cache too)
nx reset
```

**Selective Cleanup** (specific project):
```bash
# Remove single project build
rm -rf dist/apps/{app-name}/

# NX command (project-specific)
nx reset {project-name}
```

**Pre-build Cleanup**:
```json
{
  "targets": {
    "clean": {
      "executor": "nx:run-commands",
      "options": {
        "command": "rm -rf dist/apps/{project-name}"
      }
    },
    "build": {
      "dependsOn": ["clean"],
      "executor": "@nx/vite:build"
    }
  }
}
```

**FR3.2**: .gitignore configuration

**Workspace Root .gitignore**:
```gitignore
# Build outputs (standardized)
/dist

# Test outputs
/coverage
/.nyc_output

# Temporary build files
*.tsbuildinfo
.cache

# Environment-specific
.env.local
.env.*.local

# OS files
.DS_Store
Thumbs.db
```

**Project-level .gitignore** (optional):
```gitignore
# If project has local build artifacts
node_modules/
.vite/
.turbo/
```

**FR3.3**: Automated cleanup in CI/CD

**GitHub Actions**:
```yaml
jobs:
  build:
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Clean previous builds
        run: rm -rf dist/

      - name: Build
        run: nx build {app-name}

      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          name: build-output
          path: dist/apps/{app-name}/
```

#### FR4: Deployment Integration

**FR4.1**: Deployment path patterns

**Vercel** (web apps):
```json
// vercel.json
{
  "buildCommand": "nx build {app-name} --configuration=production",
  "outputDirectory": "dist/apps/{app-name}",
  "installCommand": "pnpm install"
}
```

**Chrome Web Store** (extensions):
```bash
# Build
nx build extension --configuration=production

# Package
cd dist/apps/extension
zip -r extension.zip .

# Upload
# dist/apps/extension.zip → Chrome Web Store
```

**NPM** (libraries):
```json
// package.json (in lib source)
{
  "name": "@buzztrail/{lib-name}",
  "main": "../../dist/libs/{lib-category}/{lib-name}/index.js",
  "types": "../../dist/libs/{lib-category}/{lib-name}/index.d.ts",
  "files": [
    "../../dist/libs/{lib-category}/{lib-name}/**/*"
  ]
}
```

**Docker**:
```dockerfile
# Dockerfile
FROM node:18-alpine

# Copy built artifacts
COPY dist/apps/{app-name} /app

WORKDIR /app
CMD ["node", "main.js"]
```

**FR4.2**: Artifact structure for deployment

**Web App Deployment**:
```
dist/apps/{app-name}/
├── index.html
├── assets/
│   ├── logo.svg
│   └── style.css
└── main.js
```

**Extension Deployment**:
```
dist/apps/extension/
├── manifest.json
├── background.js
├── content.js
├── popup/
│   ├── popup.html
│   └── popup.js
└── assets/
    └── icons/
```

**Library Deployment** (NPM):
```
dist/libs/{lib-category}/{lib-name}/
├── index.js        (ESM)
├── index.d.ts      (types)
└── package.json    (metadata)
```

#### FR5: Documentation & Standards

**FR5.1**: Build output documentation

**Document Structure**:
```markdown
# Build Output Standards

## Standard Paths

- Apps: `dist/apps/{app-name}/`
- Libs: `dist/libs/{lib-category}/{lib-name}/`
- Tools: `dist/tools/{tool-name}/`

## Build Commands

\`\`\`bash
# Build single app
nx build {app-name}

# Build all apps
nx run-many --target=build --projects=apps/*

# Clean and build
rm -rf dist/ && nx build {app-name}
\`\`\`

## Deployment

See project-specific deployment guides in:
- Apps: `apps/{app-name}/README.md#deployment`
- Libs: `libs/{lib-category}/{lib-name}/README.md#publishing`
```

**FR5.2**: Developer onboarding

**Include in Dev Setup Guide**:
- Where build outputs are located
- How to clean builds
- How to build for production
- How to deploy artifacts

**FR5.3**: Troubleshooting guide

**Common Issues**:
```markdown
## Build Output Issues

### Issue: "Build artifacts not found"
**Solution**: Check `outputPath` in `project.json` matches `dist/apps/{app-name}/`

### Issue: "Old build artifacts remain"
**Solution**: Run `rm -rf dist/` before building

### Issue: "NX cache not working"
**Solution**: Verify `outputs` in `project.json` includes `{options.outputPath}`

### Issue: "Git shows build files"
**Solution**: Ensure `/dist` in root `.gitignore`
```

#### FR6: Migration Strategy

**FR6.1**: Audit current output paths

**Automated Audit Script**:
```bash
#!/bin/bash
# audit-output-paths.sh

echo "Auditing build output paths..."
echo ""

for project_json in apps/*/project.json libs/*/project.json tools/*/project.json; do
  project_name=$(dirname "$project_json")
  output_path=$(jq -r '.targets.build.options.outputPath // "NOT_SET"' "$project_json")

  if [[ "$output_path" == "NOT_SET" ]]; then
    echo "❌ $project_name: No outputPath configured"
  elif [[ "$output_path" =~ ^dist/(apps|libs|tools)/ ]]; then
    echo "✅ $project_name: $output_path (standard)"
  else
    echo "⚠️  $project_name: $output_path (non-standard)"
  fi
done
```

**FR6.2**: Migration procedure

**Step-by-Step**:
1. **Audit**: Run audit script to identify violations
2. **Update project.json**: Change `outputPath` to standard
3. **Update .gitignore**: Add new paths if needed
4. **Update CI/CD**: Change artifact paths in workflows
5. **Clean Builds**: Remove old build directories
6. **Test**: Verify build and deployment work
7. **Document**: Update README with new paths

**Example Migration**:
```diff
# apps/chatbot/project.json
{
  "targets": {
    "build": {
      "options": {
-       "outputPath": "apps/chatbot/dist"
+       "outputPath": "dist/apps/chatbot"
      }
    }
  }
}
```

**FR6.3**: Automated migration script

```typescript
// tools/migrate-output-paths.ts
import { readdirSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';

function migrateOutputPath(projectJsonPath: string) {
  const content = JSON.parse(readFileSync(projectJsonPath, 'utf-8'));

  if (!content.targets?.build?.options?.outputPath) {
    return;
  }

  const projectName = content.name;
  const projectType = projectJsonPath.includes('/apps/') ? 'apps' :
                     projectJsonPath.includes('/libs/') ? 'libs' : 'tools';

  // Update to standard path
  content.targets.build.options.outputPath = `dist/${projectType}/${projectName}`;

  // Ensure outputs array includes new path
  content.targets.build.outputs = ['{options.outputPath}'];

  writeFileSync(projectJsonPath, JSON.stringify(content, null, 2));
  console.log(`✅ Migrated: ${projectJsonPath}`);
}

// Run migration
['apps', 'libs', 'tools'].forEach(type => {
  const dir = type;
  if (!existsSync(dir)) return;

  readdirSync(dir).forEach(project => {
    const projectJson = join(dir, project, 'project.json');
    if (existsSync(projectJson)) {
      migrateOutputPath(projectJson);
    }
  });
});
```

## Implementation Plan

### Phase 1: Audit & Documentation (Day 1)

**Tasks**:
- Run audit script on all projects
- Document current violations
- Create migration plan
- Write standards documentation

**Deliverables**:
- Audit report
- `/documentation/build-output-standards.md`
- Migration script

### Phase 2: Critical Projects (Day 2 Morning)

**Tasks**:
- Migrate critical apps (extension, chatbot)
- Update CI/CD for critical apps
- Verify deployments work
- Update project READMEs

**Projects**:
- extension
- chatbot
- proxy-server

### Phase 3: Remaining Projects (Day 2 Afternoon)

**Tasks**:
- Migrate all remaining projects
- Update all CI/CD workflows
- Clean old build directories
- Comprehensive testing

**Projects**:
- All libs
- All tools
- Remaining apps

### Phase 4: Validation & Cleanup (Day 3)

**Tasks**:
- Run validation script
- Fix any issues
- Update `.gitignore`
- Final documentation review

**Deliverables**:
- 100% compliance report
- Updated onboarding guide
- Troubleshooting documentation

## Success Metrics

### Compliance Metrics
- [ ] 100% of projects use standard output paths
- [ ] All project.json files have correct `outputPath`
- [ ] Single `.gitignore` pattern covers all builds
- [ ] All CI/CD scripts use standard paths

### Cleanup Metrics
- [ ] `rm -rf dist/` removes all build artifacts
- [ ] No build files in git status
- [ ] Zero orphaned build directories
- [ ] NX cache 100% effective

### Deployment Metrics
- [ ] All deployments succeed with new paths
- [ ] CI/CD artifacts uploaded correctly
- [ ] Published packages have correct paths
- [ ] No deployment failures due to paths

## Dependencies

### Related PRDs
- **nx-advanced-configuration-guide.md**: NX target configuration
- **application-library-naming-standardization.md**: Project naming
- **dev-environment-setup-onboarding.md**: Build documentation

### Tools Required
- NX CLI (build commands)
- jq (audit script)
- Bash (migration script)
- CI/CD tools (GitHub Actions, Vercel)

## Risks & Mitigation

### Risk 1: Breaking Existing Deployments
**Mitigation**:
- Migrate one project at a time
- Test deployment before proceeding
- Keep rollback plan (revert project.json)
- Update CI/CD atomically with project changes

### Risk 2: Lost Build Artifacts
**Mitigation**:
- Clean builds after migration
- Don't delete old paths until verified
- Keep backup of critical builds
- Test thoroughly before cleanup

### Risk 3: CI/CD Pipeline Failures
**Mitigation**:
- Update CI/CD config simultaneously
- Test in feature branch first
- Monitor first deployments closely
- Have rollback procedure ready

## Related PRDs

- **nx-advanced-configuration-guide.md**: NX configuration patterns
- **application-library-naming-standardization.md**: Project naming conventions
- **build-system-vite-optimization.md**: Vite build configuration
- **dev-environment-setup-onboarding.md**: Developer setup guide

## Appendix

### Complete Path Reference

```
Workspace Structure:
/
├── dist/                           # All build outputs (gitignored)
│   ├── apps/
│   │   ├── extension/              # Chrome extension build
│   │   ├── chatbot/                # Chatbot widget build
│   │   ├── proxy-server/           # Proxy service build
│   │   └── backup-workflows/       # Backup service build
│   ├── libs/
│   │   ├── shared/
│   │   │   ├── database/           # Database lib build
│   │   │   └── ui-components/      # UI lib build
│   │   └── tavus/
│   │       └── client/             # Tavus client build
│   └── tools/
│       └── readme-validator/       # Tool build
├── apps/                           # Source code (NOT build output)
├── libs/
└── tools/
```

### Audit Script Output Example

```
Auditing build output paths...

✅ extension: dist/apps/extension (standard)
⚠️  chatbot: apps/chatbot/dist (non-standard)
✅ proxy-server: dist/apps/proxy-server (standard)
✅ @buzztrail/shared-database: dist/libs/shared/database (standard)
⚠️  @buzztrail/ui-components: libs/ui-components/build (non-standard)

Summary:
- Standard: 3/5 (60%)
- Non-standard: 2/5 (40%)
- Not configured: 0/5 (0%)

Action Required: Migrate 2 projects to standard paths
```
