# PUBLISH Pattern Scripts & Commands Analysis

**Document:** `PUBLISH_SCRIPTS_BY_COMMAND.md`
**Pattern:** PUBLISH (Distribution → Customer Ready)
**Purpose:** Package and distribute production-ready code to customers. Build distribution artifacts and sync to public repositories.
**Status:** ⏳ IN PROGRESS - Basic distribution building covered. Missing publication sync and customer update guidance.

**Related Documentation:**
- [COMMAND-USE-CASE-PATTERNS.md](COMMAND-USE-CASE-PATTERNS.md) - Full pattern definitions
- [CODE_ANALYSIS_SCRIPTS_BY_COMMAND.md](CODE_ANALYSIS_SCRIPTS_BY_COMMAND.md) - CODE-ANALYSIS pattern analysis

---

## Executive Summary

### Current State Analysis

The PUBLISH pattern is **minimally developed**:
- **Commands:** 2 commands, ~4K tokens total
- **Coverage:** Only distribution building and project compilation
- **Gaps:** No publication sync, no customer update guidance, no version management
- **Problem:** Missing orchestrator and support commands

### Key Findings

1. **Two Distinct Phases:**
   - **Build Phase** (`build-project`) - Compile TypeScript utilities
   - **Distribution Phase** (`build-distribution`) - Package for customers
   - **Missing:** Sync/publish to public repo, customer guidance

2. **Missing Capabilities:**
   - ❌ No sync to public repository (publish-distribution functionality)
   - ❌ No customer update guidance
   - ❌ No version tagging/release notes
   - ❌ No multi-platform distribution
   - ❌ No installation verification

3. **Token Distribution:**
   - `build-distribution`: 2,110 tokens (53%)
   - `build-project`: 1,929 tokens (47%)
   - **Total:** 4,039 tokens (very lean)
   - **Opportunity:** Extract common build utilities

### Next Steps (Recommendations)

| Phase | Decision Point | Recommendation |
|-------|---|---|
| **Phase 1** | Extract build utilities | Create `dist-builder.ts` for shared dist/ operations |
| **Phase 2** | Create sync command | Create `/publish-distribution` for public repo sync |
| **Phase 3** | Create customer guidance | Create `/update-roadcrew-customer` for update help |
| **Phase 4** | Create version management | Create `/tag-release` for version tagging |
| **Phase 5** | Refactor orchestrator | Create `build-and-publish` orchestrator |
| **Decision 5** | Standalone commands | Decide on customer-facing commands |

---

## Command Details

### 1. build-distribution (FREE, Distribution Builder)

**Tier:** FREE
**Calls:** 6
**Tokens:** 2,110
**Role:** Build dist branch from `.submodule/`; prepare for customer installation

**Command Summary:**
- Verifies `.submodule/` directory exists
- Checks for uncommitted changes
- Switches to `dist` branch (creates if needed)
- Removes existing files from `dist` branch
- Copies `.submodule/*` contents to root
- Commits the distribution
- Returns to original branch

**Current Capabilities:**
- Pre-flight checks (working directory clean, `.submodule/` exists)
- Distribution preview (shows what will be distributed)
- Safe branch switching (automatic return to original)
- Clean slate each build (no leftover files)
- Confirmation required before building

**Key Files & I/O:**
- Reads: `.submodule/` directory structure
- Writes: `dist` branch with distribution contents
- Input: User confirmation
- Output: Distribution branch ready for push

**Architecture:**
```
Development (main/dev)          Distribution (dist)      Customer
  .submodule/                     dist/ (root)            .roadcrew/
  ├── commands/      ────────→    ├── commands/    ───→   ├── commands/
  ├── templates/     ────────→    ├── templates/   ───→   ├── templates/
  ├── scripts/       ────────→    ├── scripts/     ───→   ├── scripts/
  ├── install.js     ────────→    ├── install.js   ───→   ├── install.js
  └── README.md      ────────→    └── README.md    ───→   └── README.md
```

