import {
  DIRECTORIES,
  FILE_SYSTEM,
  LUMENFLOW_PATHS
} from "./chunk-DWMLTXKQ.js";
import {
  WORKSPACE_CONFIG_FILE_NAME,
  WORKSPACE_V2_KEYS,
  getConfig
} from "./chunk-V6OJGLBA.js";

// src/init-templates.ts
var DEFAULT_WORKTREES_DIR = DIRECTORIES.WORKTREES;
var DEFAULT_WORKTREES_PATTERN = DEFAULT_WORKTREES_DIR.endsWith("/") ? DEFAULT_WORKTREES_DIR.slice(0, -1) : DEFAULT_WORKTREES_DIR;
var DEFAULT_STATE_DIR_IGNORE = LUMENFLOW_PATHS.STATE_DIR.endsWith("/") ? LUMENFLOW_PATHS.STATE_DIR : `${LUMENFLOW_PATHS.STATE_DIR}/`;
var DEFAULT_LANE_DEFINITIONS = [
  {
    name: "Framework: Core",
    wip_limit: 1,
    code_paths: ["packages/**/core/**", "src/core/**", "lib/**"]
  },
  {
    name: "Framework: CLI",
    wip_limit: 1,
    code_paths: ["packages/**/cli/**", "src/cli/**", "bin/**"]
  },
  {
    name: "Experience: Web",
    wip_limit: 1,
    code_paths: ["apps/web/**", "web/**", "src/components/**", "src/pages/**", "src/app/**"]
  },
  {
    name: "Operations: Infrastructure",
    wip_limit: 1,
    code_paths: ["infrastructure/**", "deploy/**"]
  },
  {
    name: "Operations: CI/CD",
    wip_limit: 1,
    code_paths: [".github/workflows/**", ".github/actions/**", ".circleci/**"]
  },
  {
    name: "Content: Documentation",
    wip_limit: 1,
    code_paths: ["docs/**", "*.md"]
  }
];
var AGENTS_MD_TEMPLATE = `# Universal Agent Instructions

**Last updated:** {{DATE}}

This project uses LumenFlow workflow. For complete documentation, see [LUMENFLOW.md](LUMENFLOW.md).

---

## Quick Start

\`\`\`bash
# First-time lane setup (once per project)
pnpm lane:setup
pnpm lane:validate
pnpm lane:lock
\`\`\`

\`\`\`bash
# 1. Claim a WU
pnpm wu:claim --id WU-XXXX --lane <Lane>
cd worktrees/<lane>-wu-xxxx

# 2. Work in worktree, run gates
pnpm gates

# 3. Complete (ALWAYS run this!)
cd <project-root>
pnpm wu:done --id WU-XXXX
\`\`\`

> **Complete CLI reference:** See [quick-ref-commands.md]({{QUICK_REF_LINK}})

---

## Critical: Always wu:done

After completing work, ALWAYS run \`pnpm wu:done --id WU-XXXX\` from the main checkout.

This is the single most forgotten step. See [LUMENFLOW.md](LUMENFLOW.md) for details.

---

## Core Principles

1. **Fit-For-Surface Verification**: Choose the least brittle verification that gives strong confidence. Prefer TDD for runtime logic when policy requires it; avoid brittle UI implementation-detail tests.
2. **Worktree Discipline**: After \`wu:claim\`, work ONLY in the worktree
3. **Gates Before Done**: Run \`pnpm gates\` before \`wu:done\`
4. **Never Bypass Hooks**: No \`--no-verify\`

---

## Forbidden Commands

- \`git reset --hard\`
- \`git push --force\`
- \`git stash\` (on main)
- \`--no-verify\`

---

## Vendor-Specific Overlays

This file provides universal guidance for all AI agents. Additional vendor-specific configuration:

- **Claude Code**: See \`CLAUDE.md\` (if present)
- **Cursor**: See \`.cursor/rules/lumenflow.md\` (if present)
- **Windsurf**: See \`.windsurf/rules/lumenflow.md\` (if present)
`;
var CLAUDE_MD_TEMPLATE = `# Claude Code Instructions

**Last updated:** {{DATE}}

This project uses LumenFlow workflow. For workflow documentation, see [LUMENFLOW.md](LUMENFLOW.md).

---

## Quick Start

\`\`\`bash
# 1. Claim a WU
pnpm wu:claim --id WU-XXXX --lane <Lane>
cd worktrees/<lane>-wu-xxxx

# 2. Work in worktree, run gates
pnpm gates

# 3. Complete (ALWAYS run this!)
cd <project-root>
pnpm wu:done --id WU-XXXX
\`\`\`

---

## CLI Commands Reference

### WU Lifecycle

| Command                                   | Description                              |
| ----------------------------------------- | ---------------------------------------- |
| \`pnpm wu:status --id WU-XXX\`              | Show WU status, location, valid commands |
| \`pnpm wu:claim --id WU-XXX --lane <Lane>\` | Claim WU and create worktree             |
| \`pnpm wu:prep --id WU-XXX\`                | Run gates in worktree, prep for wu:done  |
| \`pnpm wu:done --id WU-XXX\`                | Complete WU (from main checkout)         |
| \`pnpm wu:block --id WU-XXX --reason "..."\`| Block WU with reason                     |
| \`pnpm wu:unblock --id WU-XXX\`             | Unblock WU                               |

### Gates & Quality

| Command                  | Description                |
| ------------------------ | -------------------------- |
| \`pnpm gates\`             | Run all quality gates      |
| \`pnpm gates --docs-only\` | Run gates for docs changes |
| \`pnpm format\`            | Format all files           |
| \`pnpm lint\`              | Run linter                 |
| \`pnpm typecheck\`         | Run TypeScript check       |
| \`pnpm test\`              | Run tests                  |

---

## Critical: Always wu:done

After completing work, ALWAYS run \`pnpm wu:done --id WU-XXXX\` from the main checkout.

See [LUMENFLOW.md](LUMENFLOW.md) for full workflow documentation.

---

## Warning: Do Not Edit WU YAML Files Manually

**Never manually edit WU YAML files** in \`docs/.../tasks/wu/WU-XXX.yaml\`.

Use CLI commands instead:

- \`pnpm wu:create ...\` to create new WUs
- \`pnpm wu:edit --id WU-XXX ...\` to modify WU fields
- \`pnpm wu:claim\` / \`wu:block\` / \`wu:done\` for status changes

Manual edits bypass validation and can corrupt workflow state.
`;
var CLAUDE_SETTINGS_TEMPLATE = `{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "allow": [
      "Bash",
      "Read",
      "Write",
      "Edit",
      "WebFetch",
      "WebSearch"
    ],
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Write(./.env*)",
      "Bash(git reset --hard *)",
      "Bash(git stash *)",
      "Bash(git clean -fd *)",
      "Bash(git push --force *)",
      "Bash(git push -f *)",
      "Bash(git commit --no-verify *)",
      "Bash(HUSKY=0 *)",
      "Bash(rm -rf /*)",
      "Bash(sudo *)",
      "Bash(git worktree remove *)",
      "Bash(git worktree prune *)"
    ]
  }
}
`;
var CURSOR_RULES_TEMPLATE = `# Cursor LumenFlow Rules

This project uses LumenFlow workflow. See [LUMENFLOW.md](../../LUMENFLOW.md).

## Critical Rules

1. **Always run wu:done** - After gates pass, run \`pnpm wu:done --id WU-XXX\`
2. **Work in worktrees** - After \`wu:claim\`, work only in the worktree
3. **Never bypass hooks** - No \`--no-verify\`
4. **TDD** - Write tests first

## Forbidden Commands

- \`git reset --hard\`
- \`git push --force\`
- \`git stash\` (on main)
- \`--no-verify\`

## Quick Reference

\`\`\`bash
# Claim WU
pnpm wu:claim --id WU-XXX --lane <Lane>
cd worktrees/<lane>-wu-xxx

# Run gates
pnpm gates

# Complete (from main)
cd <project-root>
pnpm wu:done --id WU-XXX
\`\`\`
`;
var WINDSURF_RULES_TEMPLATE = `# Windsurf LumenFlow Rules

This project uses LumenFlow workflow. See [LUMENFLOW.md](../../LUMENFLOW.md).

## Critical Rules

1. **Always run wu:done** - After gates pass, run \`pnpm wu:done --id WU-XXX\`
2. **Work in worktrees** - After \`wu:claim\`, work only in the worktree
3. **Never bypass hooks** - No \`--no-verify\`
4. **TDD** - Write tests first

## Forbidden Commands

- \`git reset --hard\`
- \`git push --force\`
- \`git stash\` (on main)
- \`--no-verify\`

## Quick Reference

\`\`\`bash
# Claim WU
pnpm wu:claim --id WU-XXX --lane <Lane>
cd worktrees/<lane>-wu-xxx

# Run gates
pnpm gates

# Complete (from main)
cd <project-root>
pnpm wu:done --id WU-XXX
\`\`\`
`;
var CLINE_RULES_TEMPLATE = `# Cline LumenFlow Rules

This project uses LumenFlow workflow. See [LUMENFLOW.md](LUMENFLOW.md).

## Critical Rules

1. **Always run wu:done** - After gates pass, run \`pnpm wu:done --id WU-XXX\`
2. **Work in worktrees** - After \`wu:claim\`, work only in the worktree
3. **Never bypass hooks** - No \`--no-verify\`
4. **TDD** - Write tests first

## Forbidden Commands

- \`git reset --hard\`
- \`git push --force\`
- \`git stash\` (on main)
- \`--no-verify\`

## Quick Reference

\`\`\`bash
# Claim WU
pnpm wu:claim --id WU-XXX --lane <Lane>
cd worktrees/<lane>-wu-xxx

# Run gates
pnpm gates

# Complete (from main)
cd <project-root>
pnpm wu:done --id WU-XXX
\`\`\`
`;
var AIDER_CONF_TEMPLATE = `# Aider Configuration for LumenFlow Projects
# See LUMENFLOW.md for workflow documentation

model: gpt-4-turbo
auto-commits: false
dirty-commits: false

read:
  - LUMENFLOW.md
  - .lumenflow/constraints.md
`;
var MCP_JSON_TEMPLATE = `{
  "mcpServers": {
    "lumenflow": {
      "command": "npx",
      "args": ["@lumenflow/mcp"]
    }
  }
}
`;
var BACKLOG_TEMPLATE = `---
sections:
  ready:
    heading: '## \u{1F680} Ready (pull from here)'
    insertion: after_heading_blank_line
  in_progress:
    heading: '## \u{1F527} In progress'
    insertion: after_heading_blank_line
  blocked:
    heading: '## \u26D4 Blocked'
    insertion: after_heading_blank_line
  done:
    heading: '## \u2705 Done'
    insertion: after_heading_blank_line
---

# Backlog (single source of truth)

## \u{1F680} Ready (pull from here)

(No items ready)

## \u{1F527} In progress

(No items in progress)

## \u26D4 Blocked

(No items blocked)

## \u2705 Done

(No items completed yet)
`;
var STATUS_TEMPLATE = `# Status (active work)

## In Progress

(No items in progress)

## Blocked

(No items blocked)

## Completed

(No items completed yet)
`;
var WU_TEMPLATE_YAML = `# Work Unit Template (LumenFlow WU Schema)
#
# Copy this template when creating new WUs. Fill in all required fields and
# remove optional fields if not needed.
#
# If you used "lumenflow init --full", this template lives at:
# {{DOCS_TASKS_PATH}}/templates/wu-template.yaml

# Required: Unique work unit identifier (format: WU-NNN)
id: WU-XXX

# Required: Short, descriptive title (max 80 chars)
title: 'Your WU title here'

# Required: Lane (Parent: Sublane format)
lane: '<Parent: Sublane>'

# Required: Type of work
type: 'feature' # feature | bug | documentation | process | tooling | chore | refactor

# Required: Current status
status: 'ready' # ready | in_progress | blocked | done | cancelled

# Required: Priority
priority: P2 # P0 | P1 | P2 | P3

# Required: Creation date (YYYY-MM-DD)
created: {{DATE}}

# Required: Owner/assignee (email)
assigned_to: 'unassigned@example.com'

# Required: Description
description: |
  Context: ...
  Problem: ...
  Solution: ...

# Required: Acceptance criteria (testable, binary)
acceptance:
  - Criterion 1 (specific, measurable, testable)
  - Criterion 2 (binary pass/fail)
  - Documentation updated

# Required: References to plans/specs (required for type: feature)
# Tip: use pnpm wu:create --plan to generate a plan stub at lumenflow://plans/WU-XXX-plan.md
spec_refs:
  - lumenflow://plans/WU-XXX-plan.md

# Required: Code files changed or created (empty only for docs/process WUs)
# Docs-only WUs should use docs/ or *.md paths to avoid docs-only gate failures.
code_paths:
  - path/to/file.ts

# Required: Test paths (at least one of manual/unit/e2e/integration for non-doc WUs)
tests:
  manual:
    - Manual check: Verify behavior or docs output
  unit:
    - path/to/test.test.ts
  e2e: []
  integration: []

# Required: Exposure level
exposure: 'backend-only' # ui | api | backend-only | documentation

# Optional: User journey (recommended for ui/api)
# user_journey: |
#   User navigates to ...
#   User performs ...

# Optional: UI pairing WUs (for api exposure)
# ui_pairing_wus:
#   - WU-1234

# Optional: Navigation path (required when exposure=ui and no page file)
# navigation_path: '/settings'

# Required: Deliverable artifacts (stamps, docs, etc.)
artifacts:
  - .lumenflow/stamps/WU-XXX.done

# Optional: Dependencies (other WUs that must complete first)
dependencies: []

# Optional: Risks
risks:
  - Risk 1

# Optional: Notes (required by spec linter)
notes: 'Implementation notes, rollout context, or plan summary.'

# Optional: Requires human review
requires_review: false

# Optional: Claimed mode (worktree or branch-only)
# Automatically set by wu:claim, usually don't need to specify
# claimed_mode: worktree

# Optional: Assigned to (email of current claimant)
# Automatically set by wu:claim
# assigned_to: engineer@example.com

# Optional: Locked status (prevents concurrent edits)
# Automatically set by wu:claim and wu:done
# locked: false

# Optional: Completion date (ISO 8601 format)
# Automatically set by wu:done
# completed: 2025-10-23

# Optional: Completion notes (added by wu:done)
# completion_notes: |
#   Additional notes added during wu:done.
#   Any deviations from original plan.
#   Lessons learned.

# ============================================================================
# GOVERNANCE BLOCK (WU Schema v2.0)
# ============================================================================
# Optional: COS governance rules that apply to this WU
# Only include if this WU needs specific governance enforcement

# governance:
#   # Rules that apply to this WU (evaluated during cos:gates)
#   rules:
#     - rule_id: UPAIN-01
#       satisfied: false  # Initially false, set true when evidence provided
#       evidence:
#         - type: link
#           value: docs/product/voc/feature-user-pain.md
#           description: "Voice of Customer analysis showing user pain"
#       notes: |
#         VOC analysis shows 40% of support tickets request this feature.
#         Average time wasted: 15min/user/week.
#
#     - rule_id: CASH-03
#       satisfied: false
#       evidence:
#         - type: link
#           value: docs/finance/spend-reviews/2025-10-cloud-infra.md
#           description: "Spend review for \xA31200/month cloud infrastructure"
#         - type: approval
#           value: owner@example.com
#           description: "Owner approval for spend commitment"
#       notes: |
#         New cloud infrastructure commitment: \xA31200/month for 12 months.
#         ROI: Reduces latency by 50%, improves user retention.
#
#   # Gate checks (enforced by cos-gates.ts)
#   gates:
#     narrative: "pending"  # Status: pending, passed, skipped, failed
#     finance: "pending"
#
#   # Exemptions (only if rule doesn't apply)
#   exemptions:
#     - rule_id: FAIR-01
#       reason: "No user-facing pricing changes in this WU"
#       approved_by: product-owner@example.com
#       approved_at: 2025-10-23

# ============================================================================
# USAGE NOTES
# ============================================================================
#
# 1. Remove this entire governance block if no COS rules apply to your WU
# 2. Only include rules that require enforcement (not all rules apply to all WUs)
# 3. Evidence types: link:, metric:, screenshot:, approval:
# 4. Gates are checked during wu:done (before merge)
# 5. Exemptions require approval from rule owner
#
# For more details, see:
# - {{DOCS_OPERATIONS_PATH}}/_frameworks/cos/system-prompt-v1.3.md
# - {{DOCS_OPERATIONS_PATH}}/_frameworks/cos/evidence-format.md
`;
var FRAMEWORK_HINT_TEMPLATE = `# LumenFlow Framework Hint
# Generated by: lumenflow init --framework {{FRAMEWORK_NAME}}

framework: "{{FRAMEWORK_NAME}}"
slug: "{{FRAMEWORK_SLUG}}"
`;
var FRAMEWORK_OVERLAY_TEMPLATE = `# {{FRAMEWORK_NAME}} Framework Overlay

**Last updated:** {{DATE}}

This overlay captures framework-specific conventions, constraints, and references for {{FRAMEWORK_NAME}} projects.

## Scope

- Project structure conventions
- Framework-specific testing guidance
- Common pitfalls and mitigations

## References

- Add official docs links here
`;
var WU_LIFECYCLE_SKILL_TEMPLATE = `---
name: wu-lifecycle
description: Work Unit claim/block/done workflow automation.
version: 1.0.0
---

# WU Lifecycle Skill

## When to Use

Activate this skill when:

- Claiming a WU (\`pnpm wu:claim\`)
- Blocking/unblocking WUs due to dependencies
- Running \`wu:done\` completion workflow
- Understanding WU state machine transitions

## State Machine

\`\`\`
ready -> in_progress -> waiting/blocked -> done
\`\`\`

## Core Commands

\`\`\`bash
# Claim WU
pnpm wu:claim --id WU-XXX --lane <lane>
cd worktrees/<lane>-wu-xxx   # IMMEDIATELY

# Complete WU (from main)
cd ../..
pnpm wu:done --id WU-XXX

# Block/Unblock
pnpm wu:block --id WU-XXX --reason "..."
pnpm wu:unblock --id WU-XXX

# Create (full spec)
pnpm wu:create --id WU-999 --lane "Operations" --title "Add feature" \\
  --description "Context: ... Problem: ... Solution: ..." \\
  --acceptance "Feature works" --code-paths "src/a.ts" --validate
\`\`\`

## wu:done Workflow

1. Runs gates in worktree
2. Fast-forward merge to main
3. Creates \`.lumenflow/stamps/WU-XXX.done\`
4. Updates backlog.md + status.md
5. Removes worktree

## Worktree Discipline

After \`wu:claim\`:

- \`cd worktrees/<lane>-wu-xxx\` immediately
- Use relative paths (never absolute)
- Main is read-only
`;
var WORKTREE_DISCIPLINE_SKILL_TEMPLATE = `---
name: worktree-discipline
description: Prevents the "absolute path trap" in Write/Edit/Read tools.
version: 1.0.0
---

# Worktree Discipline: Absolute Path Trap Prevention

**Purpose**: Prevent AI agents from bypassing worktree isolation via absolute file paths.

## The Absolute Path Trap

**Problem**: AI agents using Write/Edit/Read tools can bypass worktree isolation by passing absolute paths. Even when your shell is in the worktree, absolute paths target the main checkout.

### Example

\`\`\`typescript
// Shell: cd worktrees/operations-wu-427

// WRONG - Absolute path bypasses worktree
Write({
  file_path: '/<user-home>/source/project/apps/web/src/validator.ts',
  content: '...',
});
// Result: Written to MAIN checkout, not worktree!

// RIGHT - Relative path respects worktree
Write({
  file_path: 'apps/web/src/validator.ts',
  content: '...',
});
// Result: Written to worktree correctly
\`\`\`

## Pre-Operation Checklist

**Before ANY Write/Edit/Read operation:**

1. **Verify working directory**:

   \`\`\`bash
   pwd
   # Must show: .../worktrees/<lane>-wu-xxx
   \`\`\`

2. **Check file path format**:

   | Pattern                           | Safe? | Example                     |
   | --------------------------------- | ----- | --------------------------- |
   | Starts with \`/<user-home>/\`       | NO    | \`/<user-home>/.../file.ts\` |
   | Contains full repo path           | NO    | \`/source/project/...\`    |
   | Starts with package name          | YES   | \`apps/web/src/...\`       |
   | Starts with \`./\` or \`../\`         | YES   | \`./src/lib/...\`          |
   | Just filename                     | YES   | \`README.md\`              |

3. **Use relative paths for ALL file operations**

## Golden Rules

1. **Always verify pwd** before file operations
2. **Never use absolute paths** in Write/Edit/Read tools
3. **When in doubt, use relative paths**
`;
var LUMENFLOW_GATES_SKILL_TEMPLATE = `---
name: lumenflow-gates
description: Quality gates troubleshooting (format, lint, typecheck, tests).
version: 1.0.0
---

# LumenFlow Gates Skill

## When to Use

Activate this skill when:

- \`pnpm gates\` fails with format, lint, or typecheck errors
- Need to determine if failure is from your changes vs pre-existing
- Debugging test failures or coverage issues
- Deciding whether to use \`--skip-gates\` (emergency only)

## Gate Sequence

\`\`\`
pnpm gates = format:check -> lint -> typecheck -> spec:linter -> tests
\`\`\`

## Fix Patterns

| Gate      | Auto-fix        | Manual                              |
| --------- | --------------- | ----------------------------------- |
| Format    | \`pnpm format\`   | -                                   |
| Lint      | \`pnpm lint:fix\` | Fix reported issues                 |
| Typecheck | -               | Fix type errors (first error first) |
| Tests     | -               | Debug, fix mocks, update snapshots  |

## Decision Tree

**Gate failed. Is it from YOUR changes?**

\`\`\`bash
git checkout main && pnpm gates  # Check main
# Pass on main -> Your change caused it -> Fix it
# Fail on main -> Pre-existing -> Consider --skip-gates
\`\`\`

**Can you fix it?**

- In your \`code_paths\`, <=10 lines -> Fix in place
- Different paths, >10 lines -> Create Bug WU

## Skip Gates (Emergency)

Only when pre-existing failures:

\`\`\`bash
pnpm wu:done --id WU-XXX --skip-gates --reason "Pre-existing" --fix-wu WU-YYY
\`\`\`

## Common Lint Fixes

\`\`\`
no-explicit-any -> Add proper types
no-unused-vars -> Remove or prefix with _
no-restricted-paths -> Check hex boundaries
exhaustive-deps -> Add missing dependencies
\`\`\`

## Validation Commands

\`\`\`bash
pnpm gates                # All gates
pnpm gates -- --docs-only # Docs WUs
pnpm format               # Fix formatting
pnpm lint:fix             # Fix lint issues
pnpm typecheck            # Check types
\`\`\`
`;
var REQUIRED_GITIGNORE_EXCLUSIONS = [
  { pattern: "node_modules", line: "node_modules/" },
  { pattern: ".lumenflow/telemetry", line: ".lumenflow/telemetry/" },
  { pattern: ".lumenflow/flow.log", line: ".lumenflow/flow.log" },
  { pattern: ".lumenflow/commands.log", line: ".lumenflow/commands.log" },
  { pattern: ".lumenflow/sessions/", line: ".lumenflow/sessions/" },
  { pattern: ".lumenflow/memory/", line: ".lumenflow/memory/" },
  // WU-2180: Ephemeral paths that were missing, causing wu:done clean-tree failures
  { pattern: ".lumenflow/checkpoints/", line: ".lumenflow/checkpoints/" },
  { pattern: ".lumenflow/locks/", line: ".lumenflow/locks/" },
  { pattern: ".lumenflow/artifacts/", line: ".lumenflow/artifacts/" },
  {
    pattern: ".lumenflow/state/spawn-registry.jsonl",
    line: ".lumenflow/state/spawn-registry.jsonl"
  },
  { pattern: ".logs/", line: ".logs/" },
  { pattern: DEFAULT_WORKTREES_PATTERN, line: DEFAULT_WORKTREES_DIR }
];
var GITIGNORE_TEMPLATE = `# Dependencies
node_modules/

# LumenFlow runtime state (local only, not shared)
.lumenflow/telemetry/
.lumenflow/flow.log
.lumenflow/commands.log
.lumenflow/sessions/
.lumenflow/memory/
.lumenflow/checkpoints/
.lumenflow/locks/
.lumenflow/artifacts/
.lumenflow/state/spawn-registry.jsonl

# WU-1852: Gates output logs (generated by wu:done/wu:prep)
.logs/

# Worktrees (isolated parallel work directories)
${DEFAULT_WORKTREES_DIR}

# Build output
dist/
*.tsbuildinfo

# Turbo
.turbo/

# Environment files
.env
.env.local
.env.*.local

# IDE
.idea/
.vscode/
*.swp
*.swo

# OS files
.DS_Store
Thumbs.db
`;
var PRETTIERIGNORE_TEMPLATE = `# Dependencies
node_modules/

# Build output
dist/
*.tsbuildinfo

# Coverage reports
coverage/

# Turbo
.turbo/

# LumenFlow state (local only)
${DEFAULT_STATE_DIR_IGNORE}

# Worktrees
${DEFAULT_WORKTREES_DIR}

# Lockfiles (auto-generated)
pnpm-lock.yaml
package-lock.json
yarn.lock

# Environment files
.env
.env.local
.env.*.local
`;
var SCRIPT_ARG_OVERRIDES = {
  "gates:docs": "gates --docs-only"
};
var SAFE_GIT_TEMPLATE = `#!/bin/sh
#
# safe-git - LumenFlow safety wrapper for git
#
# Blocks dangerous operations that can corrupt agent state.
# For all other commands, passes through to system git.
#

set -e

# Block 'worktree remove'
if [ "$1" = "worktree" ] && [ "$2" = "remove" ]; then
  echo "" >&2
  echo "=== LUMENFLOW SAFETY BLOCK ===" >&2
  echo "" >&2
  echo "BLOCKED: Manual 'git worktree remove' is unsafe in this environment." >&2
  echo "" >&2
  echo "REASON: Manual removal leaves orphan directories and corrupts agent state." >&2
  echo "" >&2
  echo "USE INSTEAD:" >&2
  echo "  pnpm wu:done --id <ID>    (To complete a task)" >&2
  echo "  pnpm wu:cleanup --id <ID> (To discard a task)" >&2
  echo "==============================" >&2
  exit 1
fi

# Pass through to real git
exec git "$@"
`;
var PRE_COMMIT_TEMPLATE = `#!/bin/sh
#
# LumenFlow Pre-Commit Hook
#
# Enforces worktree discipline by blocking direct commits to main/master.
# Does NOT assume pnpm test or UnsafeAny other commands exist.
#
# Rules:
#   1. BLOCK commits to main/master (use WU workflow instead)
#   2. ALLOW commits on lane branches (lane/*/wu-*)
#   3. ALLOW commits on tmp/* branches (CLI micro-worktrees)
#

# Skip on tmp/* branches (CLI micro-worktrees)
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
case "$BRANCH" in tmp/*) exit 0 ;; esac

# Check for force bypass
if [ "$LUMENFLOW_FORCE" = "1" ]; then
  exit 0
fi

# Block direct commits to main/master
case "$BRANCH" in
  main|master)
    echo "" >&2
    echo "=== DIRECT COMMIT TO \${BRANCH} BLOCKED ===" >&2
    echo "" >&2
    echo "LumenFlow protects main from direct commits." >&2
    echo "" >&2
    echo "USE INSTEAD:" >&2
    echo "  pnpm wu:claim --id WU-XXXX --lane \\"<Lane>\\"" >&2
    echo "  cd worktrees/<lane>-wu-xxxx" >&2
    echo "  # Make commits in the worktree" >&2
    echo "" >&2
    echo "EMERGENCY BYPASS (logged):" >&2
    echo "  LUMENFLOW_FORCE=1 git commit ..." >&2
    echo "==========================================" >&2
    exit 1
    ;;
esac

# Allow commits on other branches
exit 0
`;
var GATE_STUB_SCRIPTS = {
  "spec:linter": 'echo "[lumenflow] spec:linter stub -- install a WU spec linter or replace this script" && exit 0',
  lint: 'echo "[lumenflow] lint stub -- add ESLint or your preferred linter to enable this gate (e.g. eslint .)" && exit 0',
  typecheck: 'echo "[lumenflow] typecheck stub -- add TypeScript or your type checker to enable this gate (e.g. tsc --noEmit)" && exit 0',
  // WU-1747: format and format:check stubs that auto-detect prettier availability.
  // When prettier is installed (after pnpm install), they run prettier directly.
  // When prettier is not installed, they exit 0 with guidance -- matching other gate stubs.
  format: 'if command -v prettier >/dev/null 2>&1; then prettier --write .; else echo "[lumenflow] format stub -- install prettier to enable formatting (pnpm install)"; fi',
  "format:check": 'if command -v prettier >/dev/null 2>&1; then prettier --check .; else echo "[lumenflow] format:check stub -- install prettier to enable this gate (pnpm install)"; fi',
  // WU-1852: cos:gates no-op stub so fresh projects can complete wu:done without manual setup.
  // wu:done unconditionally runs `pnpm cos:gates`; without this stub the command fails.
  "cos:gates": 'echo "[lumenflow] cos:gates stub -- add COS governance rules or replace this script" && exit 0'
};

