**Mode Configuration**: This prompt runs in non-interactive environments (e.g., CI/CD, automation scripts).

**Non-Interactive Mode Behavior**:
- DO NOT use `AskUserQuestion` or any interactive tools
- When user input is required, use reasonable defaults (e.g., select the most recently modified change)
- Skip optional confirmation steps, document assumptions made

**Interactive Mode Behavior**:
- Follow the normal interactive flow with user prompts

---

Archive a completed change in the experimental workflow.

**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.

**Steps**

1. **If no change name provided, use reasonable defaults**

   If a name is provided, use it. Otherwise:
   - **In non-interactive mode**: Select the most recently modified change
   - **In interactive mode**: Run `openspec list --json` to get available changes and let the user select

   When showing options to the user, show only active changes (not already archived).
   Include the schema used for each change if available.

   Always announce: "Archiving change: <name>" and how to override.

2. **Check artifact completion status**

   Run `openspec status --change "<name>" --json` to check artifact completion.

   Parse the JSON to understand:
   - `schemaName`: The workflow being used
   - `artifacts`: List of artifacts with their status (`done` or other)

   **If any artifacts are not `done`:**
   - Display warning listing incomplete artifacts
   - **In interactive mode**: Prompt user for confirmation to continue
   - **In non-interactive mode**: Document the assumption and proceed
   - Proceed if the user confirms or in non-interactive mode

3. **Check task completion status**

   Read the tasks file (typically `tasks.md`) to check for incomplete tasks.

   Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).

   **If incomplete tasks found:**
   - Display warning showing count of incomplete tasks
   - **In interactive mode**: Prompt user for confirmation to continue
   - **In non-interactive mode**: Document the assumption and proceed
   - Proceed if the user confirms or in non-interactive mode

   **If no tasks file exists:** Proceed without task-related warning.

4. **Assess delta spec sync state (Mandatory sync)**

   Check for delta specs at `openspec/changes/<name>/specs/`.

   {%-*
   EMBEDDED SYNC LOGIC FROM openspec-v1-sync.en-US.scriban
   The following steps (Find delta specs, For each delta spec, apply changes to main specs)
   are embedded from the sync template to ensure self-contained archive operation.
   *-%}

   **If no delta specs exist:**
   - Proceed directly to the archive step

   **If delta specs exist:**
   - **MUST execute spec sync operation** (Mandatory sync)

   **Step 1: Find delta specs**

   Look for delta spec files in `openspec/changes/<name>/specs/*/spec.md`.

   Each delta spec file contains sections like:
   - `## ADDED Requirements` - New requirements to add
   - `## MODIFIED Requirements` - Changes to existing requirements
   - `## REMOVED Requirements` - Requirements to remove
   - `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)

   **Step 2: For each delta spec, apply changes to main specs**

   For each capability with a delta spec at `openspec/changes/<name>/specs/<capability>/spec.md`:

   a. **Read the delta spec** to understand the intended changes

   b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)

   c. **Apply changes intelligently**:

      **ADDED Requirements:**
      - If the requirement doesn't exist in the main spec → add it
      - If the requirement already exists → update it to match (treat as implicit MODIFIED)

      **MODIFIED Requirements:**
      - Find the requirement in the main spec
      - Apply the changes - this can be:
        - Adding new scenarios (don't need to copy existing ones)
        - Modifying existing scenarios
        - Changing the requirement description
      - Preserve scenarios/content not mentioned in the delta

      **REMOVED Requirements:**
      - Remove the entire requirement block from the main spec

      **RENAMED Requirements:**
      - Find the FROM requirement, rename to TO

   d. **Create new main spec** if the capability doesn't exist yet:
      - Create `openspec/specs/<capability>/spec.md`
      - Add a Purpose section (can be brief, mark as TBD)
      - Add a Requirements section with ADDED requirements

   **Key Principle: Intelligent Merging**

   Unlike programmatic merging, you can apply **partial updates**:
   - To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
   - The delta represents *intent*, not a wholesale replacement
   - Use your judgment to merge changes sensibly

   **Sync failure handling:**
   - If sync fails (merge conflict, validation error), **block the archive operation** and display an error
   - Display detailed error information about the sync failure
   - Provide resolution guidance (e.g., "Resolve conflicts in delta spec, then retry archive")
   - Preserve the change directory in its original location (don't partially archive)

   **Show a combined summary before execution** including:
   - What changes would be applied (requirements added/modified/removed/renamed)
   - Which capabilities would be updated

5. **Perform the archive (Unconditional)**

   **Archiving is unconditional**: The archive operation MUST proceed regardless of artifact or task completion status.

   Create the archive directory if it doesn't exist:
   ```bash
   mkdir -p openspec/changes/archive
   ```

   Generate the target name using the current date: `YYYY-MM-DD-<change-name>`

   **Check if the target already exists:**
   - If yes: Fail with error, suggest renaming the existing archive or using a different date
   - If no: Move the change directory to the archive

   ```bash
   mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
   git add openspec/changes/<name>
   git add openspec/changes/archive/YYYY-MM-DD-<name>
   ```

   {{#if isMonoSpecs}}
   **This is a MonoSpecs repository.**

   **Repository Type**: MonoSpecs (specs-driven development)
   **Repository Path**: `{{ monospecsRepoPath }}`
   {{/if}}

   {{#if commitWhenArchive}}
   **Auto-commit is enabled for this repository.**

   **IMPORTANT**: You MUST perform a Git commit after archiving the change.

   **CRITICAL**: Commit ONLY in the MonoSpecs repository at: `{{ monospecsRepoPath }}`

   **WARNING**: Do NOT commit in any code repositories under the `repos/` directory.
   The commit must ONLY affect the MonoSpecs repository containing the `openspec/` directory.

   **Precise Staging Strategy**:
   - The `mv` command moves the directory, then `git add` stages the deletion and addition
   - If delta specs exist and were synced in step 4, additionally stage the synced spec file changes with `git add openspec/specs/`
   - **MonoSpecs multi-user environment warning**: Use precise staging to avoid committing other users' changes

   ```bash
   # Verify you're in the MonoSpecs repository root
   pwd  # Should show: {{ monospecsRepoPath }}

   # If delta specs existed and were synced in step 4, stage the synced spec file changes
   # Check if openspec/specs/ was modified during the sync operation
   git status openspec/specs/
   # If the above shows modifications, execute: git add openspec/specs/

   # Check staged content (verify archive-related changes are staged)
   git diff --cached --name-only

   # If output contains openspec/changes/archive/YYYY-MM-DD-<name>/, execute the commit
   # Commit with enhanced message format (including proposal context and Co-Authored-By)
   ```

   **Generate Enhanced Commit Message**:

   a. **Read the proposal content**:
      - Read the `openspec/changes/archive/YYYY-MM-DD-<name>/proposal.md` file in the archive directory
      - Note: Since the directory has been moved via `mv` to archive, use the path under archive

   b. **Extract key information**:
      - **Summary**: Extract 1-2 sentences from the "## Why" section as the proposal summary
      - **Changes**: Extract the change list from the "## What Changes" section (convert to bullet points)
      - **Capabilities**: Extract the modified capability names from the "## Capabilities > Modified Capabilities" section

   c. **Format the commit message**:
      Use the following template to generate a multi-line commit message:

      ```bash
      git commit -m "$(cat <<'EOF'
      Archive OpenSpec change: <change-name>

      <Summary from Why section (1-2 sentences)>

      Changes:
      - <Change 1 from What Changes>
      - <Change 2 from What Changes>
      - <Change 3...>

      Capabilities: <modified-specs>

      Co-Authored-By: Hagicode <noreply@hagicode.com>
      EOF
      )"
      ```

   d. **Fallback handling**:
      - If the `proposal.md` file does not exist or cannot be read, use a simplified format:
      ```bash
      git commit -m "$(cat <<'EOF'
      Archive OpenSpec change: <change-name>

      Co-Authored-By: Hagicode <noreply@hagicode.com>
      EOF
      )"
      ```
      - If the proposal.md exists but cannot be parsed (format anomaly, missing expected sections, etc.):
        - If only the Why section is parseable, generate the enhanced format with only Summary
        - If only the What Changes section is parseable, generate the enhanced format with only the Changes list
        - If neither section can be parsed, use the above fallback format
      - **Ensure the Co-Authored-By declaration is always included in all formats**

   **Commit Message Format Requirements**:
   - Summary paragraph must not exceed 2 sentences
   - Changes list should contain at most 7 change items (if more, use a general description or omit minor items)
   - Capabilities line lists all modified capabilities, separated by commas
   - Co-Authored-By line is at the end of the commit message, with a blank line before it

   **After committing:**
   - Verify the commit was created: `git log -1 --oneline`
   - The archive is complete and committed
   {{/if}}

6. **Display summary**

   Show the archive completion summary including:
   - Change name
   - Schema that was used
   - Archive location
   - Spec sync status (synced / sync skipped / no delta specs)
   - Note about any warnings (incomplete artifacts/tasks)

**Output On Success**

```
## Archive Complete

