# PLANNING Pattern: Commands & Scripts Analysis v1.6.x

**Goal:** Analyze PLANNING pattern commands to identify opportunities for reducing command duplication, reusing scripts, and extracting shared utilities.

**PLANNING Commands:** complete-release, sync-release-status, advance-release, create-release-docs

---

## EXECUTIVE SUMMARY

### Decision Points

#### Phase Decisions

1. **Phase 1: Extract release-status-manager.ts?**
   - **Status:** ✅ **APPROVED**
   - **Scope:** Consolidate sync-release-status, advance-release version transition and specification generation logic
   - **Expected Savings:** 2-3K tokens (reduction pending analysis)
   - **Command Language Reduction:** TBD (pending analysis)
   - **Effort:** Medium | **Timeline:** 2-3 days

2. **Phase 2: Extract doc-generator.ts?**
   - **Status:** ✅ **APPROVED**
   - **Scope:** Consolidate create-release-docs BRD/PRD/Spec generation orchestration logic
   - **Expected Savings:** 1-2K tokens (reduction pending analysis)
   - **Command Language Reduction:** TBD (pending analysis)
   - **Effort:** Medium | **Timeline:** 2-3 days

3. **Phase 3: Future Extensions?**
   - **Status:** ✅ **APPROVED - NO**
   - **Scope:** Build minimal (extend later if needed)
   - **Rationale:** Avoid over-engineering; focus on current commands only

#### Support Decisions

4. **Script Organization & Imports**
   - **Status:** ✅ **APPROVED - USE `scripts/utils/roadcrew/`**
   - **Location:** Place both new scripts in `scripts/utils/roadcrew/`
   - **Implementation Details:**
     - `release-status-manager.ts` - NEW file I/O + GitHub operations coordinator
     - `doc-generator.ts` - NEW document generation coordinator
   - **Distribution:** Both scripts compile to `dist/scripts/utils/roadcrew/` and publish to customers
   - **Rationale:** Uses existing pattern, maintains consistency with ANALYSIS decisions

5. **Testing Strategy**
   - **Status:** ✅ **APPROVED - BOTH UNIT + INTEGRATION TESTS**
   - **Unit Tests** (`scripts/__tests__/`):
     - `release-status-manager.test.ts` - Test file I/O, GitHub API batching, version management
     - `doc-generator.test.ts` - Test template compilation, data validation, rendering
   - **Integration Tests** (`scripts/__tests__/`):
     - `complete-release.integration.test.ts` - Verify output identical before/after refactoring
     - `sync-release-status.integration.test.ts` - Verify output identical before/after refactoring
     - `advance-release.integration.test.ts` - Verify output identical before/after refactoring
     - `create-release-docs.integration.test.ts` - Verify output identical before/after refactoring
   - **Test Coverage:** Unit tests verify script correctness; integration tests verify commands still work identically
   - **Rationale:** Critical commands require both internal correctness and integration validation

6. **Measurement & Validation**
   - **Status:** ✅ **APPROVED - BOTH + PERFORMANCE BENCHMARKS**
   - **Phase 1: Manual Baseline (Before refactoring starts)**
     - One-time manual token count of all PLANNING commands (establish credibility)
     - Performance benchmark: execution time, API call volume, file sizes
     - Documented in `config/token-baseline.json` and `config/performance-baseline.json`
   - **Phase 2: Automated CI/CD Tracking (During refactoring)**
     - New utility: `scripts/utils/token-counter.ts` (counts tokens in command files)
     - CI/CD job: `npm run measure-tokens` runs on every commit
     - Tracks delta vs. baseline after each phase
     - Stores history in `config/token-history.json`
   - **Phase 3: Performance Re-Benchmark (After each phase)**
     - Measure actual execution time improvement
     - Measure actual LLM API call reduction (in practice)
     - Compare against estimates in PLANNING_SCRIPTS_BY_COMMAND.md
     - Validate Phase 1, 2 savings independently
   - **Deliverables:**
     - `config/token-baseline.json` - Initial measurements
     - `config/token-history.json` - Phase-by-phase tracking
     - `config/performance-baseline.json` - Initial performance metrics
     - Post-refactoring report: Expected vs. Actual savings
   - **Rationale:** Credible baseline + automated tracking + performance validation demonstrates ROI and prevents regressions