**Scripts Called (Current):**
- None (all logic inline)
- Internal functions: `checkPrerequisites()`, `showDistribution()`, `confirmBuild()`, `buildDist()`, `showSummary()`

**Potential Refactoring:**
- Extract file operations → `dist-builder.ts`
- Extract safety checks → `dist-validator.ts`

---

### 2. build-project (ENTERPRISE, Project Builder)

**Tier:** ENTERPRISE
**Calls:** 2
**Tokens:** 1,929
**Role:** Compile TypeScript utilities; install dependencies; validate build

**Command Summary:**
- Checks Node.js installation
- Installs npm dependencies
- Compiles TypeScript source to JavaScript
- Validates build success
- Shows build summary

**Current Capabilities:**
- Node.js version checking
- Smart dependency installation
- TypeScript compilation with `npm run ensure-built`
- Build validation
- Type checking (optional)
- Linting (optional)

**Key Files & I/O:**
- Reads: `scripts/utils/*.ts`, `tsconfig.json`, `package.json`
- Writes: `dist/scripts/utils/*.js`, `dist/scripts/utils/*.d.ts`
- Config: TypeScript compiler settings
- Output: Compiled JavaScript files ready to use

**Build Process:**
1. Check Node.js installed (≥18.0.0)
2. Install dependencies (if needed)
3. Compile TypeScript (`npm run ensure-built`)
4. Verify build success
5. Show summary with file sizes

**Scripts Called (Current):**
- None (all logic inline, delegates to npm scripts)
- Uses: `npm run ensure-built`, `npm run type-check`, `npm run lint`

**Potential Refactoring:**
- Extract dependency checking → `dependency-validator.ts`
- Extract build verification → `build-validator.ts`

---

## Pattern Gaps & Opportunities

### Gap 1: No Publication Sync
**Impact:** Can't publish to public repository automatically
**Solution:** Create `/publish-distribution` command

**What It Does:**
- Check `dist` branch is up to date
- Create PR to public roadcrew repo
- Merge with CI/CD validation
- Tag release on dist branch
- Update GitHub releases

**Token Estimate:** 400-600 tokens

---

### Gap 2: No Customer Update Guidance
**Impact:** Customers don't know how to update
**Solution:** Create `/update-roadcrew-customer` command

**What It Does:**
- Detect current roadcrew version
- Check for updates available
- Show upgrade instructions
- Backup before upgrade
- Verify upgrade successful

**Token Estimate:** 300-500 tokens

---

### Gap 3: No Version Management
**Impact:** No systematic version tagging
**Solution:** Create `/tag-release` command

**What It Does:**
- Update version in package.json
- Generate release notes from commits
- Create git tag
- Push to GitHub
- Create GitHub release

**Token Estimate:** 300-500 tokens

---

### Gap 4: No Installation Verification
**Impact:** Can't verify customer installs working
**Solution:** Create `/verify-install` command

**What It Does:**
- Check `.roadcrew/` structure
- Verify all files present
- Test command execution
- Validate permissions
- Show diagnostic report

**Token Estimate:** 200-400 tokens

---

## Proposed Script Extraction

### Helper Scripts

#### 1. dist-builder.ts (NEW)
**Purpose:** Consolidate file operations for building dist branch

**Functions:**
- `checkDistPrerequisites()` - Verify `.submodule/` and clean working dir
- `getDistributionContents()` - List files to distribute
- `createDistBranch()` - Create or switch to dist branch
- `clearDistBranch()` - Remove existing files
- `copyToDistBranch()` - Copy `.submodule/*` to root
- `commitDistribution()` - Commit with message
- `returnToPreviousBranch()` - Switch back

**Token Savings:**
- Extract from `build-distribution`: 600-800 tokens
- Share with `/publish-distribution` command: 200-300 tokens saved
- **Total:** 800-1.1K tokens saved

**Distribution:** Yes

---

