## Apply: {{ instructions.changeName }}
Schema: {{ instructions.schemaName }}

{% if instructions.state == "blocked" and instructions.missingArtifacts %}
### ⚠️ Blocked

Missing artifacts: {{ instructions.missingArtifacts|join(", ") }}
Use the ito-continue-change skill to create these first.

{% endif %}
{% if context_files and context_files|length > 0 %}
### Context Files
{% for entry in context_files %}
- {{ entry.id }}: {{ entry.path }}
{% endfor %}

{% endif %}
{% if worktree.enabled and worktree.apply_enabled %}
### Worktree Setup

Strategy: `{{ worktree.strategy }}`
Default branch: `{{ worktree.default_branch }}`
{% if worktree.layout_base_dir %}
Base directory: `{{ worktree.layout_base_dir }}`
{% endif %}
Worktree directory name: `{{ worktree.layout_dir_name }}`

{% if worktree.strategy == "checkout_subdir" %}
#### Workspace Layout (checkout_subdir)

```
<project>/                          # normal git checkout ({{ worktree.default_branch }} branch)
├── .git/
├── src/
└── .{{ worktree.layout_dir_name }}/  # gitignored subdirectory
    └── {{ instructions.changeName }}/
```

**Setup steps:**

```bash
# Ensure .{{ worktree.layout_dir_name }}/ is gitignored
grep -qxF '.{{ worktree.layout_dir_name }}/' .gitignore 2>/dev/null || echo '.{{ worktree.layout_dir_name }}/' >> .gitignore

# Create or reuse the change worktree
CHANGE_DIR=".{{ worktree.layout_dir_name }}/{{ instructions.changeName }}"
if [ ! -d "$CHANGE_DIR" ]; then
  git worktree add "$CHANGE_DIR" -b {{ instructions.changeName }}
fi

echo "Working directory: $CHANGE_DIR"
```
{% elif worktree.strategy == "checkout_siblings" %}
#### Workspace Layout (checkout_siblings)

```
~/Code/
├── <project>/                      # normal git checkout ({{ worktree.default_branch }} branch)
│   ├── .git/
│   └── src/
└── <project>-{{ worktree.layout_dir_name }}/  # dedicated sibling folder
    └── {{ instructions.changeName }}/
```

**Setup steps:**

```bash
# Determine project name and sibling directory
PROJECT_NAME=$(basename "$(pwd)")
WORKTREE_BASE="../${PROJECT_NAME}-{{ worktree.layout_dir_name }}"
CHANGE_DIR="${WORKTREE_BASE}/{{ instructions.changeName }}"

# Create the worktree base directory if needed
mkdir -p "$WORKTREE_BASE"

# Create or reuse the change worktree
if [ ! -d "$CHANGE_DIR" ]; then
  git worktree add "$CHANGE_DIR" -b {{ instructions.changeName }}
fi

echo "Working directory: $CHANGE_DIR"
```
{% elif worktree.strategy == "bare_control_siblings" %}
#### Workspace Layout (bare_control_siblings)

```
~/Code/<project>/                   # bare/control repo
├── .bare/                          # git object store
├── .git                            # gitdir pointer
├── {{ worktree.default_branch }}/  # main branch worktree
└── {{ worktree.layout_dir_name }}/  # Ito-managed change worktrees
    └── {{ instructions.changeName }}/
```

**Setup steps:**

```bash
# Ensure main worktree exists
if [ ! -d "{{ worktree.default_branch }}" ]; then
  git worktree add {{ worktree.default_branch }}
fi

# Create or reuse the change worktree
CHANGE_DIR="{{ worktree.layout_dir_name }}/{{ instructions.changeName }}"
mkdir -p "{{ worktree.layout_dir_name }}"
if [ ! -d "$CHANGE_DIR" ]; then
  git worktree add "$CHANGE_DIR" -b {{ instructions.changeName }}
fi

echo "Working directory: $CHANGE_DIR"
```
{% else %}
#### ⚠️ Unknown Strategy

The configured strategy `{{ worktree.strategy }}` is not recognized. Please set `worktrees.strategy` to one of: `checkout_subdir`, `checkout_siblings`, or `bare_control_siblings`.

```bash
ito config set worktrees.strategy checkout_subdir
```
{% endif %}
{% if worktree.copy_from_main and worktree.copy_from_main|length > 0 %}

#### Copy Local Files from Main

Copy local/uncommitted setup files from the main worktree into the change worktree (missing files are skipped):

```bash
{% for pattern in worktree.copy_from_main %}
[ -f "{{ pattern }}" ] && cp "{{ pattern }}" "$CHANGE_DIR/" 2>/dev/null || true
{% endfor %}
```
{% endif %}
{% if worktree.setup_commands and worktree.setup_commands|length > 0 %}

#### Setup Commands

Run the following commands in the change worktree before starting implementation:

```bash
cd "$CHANGE_DIR"
{% for cmd in worktree.setup_commands %}
{{ cmd }}
{% endfor %}
```
{% endif %}

{% elif worktree.enabled and not worktree.apply_enabled %}
### Worktree Mode