7. **Rollout Order**
   - **Status:** ✅ **APPROVED - SEQUENTIAL (OPTION A)**
   - **Rationale:** No external customers yet, so simplicity/clarity preferred; consistent with ANALYSIS pattern
   - **Implementation Timeline:**
     - **Phase 1 (Days 1-3):** Extract release-status-manager.ts
       - Extract, unit test, integrate into complete-release & sync-release-status
       - Internal testing + performance benchmark
       - Measure Phase 1 token savings (400-600 tokens expected)
       - Deploy internally / publish to dist/
     - **Phase 2 (Days 4-7):** Extract doc-generator.ts
       - Extract, unit test, integrate into create-release-docs
       - Internal testing + performance benchmark
       - Measure Phase 2 token savings (500-800 tokens expected)
       - Deploy internally / publish to dist/
     - **Phase 3 (Days 8-10):** Testing & Validation
       - Full integration testing of all PLANNING commands
       - Performance re-benchmark vs. baseline
       - Validate Phase 1 + 2 savings (1.4-2.3K tokens expected)
       - Documentation updates
   - **Deployment Strategy:** Internal-only until all phases complete; then publish as unified distribution
   - **Success Criteria:** All phases complete, tested, and deployed within 3 weeks; achieve 1.4-2.3K token savings (9-15% reduction)

---

### Current State
- **4 PLANNING commands** consuming ~19K tokens
- **Duplication patterns** to be identified
- **Optimization opportunity:** Consolidate file sync, version transition, and documentation orchestration logic

### Key Findings

**Pattern Analysis Required:**
- complete-release: Version tagging + changelog update
- sync-release-status: GitHub issue status sync + markdown updates
- advance-release: Version transition + epic spec generation
- create-release-docs: Narrative transformation → structured BRD/PRD/Spec
- Potential shared: File I/O, GitHub API operations, template processing, orchestration logic

---

## DETAILED ANALYSIS

## Command 1: complete-release

**Tier:** FREE | **Tokens:** 1,598 | **Calls:** 1 command

### Command Text Summary

Marks a release as complete by versioning, tagging, and updating CHANGELOG. Minimal command that triggers version finalization workflow.

**Capabilities:**
- Update version in relevant files (package.json, etc.)
- Create git tag (vX.Y.Z)
- Update config/releases/CHANGELOG.md
- Create release notes
- Close release tracking issue
- Update memory-bank/activeContext.md (legacy: context/vision.md) (mark as ✅ COMPLETE)

**Key Files & I/O:**
- **Reads:** package.json, CHANGELOG.md, memory-bank/activeContext.md (legacy: context/vision.md)
- **Writes:** package.json, CHANGELOG.md, memory-bank/activeContext.md (legacy: context/vision.md) (phase marker), git tags
- **Calls:** Git tagging, file updates

### Scripts Called

**Direct:** None (uses git directly)

**Internal Logic:**
- Version extraction from package.json
- File updates (package.json version bump)
- Git tag creation
- Regex transformations to update vision.md phase markers
- CHANGELOG append

---

## Command 2: sync-release-status

**Tier:** FREE | **Tokens:** 2,871 | **Calls:** 8 commands

### Command Text Summary

Queries GitHub API to fetch current issue status for all issues in current-release.md, updates checkboxes in markdown file to reflect reality. Syncs execution state back to documentation.