#### 2. build-validator.ts (NEW)
**Purpose:** Validate build output and project health

**Functions:**
- `checkNodeVersion()` - Verify Node.js >= 18.0.0
- `validateBuildOutput()` - Check compiled files exist
- `verifyDependencies()` - Check node_modules integrity
- `runTypeCheck()` - Run TypeScript type checking
- `runLinting()` - Run ESLint checks
- `generateBuildReport()` - Summary report

**Token Savings:**
- Extract from `build-project`: 400-600 tokens
- Used by `/verify-install` and potential CI/CD: 200-300 tokens saved
- **Total:** 600-900 tokens saved

**Distribution:** Yes

---

### New Standalone Commands

#### /publish-distribution (STARTER, NEW)
**Purpose:** Sync distribution to public repository

**What It Does:**
- Verify `dist` branch built correctly
- Create PR to public roadcrew repo (if separate)
- Run CI/CD validation
- Merge automatically (if tests pass)
- Create GitHub release
- Update release notes

**Token Estimate:** 500-700 tokens

---

#### /update-roadcrew-customer (STARTER, NEW)
**Purpose:** Guide customers through Roadcrew updates

**What It Does:**
- Detect current version in `.roadcrew/`
- Check for available updates
- Create backup before upgrade
- Show upgrade commands
- Run post-upgrade verification
- Report success/issues

**Token Estimate:** 400-600 tokens

---

#### /tag-release (FREE, NEW)
**Purpose:** Manage version releases

**What It Does:**
- Update version in package.json
- Generate release notes from commits
- Create annotated git tag
- Push tag to GitHub
- Create GitHub release with notes

**Token Estimate:** 300-500 tokens

---

## Tier Impact

### Current Tier Coverage

| Tier | Commands | Tokens | Status |
|------|----------|--------|--------|
| **FREE** | build-distribution | 2,110 | ⚠️ Minimal |
| **STARTER** | (none) | 0 | ❌ Gap |
| **ENTERPRISE** | build-project | 1,929 | ⚠️ Limited |

### Proposed New Tier Coverage

| Tier | Commands | Tokens | Status |
|------|----------|--------|--------|
| **FREE** | build-distribution (refactored), tag-release (NEW) | 2.1K + 0.4K | ✅ Core publishing |
| **STARTER** | publish-distribution (NEW), update-roadcrew-customer (NEW), verify-install (NEW) | 1.3K new | ✅ Customer support |
| **ENTERPRISE** | build-project (refactored) | 1.9K | ✅ Enterprise build |

---

## Current State Analysis

### Token Distribution

```
PUBLISH Pattern: ~4K tokens total

Build Phase:
  build-project: 1,929 tokens (48%)
  ✓ Compile TypeScript, install deps

Distribution Phase:
  build-distribution: 2,110 tokens (52%)
  ✓ Package for customer distribution

Gaps:
  ✗ No sync/publish to public repo
  ✗ No customer update guidance
  ✗ No version tagging
  ✗ No verification
```

### Command Calls Analysis

```
build-distribution: 6 calls
  - checkPrerequisites()
  - showDistribution()
  - confirmBuild()
  - buildDist()
  - showSummary()

build-project: 2 calls
  - checkNodeVersion()
  - runBuild()

Opportunity: Extract common build/dist operations
```

---

## Decision Framework

### Phase 1: Extract Distribution Utilities (Low Risk)
**Goal:** Create `dist-builder.ts` consolidating file operations

**Decision Point 1: Should dist operations be separate utility or stay embedded?**

**Option A:** Extract as `dist-builder.ts` ✅ RECOMMENDED
- Pros: Reusable, reduces duplication, foundation for new commands
- Cons: Adds new file, requires refactoring
- Risk: Low (file operations already proven)
- Tokens: 600-800 tokens saved, +200 for new script = **net 400-600 saved**

