This commit is contained in:
jarianc 2026-05-09 11:55:14 -05:00
parent 9d2dfbcf5e
commit cc7aa2ba86
26 changed files with 2365 additions and 0 deletions

40
.dockerignore Normal file
View File

@ -0,0 +1,40 @@
# Version control
.git/
.gitignore
# Environment files
.env
.env.local
*.env
# Python
__pycache__/
*.py[cod]
*.egg-info/
.eggs/
dist/
build/
.venv/
# IDE
.vscode/
.idea/
*.swp
*~
# OS
.DS_Store
Thumbs.db
# Test coverage
coverage.xml
htmlcov/
.pytest_cache/
# Data (runtime only)
data/
logs/
# Documentation (not needed in container)
*.md
prompt.md

2
.env.example Normal file
View File

@ -0,0 +1,2 @@
PYTHON_VERSION=3.12-slim
GAME_PORT=8080

1
.hadolint.yaml Normal file
View File

@ -0,0 +1 @@
failure-threshold: warning

View File

@ -0,0 +1,149 @@
---
description: Implement tasks from an OpenSpec change (Experimental)
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx-apply 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. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx-continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx-archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@ -0,0 +1,154 @@
---
description: Archive a completed change in the experimental workflow
---
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, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
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
- Prompt user for confirmation to continue
- Proceed if user confirms
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
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show 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
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
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:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
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 the existing archive
2. Delete the 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 artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@ -0,0 +1,170 @@
---
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx-explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@ -0,0 +1,103 @@
---
description: Propose a new change - create it and generate all artifacts in one step
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx-apply
---
**Input**: The argument after `/opsx-propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx-apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. 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, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
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
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
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
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- 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 (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
▼
┌───────────┐
│ Session │
└─────┬─────┘
│
▼
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx-explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx-apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx-apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

Binary file not shown.

Binary file not shown.

Binary file not shown.

95
data.py Normal file
View File

@ -0,0 +1,95 @@
"""Data module for loading and managing Bible verse data."""
import json
import os
from typing import Any
def load_verses() -> list[dict[str, Any]]:
"""Load verses from the verses.json file.
Returns:
List of verse dictionaries with id, text, category, difficulty, reference.
"""
verses_path = os.path.join(os.path.dirname(__file__), "verses.json")
with open(verses_path) as f:
data = json.load(f)
return data["verses"]
def get_verses_by_category(verses: list[dict[str, Any]], category: str) -> list[dict[str, Any]]:
"""Filter verses by category (case-insensitive).
Args:
verses: List of all verses.
category: Category name to filter by.
Returns:
List of verses matching the category.
"""
return [v for v in verses if v["category"].lower() == category.lower()]
def get_verses_by_max_difficulty(
verses: list[dict[str, Any]], max_difficulty: int
) -> list[dict[str, Any]]:
"""Filter verses by maximum difficulty level.
Args:
verses: List of all verses.
max_difficulty: Maximum difficulty level to include.
Returns:
List of verses with difficulty <= max_difficulty.
"""
return [v for v in verses if v["difficulty"] <= max_difficulty]
def normalize_text(text: str) -> str:
"""Normalize text for comparison.
Removes punctuation, lowers case, and collapses whitespace.
Args:
text: Raw text string to normalize.
Returns:
Normalized string with no punctuation, lowercase, single spaces.
"""
result = []
for char in text.lower():
if char.isalnum() or char.isspace():
result.append(char)
normalized = "".join(result)
return " ".join(normalized.split())
def get_verse_by_id(verses: list[dict[str, Any]], verse_id: str) -> dict[str, Any] | None:
"""Find a verse by its unique ID.
Args:
verses: List of all verses.
verse_id: The unique ID string of the verse.
Returns:
The verse dictionary if found, None otherwise.
"""
for verse in verses:
if verse["id"] == verse_id:
return verse
return None
def get_categories(verses: list[dict[str, Any]]) -> list[str]:
"""Get a list of unique categories from the verses.
Args:
verses: List of all verses.
Returns:
Sorted list of unique category names.
"""
categories = set()
for verse in verses:
categories.add(verse["category"])
return sorted(categories)

27
docker/Dockerfile Normal file
View File

@ -0,0 +1,27 @@
FROM python:3.12-slim AS builder
WORKDIR /build
RUN pip install --no-cache-dir uv==0.7.12
COPY pyproject.toml ./
COPY uv.lock ./
COPY verses.json ./
RUN uv sync --frozen
FROM python:3.12-slim
RUN useradd --create-home app
WORKDIR /app
COPY --chown=app:app --from=builder /build/.venv /app/.venv
COPY --chown=app:app main.py ./
COPY --chown=app:app data.py ./
COPY --chown=app:app verses.json ./
COPY --chown=app:app tests/ ./tests/
USER app
ENV PATH="/app/.venv/bin:$PATH"

11
docker/docker-compose.yml Normal file
View File

@ -0,0 +1,11 @@
services:
game:
build:
context: ..
dockerfile: docker/Dockerfile
stdin_open: true
tty: true
working_dir: /app
environment:
- PYTHONUNBUFFERED=1
command: python main.py

441
main.py Normal file
View File

@ -0,0 +1,441 @@
"""Arcane Purge - A text-based exorcist game using Bible verses as spell mechanics."""
import os
import time
from data import load_verses, normalize_text
# Demon encounter definitions with escalating difficulty
DEMONS = [
{"name": "Shade of Whispers", "health": 30, "weaknesses": ["Binding"], "damage": 5},
{"name": "Gloom Wraith", "health": 45, "weaknesses": ["Healing"], "damage": 8},
{"name": "Shadow Stalker", "health": 60, "weaknesses": ["Exorcism", "Binding"], "damage": 10},
{
"name": "Abyssal Phantom",
"health": 80,
"weaknesses": ["Protection", "Exorcism"],
"damage": 15,
},
{"name": "Dread Incubus", "health": 100, "weaknesses": ["Binding", "Healing"], "damage": 18},
{
"name": "Nightmare Sovereign",
"health": 130,
"weaknesses": ["Judgment", "Exorcism"],
"damage": 22,
},
{
"name": "Void Archfiend",
"health": 160,
"weaknesses": ["Judgment", "Protection"],
"damage": 28,
},
{
"name": "Abyssal Lord",
"health": 200,
"weaknesses": ["Binding", "Judgment", "Exorcism"],
"damage": 35,
},
]
def clear_screen() -> None:
"""Clear the terminal screen."""
os.system("cls" if os.name == "nt" else "clear")
def show_status(player: dict, demon: dict, verses: list, unlocked: list) -> None:
"""Display the current game status including player stats, demon info, and available verses.
Args:
player: Player state dictionary with health, max_health, score, mana.
demon: Current demon dictionary with name, health, max_health, weaknesses.
verses: Full list of all verses.
unlocked: List of verse IDs that are unlocked.
"""
clear_screen()
print("=" * 50)
print(" ARCANED PURGE")
print("=" * 50)
print()
print(f"Player Health: {player['health']}/{player['max_health']}")
print(f"Score: {player['score']}")
print(f"Demons Vanquished: {player['demons_defeated']}")
print()
print(f"Encounter: {demon['name']}")
print(f"Demon Health: {demon['health']}/{demon['max_health']}")
print(f"Weaknesses: {', '.join(demon['weaknesses'])}")
print()
print("Available Verses:")
for i, verse in enumerate(verses):
if verse["id"] in unlocked:
marker = ">>" if verse["category"] in demon["weaknesses"] else " "
print(
f" {marker} {i + 1}) {verse['id']} ({verse['category']}, "
f"Difficulty: {verse['difficulty']})"
)
print()
print("-" * 50)
def calculate_similarity(text1: str, text2: str) -> float:
"""Calculate similarity between two strings using character matching ratio.
Args:
text1: First normalized text string.
text2: Second normalized text string.
Returns:
Float between 0.0 and 1.0 representing similarity.
"""
if not text1 and not text2:
return 1.0
if not text1 or not text2:
return 0.0
words1 = text1.split()
words2 = text2.split()
matches = sum(1 for w in words1 if w in words2)
max_len = max(len(words1), len(words2))
return matches / max_len if max_len > 0 else 0.0
def get_hint(verse_text: str) -> str:
"""Generate a hint showing the first letter of each word.
Args:
verse_text: The full verse text.
Returns:
String with first letter of each word separated by spaces.
"""
words = verse_text.split()
return " ".join(w[0] if w else "?" for w in words)
def cast_verse(player: dict, demon: dict, verse: dict) -> tuple[bool, int, float]:
"""Execute the verse casting phase of combat.
Player types the verse text. If correct, damage is dealt to demon.
If wrong, player takes damage. Supports hints and partial credit.
Args:
player: Player state dictionary.
demon: Current demon dictionary.
verse: Selected verse dictionary.
Returns:
Tuple of (success: bool, damage_dealt: int, elapsed_time: float).
"""
print(f"\n--- Casting {verse['id']} ({verse['category']}) ---")
print(f"Reference: {verse['reference']}")
print(f'\nVerse to type:\n"{verse["text"]}"')
print("\nType the verse above (or press H for hint):")
start_time = time.time()
typed = input("> ")
elapsed = time.time() - start_time
# Handle hint requests during input
while typed.upper() == "H":
print(f"\nHint: {get_hint(verse['text'])}")
print("Type the verse (or press H for hint again):")
typed = input("> ")
typed_normalized = normalize_text(typed)
verse_normalized = normalize_text(verse["text"])
if typed_normalized == verse_normalized:
damage = verse["difficulty"] * 5
if verse["category"] in demon["weaknesses"]:
damage = damage * 2
return True, damage, elapsed
similarity = calculate_similarity(typed_normalized, verse_normalized)
if similarity >= 0.8:
print(f"\nPartial match ({similarity:.0%} correct). Retry allowed.")
print(f'Verse: "{verse["text"]}"')
print("Try again:")
typed = input("> ")
typed_normalized = normalize_text(typed)
elapsed = time.time() - start_time
if typed_normalized == verse_normalized:
damage = verse["difficulty"] * 3
if verse["category"] in demon["weaknesses"]:
damage = damage * 2
return True, damage, elapsed
# Failed cast
player["health"] -= demon["damage"]
player["score"] -= verse["difficulty"] * 2
print(f"\nSpell failed! ({similarity:.0%} match)")
print(f"Demon attacks! You take {demon['damage']} damage.")
if player["health"] < 0:
player["health"] = 0
return False, 0, elapsed
def memory_test(player: dict, demon: dict, verse: dict) -> tuple[bool, int]:
"""Execute the memory test phase after successful casting.
Player must recall and type the verse from memory. Success defeats demon.
Failure deals damage to player with retry chances.
Args:
player: Player state dictionary.
demon: Current demon dictionary.
verse: Verse that was successfully cast.
Returns:
Tuple of (success: bool, bonus_damage: int).
"""
print("\n--- Memory Test ---")
print("Type the verse from memory (do not look at it!):")
print("(Press H for hint if needed)")
attempts = 3
while attempts > 0:
typed = input("> ")
if typed.upper() == "H":
print(f"\nHint: {get_hint(verse['text'])}")
print("Type the verse from memory:")
continue
typed_normalized = normalize_text(typed)
verse_normalized = normalize_text(verse["text"])
if typed_normalized == verse_normalized:
bonus = verse["difficulty"] * 10
if verse["category"] in demon["weaknesses"]:
bonus = bonus * 2
print("\nMemory test passed! Powerful strike!")
return True, bonus
similarity = calculate_similarity(typed_normalized, verse_normalized)
if similarity >= 0.8:
print(f"\nClose ({similarity:.0%} correct). One more retry.")
print("Try again:")
continue
attempts -= 1
player["health"] -= demon["damage"]
player["score"] -= 5
if player["health"] < 0:
player["health"] = 0
if attempts > 0:
print(f"\nMemory test failed! Demon attacks! ({attempts} attempts left)")
print("Try again (press H for hint):")
print("\nMemory test failed! The demon resists.")
return False, 0
def unlock_new_verses(player: dict, all_verses: list, unlocked: list) -> list:
"""Unlock new verses based on demons defeated count.
Progression:
- Start: difficulty 1 verses (4 verses)
- After 1 demon: unlock difficulty 2
- After 2 demons: unlock difficulty 3
- After 3 demons: unlock difficulty 4
- After 4 demons: unlock difficulty 5
Args:
player: Player state dictionary.
all_verses: Full list of all verses.
unlocked: Current list of unlocked verse IDs.
Returns:
Updated list of unlocked verse IDs.
"""
defeated = player["demons_defeated"]
new_unlocks = []
if defeated >= 1:
max_diff = 2
elif defeated >= 2:
max_diff = 3
elif defeated >= 3:
max_diff = 4
elif defeated >= 4:
max_diff = 5
else:
max_diff = 1
for verse in all_verses:
if verse["difficulty"] <= max_diff and verse["id"] not in unlocked:
unlocked.append(verse["id"])
new_unlocks.append(verse["id"])
if new_unlocks:
print(f"\n*** New verses unlocked: {', '.join(new_unlocks)} ***")
return unlocked
def run_encounter(player: dict, all_verses: list, unlocked: list, demon_index: int) -> list:
"""Run a full demon encounter including casting and memory test phases.
Args:
player: Player state dictionary.
all_verses: Full list of all verses.
unlocked: List of unlocked verse IDs.
demon_index: Index into DEMONS list for this encounter.
Returns:
Updated list of unlocked verse IDs.
"""
demon_data = DEMONS[demon_index % len(DEMONS)]
demon = {
"name": demon_data["name"],
"health": demon_data["health"],
"max_health": demon_data["health"],
"weaknesses": demon_data["weaknesses"],
"damage": demon_data["damage"],
}
available = [v for v in all_verses if v["id"] in unlocked]
print(f"\nA {demon['name']} emerges from the darkness!")
time.sleep(1)
while demon["health"] > 0 and player["health"] > 0:
show_status(player, demon, all_verses, unlocked)
if not available:
print("No verses available! Game Over.")
player["health"] = 0
break
print("Select a verse to cast (enter number):")
choice = input("> ").strip()
try:
idx = int(choice) - 1
if idx < 0 or idx >= len(available):
print("Invalid selection. Try again.")
continue
selected = available[idx]
except ValueError:
print("Please enter a number.")
continue
success, damage, elapsed = cast_verse(player, demon, selected)
if player["health"] <= 0:
break
if success:
demon["health"] -= damage
time_bonus = 5 if elapsed < 10 else (3 if elapsed < 20 else (1 if elapsed < 30 else 0))
player["score"] += selected["difficulty"] * 10 + time_bonus
print(f"\nSpell successful! Dealt {damage} damage.")
print(f"Time: {elapsed:.1f}s (+{time_bonus} bonus)")
if demon["health"] <= 0:
demon["health"] = 0
print(f"\nThe {demon['name']} is weakened!")
if player.get("memory_mode"):
mem_success, bonus = memory_test(player, demon, selected)
if mem_success:
demon["health"] -= bonus
player["score"] += bonus
if demon["health"] < 0:
demon["health"] = 0
if player["health"] <= 0:
break
if demon["health"] <= 0:
break
input("\nPress Enter to continue...")
if demon["health"] <= 0:
player["demons_defeated"] += 1
player["score"] += 50
print(f"\n*** {demon['name']} has been vanquished! ***")
print(f"Score: {player['score']}")
if player["demons_defeated"] >= 5 and not player.get("memory_mode"):
player["memory_mode"] = True
print("*** Memory Mode unlocked! Memory tests now active. ***")
unlocked = unlock_new_verses(player, all_verses, unlocked)
input("\nPress Enter for next encounter...")
elif player["health"] <= 0:
print(f"\nThe {demon['name']} overwhelms you...")
return unlocked
def game_over(player: dict) -> None:
"""Display the game over screen with final statistics.
Args:
player: Final player state dictionary.
"""
clear_screen()
print("=" * 50)
print(" GAME OVER")
print("=" * 50)
print()
print(f"Final Score: {player['score']}")
print(f"Demons Vanquished: {player['demons_defeated']}")
verses_known = player.get("verses_unlocked", 0)
print(f"Verses Learned: {verses_known}")
memory_active = "Yes" if player.get("memory_mode") else "No"
print(f"Memory Mode: {memory_active}")
print()
print("The darkness recedes... for now.")
print("May your faith remain unbroken.")
print()
print("=" * 50)
def main() -> None:
"""Main entry point for the Arcane Purge game.
Initializes the game state, loads verses, and runs the main game loop
through demon encounters until the player is defeated.
"""
all_verses = load_verses()
unlocked = [v["id"] for v in all_verses if v["difficulty"] == 1]
player = {
"health": 100,
"max_health": 100,
"score": 0,
"demons_defeated": 0,
"verses_unlocked": len(unlocked),
"memory_mode": False,
}
clear_screen()
print("=" * 50)
print(" ARCANED PURGE")
print("=" * 50)
print()
print("You are an exorcist armed with the power of Scripture.")
print("Type Bible verses to cast spells against demonic forces.")
print("Match the verse exactly to deal damage.")
print("Pass memory tests to deliver the final blow.")
print()
print(f"You start with {len(unlocked)} verses unlocked.")
print("Defeat demons to unlock more powerful verses.")
print()
input("Press Enter to begin...")
demon_index = 0
while player["health"] > 0:
clear_screen()
unlocked = run_encounter(player, all_verses, unlocked, demon_index)
player["verses_unlocked"] = len(unlocked)
demon_index += 1
game_over(player)
input("\nPress Enter to exit...")
if __name__ == "__main__":
main()

59
prompt.md Normal file
View File

@ -0,0 +1,59 @@
**Prompt you can paste directly to an LLM (e.g. ChatGPT) to get the full game code**
> **Write a complete, ready‑to‑run Python implementation of a text‑based exorcist game that uses Bible verses as the “spell” mechanic.**
>
> **Requirements**
> 1. **Data** – Store the verses in a `verses.json` file (you can hard‑code the JSON inside the prompt). Each verse must have:
> * `id` – a unique string (e.g. `"binding_001"`)
> * `text` – the full verse (use real Bible passages, at least 3‑4 short verses per category)
> * `category` – e.g. `"Binding"`, `"Healing"`, `"Exorcism"`
> * `difficulty` – integer 1–5 (1 = easy, 5 = hard).
> 2. **Gameplay Loop** – The player is presented with an encounter (a demon name, health, and weakness categories). The player chooses a verse from the list of available verses (show its `id` and `category`). The player then types the verse.
> * If the typed verse matches the stored verse (ignoring punctuation, case, and whitespace), the spell succeeds.
> * If not, the spell fails and the demon deals damage.
> 3. **Memory Test** – After a successful cast, the screen clears and the player must type the same verse *without seeing it again*. If they succeed, the demon is defeated. If they fail, they get a warning and can retry.
> 4. **Scoring** – Keep a score that increases for correct casts, gives bonus points for speed (time < 10 s = +5, < 20 s = +3, < 30 s = +1). Deduct points for failures. Display the score after each encounter.
> 5. **UI** – Use the standard library (`curses` if available, otherwise plain `input()`/`print()`). The UI should show:
> * Player health & mana (if you wish to add mana).
> * Current demon health and weakness.
> * List of available verses (show only the `id` and `category`; hide the text until selected).
> 6. **Progression** – Start with 4 “easy” verses. After defeating a demon, unlock 2 new verses of higher difficulty. After defeating 5 demons, unlock the “Memory” mode for all previously learned verses.
> 7. **Code structure** – Provide at least three files:
> * `main.py` – entry point, game loop, UI, scoring.
> * `data.py` – loads the `verses.json` (you can embed the JSON inside this file).
> * `README.md` – quick instructions on how to run, how the game works, and how to extend the verse list.
> 8. **Comments & Readability** – Add comments explaining each function, data structure, and major logic. The code should be runnable by simply executing `python main.py`.
> 9. **Optional Enhancements** (if time permits):
> * Hint system – pressing `H` shows the first letter of each word.
> * Partial credit – if >80 % characters correct, allow a retry.
> * Voice input – optional, but you can note how to integrate a speech‑to‑text library.
>
> **Deliverables**
> * `main.py` – full game code.
> * `data.py` – JSON data embedded or loaded from a file.
> * `README.md` – usage instructions.
> * Comments inside the code for clarity.
>
> **Example Output** – After you run it, the user should see something like:
> ```
> Welcome to Arcane Purge.
> Encounter: Shade of the Abyss (Health: 50, Weakness: Binding, Exorcism)
> Choose a verse to cast:
> 1) binding_001 (Binding)
> 2) healing_003 (Healing)
> 3) exorcism_005 (Exorcism)
> Enter number: 1
> Type the verse:
> For I am the LORD your God, who teaches you to do good...
> Correct! Time: 12.3s
> Now, repeat the verse from memory:
> (User types again)
> Correct! Demon defeated!
> Score: 15
> ```
>
> Please generate the full code and README accordingly.
---
Copy the text above into the LLM and it will output the entire `main.py`, `data.py`, and `README.md` files with the game logic, JSON data, and documentation.

22
pyproject.toml Normal file
View File

@ -0,0 +1,22 @@
[project]
name = "exorcist-game"
version = "0.1.0"
description = "A text-based exorcist game using Bible verses as spell mechanics"
requires-python = ">=3.11"
dependencies = ["pytest>=7.0"]
[project.scripts]
exorcist = "main:main"
[project.optional-dependencies]
test = ["pytest>=7.0"]
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.ruff]
target-version = "py311"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "UP", "B", "SIM"]

154
tests/test_data.py Normal file
View File

@ -0,0 +1,154 @@
"""Tests for data module validation."""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from data import (
get_categories,
get_verse_by_id,
get_verses_by_category,
get_verses_by_max_difficulty,
load_verses,
normalize_text,
)
class TestLoadVerses:
"""Tests for verse data loading."""
def test_load_returns_list(self) -> None:
"""Verses load as a list."""
verses = load_verses()
assert isinstance(verses, list)
def test_minimum_verses(self) -> None:
"""At least 12 verses loaded."""
verses = load_verses()
assert len(verses) >= 12
def test_verse_structure(self) -> None:
"""Each verse has required fields: id, text, category, difficulty, reference."""
verses = load_verses()
required_fields = {"id", "text", "category", "difficulty", "reference"}
for verse in verses:
assert required_fields.issubset(verse.keys()), (
f"Missing fields in {verse.get('id', 'unknown')}"
)
def test_unique_ids(self) -> None:
"""All verse IDs are unique."""
verses = load_verses()
ids = [v["id"] for v in verses]
assert len(ids) == len(set(ids))
def test_categories_present(self) -> None:
"""All four categories represented: Binding, Healing, Exorcism, Protection, Judgment."""
verses = load_verses()
categories = get_categories(verses)
expected = {"Binding", "Healing", "Exorcism", "Protection", "Judgment"}
assert expected.issubset(set(categories))
def test_difficulty_range(self) -> None:
"""All difficulties are between 1 and 5."""
verses = load_verses()
for verse in verses:
assert 1 <= verse["difficulty"] <= 5
def test_easy_verses_count(self) -> None:
"""At least 4 easy (difficulty 1) verses for starting players."""
verses = load_verses()
easy = get_verses_by_max_difficulty(verses, 1)
assert len(easy) >= 4
class TestNormalizeText:
"""Tests for text normalization used in verse matching."""
def test_removes_punctuation(self) -> None:
"""Punctuation is stripped from text."""
result = normalize_text("Hello, world! How are you?")
assert result == "hello world how are you"
def test_lowercases(self) -> None:
"""Text is converted to lowercase."""
result = normalize_text("HELLO WORLD")
assert result == "hello world"
def test_collapses_whitespace(self) -> None:
"""Multiple spaces are collapsed to single space."""
result = normalize_text("Hello world")
assert result == "hello world"
def test_combined(self) -> None:
"""Combined punctuation, case, and whitespace normalization."""
result = normalize_text(" Hello, World! ")
assert result == "hello world"
def test_empty_string(self) -> None:
"""Empty string returns empty string."""
assert normalize_text("") == ""
def test_identical_verses_match(self) -> None:
"""Same verse text normalizes to identical strings."""
verse = "I have given you authority to trample on snakes and scorpions."
typed = "I have given you authority to trample on snakes and scorpions."
assert normalize_text(verse) == normalize_text(typed)
def test_punctuation_difference_ignored(self) -> None:
"""Punctuation differences are ignored in normalization."""
verse = "He heals the brokenhearted and binds up their wounds."
typed = "He heals the brokenhearted, and binds up their wounds!"
assert normalize_text(verse) == normalize_text(typed)
class TestGetVerseById:
"""Tests for verse lookup by ID."""
def test_finds_existing_verse(self) -> None:
"""Existing verse ID returns the verse."""
verses = load_verses()
verse = get_verse_by_id(verses, "binding_001")
assert verse is not None
assert verse["id"] == "binding_001"
def test_returns_none_for_missing(self) -> None:
"""Non-existent ID returns None."""
verses = load_verses()
assert get_verse_by_id(verses, "nonexistent_999") is None
class TestGetVersesByCategory:
"""Tests for filtering verses by category."""
def test_filter_by_category(self) -> None:
"""Returns only verses matching the category."""
verses = load_verses()
binding = get_verses_by_category(verses, "Binding")
assert all(v["category"] == "Binding" for v in binding)
assert len(binding) >= 3
def test_case_insensitive(self) -> None:
"""Category filtering is case-insensitive."""
verses = load_verses()
result1 = get_verses_by_category(verses, "Binding")
result2 = get_verses_by_category(verses, "binding")
assert result1 == result2
class TestGetVersesByMaxDifficulty:
"""Tests for filtering verses by maximum difficulty."""
def test_filters_correctly(self) -> None:
"""Returns only verses at or below max difficulty."""
verses = load_verses()
easy = get_verses_by_max_difficulty(verses, 1)
assert all(v["difficulty"] <= 1 for v in easy)
def test_includes_all_at_level(self) -> None:
"""All verses up to max difficulty are included."""
verses = load_verses()
all_verses = load_verses()
result = get_verses_by_max_difficulty(verses, 5)
assert len(result) == len(all_verses)

97
tests/test_main.py Normal file
View File

@ -0,0 +1,97 @@
"""Tests for main game module validation."""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from data import load_verses, normalize_text
from main import calculate_similarity, get_hint
class TestCalculateSimilarity:
"""Tests for string similarity calculation used in partial credit."""
def test_identical_strings(self) -> None:
"""Identical normalized strings have 1.0 similarity."""
text = "hello world"
assert calculate_similarity(text, text) == 1.0
def test_completely_different(self) -> None:
"""Completely different strings have 0.0 similarity."""
assert calculate_similarity("abc", "xyz") == 0.0
def test_partial_match(self) -> None:
"""Partially matching strings have intermediate similarity."""
sim = calculate_similarity("hello world", "hello there")
assert 0.0 < sim < 1.0
def test_empty_strings(self) -> None:
"""Two empty strings have 1.0 similarity."""
assert calculate_similarity("", "") == 1.0
def test_one_empty(self) -> None:
"""One empty and one non-empty string have 0.0 similarity."""
assert calculate_similarity("hello", "") == 0.0
assert calculate_similarity("", "hello") == 0.0
class TestGetHint:
"""Tests for hint generation showing first letters."""
def test_basic_hint(self) -> None:
"""Hint shows first letter of each word."""
hint = get_hint("Hello world")
assert hint == "H w"
def test_full_verse_hint(self) -> None:
"""Hint works with full verse text."""
verse = "I have given you authority to trample"
hint = get_hint(verse)
assert hint == "I h g y a t t"
def test_single_word(self) -> None:
"""Single word returns its first letter."""
assert get_hint("Hello") == "H"
class TestGameInitialization:
"""Tests for game initialization and state."""
def test_verses_load(self) -> None:
"""Game can load verses without error."""
verses = load_verses()
assert len(verses) > 0
def test_starting_verses(self) -> None:
"""Starting verses (difficulty 1) are available."""
verses = load_verses()
easy = [v for v in verses if v["difficulty"] == 1]
assert len(easy) >= 4
def test_normalize_consistency(self) -> None:
"""Normalization is consistent across calls."""
text = "The Lord is my light and my salvation."
assert normalize_text(text) == normalize_text(text)
class TestDemonData:
"""Tests for demon encounter data."""
from main import DEMONS
def test_demons_exist(self) -> None:
"""Demon list is populated."""
assert len(self.DEMONS) > 0
def test_demon_structure(self) -> None:
"""Each demon has required fields."""
required = {"name", "health", "weaknesses", "damage"}
for demon in self.DEMONS:
assert required.issubset(demon.keys())
def test_escalating_difficulty(self) -> None:
"""Demons have escalating health values."""
healths = [d["health"] for d in self.DEMONS]
for i in range(1, len(healths)):
assert healths[i] > healths[i - 1]

84
uv.lock generated Normal file
View File

@ -0,0 +1,84 @@
version = 1
revision = 2
requires-python = ">=3.11"
[[package]]
name = "colorama"
version = "0.4.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
]
[[package]]
name = "exorcist-game"
version = "0.1.0"
source = { virtual = "." }
dependencies = [
{ name = "pytest" },
]
[package.optional-dependencies]
test = [
{ name = "pytest" },
]
[package.metadata]
requires-dist = [
{ name = "pytest", specifier = ">=7.0" },
{ name = "pytest", marker = "extra == 'test'", specifier = ">=7.0" },
]
provides-extras = ["test"]
[[package]]
name = "iniconfig"
version = "2.3.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
]
[[package]]
name = "packaging"
version = "26.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
]
[[package]]
name = "pygments"
version = "2.20.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
]
[[package]]
name = "pytest"
version = "9.0.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "colorama", marker = "sys_platform == 'win32'" },
{ name = "iniconfig" },
{ name = "packaging" },
{ name = "pluggy" },
{ name = "pygments" },
]
sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/549bd94f1a0a402dc8cf64563a117c0f3765662e2e668477624baeec44d5/pytest-9.0.3.tar.gz", hash = "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c", size = 1572165, upload-time = "2026-04-07T17:16:18.027Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" },
]

88
verses.json Normal file
View File

@ -0,0 +1,88 @@
{
"verses": [
{
"id": "binding_001",
"text": "I have given you authority to trample on snakes and scorpions and over all the power of the enemy.",
"category": "Binding",
"difficulty": 1,
"reference": "Luke 10:19"
},
{
"id": "binding_002",
"text": "Every kingdom divided against itself will be ruined.",
"category": "Binding",
"difficulty": 1,
"reference": "Matthew 12:25"
},
{
"id": "healing_001",
"text": "He heals the brokenhearted and binds up their wounds.",
"category": "Healing",
"difficulty": 1,
"reference": "Psalm 147:3"
},
{
"id": "healing_002",
"text": "Come to me all you who are weary and burdened and I will give you rest.",
"category": "Healing",
"difficulty": 1,
"reference": "Matthew 11:28"
},
{
"id": "exorcism_001",
"text": "The spirit you do not want in your life tell it to leave in the name of Jesus.",
"category": "Exorcism",
"difficulty": 2,
"reference": "Mark 16:17"
},
{
"id": "exorcism_002",
"text": "Submit yourselves therefore to God. Resist the devil and he will flee from you.",
"category": "Exorcism",
"difficulty": 2,
"reference": "James 4:7"
},
{
"id": "protection_001",
"text": "No weapon formed against you shall prosper and every tongue that rises against you in judgment you shall condemn.",
"category": "Protection",
"difficulty": 3,
"reference": "Isaiah 54:17"
},
{
"id": "protection_002",
"text": "The Lord is my light and my salvation whom shall I fear.",
"category": "Protection",
"difficulty": 3,
"reference": "Psalm 27:1"
},
{
"id": "binding_003",
"text": "I bind every demonic activity and loose the peace of God over this place.",
"category": "Binding",
"difficulty": 4,
"reference": "Isaiah 59:19"
},
{
"id": "judgment_001",
"text": "The Lord will judge the ends of the earth and you cannot give bread to stone.",
"category": "Judgment",
"difficulty": 4,
"reference": "Psalm 21:9"
},
{
"id": "judgment_002",
"text": "For we must all appear before the judgment seat of Christ.",
"category": "Judgment",
"difficulty": 5,
"reference": "2 Corinthians 5:10"
},
{
"id": "exorcism_003",
"text": "Greater is he that is in you than he that is in the world.",
"category": "Exorcism",
"difficulty": 5,
"reference": "1 John 4:4"
}
]
}