**Capabilities:**
- Parse release file (current-release.md or minor-release.md) to extract GitHub issue numbers
- Query GitHub API to check each issue's status (open/closed)
- Update checkboxes in release file: `- [ ]` → `- [x]` for closed issues
- Update Release Criteria checkboxes at top level
- Write updated content back to file
- Display detailed sync report with progress percentage
- Dry-run mode (preview changes without writing)
- Support for both current-release.md and minor-release.md

**Key Files & I/O:**
- **Reads:** milestones/current-release.md or milestones/minor-release.md
- **Writes:** milestones/current-release.md or milestones/minor-release.md (checkbox updates)
- **GitHub API Calls:** Batch queries (10 issues per batch) to respect rate limits

### Scripts Called

**Direct:** GitHub API via Octokit (getOctokit)

**Internal Logic:**
- Markdown parsing: Extract issue numbers from file
- GitHub API: Query issue status (respects batch processing for rate limits)
- Markdown transformation: Update checkboxes based on GitHub status
- File writing: Append updates back to file

**Estimated shared utilities potential:**
- GitHub issue parsing (could be `github-issue-parser.ts`)
- GitHub API batching (could be `github-api-batcher.ts`)

---

## Command 3: advance-release

**Tier:** FREE | **Tokens:** 5,233 | **Calls:** 6 commands

### Command Text Summary

Archives current release to past-releases.md, pulls next phase from future-releases.md, runs `/analyze-repo` for current tech context, generates detailed epic specifications with all structural requirements, and populates current-release.md.

**Capabilities:**
- Archive current-release.md → past-releases.md (extract version, name, achievements, metrics)
- Pull next phase from future-releases.md
- Run `/analyze-repo` to capture tech context (framework, database, CI/CD, deployment, schema, testing)
- Review linked PRDs/specs from memory-bank/activeContext.md (legacy: context/vision.md)
- Generate detailed epic descriptions with spec references
- Auto-increment version number (minor for phase changes, patch for patch releases)
- Update vision.md phase markers (old: COMPLETE, new: NEXT)
- Populate current-release.md with complete specifications including issue details
- **Update Mode (`--update`):** Validate and enrich existing current-release.md, auto-add missing classification hints, spec references, success criteria

**Key Files & I/O:**
- **Reads:** milestones/current-release.md, milestones/future-releases.md, memory-bank/activeContext.md (legacy: context/vision.md), context/specs/[spec-name].md, memory-bank/techContext.md (analyze-repo output)
- **Writes:** milestones/current-release.md, milestones/past-releases.md, milestones/future-releases.md, memory-bank/activeContext.md (legacy: context/vision.md) (phase markers)
- **Templates:** templates/current-release.template.md
- **Uses Handlebars** for template compilation

### Scripts Called

**Direct:** `/analyze-repo` (to capture tech context)

**Internal Logic:**
- File I/O: Read/parse markdown, append to past-releases.md
- Version parsing: Extract version from current-release.md (e.g., v1.1.0 → v1.2.0)
- Regex transformations: Update vision.md phase markers (🎯 NEXT → ✅ COMPLETE)
- Spec parsing: Extract epic structure from linked spec files
- Template compilation: Handlebars rendering with data from future-releases.md

**Estimated shared utilities potential:**
- Version increment logic (could be `version-manager.ts`)
- Release file archiving (could be `release-archiver.ts`)
- Template compilation (shared with create-release-docs)

---

## Command 4: create-release-docs

**Tier:** FREE | **Tokens:** 5,198 | **Calls:** 9 commands

### Command Text Summary

Transforms narrative documents from context/narratives/[subfolder]/ into structured BRD → PRD → Spec documents. Sequential generation with cross-references: BRD provides context for PRD, PRD provides context for Spec. Handles pre-formatted documents and aggregates all narrative files.