**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
{{#if isMonoSpecs}}
**Repository Type:** MonoSpecs
{{/if}}
{{#if commitWhenArchive}}
**Git:** ✓ Committed (Archive OpenSpec change: <change-name>)
{{/if}}

All artifacts complete. All tasks complete.
```

**Output On Success (No Delta Specs)**

```
## Archive Complete

**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
{{#if isMonoSpecs}}
**Repository Type:** MonoSpecs
{{/if}}
{{#if commitWhenArchive}}
**Git:** ✓ Committed (Archive OpenSpec change: <change-name>)
{{/if}}

All artifacts complete. All tasks complete.
```

**Output On Success With Warnings**

```
## Archive Complete (with warnings)

**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs

**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks

Review the archive if this was not intentional.
```

**Output On Error (Archive Exists)**

```
## Archive Failed

**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/

Target archive directory already exists.

**Options:**
1. Rename existing archive
2. Delete existing archive if it's a duplicate
3. Wait until a different date to archive
```

**Guardrails**
- Always prompt for change selection if not provided
- Use the artifact graph (openspec status --json) for completion checking
- **Mandatory sync**: If delta specs exist, must execute spec sync operation first
- **Unconditional archiving**: Archive must proceed regardless of artifact or task completion status
- **Block on sync failure**: If spec sync fails, block archive and display error message
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- Always run sync assessment and show combined summary before execution
{{#if commitWhenArchive}}
- **Git commit scope limitation**: Commit ONLY in the MonoSpecs repository at `{{ monospecsRepoPath }}`
- **Do NOT commit in code repositories**: Never commit in any repositories under the `repos/` directory
- **Always commit after archive**: Always perform Git commit in MonoSpecs repository after archiving
- **Use mv for untracked files**: Use `mv` instead of `git mv` to move change directories, as `git mv` fails on untracked files
- **Precise staging strategy**:
  - After `mv`, use `git add` to stage the deletion at the original location
  - Use `git add` to stage the addition at the new location
  - Only execute `git add openspec/specs/` when delta specs exist
  - Check staged content (`git diff --cached --name-only`) before committing
- **MonoSpecs multi-user environment warning**: MonoSpecs repository may have simultaneous edits; use precise staging to avoid committing unrelated changes
- **Verify working directory**: Always verify current directory before running git commands
{{/if}}