**Option B:** Keep embedded in commands
- Pros: No refactoring needed
- Cons: Duplication with `/publish-distribution`, harder to maintain
- Tokens: No savings, higher maintenance cost

**Recommendation:** **Option A** - Extract as `dist-builder.ts`
- `/publish-distribution` will need same operations
- Better code reuse
- Cleaner command files

---

### Phase 2: Create Build Validator (Low Risk)
**Goal:** Create `build-validator.ts` for validation operations

**Decision Point 2: Should validation be separate utility or inline?**

**Option A:** Extract as `build-validator.ts` ✅ RECOMMENDED
- Pros: Reusable across build commands
- Cons: Another new file
- Risk: Low (validation logic proven)
- Tokens: 400-600 tokens saved

**Option B:** Keep inline
- Pros: Self-contained
- Cons: `/verify-install` will need similar checks
- Tokens: No savings

**Recommendation:** **Option A** - Extract as `build-validator.ts`
- `/verify-install` command reuses validation logic
- Better code reuse and consistency

---

### Phase 3: Create Publish Command (Medium Risk)
**Goal:** Create `/publish-distribution` command for public repo sync

**Decision Point 3: Should publish sync directly or via PR?**

**Option A:** Direct sync (auto-push to public repo)
- Syncs `.submodule/` directly to public repo
- Automatic merge (if tests pass)
- Pros: Fastest, hands-off
- Cons: Less visibility, potential issues
- Tokens: 400-500 tokens

**Option B:** Create PR for review
- Create PR to public repo
- Show what will change
- Require manual merge
- Pros: Review opportunity, safer
- Cons: Extra step, slower
- Tokens: 500-700 tokens

**Option C:** Interactive (ask user each time)
- Show changes
- Ask for approval
- Then sync/create PR
- Pros: User control, transparency
- Cons: Extra manual step
- Tokens: 600-800 tokens

**Recommendation:** **Option B** - Create PR for review
- CI/CD validation on PR
- Review window for changes
- Safer for customer-facing code
- Still relatively hands-off

---

### Phase 4: Create Customer Update Command (Low-Medium Risk)
**Goal:** Create `/update-roadcrew-customer` for customer guidance

**Decision Point 4: Should updates be automated or guided?**

**Option A:** Automated updates
- Detect version mismatch
- Auto-backup current version
- Auto-pull latest from dist branch
- Auto-verify new version
- Pros: Fast, hands-off
- Cons: May break things, no review
- Tokens: 400-500 tokens

**Option B:** Guided updates (recommended)
- Show available updates
- Create backup
- Show upgrade steps
- User confirms
- Then update and verify
- Pros: User control, transparency
- Cons: More manual steps
- Tokens: 500-700 tokens

**Recommendation:** **Option B** - Guided updates
- Customers should review changes
- Backup creation is user-visible
- Verification step catches issues
- Better aligns with customer safety

---

### Phase 5: Create Version Tagging (Low Risk)
**Goal:** Create `/tag-release` for systematic versioning

**Decision Point 5: Should tagging follow semver strictly?**

**Option A:** Flexible tagging (user specifies version)
- User provides version number
- System validates semver format
- Generates release notes
- Creates tag
- Pros: Flexible, user control
- Cons: Can get messy if not careful
- Tokens: 300-400 tokens

**Option B:** Strict semver (bump by major/minor/patch)
- System calculates next version
- User chooses bump type (major/minor/patch)
- Generates release notes automatically
- Creates tag
- Pros: Consistent, less error-prone
- Cons: Less flexible for edge cases
- Tokens: 400-500 tokens

**Recommendation:** **Option B** - Strict semver with bump types
- Roadcrew should follow semver
- Consistent versioning easier to manage
- `major`, `minor`, or `patch` flags
- User chooses, system implements

---

### Phase 6: Create Verification Command (Low Risk)
**Goal:** Create `/verify-install` to validate customer installations

**Decision Point 6: Should verification be automated check or interactive guide?**