Worktrees are enabled but apply-time worktree setup is disabled. Work in your current directory.

{% endif %}
{% if instructions.tracksFile and instructions.tracksPath %}
### Task Tracking
- file: {{ instructions.tracksFile }}
{% if instructions.tracksFormat %}
- format: {{ instructions.tracksFormat }}
{% endif %}
- path: {{ instructions.tracksPath }}
{% if tracking_errors %}
- errors: {{ tracking_errors }}
{% endif %}
{% if tracking_warnings %}
- warnings: {{ tracking_warnings }}
{% endif %}

{% endif %}
### Testing Policy
- TDD workflow: {{ testing_policy.tdd_workflow }} (RED -> GREEN -> REFACTOR)
- TDD loop: write a failing test (RED), implement the minimum to pass (GREEN), then refactor (REFACTOR)
- Coverage target: {{ testing_policy.coverage_target_percent }}% (guidance; override per project)
- Override keys: defaults.testing.tdd.workflow, defaults.testing.coverage.target_percent
- Override files (low -> high): ito.json, .ito.json, .ito/config.json, $PROJECT_DIR/config.json

{% if instructions.progress.total > 0 or (instructions.tasks and instructions.tasks|length > 0) %}
### Progress
{% if instructions.state == "all_done" %}
{{ instructions.progress.complete }}/{{ instructions.progress.total }} complete ✓
{% else %}
{{ instructions.progress.complete }}/{{ instructions.progress.total }} complete
{% endif %}

{% endif %}
{% if instructions.tasks and instructions.tasks|length > 0 %}
### Tasks
{% for task in instructions.tasks %}
- [{% if task.done %}x{% else %} {% endif %}] {{ task.description }}
{% endfor %}

{% endif %}
### Audit Trail

Ito automatically records audit events for CLI operations (task changes, module/change creation, archival, config updates). No manual action is needed.

- View the audit log: `ito audit log --change {{ instructions.changeName }}`
- Check for drift: `ito audit reconcile`
- Fix drift: `ito audit reconcile --fix`
- Validate log integrity: `ito audit validate`

**Audit requirements:**
- MUST use `ito tasks start/complete/shelve/unshelve/add` CLI commands for all task state changes (this emits audit events automatically)
- If a direct edit to `tasks.md` is unavoidable, MUST run `ito audit reconcile --change {{ instructions.changeName }} --fix` immediately after
- Run `ito audit reconcile --change {{ instructions.changeName }}` before `ito archive` to ensure audit consistency

### Instruction
{{ instructions.instruction }}
{% if worktree.enabled and worktree.apply_enabled %}

### Integration Guidance
{% if worktree.integration_mode == "commit_pr" %}

**Mode: Commit & PR** (`commit_pr`)

After implementation is complete:

1. Stage and commit your changes in the change worktree:
   ```bash
   cd "$CHANGE_DIR"
   git add -A
   git commit -m "feat: {{ instructions.changeName }}"
   ```
2. Push the branch and create a pull request:
   ```bash
   git push -u origin {{ instructions.changeName }}
   # Create PR using gh, or your preferred method
   gh pr create --title "{{ instructions.changeName }}" --body "Implements change {{ instructions.changeName }}"
   ```
3. After PR is merged, proceed to cleanup (below).
{% elif worktree.integration_mode == "merge_parent" %}

**Mode: Merge into Parent** (`merge_parent`)

After implementation is complete:

1. Stage and commit your changes in the change worktree:
   ```bash
   cd "$CHANGE_DIR"
   git add -A
   git commit -m "feat: {{ instructions.changeName }}"
   ```
2. Switch to the main branch and merge:
   ```bash
{% if worktree.strategy == "bare_control_siblings" %}
   cd ../{{ worktree.default_branch }}
{% else %}
   cd "$(git worktree list --porcelain | grep -A1 'worktree.*{{ worktree.default_branch }}' | tail -1 | sed 's/worktree //')" 2>/dev/null || cd ..
{% endif %}
   git merge {{ instructions.changeName }}
   ```
3. After merge is complete, proceed to cleanup (below).
{% else %}

**Mode: {{ worktree.integration_mode }}** (unrecognized)

Please set `worktrees.apply.integration_mode` to `commit_pr` or `merge_parent`:
```bash
ito config set worktrees.apply.integration_mode commit_pr
```
{% endif %}

### Post-Merge Cleanup

After the change branch has been merged (via PR or direct merge):

```bash
# 1. Remove the change worktree
git worktree remove {{ instructions.changeName }} 2>/dev/null || git worktree remove "$CHANGE_DIR" 2>/dev/null || true

# 2. Delete the local branch
git branch -d {{ instructions.changeName }} 2>/dev/null || true

# 3. Prune stale worktree metadata
git worktree prune
```

**Safety notes:**
- `git worktree remove` will refuse to remove a worktree with uncommitted changes. Force with `--force` only if you are sure.
- `git branch -d` will refuse to delete an unmerged branch. Force with `-D` only if you are sure.
- Run `git worktree list` to verify cleanup was successful.
{% endif %}

{% if user_guidance %}
### User Guidance

{{ user_guidance }}

{% endif %}
