Linear Integration Strategy - Comprehensive Plan
Version: 1.0.0 Created: 2025-10-26 Status: Ready for Implementation Estimated Timeline: 4-6 weeks (phased approach)
Executive Summary
This document provides a comprehensive strategy for integrating Linear project management into the TVL Platform development workflow through:
- Programmatic Sync - Automated scripts to sync TODOs, git commits, ADRs, and checklists to Linear
- IDE Integration - VS Code extensions and editor plugins for seamless Linear access
- Git Integration - Pre-commit hooks and GitHub Actions for automatic issue tracking
- Bi-directional Sync - Keep Linear and codebase in sync (Linear → Code, Code → Linear)
- Advanced Features - Velocity tracking, burndown charts, auto-assignment, and automation
Key Technologies:
- Linear SDK (@linear/sdk v31.0.0) - Already installed
- Linear GraphQL API - For advanced queries and mutations
- Linear Webhooks - For real-time updates
- VS Code Linear Extension - For IDE integration
- GitHub Actions - For CI/CD integration
Total Effort: ~140 hours (4-6 weeks, 1 developer)
Table of Contents
- Current State Analysis
- Phase 1: Programmatic Integration
- Phase 2: IDE Integration
- Phase 3: Git Integration
- Phase 4: Bi-directional Sync
- Phase 5: Advanced Features
- Testing Strategy
- Deployment & Rollout
- Cost Analysis
- Risk Assessment
Current State Analysis
Existing Assets
1. Linear Setup Script (scripts/setup-linear.ts)
- Creates MVP.0 Foundation Team
- Sets up 21 labels (domains, technical, priority, status)
- Creates 20 stories and 71 tasks
- Total: ~120 story points estimated
- Status: Fully functional
2. Linear SDK Integration
- Package: @linear/sdkv31.0.0
- Installed at root level
- API key authentication ready
- GraphQL client configured
3. Documentation
- Linear workflow guide: .claude/planning/linear-scrum-workflow-guide.md
- Development checklist: docs/DEVELOPMENT_PREP_CHECKLIST.md
- 54 ADRs in docs/reference/decisions/
- Complete domain specifications in docs/specifications/domains/
Task Sources Identified
1. TODO Comments in Code
- Found minimal TODOs in current codebase
- Primarily in session files and git hooks (not actionable)
- Future code will have more TODOs
2. Git Commits
- Active development in database package
- 15 TypeScript files in packages/database/
- Migration scripts, tests, RLS policies
3. ADR Checklists
- 54 ADRs in docs/reference/decisions/
- Many have implementation checklists
- Example: ADR-0050 (Husky Git Hooks) has 8-step checklist
4. DEVELOPMENT_PREP_CHECKLIST.md
- 7 phases (Documentation, CI/CD, Infrastructure, Monitoring, Scaffolding, Onboarding, Sprint Prep)
- 150+ tasks across phases
- Many unchecked (in-progress work)
Gaps & Opportunities
Current Gaps:
- No automated TODO → Linear sync
- No git commit → Linear linking (manual only)
- No ADR checklist tracking in Linear
- No bi-directional sync (Linear updates don't update code)
- No IDE integration for Linear access
Opportunities:
- Automate 90% of issue creation from existing task sources
- Reduce context switching (stay in IDE)
- Improve velocity tracking through automation
- Better sprint planning with actual effort data
- Prevent duplicate work through sync
Phase 1: Programmatic Integration
Timeline: 2 weeks (60 hours) Dependencies: Linear API key, @linear/sdk installed Success Criteria: All task sources automatically sync to Linear
1.1: TODO Comment Parser (12 hours)
Objective: Extract and sync TODO/FIXME/XXX/HACK comments to Linear tasks
Implementation:
File: scripts/sync-todos-to-linear.ts
/**
 * TODO Comment Parser
 *
 * Scans codebase for TODO comments and creates Linear tasks
 *
 * Supported formats:
 * - // TODO: Description
 * - // TODO(username): Description
 * - // FIXME: Description
 * - // XXX: Description
 * - // HACK: Description
 *
 * Metadata extracted:
 * - File path
 * - Line number
 * - Author (from git blame)
 * - Domain (inferred from file path)
 * - Priority (TODO=low, FIXME=medium, HACK=high)
 */
Features:
- Scan TypeScript/JavaScript/SQL files for TODO comments
- Extract metadata (file, line number, author, domain)
- Create Linear tasks with proper labels
- Link to file location (GitHub URL)
- Detect duplicates (hash-based deduplication)
- Support TODO(username) format for auto-assignment
Tasks:
- [2h] Create TODO regex parser - Extract TODOs from file content
- [2h] Implement file scanner - Glob pattern matching, ignore node_modules
- [2h] Add git blame integration - Extract author from git history
- [2h] Create Linear task mapper - Map TODO to Linear issue format
- [2h] Implement duplicate detection - SHA-256 hash of (file + line + text)
- [2h] Add dry-run mode - Preview changes before syncing
Dependencies:
- @linear/sdk- Linear API client
- fast-glob- Fast file pattern matching
- simple-git- Git operations
- zod- Schema validation
Testing:
- Unit tests for TODO parsing (20 test cases)
- Integration tests with Linear API (mock)
- Test duplicate detection
- Test domain inference logic
Success Criteria:
- Scans entire codebase in <5 seconds
- Creates tasks with correct labels/assignees
- Zero duplicate tasks created
- Handles 100+ TODOs without rate limiting
1.2: Git Commit Tracker (10 hours)
Objective: Parse git commits and link to Linear issues
Implementation:
File: scripts/sync-commits-to-linear.ts
/**
 * Git Commit Tracker
 *
 * Parses git commit history and links commits to Linear issues
 *
 * Supported formats:
 * - "feat: Add feature (Fixes FOUND-123)"
 * - "fix: Bug fix (Closes FOUND-456)"
 * - "chore: Update deps [FOUND-789]"
 *
 * Actions:
 * - Link commit to Linear issue
 * - Add commit details as comment
 * - Move issue to "In Progress" on first commit
 * - Move to "In Review" when PR opened
 */
Features:
- Parse commit messages for Linear issue references
- Extract issue ID (FOUND-123, TEAM-456, etc.)
- Add commit SHA, author, timestamp as comment
- Auto-transition issue states based on commit activity
- Support conventional commits format
Tasks:
- [2h] Create commit parser - Regex for Linear issue IDs
- [2h] Implement git log integration - Get commits since last sync
- [2h] Create Linear comment generator - Format commit details
- [2h] Add state transition logic - Move issues based on activity
- [2h] Implement sync checkpointing - Track last synced commit
Dependencies:
- simple-git- Git operations
- @linear/sdk- Linear API
Testing:
- Test commit message parsing (15 formats)
- Test state transitions
- Test checkpoint resume
- Test rate limiting handling
Success Criteria:
- Syncs 1000+ commits in <30 seconds
- Correctly identifies all Linear references
- Proper state transitions (Backlog → In Progress → In Review)
- Idempotent (can re-run without duplicates)
1.3: ADR Checklist Sync (16 hours)
Objective: Extract checklists from ADRs and create Linear tasks
Implementation:
File: scripts/sync-adrs-to-linear.ts
/**
 * ADR Checklist Sync
 *
 * Extracts implementation checklists from ADR markdown files
 * and creates Linear tasks grouped under ADR stories
 *
 * Example ADR structure:
 * ---
 * ## Implementation Checklist
 *
 * - [ ] Setup ESLint config
 * - [ ] Add pre-commit hook
 * - [ ] Update CI/CD pipeline
 * ---
 *
 * Creates:
 * - Story: [ADR-0048] ESLint Configuration
 * - Tasks: 3 tasks from checklist
 */
Features:
- Parse markdown checklists from ADR files
- Create parent story for each ADR
- Create child tasks for each checklist item
- Track completion status (checked vs unchecked)
- Link to ADR file in GitHub
- Auto-assign based on ADR author
Tasks:
- [3h] Create markdown parser - Extract frontmatter and checklists
- [3h] Implement ADR scanner - Scan docs/reference/decisions/
- [3h] Create story/task hierarchy - Parent ADR story + child tasks
- [3h] Add completion tracking - Sync checked status from markdown
- [2h] Implement ADR-to-domain mapping - Infer domain labels
- [2h] Add bi-directional update - Update markdown when Linear task completed
Dependencies:
- gray-matter- Frontmatter parsing
- remark- Markdown AST parsing
- @linear/sdk- Linear API
Testing:
- Test parsing of 54 ADR files
- Test checklist extraction
- Test story/task creation
- Test completion status sync
Success Criteria:
- Processes all 54 ADRs in <10 seconds
- Creates correct story/task hierarchy
- Properly assigns domain labels
- Bi-directional sync works (Linear ↔ Markdown)
1.4: Development Checklist Sync (14 hours)
Objective: Sync DEVELOPMENT_PREP_CHECKLIST.md to Linear epics/stories/tasks
Implementation:
File: scripts/sync-dev-checklist-to-linear.ts
/**
 * Development Checklist Sync
 *
 * Parses DEVELOPMENT_PREP_CHECKLIST.md and creates hierarchical
 * Linear issues (Epics → Stories → Tasks)
 *
 * Hierarchy:
 * - Phase 0: Documentation Complete → Epic
 *   - Architecture Decision Records → Story
 *     - Foundation ADRs (0005-0014) → Task
 *     - Frontend ADRs (0015-0021) → Task
 */
Features:
- Parse markdown heading hierarchy (H2 = Epic, H3 = Story, H4 = Task)
- Detect checkbox status (completed vs pending)
- Extract time estimates from text ("(2h)", "(5 min)")
- Create proper epic/story/task relationships
- Track dependencies between tasks
- Auto-assign phases to sprints
Tasks:
- [3h] Create hierarchical markdown parser - Parse H2/H3/H4 structure
- [3h] Implement checkbox parser - Extract completion status
- [2h] Add time estimate extraction - Parse duration strings
- [3h] Create Linear hierarchy mapper - Epic/Story/Task relationships
- [2h] Implement dependency tracking - Extract "Blocks/Depends on"
- [1h] Add sprint assignment logic - Auto-assign to cycles
Dependencies:
- remark- Markdown parsing
- remark-gfm- GitHub Flavored Markdown
- @linear/sdk- Linear API
Testing:
- Test 7-phase checklist parsing
- Test hierarchy creation (Epics → Stories → Tasks)
- Test time estimate extraction
- Test dependency linking
Success Criteria:
- Processes 150+ checklist items in <15 seconds
- Creates correct 3-level hierarchy
- Properly extracts time estimates
- Dependencies correctly linked
1.5: Unified Sync CLI (8 hours)
Objective: Create single CLI tool for all sync operations
Implementation:
File: scripts/linear-sync.ts
/**
 * Linear Sync CLI
 *
 * Unified interface for all Linear sync operations
 *
 * Usage:
 *   pnpm linear:sync todos           - Sync TODO comments
 *   pnpm linear:sync commits         - Sync git commits
 *   pnpm linear:sync adrs            - Sync ADR checklists
 *   pnpm linear:sync checklist       - Sync dev checklist
 *   pnpm linear:sync all             - Sync everything
 *   pnpm linear:sync --dry-run       - Preview changes
 *   pnpm linear:sync --watch         - Continuous sync mode
 */
Features:
- Single entry point for all sync operations
- Dry-run mode (preview without changes)
- Watch mode (continuous sync)
- Progress reporting (spinners, status updates)
- Error handling and retry logic
- Configurable via .linear-sync.json
Tasks:
- [2h] Create CLI framework - Commander.js setup
- [2h] Implement command routing - Route to specific sync scripts
- [2h] Add progress reporting - Ora spinners, progress bars
- [2h] Create config file support - JSON/YAML configuration
Dependencies:
- commander- CLI framework
- ora- Progress spinners
- chalk- Colored output
- cosmiconfig- Configuration loading
Testing:
- Test all CLI commands
- Test dry-run mode
- Test watch mode
- Test error handling
Success Criteria:
- Intuitive CLI interface
- Clear progress reporting
- Handles errors gracefully
- Configurable without code changes
Phase 2: IDE Integration
Timeline: 2 weeks (50 hours) Dependencies: Phase 1 complete Success Criteria: Seamless Linear access from IDE
2.1: VS Code Extension Setup (12 hours)
Objective: Configure Linear VS Code extension for optimal workflow
Implementation:
Extension: Linear (Official)
Features:
- View assigned issues in sidebar
- Create issues from selection
- Link issues to code locations
- Search Linear workspace
- Update issue status
- Add comments to issues
Tasks:
- [2h] Install and configure extension - Install from marketplace
- [2h] Setup OAuth authentication - Connect to Linear workspace
- [2h] Configure workspace settings - Team, labels, templates
- [2h] Create custom commands - Keybindings for common actions
- [2h] Test integration with codebase - Create issues, link code
- [2h] Document workflow - Create quickstart guide
Configuration:
File: .vscode/settings.json
{
  "linear.team": "FOUND",
  "linear.defaultLabels": ["tech:database"],
  "linear.createIssueFromSelection": true,
  "linear.linkCodeLocation": true,
  "linear.statusBarEnabled": true
}
Custom Commands:
File: .vscode/keybindings.json
[
  {
    "key": "cmd+shift+l i",
    "command": "linear.createIssue",
    "when": "editorTextFocus"
  },
  {
    "key": "cmd+shift+l s",
    "command": "linear.searchIssues"
  },
  {
    "key": "cmd+shift+l a",
    "command": "linear.viewMyIssues"
  }
]
Testing:
- Test issue creation from code
- Test issue search
- Test status updates
- Test comment addition
Success Criteria:
- Extension installed and configured
- Can create issues without leaving VS Code
- Can update issue status inline
- Keybindings work as expected
2.2: VS Code TODO Extension Integration (10 hours)
Objective: Integrate TODO comments with Linear using VS Code extension
Extension: Todo Tree
Features:
- Highlight TODO/FIXME/HACK comments
- Tree view of all TODOs
- Click to jump to TODO location
- Filter by type/author/file
- Export TODOs to Linear
Tasks:
- [2h] Install Todo Tree extension - Configure highlights
- [2h] Create custom TODO integration - Bridge to Linear
- [2h] Implement "Export to Linear" command - Create issues from TODOs
- [2h] Add auto-sync on save - Sync TODOs when file saved
- [2h] Test integration - Create/update/delete scenarios
Configuration:
File: .vscode/settings.json
{
  "todo-tree.general.tags": [
    "TODO",
    "FIXME",
    "HACK",
    "XXX",
    "NOTE"
  ],
  "todo-tree.highlights.defaultHighlight": {
    "icon": "check",
    "type": "text",
    "foreground": "#ffffff",
    "background": "#ffbd2e",
    "opacity": 50,
    "iconColour": "#ffbd2e"
  },
  "todo-tree.highlights.customHighlight": {
    "TODO": {
      "icon": "check",
      "foreground": "#ffffff",
      "background": "#2563eb"
    },
    "FIXME": {
      "icon": "alert",
      "foreground": "#ffffff",
      "background": "#ea580c"
    },
    "HACK": {
      "icon": "flame",
      "foreground": "#ffffff",
      "background": "#dc2626"
    }
  },
  "todo-tree.general.showActivityBarBadge": true,
  "todo-tree.general.statusBar": "total"
}
Custom Extension:
File: .vscode/extensions/linear-todo-sync/package.json
{
  "name": "linear-todo-sync",
  "displayName": "Linear TODO Sync",
  "version": "1.0.0",
  "engines": {
    "vscode": "^1.80.0"
  },
  "categories": ["Other"],
  "activationEvents": ["onStartupFinished"],
  "main": "./out/extension.js",
  "contributes": {
    "commands": [
      {
        "command": "linear-todo-sync.exportTodo",
        "title": "Export TODO to Linear"
      },
      {
        "command": "linear-todo-sync.syncAll",
        "title": "Sync All TODOs to Linear"
      }
    ]
  }
}
Testing:
- Test TODO highlighting
- Test export to Linear
- Test auto-sync on save
- Test filtering and search
Success Criteria:
- All TODOs visible in tree view
- Can export individual TODOs to Linear
- Auto-sync works reliably
- No duplicate issues created
2.3: JetBrains IDE Support (8 hours)
Objective: Support Linear integration for IntelliJ/WebStorm users
Plugin: Linear Integration
Tasks:
- [2h] Research JetBrains plugin - Available features
- [2h] Create setup documentation - Installation guide
- [2h] Configure for TVL workflow - Team, labels, templates
- [2h] Test basic operations - Create, update, search issues
Note: This is lower priority - focus on VS Code first
Success Criteria:
- Installation guide created
- Basic operations documented
- Tested with at least one JetBrains IDE
2.4: Cursor AI Integration (12 hours)
Objective: Enhance Cursor AI with Linear context awareness
Implementation:
File: .cursorrules
## Linear Integration
When working on Linear issues:
1. **Read Issue Context**: Use Linear API to fetch full issue details
2. **Extract Acceptance Criteria**: Parse markdown checklists
3. **Link to Domain Specs**: Read referenced domain specification files
4. **Generate Branch Name**: Use Linear format: {TEAM}-{NUM}-{title-kebab}
5. **Update Issue Status**: Move to "In Progress" when starting work
6. **Verify Completion**: Check all acceptance criteria before marking done
## Cursor Commands for Linear
### Start Task
Input: "Start work on FOUND-123"
Actions:
1. Fetch issue from Linear API
2. Read issue description and acceptance criteria
3. Check referenced domain specs in /docs/
4. Create branch: git checkout -b FOUND-123-{title}
5. Move Linear issue to "In Progress"
6. List implementation steps based on acceptance criteria
### Check Completion
Input: "Check if FOUND-123 is complete"
Actions:
1. Fetch issue from Linear API
2. Parse acceptance criteria checkboxes
3. Verify each criterion is met in codebase
4. Report completion status with missing items
### Create Migration
Input: "Create migration for FOUND-123"
Actions:
1. Read issue description
2. Determine domain from labels
3. Generate migration SQL following TVL standards
4. Include all required columns (id, org_id, account_id, timestamps)
5. Add proper indexes and constraints
Tasks:
- [3h] Update .cursorrules - Add Linear-specific prompts
- [3h] Create Cursor commands - Custom AI commands for Linear
- [3h] Implement Linear context fetching - API integration in rules
- [3h] Test AI-driven workflow - Start/complete task scenarios
Testing:
- Test Linear issue fetching
- Test acceptance criteria parsing
- Test branch creation
- Test completion verification
Success Criteria:
- Cursor can fetch Linear issues
- Acceptance criteria properly parsed
- Branch names follow convention
- Issue status updates work
2.5: Command Palette Integration (8 hours)
Objective: Create VS Code command palette commands for Linear operations
Implementation:
File: .vscode/extensions/tvl-linear/src/commands.ts
import * as vscode from 'vscode';
import { LinearClient } from '@linear/sdk';
export function registerCommands(context: vscode.ExtensionContext) {
  // Create issue from selection
  context.subscriptions.push(
    vscode.commands.registerCommand('tvl.linear.createIssueFromSelection', async () => {
      const editor = vscode.window.activeTextEditor;
      if (!editor) return;
      const selection = editor.document.getText(editor.selection);
      const fileName = editor.document.fileName;
      const lineNumber = editor.selection.start.line + 1;
      // Create Linear issue with code context
      const client = new LinearClient({ apiKey: process.env.LINEAR_API_KEY });
      const issue = await client.createIssue({
        teamId: 'FOUND',
        title: `Code review needed: ${fileName}:${lineNumber}`,
        description: `\`\`\`typescript\n${selection}\n\`\`\`\n\n[View in GitHub](https://github.com/org/repo/blob/main/${fileName}#L${lineNumber})`,
      });
      vscode.window.showInformationMessage(`Created issue: ${issue.identifier}`);
    })
  );
  // More commands...
}
Commands:
- Create Issue from Selection - Create issue with code snippet
- Link Current File to Issue - Link file to Linear issue
- View My Issues - Quick pick of assigned issues
- Search Issues - Fuzzy search Linear workspace
- Update Issue Status - Change status without leaving editor
Tasks:
- [2h] Create VS Code extension boilerplate - Scaffold extension
- [2h] Implement command registration - Register 5 commands
- [2h] Add Linear API integration - Connect to Linear
- [2h] Test commands - Verify all operations work
Testing:
- Test each command
- Test error handling
- Test rate limiting
- Test authentication
Success Criteria:
- All commands registered and working
- Commands accessible from palette (Cmd+Shift+P)
- Error handling robust
- User-friendly error messages
Phase 3: Git Integration
Timeline: 1.5 weeks (40 hours) Dependencies: Phase 1 complete Success Criteria: Automatic git ↔ Linear linking
3.1: Pre-commit Hook (8 hours)
Objective: Validate commit messages and create Linear issues from TODOs
Implementation:
File: .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Run linter
pnpm lint-staged
# Validate commit message format
pnpm exec commitlint --edit $1
# Check for new TODOs and suggest creating Linear issues
node scripts/check-todos-in-staged.js
# Validate Linear issue reference if mentioned
node scripts/validate-linear-reference.js
Features:
- Validate commit message format (conventional commits)
- Check for Linear issue reference (FOUND-123)
- Detect new TODOs in staged files
- Prompt to create Linear issue for new TODOs
- Validate Linear issue exists and is open
Tasks:
- [2h] Create commit message validator - Check format compliance
- [2h] Implement TODO detector - Scan staged files for new TODOs
- [2h] Add Linear issue validator - Verify issue exists
- [2h] Create interactive prompts - Ask to create issues
Dependencies:
- husky- Git hooks manager
- commitlint- Commit message linting
- lint-staged- Run linters on staged files
- @linear/sdk- Linear API
Testing:
- Test with valid/invalid commit messages
- Test TODO detection
- Test Linear reference validation
- Test interactive prompts
Success Criteria:
- Commit messages follow convention
- New TODOs prompt issue creation
- Invalid Linear references blocked
- Interactive prompts user-friendly
3.2: Commit Message Parser (6 hours)
Objective: Extract Linear issue references from commit messages
Implementation:
File: scripts/parse-commit-message.ts
/**
 * Commit Message Parser
 *
 * Extracts Linear issue references from commit messages
 *
 * Supported formats:
 * - "feat: Add feature (Fixes FOUND-123)"
 * - "fix: Bug fix (Closes FOUND-456, FOUND-789)"
 * - "chore: Update [FOUND-100]"
 * - "docs: Update FOUND-200"
 *
 * Returns:
 * - Issue IDs: ['FOUND-123', 'FOUND-456']
 * - Closing keywords: ['Fixes', 'Closes']
 * - Type: 'feat' | 'fix' | 'chore' | etc.
 */
interface CommitInfo {
  issueIds: string[];
  closingKeywords: string[];
  type: string;
  scope?: string;
  description: string;
}
export function parseCommitMessage(message: string): CommitInfo {
  // Implementation
}
Tasks:
- [2h] Create regex patterns - Match all Linear reference formats
- [2h] Implement parser - Extract issue IDs and keywords
- [2h] Add tests - 20+ test cases for different formats
Testing:
- Test conventional commit formats
- Test multiple issue references
- Test closing keywords
- Test edge cases
Success Criteria:
- Parses all commit message formats
- Extracts all issue references
- Detects closing keywords correctly
- Handles edge cases gracefully
3.3: GitHub Actions Workflow (12 hours)
Objective: Automate Linear sync on GitHub events (push, PR, merge)
Implementation:
File: .github/workflows/linear-sync.yml
name: Linear Sync
on:
  push:
    branches: [main, develop]
  pull_request:
    types: [opened, closed, synchronize]
  issues:
    types: [opened, closed]
jobs:
  sync-commits:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Fetch all history
      - uses: pnpm/action-setup@v2
        with:
          version: 8
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'
      - name: Install dependencies
        run: pnpm install --frozen-lockfile
      - name: Sync commits to Linear
        run: pnpm linear:sync commits
        env:
          LINEAR_API_KEY: ${{ secrets.LINEAR_API_KEY }}
      - name: Update Linear issue status
        run: pnpm linear:update-status
        env:
          LINEAR_API_KEY: ${{ secrets.LINEAR_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  sync-pr:
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request'
    steps:
      - uses: actions/checkout@v4
      - name: Link PR to Linear issue
        uses: linear/action-sync-pr@v1
        with:
          linear-api-key: ${{ secrets.LINEAR_API_KEY }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
      - name: Move issue to "In Review"
        run: pnpm linear:transition-to-review
        env:
          LINEAR_API_KEY: ${{ secrets.LINEAR_API_KEY }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
Features:
- Sync commits on push
- Link PRs to Linear issues
- Move issues to "In Review" when PR opened
- Move issues to "Done" when PR merged
- Add PR link as comment on Linear issue
- Update issue description with PR details
Tasks:
- [3h] Create workflow file - Define GitHub Actions workflow
- [3h] Implement commit sync job - Sync commits to Linear
- [3h] Implement PR link job - Link PRs to issues
- [3h] Add status transition logic - Move issues based on PR state
Dependencies:
- GitHub Actions
- Linear API key (stored in GitHub Secrets)
Testing:
- Test on push events
- Test on PR events
- Test status transitions
- Test error handling
Success Criteria:
- Workflow runs on all events
- Commits properly synced
- PRs linked to issues
- Status transitions work
- Errors handled gracefully
3.4: GitHub Linear Integration (8 hours)
Objective: Configure native Linear GitHub integration
Implementation:
Steps:
- Install Linear GitHub app in repository
- Configure auto-linking (branches, PRs, commits)
- Enable auto-close on merge
- Setup PR templates with Linear references
- Configure issue templates with Linear links
Features:
- Auto-link branches created from Linear
- Auto-attach PRs to Linear issues
- Auto-close issues on PR merge
- Sync PR comments to Linear
- Display Linear status in PR
Tasks:
- [2h] Install GitHub app - Authorize Linear app
- [2h] Configure settings - Enable auto-linking, auto-close
- [2h] Create PR template - Include Linear reference
- [2h] Test integration - Create branch, PR, merge
PR Template:
File: .github/PULL_REQUEST_TEMPLATE.md
## Linear Issue
Fixes: [FOUND-XXX](https://linear.app/tvl/issue/FOUND-XXX)
## Description
<!-- What does this PR do? -->
## Acceptance Criteria
<!-- Copy from Linear issue -->
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Criterion 3
## Testing
<!-- How was this tested? -->
## Checklist
- [ ] Tests added/updated
- [ ] Documentation updated
- [ ] All acceptance criteria met
- [ ] Linear issue status updated
Testing:
- Test branch auto-linking
- Test PR attachment
- Test auto-close on merge
- Test comment sync
Success Criteria:
- GitHub app installed and configured
- Auto-linking works
- Auto-close works
- PR templates used consistently
3.5: Branch Naming Enforcement (6 hours)
Objective: Enforce Linear-compatible branch names
Implementation:
File: .husky/pre-push
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Validate branch name format
node scripts/validate-branch-name.js
# Check if Linear issue exists
node scripts/validate-linear-issue.js
Branch Name Format:
{TEAM}-{NUMBER}-{description-kebab-case}
Examples:
✅ FOUND-123-add-organizations-table
✅ SUPP-456-create-spaces-schema
❌ feature/add-table (no Linear reference)
❌ fix-bug (no Linear reference)
Tasks:
- [2h] Create branch name validator - Regex validation
- [2h] Add Linear issue checker - Verify issue exists
- [2h] Implement pre-push hook - Block invalid branches
Testing:
- Test valid branch names
- Test invalid branch names
- Test Linear issue validation
- Test error messages
Success Criteria:
- Only valid branch names allowed
- Clear error messages
- Linear issues verified
- Can bypass for hotfixes (--no-verify)
Phase 4: Bi-directional Sync
Timeline: 1 week (30 hours) Dependencies: Phase 1-3 complete Success Criteria: Linear ↔ Code stays in sync automatically
4.1: Webhook Receiver (10 hours)
Objective: Receive and process Linear webhooks for real-time updates
Implementation:
File: services/linear-webhook-receiver/src/server.ts
import fastify from 'fastify';
import { LinearClient, LinearWebhooks } from '@linear/sdk';
const app = fastify({ logger: true });
// Webhook endpoint
app.post('/webhooks/linear', async (req, reply) => {
  const signature = req.headers['linear-signature'] as string;
  const body = JSON.stringify(req.body);
  // Verify webhook signature
  const webhooks = new LinearWebhooks(process.env.LINEAR_WEBHOOK_SECRET!);
  const isValid = webhooks.verify(body, signature);
  if (!isValid) {
    return reply.code(401).send({ error: 'Invalid signature' });
  }
  // Process webhook event
  const event = req.body as LinearWebhookEvent;
  switch (event.type) {
    case 'Issue':
      await handleIssueEvent(event);
      break;
    case 'Comment':
      await handleCommentEvent(event);
      break;
    case 'Project':
      await handleProjectEvent(event);
      break;
  }
  return reply.code(200).send({ success: true });
});
async function handleIssueEvent(event: IssueEvent) {
  const { action, data } = event;
  switch (action) {
    case 'create':
      // Create TODO comment in code if applicable
      break;
    case 'update':
      // Update TODO status or ADR checklist
      break;
    case 'remove':
      // Remove TODO comment or mark as obsolete
      break;
  }
}
app.listen({ port: 3000 });
Features:
- Receive Linear webhooks (issue, comment, project events)
- Verify webhook signatures (HMAC-SHA256)
- Process events in background queue (BullMQ)
- Update code artifacts (TODOs, ADRs, checklists)
- Handle webhook retries gracefully
Tasks:
- [3h] Create Fastify webhook server - HTTP server setup
- [2h] Implement signature verification - HMAC validation
- [2h] Add event routing - Route to handlers
- [2h] Implement queue processing - BullMQ integration
- [1h] Add webhook registration - Register with Linear API
Dependencies:
- fastify- HTTP server
- @linear/sdk- Linear webhooks
- bullmq- Background job queue
- ioredis- Redis client
Testing:
- Test signature verification
- Test event routing
- Test queue processing
- Test retry logic
Success Criteria:
- Webhook server running
- Signatures verified correctly
- Events processed reliably
- Queue handles retries
4.2: TODO Comment Updater (8 hours)
Objective: Update TODO comments in code when Linear issues change
Implementation:
File: services/linear-webhook-receiver/src/handlers/todo-updater.ts
/**
 * TODO Comment Updater
 *
 * Updates TODO comments when Linear issues change
 *
 * Scenarios:
 * 1. Issue marked done → Add "DONE:" prefix to TODO
 * 2. Issue assigned → Add assignee to TODO
 * 3. Issue deleted → Remove TODO comment
 * 4. Issue description updated → Update TODO text
 *
 * Example:
 * Before: // TODO: Add RLS policy for users table
 * After:  // DONE: Add RLS policy for users table (Completed by @john)
 */
export async function updateTodoComment(issue: LinearIssue) {
  // Find TODO comment linked to this issue
  const todo = await findTodoByIssueId(issue.id);
  if (!todo) return;
  // Update TODO comment based on issue state
  const newComment = generateUpdatedComment(issue, todo);
  await updateFileComment(todo.file, todo.line, newComment);
  // Commit change
  await git.commit(`chore: Update TODO status (${issue.identifier})`);
}
Features:
- Find TODO comments linked to Linear issues
- Update TODO text when issue changes
- Mark as DONE when issue completed
- Remove TODO when issue deleted
- Add assignee when issue assigned
- Commit changes automatically (via bot)
Tasks:
- [2h] Create TODO finder - Map Linear issue → TODO comment
- [2h] Implement comment updater - Modify file content
- [2h] Add git operations - Commit changes
- [2h] Test update scenarios - Done, assigned, deleted
Testing:
- Test TODO updates
- Test DONE marking
- Test TODO removal
- Test git commits
Success Criteria:
- TODOs update when issues change
- Changes committed automatically
- No conflicts with manual edits
- Idempotent (can re-run)
4.3: ADR Checklist Updater (6 hours)
Objective: Update ADR checklists when Linear tasks complete
Implementation:
File: services/linear-webhook-receiver/src/handlers/adr-updater.ts
/**
 * ADR Checklist Updater
 *
 * Updates ADR markdown checklists when Linear tasks complete
 *
 * Example:
 * Linear task "FOUND-50: Setup ESLint config" marked done
 * → Updates ADR-0048-eslint-configuration.md:
 *
 * Before: - [ ] Setup ESLint config
 * After:  - [x] Setup ESLint config
 */
export async function updateAdrChecklist(task: LinearIssue) {
  // Find ADR file linked to this task
  const adr = await findAdrByTaskId(task.id);
  if (!adr) return;
  // Update checkbox in ADR markdown
  const updatedContent = toggleCheckbox(adr.content, task.title, task.state === 'completed');
  await fs.writeFile(adr.file, updatedContent);
  // Commit change
  await git.commit(`docs: Update ADR checklist (${task.identifier})`);
}
Features:
- Find ADR files linked to Linear tasks
- Toggle checkboxes in markdown
- Preserve markdown formatting
- Commit changes automatically
- Handle multiple checklists per ADR
Tasks:
- [2h] Create ADR finder - Map Linear task → ADR file
- [2h] Implement checkbox toggler - Update markdown
- [2h] Test checklist updates - Various scenarios
Testing:
- Test checkbox toggling
- Test multiple checklists
- Test markdown preservation
- Test git commits
Success Criteria:
- ADR checklists update automatically
- Markdown formatting preserved
- Changes committed reliably
- No duplicate updates
4.4: Dev Checklist Updater (6 hours)
Objective: Update DEVELOPMENT_PREP_CHECKLIST.md when Linear tasks complete
Implementation:
File: services/linear-webhook-receiver/src/handlers/checklist-updater.ts
/**
 * Development Checklist Updater
 *
 * Updates DEVELOPMENT_PREP_CHECKLIST.md when Linear tasks complete
 *
 * Maintains phase completion tracking and progress reporting
 */
export async function updateDevChecklist(task: LinearIssue) {
  // Find checklist item linked to this task
  const item = await findChecklistItem(task.id);
  if (!item) return;
  // Update checkbox
  const content = await fs.readFile('docs/DEVELOPMENT_PREP_CHECKLIST.md', 'utf-8');
  const updated = toggleCheckbox(content, item.text, task.state === 'completed');
  await fs.writeFile('docs/DEVELOPMENT_PREP_CHECKLIST.md', updated);
  // Update phase completion percentage
  const phase = extractPhase(item);
  const completion = calculateCompletion(phase);
  const withProgress = updatePhaseProgress(updated, phase, completion);
  await fs.writeFile('docs/DEVELOPMENT_PREP_CHECKLIST.md', withProgress);
  // Commit
  await git.commit(`docs: Update dev checklist - ${phase} (${completion}%)`);
}
Features:
- Update checklist checkboxes
- Calculate phase completion percentage
- Add progress indicators to phases
- Commit changes with progress info
Tasks:
- [2h] Create checklist item finder - Map task → checklist
- [2h] Implement completion calculator - Calculate phase progress
- [2h] Test checklist updates - Various scenarios
Testing:
- Test checkbox updates
- Test completion calculation
- Test progress indicators
- Test git commits
Success Criteria:
- Checklist updates automatically
- Phase completion accurate
- Progress indicators correct
- Changes committed reliably
Phase 5: Advanced Features
Timeline: 1 week (30 hours) Dependencies: Phase 1-4 complete Success Criteria: Advanced automation and insights
5.1: Auto-Assignment (6 hours)
Objective: Automatically assign Linear issues based on rules
Implementation:
File: scripts/linear-auto-assign.ts
/**
 * Linear Auto-Assignment
 *
 * Assigns issues based on:
 * - Git blame (last author of related files)
 * - Domain expertise (developer specialization)
 * - Workload (current issue count)
 * - Availability (calendar integration)
 *
 * Rules:
 * 1. If TODO created by developer X → assign to X
 * 2. If domain is "supply" and Y is expert → assign to Y
 * 3. If workload is balanced → round-robin
 * 4. If developer out of office → skip
 */
interface AssignmentRule {
  priority: number;
  condition: (issue: LinearIssue) => boolean;
  assign: (issue: LinearIssue) => Promise<string>; // Returns user ID
}
const rules: AssignmentRule[] = [
  {
    priority: 1,
    condition: (issue) => issue.labels.includes('tech:database'),
    assign: async (issue) => {
      // Find last author of related database files
      const author = await getGitBlameAuthor(issue);
      return author.linearUserId;
    },
  },
  {
    priority: 2,
    condition: (issue) => issue.labels.some((l) => l.startsWith('domain:')),
    assign: async (issue) => {
      // Find domain expert
      const domain = issue.labels.find((l) => l.startsWith('domain:'));
      return getDomainExpert(domain!);
    },
  },
  {
    priority: 3,
    condition: () => true,
    assign: async () => {
      // Round-robin by workload
      return getLeastLoadedDeveloper();
    },
  },
];
export async function autoAssign(issue: LinearIssue) {
  // Apply rules in priority order
  for (const rule of rules) {
    if (rule.condition(issue)) {
      const assigneeId = await rule.assign(issue);
      await issue.update({ assigneeId });
      return;
    }
  }
}
Features:
- Rule-based assignment
- Git blame integration
- Domain expertise mapping
- Workload balancing
- Calendar integration (optional)
Tasks:
- [2h] Create assignment rule engine - Priority-based rules
- [2h] Implement git blame lookup - Find last author
- [2h] Add workload balancing - Count current issues
Testing:
- Test each assignment rule
- Test priority ordering
- Test workload calculation
- Test git blame accuracy
Success Criteria:
- Issues assigned automatically
- Rules applied correctly
- Workload balanced
- Can override manual assignments
5.2: Velocity Tracking (8 hours)
Objective: Track team velocity and predict sprint capacity
Implementation:
File: scripts/linear-velocity-tracker.ts
/**
 * Linear Velocity Tracker
 *
 * Calculates team velocity based on completed story points
 * and predicts future sprint capacity
 *
 * Metrics:
 * - Velocity: Story points completed per sprint
 * - Trend: Velocity over last 3 sprints
 * - Capacity: Predicted points for next sprint
 * - Accuracy: Estimated vs actual completion rate
 */
interface VelocityMetrics {
  currentSprint: {
    planned: number;
    completed: number;
    remaining: number;
  };
  lastSprint: {
    planned: number;
    completed: number;
    velocity: number;
  };
  last3Sprints: {
    average: number;
    trend: 'up' | 'down' | 'stable';
  };
  nextSprint: {
    predicted: number;
    confidence: number; // 0-100%
  };
}
export async function calculateVelocity(): Promise<VelocityMetrics> {
  // Fetch completed issues from last 3 sprints
  const sprints = await getLastSprints(3);
  // Calculate velocity for each sprint
  const velocities = sprints.map((sprint) => ({
    planned: sprint.issues.reduce((sum, i) => sum + i.estimate, 0),
    completed: sprint.completedIssues.reduce((sum, i) => sum + i.estimate, 0),
  }));
  // Calculate average and trend
  const average = velocities.reduce((sum, v) => sum + v.completed, 0) / velocities.length;
  const trend = calculateTrend(velocities);
  // Predict next sprint capacity
  const predicted = predictCapacity(average, trend);
  return {
    currentSprint: getCurrentSprintMetrics(),
    lastSprint: velocities[0],
    last3Sprints: { average, trend },
    nextSprint: { predicted, confidence: calculateConfidence(velocities) },
  };
}
Features:
- Calculate velocity per sprint
- Track velocity trend (up/down/stable)
- Predict next sprint capacity
- Calculate estimation accuracy
- Generate velocity charts
Tasks:
- [2h] Create velocity calculator - Story points per sprint
- [2h] Implement trend analysis - Moving average, regression
- [2h] Add capacity predictor - Machine learning (simple)
- [2h] Generate charts - Chart.js or similar
Testing:
- Test velocity calculation
- Test trend detection
- Test capacity prediction
- Test chart generation
Success Criteria:
- Accurate velocity tracking
- Trend detection works
- Predictions within 20% accuracy
- Charts visualize data well
5.3: Burndown Chart Generator (8 hours)
Objective: Generate sprint burndown charts
Implementation:
File: scripts/linear-burndown-chart.ts
/**
 * Linear Burndown Chart Generator
 *
 * Generates burndown charts for current sprint
 *
 * Chart shows:
 * - Ideal burndown (linear)
 * - Actual burndown (completed points over time)
 * - Remaining work
 * - Trend line
 */
interface BurndownData {
  dates: string[];
  ideal: number[];
  actual: number[];
  remaining: number[];
  trend: number[];
}
export async function generateBurndown(sprintId: string): Promise<BurndownData> {
  const sprint = await getSprint(sprintId);
  const startDate = new Date(sprint.startDate);
  const endDate = new Date(sprint.endDate);
  const totalPoints = sprint.issues.reduce((sum, i) => sum + i.estimate, 0);
  // Generate daily data
  const dates: string[] = [];
  const ideal: number[] = [];
  const actual: number[] = [];
  const remaining: number[] = [];
  for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
    dates.push(d.toISOString().split('T')[0]);
    // Ideal burndown (linear)
    const daysElapsed = (d.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
    const totalDays = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
    ideal.push(totalPoints - (totalPoints * daysElapsed) / totalDays);
    // Actual burndown
    const completedByDate = await getCompletedPoints(sprint, d);
    actual.push(totalPoints - completedByDate);
    remaining.push(totalPoints - completedByDate);
  }
  // Calculate trend line (linear regression)
  const trend = calculateTrendLine(actual);
  return { dates, ideal, actual, remaining, trend };
}
Features:
- Daily burndown calculation
- Ideal vs actual comparison
- Trend line projection
- Export as PNG/SVG
- Embed in README or docs
Tasks:
- [2h] Create burndown calculator - Daily point tracking
- [2h] Implement trend line - Linear regression
- [2h] Generate chart - Chart.js or D3.js
- [2h] Add export options - PNG, SVG, JSON
Testing:
- Test burndown calculation
- Test trend line accuracy
- Test chart generation
- Test export formats
Success Criteria:
- Accurate burndown tracking
- Charts update daily
- Trend line helpful
- Export formats work
5.4: Effort vs Estimate Analysis (4 hours)
Objective: Compare estimated vs actual effort for better future estimates
Implementation:
File: scripts/linear-effort-analysis.ts
/**
 * Effort vs Estimate Analysis
 *
 * Compares story point estimates with actual time spent
 * to improve future estimation accuracy
 *
 * Metrics:
 * - Estimation accuracy: Estimated vs actual ratio
 * - Overestimation rate: % of tasks over-estimated
 * - Underestimation rate: % of tasks under-estimated
 * - Domain-specific accuracy: Accuracy per domain
 */
interface EffortAnalysis {
  overall: {
    averageAccuracy: number; // 0-100%
    overestimationRate: number; // 0-100%
    underestimationRate: number; // 0-100%
  };
  byDomain: Record<
    string,
    {
      accuracy: number;
      samples: number;
    }
  >;
  byDeveloper: Record<
    string,
    {
      accuracy: number;
      samples: number;
    }
  >;
  recommendations: string[];
}
export async function analyzeEffort(): Promise<EffortAnalysis> {
  // Fetch completed issues with estimates and actual time
  const issues = await getCompletedIssues();
  // Calculate accuracy for each issue
  const accuracies = issues.map((issue) => ({
    estimated: issue.estimate,
    actual: calculateActualEffort(issue), // From commits, PR time, etc.
    accuracy: (issue.estimate / calculateActualEffort(issue)) * 100,
    domain: extractDomain(issue),
    developer: issue.assignee.name,
  }));
  // Aggregate metrics
  const overall = calculateOverallMetrics(accuracies);
  const byDomain = groupBy(accuracies, 'domain');
  const byDeveloper = groupBy(accuracies, 'developer');
  // Generate recommendations
  const recommendations = generateRecommendations(overall, byDomain);
  return { overall, byDomain, byDeveloper, recommendations };
}
Features:
- Track estimated vs actual effort
- Calculate estimation accuracy
- Identify patterns (over/under estimation)
- Generate recommendations
- Domain-specific insights
Tasks:
- [2h] Create effort calculator - Extract actual time from commits/PRs
- [2h] Implement analysis - Calculate accuracy metrics
Testing:
- Test effort calculation
- Test accuracy metrics
- Test recommendations
Success Criteria:
- Accurate effort tracking
- Useful insights generated
- Recommendations actionable
- Metrics improve over time
5.5: Sprint Report Generator (4 hours)
Objective: Generate comprehensive sprint reports
Implementation:
File: scripts/linear-sprint-report.ts
/**
 * Linear Sprint Report Generator
 *
 * Generates sprint retrospective reports with:
 * - Velocity metrics
 * - Burndown chart
 * - Completed work summary
 * - Effort analysis
 * - Team highlights
 * - Action items
 */
interface SprintReport {
  sprint: {
    name: string;
    dates: { start: string; end: string };
    goal: string;
  };
  velocity: VelocityMetrics;
  burndown: BurndownData;
  completed: {
    stories: LinearIssue[];
    tasks: LinearIssue[];
    totalPoints: number;
  };
  effort: EffortAnalysis;
  highlights: string[];
  actionItems: string[];
}
export async function generateSprintReport(sprintId: string): Promise<SprintReport> {
  // Gather all data
  const sprint = await getSprint(sprintId);
  const velocity = await calculateVelocity();
  const burndown = await generateBurndown(sprintId);
  const completed = await getCompletedWork(sprintId);
  const effort = await analyzeEffort();
  // Generate report
  const report: SprintReport = {
    sprint: {
      name: sprint.name,
      dates: { start: sprint.startDate, end: sprint.endDate },
      goal: sprint.description,
    },
    velocity,
    burndown,
    completed,
    effort,
    highlights: generateHighlights(completed),
    actionItems: generateActionItems(velocity, effort),
  };
  // Export as markdown
  await exportAsMarkdown(report);
  return report;
}
Features:
- Comprehensive sprint summary
- All metrics in one report
- Export as markdown
- Auto-post to Slack/Discord
- Archive in git repository
Tasks:
- [2h] Create report generator - Aggregate all metrics
- [2h] Implement markdown export - Format as readable doc
Testing:
- Test report generation
- Test markdown formatting
- Test export
Success Criteria:
- Complete sprint summary
- Readable markdown format
- Helpful insights
- Archived consistently
Testing Strategy
Unit Testing (All Phases)
Framework: Vitest Coverage Target: 80%+
Test Categories:
- Parser Tests - TODO, commit, ADR, checklist parsing
- Linear API Tests - Mocked SDK calls
- Git Operations Tests - Mocked git commands
- Validation Tests - Branch names, commit messages
- Integration Tests - End-to-end workflows
Example Test:
import { describe, it, expect, vi } from 'vitest';
import { parseTodoComment } from '../src/parsers/todo-parser';
describe('TODO Comment Parser', () => {
  it('should extract TODO with author', () => {
    const code = '// TODO(john): Add RLS policy';
    const result = parseTodoComment(code);
    expect(result).toEqual({
      type: 'TODO',
      author: 'john',
      description: 'Add RLS policy',
      priority: 'low',
    });
  });
  it('should handle FIXME with high priority', () => {
    const code = '// FIXME: Critical bug in auth';
    const result = parseTodoComment(code);
    expect(result.type).toBe('FIXME');
    expect(result.priority).toBe('medium');
  });
});
Integration Testing
Test Scenarios:
- TODO → Linear - Create TODO, verify Linear issue created
- Commit → Linear - Commit with reference, verify issue updated
- ADR → Linear - ADR checklist creates story + tasks
- Linear → Code - Issue completed, TODO marked DONE
- PR → Linear - PR opened, issue moves to "In Review"
Test Environment:
- Mock Linear API (using MSW)
- Test git repository (in-memory)
- Test files in /tmp
Manual Testing Checklist
Phase 1:
-  Run pnpm linear:sync todos --dry-run
- Verify TODOs detected correctly
-  Run pnpm linear:sync todos
- Check Linear for created tasks
- Verify no duplicates
- Test all sync commands (commits, adrs, checklist)
Phase 2:
- Install VS Code extension
- Create issue from code selection
- Search for issues
- Update issue status
- Test Cursor AI commands
Phase 3:
- Create commit with Linear reference
- Verify pre-commit hook runs
- Push to GitHub
- Verify GitHub Action runs
- Check Linear issue updated
Phase 4:
- Mark Linear issue done
- Verify TODO updated in code
- Check ADR checklist updated
- Verify dev checklist updated
Phase 5:
- Create new issue without assignee
- Verify auto-assignment
- Check velocity metrics
- Generate burndown chart
- Run sprint report
Deployment & Rollout
Phase 1: Pilot (Week 1-2)
Team: 1 developer (you) Scope: Programmatic sync only
Actions:
- Deploy scripts to scripts/directory
- Add npm scripts to package.json
- Run initial sync (dry-run first)
- Monitor Linear for issues
- Fix any bugs
- Document learnings
Success Criteria:
- All scripts working
- Linear issues created correctly
- No duplicates
- Documentation complete
Phase 2: Team Rollout (Week 3-4)
Team: Full development team Scope: IDE integration + Git integration
Actions:
- Share VS Code extension setup guide
- Configure GitHub Actions
- Enable pre-commit hooks
- Train team on workflow
- Monitor adoption
- Gather feedback
Success Criteria:
- All developers using extensions
- GitHub Actions running on all PRs
- Pre-commit hooks enforced
- Team feedback positive
Phase 3: Automation (Week 5-6)
Team: Full team + stakeholders Scope: Bi-directional sync + Advanced features
Actions:
- Deploy webhook receiver
- Enable bi-directional sync
- Configure auto-assignment
- Generate velocity reports
- Share sprint reports with stakeholders
Success Criteria:
- Webhooks processing reliably
- Bi-directional sync working
- Auto-assignment accurate
- Stakeholders informed
Cost Analysis
Infrastructure Costs
Linear: $0/month (Free tier)
- 250 issues
- Unlimited members
- GitHub integration included
GitHub Actions: $0/month (Free tier)
- 2,000 minutes/month
- Linear sync uses ~50 min/month
Webhook Receiver: $5/month (Railway/Render)
- 512MB RAM
- Handles 1000 webhooks/day
Redis (BullMQ): $0/month (Upstash free tier)
- 10,000 commands/day
- Sufficient for queue processing
Total Infrastructure: $5/month
Development Costs
Phase 1: 60 hours × $100/hr = $6,000 Phase 2: 50 hours × $100/hr = $5,000 Phase 3: 40 hours × $100/hr = $4,000 Phase 4: 30 hours × $100/hr = $3,000 Phase 5: 30 hours × $100/hr = $3,000
Total Development: $21,000
ROI Analysis
Time Saved Per Developer Per Week:
- Manual issue creation: 2 hours → 0 hours (automated)
- Context switching: 3 hours → 1 hour (IDE integration)
- Sprint planning: 2 hours → 1 hour (velocity tracking)
- Status updates: 1 hour → 0 hours (auto-sync)
Total Saved: 7 hours/week/developer
Team of 3 Developers:
- 21 hours/week saved
- $2,100/week saved (at $100/hr)
- $8,400/month saved
Break-even: ~2.5 months
Annual Savings: $100,800
Risk Assessment
Technical Risks
1. Linear API Rate Limiting
- Risk: High sync volume hits rate limits
- Mitigation: Implement exponential backoff, batch operations
- Severity: Medium
2. Webhook Delivery Failures
- Risk: Webhooks fail, sync breaks
- Mitigation: Retry queue, fallback polling
- Severity: High
3. Git Conflicts
- Risk: Auto-commits conflict with manual edits
- Mitigation: Lock files during updates, conflict detection
- Severity: Medium
4. Duplicate Issues
- Risk: Same TODO creates multiple issues
- Mitigation: Hash-based deduplication, unique IDs
- Severity: High
Operational Risks
1. Team Adoption
- Risk: Team doesn't use new workflow
- Mitigation: Training, documentation, gradual rollout
- Severity: High
2. Maintenance Burden
- Risk: Integration breaks with Linear API changes
- Mitigation: API versioning, comprehensive tests
- Severity: Medium
3. Data Consistency
- Risk: Linear and code get out of sync
- Mitigation: Reconciliation scripts, manual overrides
- Severity: Medium
Appendix
A. File Structure
/mnt/c/GitHub/the-villa-life/
├── scripts/
│   ├── sync-todos-to-linear.ts        # Phase 1.1
│   ├── sync-commits-to-linear.ts      # Phase 1.2
│   ├── sync-adrs-to-linear.ts         # Phase 1.3
│   ├── sync-dev-checklist-to-linear.ts # Phase 1.4
│   ├── linear-sync.ts                 # Phase 1.5 (CLI)
│   ├── linear-auto-assign.ts          # Phase 5.1
│   ├── linear-velocity-tracker.ts     # Phase 5.2
│   ├── linear-burndown-chart.ts       # Phase 5.3
│   ├── linear-effort-analysis.ts      # Phase 5.4
│   └── linear-sprint-report.ts        # Phase 5.5
├── services/
│   └── linear-webhook-receiver/       # Phase 4.1
│       ├── src/
│       │   ├── server.ts
│       │   ├── handlers/
│       │   │   ├── todo-updater.ts    # Phase 4.2
│       │   │   ├── adr-updater.ts     # Phase 4.3
│       │   │   └── checklist-updater.ts # Phase 4.4
│       │   └── utils/
│       └── package.json
├── .vscode/
│   ├── extensions/
│   │   └── tvl-linear/                # Phase 2.5
│   ├── settings.json                  # Phase 2.1, 2.2
│   └── keybindings.json               # Phase 2.1
├── .github/
│   ├── workflows/
│   │   └── linear-sync.yml            # Phase 3.3
│   └── PULL_REQUEST_TEMPLATE.md       # Phase 3.4
├── .husky/
│   ├── pre-commit                     # Phase 3.1
│   └── pre-push                       # Phase 3.5
├── .cursorrules                       # Phase 2.4
└── .linear-sync.json                  # Configuration
B. Configuration File
File: .linear-sync.json
{
  "linear": {
    "teamId": "FOUND",
    "defaultLabels": ["tech:database"],
    "apiKey": "${LINEAR_API_KEY}"
  },
  "sync": {
    "todos": {
      "enabled": true,
      "patterns": ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.sql"],
      "exclude": ["node_modules/**", "dist/**", "build/**"],
      "keywords": ["TODO", "FIXME", "HACK", "XXX"],
      "createIssues": true,
      "autoAssign": true
    },
    "commits": {
      "enabled": true,
      "patterns": ["Fixes", "Closes", "Resolves"],
      "addComments": true,
      "updateStatus": true
    },
    "adrs": {
      "enabled": true,
      "directory": "docs/reference/decisions",
      "pattern": "adr-*.md",
      "createStories": true
    },
    "checklist": {
      "enabled": true,
      "file": "docs/DEVELOPMENT_PREP_CHECKLIST.md",
      "createEpics": true
    }
  },
  "webhooks": {
    "enabled": true,
    "url": "https://your-webhook-receiver.com/webhooks/linear",
    "secret": "${LINEAR_WEBHOOK_SECRET}",
    "events": ["Issue", "Comment", "Project"]
  },
  "automation": {
    "autoAssign": {
      "enabled": true,
      "rules": "scripts/assignment-rules.json"
    },
    "velocity": {
      "enabled": true,
      "trackLast": 3,
      "reportInterval": "weekly"
    }
  }
}
C. API Reference
Linear SDK Methods Used:
// Create issue
const issue = await client.createIssue({
  teamId: string,
  title: string,
  description?: string,
  assigneeId?: string,
  labelIds?: string[],
  estimate?: number,
  parentId?: string,
  stateId?: string,
});
// Update issue
await issue.update({
  stateId?: string,
  assigneeId?: string,
  estimate?: number,
});
// Add comment
await client.createComment({
  issueId: string,
  body: string,
});
// Search issues
const issues = await client.issues({
  filter: {
    team: { key: { eq: 'FOUND' } },
    state: { type: { eq: 'completed' } },
  },
});
// Get team
const team = await client.team('teamId');
// Get user
const user = await client.user('userId');
D. Resources
Linear Documentation:
- API Docs: https://developers.linear.app/docs
- SDK Docs: https://developers.linear.app/docs/sdk
- Webhooks: https://developers.linear.app/docs/webhooks
- GraphQL Playground: https://linear.app/graphql
VS Code Extensions:
- Linear (Official): https://marketplace.visualstudio.com/items?itemName=LinearApp.linear
- Todo Tree: https://marketplace.visualstudio.com/items?itemName=Gruntfuggly.todo-tree
GitHub Actions:
- Linear Action: https://github.com/linear/action-sync-pr
Libraries:
- @linear/sdk: https://www.npmjs.com/package/@linear/sdk
- fast-glob: https://www.npmjs.com/package/fast-glob
- simple-git: https://www.npmjs.com/package/simple-git
- remark: https://www.npmjs.com/package/remark
- gray-matter: https://www.npmjs.com/package/gray-matter
- commander: https://www.npmjs.com/package/commander
Summary
This comprehensive Linear integration strategy provides a 4-6 week roadmap to fully automate project management for the TVL Platform.
Key Deliverables:
- Programmatic Sync - Automate 90% of issue creation
- IDE Integration - Eliminate context switching
- Git Integration - Auto-link commits and PRs
- Bi-directional Sync - Keep Linear and code in sync
- Advanced Features - Velocity, burndown, auto-assignment
Total Investment: $21,000 development + $5/month infrastructure ROI: $100,800/year savings (3-developer team) Break-even: 2.5 months
Next Steps:
- Review and approve this strategy
- Allocate resources (1 developer, 4-6 weeks)
- Begin Phase 1 (Programmatic Integration)
- Iterate based on team feedback
Document Version: 1.0.0 Last Updated: 2025-10-26 Author: Claude (Anthropic) Status: Ready for Implementation