**Option A:** Automated check
- Check `.roadcrew/` structure
- Verify files present
- Run self-test
- Generate report
- Show any issues
- Pros: Fast, comprehensive
- Cons: Less educational
- Tokens: 300-400 tokens

**Option B:** Interactive guide
- Explain what should be there
- Check each component step-by-step
- Guide user through fixes if issues
- Confirm success
- Pros: Educational, helps customers learn
- Cons: More manual steps
- Tokens: 400-600 tokens

**Recommendation:** **Option A** - Automated check with clear reporting
- Most customers want quick verification
- Clear report shows what's working
- Can escalate to interactive guide if issues found
- Faster for healthy installations

---

### Phase 7: Rollout Strategy (Low Risk)
**Goal:** Deploy PUBLISH pattern improvements

**Decision Point 7: Should rollout be all-at-once or phased?**

**Option A:** Phased rollout (recommended)
- Week 1: Extract utilities (`dist-builder.ts`, `build-validator.ts`)
- Week 2: Create `/publish-distribution`, `/tag-release`
- Week 3: Create `/update-roadcrew-customer`, `/verify-install`
- Timeline: 3 weeks
- Pros: Lower risk, each phase tested before next
- Cons: Slower to market

**Option B:** All-at-once
- Create everything simultaneously
- Release all new commands together
- Timeline: 2 weeks
- Pros: Faster
- Cons: Higher risk, harder to debug issues

**Recommendation:** **Option A** - Phased rollout
- Utilities first (foundation)
- Publish/tag commands next (core functionality)
- Customer commands last (depends on others)
- Lower risk, proven approach

---

## Support Decisions

### Testing Strategy
- **Unit Tests:** All new scripts and commands
- **Integration Tests:** Full publish workflow (build → dist → public repo)
- **E2E Tests:** Full customer install/update scenario
- **Approach:** Mock git operations, real filesystem operations

### Measurement & Validation
- **Baseline:** Manual baseline for each new command
- **Automated:** CI/CD tracking via token consumption
- **Quality:** Publish process validation (files correct, no corruption)
- **Performance:** Measure publish time, update time, verification time

### Rollout Order
- **Phase 1 (Week 1):** Extract utilities (dist-builder.ts, build-validator.ts)
- **Phase 2 (Week 2):** Create publish-distribution, tag-release
- **Phase 3 (Week 3):** Create update-roadcrew-customer, verify-install
- **Production:** All commands tested, documented, ready for distribution

---

## Key Files & Locations

### Existing Commands
- `commands/roadcrew/free/release-management/build-distribution.md` - Distribution builder
- `commands/roadcrew/enterprise/build-project.md` - Project compiler

### New Scripts (to create)
- `scripts/utils/roadcrew/dist-builder.ts` - Distribution operations
- `scripts/utils/roadcrew/build-validator.ts` - Build validation utilities

### New Commands (to create)
- `commands/roadcrew/free/publish-distribution.md` - Publish to public repo
- `commands/roadcrew/free/tag-release.md` - Version tagging
- `commands/roadcrew/starter/update-roadcrew-customer.md` - Customer updates
- `commands/roadcrew/starter/verify-install.md` - Installation verification

---

## Summary

**Current PUBLISH pattern:** Minimal, two commands for build and distribution

**Proposed improvements:**
1. Extract distribution utilities (dist-builder.ts) - **Foundation**
2. Extract build validation (build-validator.ts) - **Support**
3. Create publish-distribution command - **Public repo sync**
4. Create tag-release command - **Version management**
5. Create update-roadcrew-customer command - **Customer support**
6. Create verify-install command - **Installation validation**

**Expected impact:**
- **Token Savings:** 400-600 tokens (10-15% of current pattern, but enables more)
- **New Commands:** 4 new commands for publishing and customer support
- **Efficiency:** Publication and updates become hands-off
- **Timeline:** 3 weeks (phased rollout)
- **Risk Level:** Low-Medium (proven patterns, clear requirements)