// src/lane-lifecycle-process.ts
import { existsSync, readdirSync, readFileSync, writeFileSync } from "fs";
import path from "path";
import YAML from "yaml";
var LANE_CONFIG_KEY = "lanes";
var LANE_DEFINITIONS_KEY = "definitions";
var LANE_LIFECYCLE_KEY = "lifecycle";
var LANE_LIFECYCLE_STATUS_KEY = "status";
var LANE_LIFECYCLE_UPDATED_AT_KEY = "updated_at";
var LANE_LIFECYCLE_MIGRATED_AT_KEY = "migrated_at";
var LANE_LIFECYCLE_MIGRATION_REASON_KEY = "migration_reason";
var EMPTY_OBJECT = "{}";
var NEWLINE = "\n";
var WU_CREATE_PREFIX = "[wu:create]";
var INITIATIVE_CREATE_PREFIX = "[initiative:create]";
var INIT_PREFIX = "[lumenflow init]";
var LANE_SETUP_COMMAND = "pnpm lane:setup";
var LANE_LOCK_COMMAND = "pnpm lane:lock";
var LANE_READY_SENTINEL = "lanes ready";
var SOFTWARE_DELIVERY_KEY = WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY;
var LANE_LIFECYCLE_STATUS = {
  UNCONFIGURED: "unconfigured",
  DRAFT: "draft",
  LOCKED: "locked"
};
function asRecord(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
}
function toIsoTimestamp() {
  return (/* @__PURE__ */ new Date()).toISOString();
}
function isLaneLifecycleStatus(value) {
  return value === LANE_LIFECYCLE_STATUS.UNCONFIGURED || value === LANE_LIFECYCLE_STATUS.DRAFT || value === LANE_LIFECYCLE_STATUS.LOCKED;
}
function getConfigPath(projectRoot) {
  return path.join(projectRoot, WORKSPACE_CONFIG_FILE_NAME);
}
function readWorkspaceDoc(projectRoot) {
  const configPath = getConfigPath(projectRoot);
  if (!existsSync(configPath)) {
    return {};
  }
  try {
    const content = readFileSync(configPath, FILE_SYSTEM.UTF8);
    const parsed = asRecord(YAML.parse(content));
    return parsed ?? {};
  } catch {
    return {};
  }
}
function readConfigDoc(projectRoot) {
  const workspace = readWorkspaceDoc(projectRoot);
  const softwareDelivery = asRecord(workspace[SOFTWARE_DELIVERY_KEY]);
  return softwareDelivery ?? {};
}
function writeConfigDoc(projectRoot, config) {
  const configPath = getConfigPath(projectRoot);
  const workspace = readWorkspaceDoc(projectRoot);
  workspace[SOFTWARE_DELIVERY_KEY] = config;
  const nextContent = YAML.stringify(workspace);
  writeFileSync(
    configPath,
    nextContent || EMPTY_OBJECT + NEWLINE,
    FILE_SYSTEM.UTF8
  );
}
function getLifecycleStatusFromDoc(config) {
  const status = config?.lanes?.lifecycle?.status;
  return isLaneLifecycleStatus(status) ? status : null;
}
function ensureLanesDoc(config) {
  if (!config[LANE_CONFIG_KEY] || typeof config[LANE_CONFIG_KEY] !== "object") {
    config[LANE_CONFIG_KEY] = {};
  }
  return config[LANE_CONFIG_KEY];
}
function setLifecycleStatusInDoc(config, status, migrationReason) {
  const lanes = ensureLanesDoc(config);
  const existingLifecycle = lanes[LANE_LIFECYCLE_KEY] && typeof lanes[LANE_LIFECYCLE_KEY] === "object" ? lanes[LANE_LIFECYCLE_KEY] : {};
  const now = toIsoTimestamp();
  const lifecycle = {
    ...existingLifecycle,
    [LANE_LIFECYCLE_STATUS_KEY]: status,
    [LANE_LIFECYCLE_UPDATED_AT_KEY]: now
  };
  if (migrationReason) {
    lifecycle[LANE_LIFECYCLE_MIGRATED_AT_KEY] = now;
    lifecycle[LANE_LIFECYCLE_MIGRATION_REASON_KEY] = migrationReason;
  }
  lanes[LANE_LIFECYCLE_KEY] = lifecycle;
}
function hasLaneDefinitions(config) {
  const definitions = config?.lanes?.definitions;
  return Array.isArray(definitions) && definitions.length > 0;
}
function deepCloneDefaultLaneDefinitions() {
  return JSON.parse(JSON.stringify(DEFAULT_LANE_DEFINITIONS));
}
function classifyLaneLifecycleForProject(projectRoot) {
  const config = readConfigDoc(projectRoot);
  const configuredStatus = getLifecycleStatusFromDoc(config);
  if (configuredStatus) {
    return {
      status: configuredStatus,
      source: "config",
      migrationReason: null,
      persisted: false
    };
  }
  const definitionsPresent = hasLaneDefinitions(config);
  if (!definitionsPresent) {
    return {
      status: LANE_LIFECYCLE_STATUS.UNCONFIGURED,
      source: "migration",
      migrationReason: "no lane definitions",
      persisted: false
    };
  }
  return {
    status: LANE_LIFECYCLE_STATUS.LOCKED,
    source: "migration",
    migrationReason: "lane definitions detected",
    persisted: false
  };
}
function ensureLaneLifecycleForProject(projectRoot, options = {}) {
  const persist = options.persist ?? true;
  const classification = classifyLaneLifecycleForProject(projectRoot);
  if (!persist || classification.source === "config") {
    return classification;
  }
  const config = readConfigDoc(projectRoot);
  setLifecycleStatusInDoc(
    config,
    classification.status,
    classification.migrationReason ?? void 0
  );
  writeConfigDoc(projectRoot, config);
  return {
    ...classification,
    persisted: true
  };
}
function setLaneLifecycleStatus(projectRoot, status) {
  const config = readConfigDoc(projectRoot);
  setLifecycleStatusInDoc(config, status);
  writeConfigDoc(projectRoot, config);
}
function recommendLaneLifecycleNextStep(status) {
  if (status === LANE_LIFECYCLE_STATUS.UNCONFIGURED) {
    return LANE_SETUP_COMMAND;
  }
  if (status === LANE_LIFECYCLE_STATUS.DRAFT) {
    return LANE_LOCK_COMMAND;
  }
  return LANE_READY_SENTINEL;
}
function buildWuCreateLaneLifecycleMessage(status) {
  return [
    `${WU_CREATE_PREFIX} Lane lifecycle status: ${status}`,
    "Cannot create delivery WU until lanes are locked.",
    `Next step: ${recommendLaneLifecycleNextStep(status)}`
  ].join(NEWLINE);
}
function buildInitiativeCreateLaneLifecycleMessage(status) {
  return [
    `${INITIATIVE_CREATE_PREFIX} Lane lifecycle: ${status}`,
    "Initiative creation is allowed before lane setup.",
    `When ready for delivery WUs, run: ${recommendLaneLifecycleNextStep(status)}`
  ].join(NEWLINE);
}
function buildInitLaneLifecycleMessage(status) {
  return [
    `${INIT_PREFIX} Lane lifecycle: ${status}`,
    "Lanes are configured after project context is defined (plan/architecture).",
    `Next step: ${recommendLaneLifecycleNextStep(status)}`
  ].join(NEWLINE);
}
function detectWorkspaceLanes(projectRoot) {
  const lanes = [];
  const pnpmWorkspacePath = path.join(projectRoot, "pnpm-workspace.yaml");
  let workspacePatterns = [];
  if (existsSync(pnpmWorkspacePath)) {
    try {
      const content = readFileSync(pnpmWorkspacePath, FILE_SYSTEM.ENCODING);
      const parsed = YAML.parse(content);
      workspacePatterns = parsed?.packages ?? [];
    } catch {
    }
  }
  if (workspacePatterns.length === 0) {
    const pkgJsonPath = path.join(projectRoot, "package.json");
    if (existsSync(pkgJsonPath)) {
      try {
        const content = readFileSync(pkgJsonPath, FILE_SYSTEM.ENCODING);
        const parsed = JSON.parse(content);
        if (Array.isArray(parsed?.workspaces)) {
          workspacePatterns = parsed.workspaces;
        } else if (parsed?.workspaces?.packages) {
          workspacePatterns = parsed.workspaces.packages;
        }
      } catch {
      }
    }
  }
  if (workspacePatterns.length === 0) {
    return deepCloneDefaultLaneDefinitions();
  }
  for (const pattern of workspacePatterns) {
    const baseDir = pattern.replace(/\/?\*$/, "");
    const fullPath = path.join(projectRoot, baseDir);
    if (!existsSync(fullPath)) continue;
    try {
      const entries = readdirSync(fullPath, { withFileTypes: true });
      for (const entry of entries) {
        if (!entry.isDirectory()) continue;
        const pkgPath = path.join(fullPath, entry.name, "package.json");
        if (!existsSync(pkgPath)) continue;
        const isApp = baseDir.includes("app");
        const category = isApp ? "Experience" : "Framework";
        const displayName = entry.name.replace(/^@[^/]+\//, "");
        lanes.push({
          name: `${category}: ${displayName.charAt(0).toUpperCase() + displayName.slice(1)}`,
          wip_limit: 1,
          code_paths: [`${baseDir}/${entry.name}/**`]
        });
      }
    } catch {
    }
  }
  const docsDir = getConfig({ projectRoot }).directories.docs.replace(/\/+$/, "");
  if (existsSync(path.join(projectRoot, docsDir))) {
    lanes.push({
      name: "Content: Documentation",
      wip_limit: 1,
      code_paths: [`${docsDir}/**`, "*.md"]
    });
  }
  if (existsSync(path.join(projectRoot, ".github"))) {
    lanes.push({
      name: "Operations: CI/CD",
      wip_limit: 1,
      code_paths: [".github/workflows/**", ".github/actions/**"]
    });
  }
  return lanes.length > 0 ? lanes : deepCloneDefaultLaneDefinitions();
}
function ensureDraftLaneArtifacts(projectRoot) {
  const config = readConfigDoc(projectRoot);
  const lanes = ensureLanesDoc(config);
  let createdDefinitions = false;
  if (!hasLaneDefinitions(config)) {
    lanes[LANE_DEFINITIONS_KEY] = detectWorkspaceLanes(projectRoot);
    createdDefinitions = true;
  }
  setLifecycleStatusInDoc(config, LANE_LIFECYCLE_STATUS.DRAFT);
  writeConfigDoc(projectRoot, config);
  return {
    createdDefinitions,
    status: LANE_LIFECYCLE_STATUS.DRAFT
  };
}
function validateLaneArtifacts(projectRoot) {
  const configPath = getConfigPath(projectRoot);
  const warnings = [];
  const invalidLanes = [];
  if (!existsSync(configPath)) {
    warnings.push(`Missing ${WORKSPACE_CONFIG_FILE_NAME}. Run: ${LANE_SETUP_COMMAND}`);
    return {
      warnings,
      invalidLanes,
      missingDefinitions: true
    };
  }
  try {
    getConfig({
      projectRoot,
      reload: true,
      strictWorkspace: true
    });
  } catch (error) {
    warnings.push(
      `Invalid ${WORKSPACE_CONFIG_FILE_NAME}: ${error instanceof Error ? error.message : String(error)}`
    );
    return {
      warnings,
      invalidLanes,
      missingDefinitions: true
    };
  }
  const config = readConfigDoc(projectRoot);
  const missingDefinitions = !hasLaneDefinitions(config);
  if (missingDefinitions) {
    warnings.push(
      `No lane definitions found in ${WORKSPACE_CONFIG_FILE_NAME} (${SOFTWARE_DELIVERY_KEY}.lanes). Run: ${LANE_SETUP_COMMAND}`
    );
  }
  return {
    warnings,
    invalidLanes,
    missingDefinitions
  };
}

export {
  DEFAULT_LANE_DEFINITIONS,
  AGENTS_MD_TEMPLATE,
  CLAUDE_MD_TEMPLATE,
  CLAUDE_SETTINGS_TEMPLATE,
  CURSOR_RULES_TEMPLATE,
  WINDSURF_RULES_TEMPLATE,
  CLINE_RULES_TEMPLATE,
  AIDER_CONF_TEMPLATE,
  MCP_JSON_TEMPLATE,
  BACKLOG_TEMPLATE,
  STATUS_TEMPLATE,
  WU_TEMPLATE_YAML,
  FRAMEWORK_HINT_TEMPLATE,
  FRAMEWORK_OVERLAY_TEMPLATE,
  WU_LIFECYCLE_SKILL_TEMPLATE,
  WORKTREE_DISCIPLINE_SKILL_TEMPLATE,
  LUMENFLOW_GATES_SKILL_TEMPLATE,
  REQUIRED_GITIGNORE_EXCLUSIONS,
  GITIGNORE_TEMPLATE,
  PRETTIERIGNORE_TEMPLATE,
  SCRIPT_ARG_OVERRIDES,
  SAFE_GIT_TEMPLATE,
  PRE_COMMIT_TEMPLATE,
  GATE_STUB_SCRIPTS,
  LANE_LIFECYCLE_STATUS,
  classifyLaneLifecycleForProject,
  ensureLaneLifecycleForProject,
  setLaneLifecycleStatus,
  recommendLaneLifecycleNextStep,
  buildWuCreateLaneLifecycleMessage,
  buildInitiativeCreateLaneLifecycleMessage,
  buildInitLaneLifecycleMessage,
  ensureDraftLaneArtifacts,
  validateLaneArtifacts
};