**Capabilities:**
- Discover source material in narratives/[subfolder]/ (list all .md files)
- Detect pre-formatted documents (check YAML frontmatter `type:` field)
- Extract feature ID and metadata (folder name, H1 headings, Owner, Version)
- **Phase 1/3 - Generate BRD:** Extract business context (goals, segments, revenue, pricing tiers, metrics, risks)
- **Phase 2/3 - Generate PRD:** Extract product requirements (R1-R6 functional reqs, user stories, user journey), reference BRD for business context
- **Phase 3/3 - Generate Spec:** Extract technical requirements (non-functional, architecture, data models, APIs, issue breakdown with classifications), reference BRD + PRD
- **Sequential generation with context carryover:** BRD read once, then PRD uses BRD for context, then Spec uses both for context (60-70% token efficiency vs 3 separate commands)
- Validate each document before proceeding (length limits, required sections, cross-references)
- Update cross-references after all docs generated (BRD→PRD, PRD→Spec links)
- Handle existing documents (keep, regenerate, or cancel)
- Smart defaults for missing sections (infer pricing, user journey, issue breakdowns)

**Key Files & I/O:**
- **Reads:** All .md files in context/narratives/[subfolder]/, templates/brd.template.md, templates/prd.template.md, templates/spec.template.md
- **Writes:** context/brds/[feature-id]-brd.md, context/prds/[feature-id]-prd.md, context/specs/[feature-id]-spec.md
- **Templates Used:** 3 template files (BRD, PRD, Spec) with YAML frontmatter for cross-referencing

### Scripts Called

**Direct:** None (all logic is internal)

**Internal Logic:**
- File discovery: `find context/narratives/[subfolder]/ -name "*.md" -type f`
- Frontmatter parsing: Extract `type:`, `version:`, `feature_id:` from YAML
- Content aggregation: Read all .md files, track source for each section
- Sequential generation: BRD → PRD → Spec with context carryover
- Length validation: Enforce word limits for each section
- Mapping tables: Create PRD→Spec mappings, Spec→PRD reverse mappings
- Cross-reference updates: Add relative paths to frontmatter

**Estimated shared utilities potential:**
- Template compilation (shared with advance-release)
- Frontmatter parsing/validation (could be `doc-metadata.ts`)
- Content aggregation from multiple files (could be `content-aggregator.ts`)
- Markdown validation/sanitization (could be `markdown-validator.ts`)

---

## Analysis Summary

### Total Commands: 4
### Total Tokens: ~15,000

### **Key Duplication Opportunities:**

1. **File I/O & GitHub Operations:**
   - `complete-release`: Git tagging, version updates
   - `sync-release-status`: GitHub API queries, markdown updates
   - **Extract Potential:** `release-status-manager.ts` (unified file/GitHub operations)
   - **Token Savings:** ~400-600 tokens

2. **Template Compilation (Handlebars):**
   - `advance-release`: Uses Handlebars to compile `current-release.template.md`
   - `create-release-docs`: Uses templates/brd.template.md, prd.template.md, spec.template.md
   - **Extract Potential:** `doc-generator.ts` (template registry + compilation)
   - **Token Savings:** ~500-800 tokens

3. **Markdown Parsing & Version Management:**
   - `advance-release`: Version parsing, release file archiving, regex transformations
   - `sync-release-status`: Markdown parsing, checkbox updates
   - **Extract Potential:** `release-file-manager.ts` (unified markdown operations)
   - **Token Savings:** ~300-500 tokens

4. **Orchestration Logic:**
   - `advance-release`: Sequential steps (validate → archive → analyze → generate → increment → write)
   - `create-release-docs`: Sequential phases (discover → validate → generate BRD → PRD → Spec → cross-ref)
   - **Extract Potential:** `release-coordinator.ts` (command orchestration framework)
   - **Token Savings:** ~200-400 tokens

**Total Phase 1 + Phase 2 Potential Savings:** 1.4-2.3K tokens (9-15% of PLANNING total)

**Next Steps:**
1. Decide on Phase 1: Extract release transition utilities (sync + version transition)
2. Decide on Phase 2: Extract doc orchestration utilities
3. Walk through 7 decisions (organization, testing, measurement, rollout)

