11 Commits

Author SHA1 Message Date
steve e973b2ce20 feat: add project export and import functionality
- Implemented `pcli project export` command to export project hierarchy as JSON.
- Added `pcli project import` command to import project data from JSON.
- Created user client to fetch user details for comment attribution.
- Introduced new data structures for export and import processes.
- Ensured name-based references in exports and handled conflicts during imports.
- Added versioning and progress reporting for import operations.
- Updated documentation and specifications for new features.
2026-03-04 19:53:55 +00:00
Steve Cliff e352fd530f removed test no longer required 2026-03-02 12:13:14 +00:00
Steve Cliff 7452734e38 removed name filtering prior to demo 2026-03-02 12:06:07 +00:00
Steve Cliff ead055a73a feat(kanban): remove Backlog and Planning lists from board initialization
- Removed "Backlog" list creation (position 65536) from board setup
- Removed "Planning" list creation (position 196608) from board setup
- Retained core workflow lists: To Do, In Progress, Review, Done
2026-02-24 15:12:47 +00:00
Steve Cliff 22e9d809c5 Added Windsurf rule for Kanban 2026-02-23 14:16:35 +00:00
Steve Cliff 7401e92116 Configured openspec/planka for Windsurf as well as Claude 2026-02-23 08:11:28 +00:00
Steve Cliff 5016d4c39c feat(sync): implement kanban-project-sync script with concurrency control and background execution 2026-02-19 11:08:15 +00:00
Steve Cliff 7937266262 feat(status): add --project flag for filtering boards by project name
- Implemented the --project flag in the pcli status command to filter boards based on the specified project name.
- Updated the command to resolve project names to IDs using case-insensitive matching.
- Adjusted the totalBoards count in the output to reflect the number of boards matching the project filter.
- Enhanced command help text and README documentation to include usage examples for the new flag.
- Verified functionality through manual testing and ensured default behavior remains unchanged when the flag is omitted.

feat(board): expand GetBoard response to include labels and card associations

- Modified the Board struct to include Labels, CardLabels, and CardMemberships fields.
- Updated the GetBoard method to parse additional fields from the API response.
- Enhanced ListCardsByBoard to include label names for each card based on the enriched board data.
- Ensured backward compatibility by making new fields optional and preserving existing output structure.
2026-02-18 21:38:41 +00:00
Steve Cliff 22d5848e1a feat: Add openspec-sync-specs and openspec-verify-change skills
- Introduced `openspec-sync-specs` skill to sync delta specs to main specs, allowing intelligent merging of requirements.
- Added `openspec-verify-change` skill to verify implementation against change artifacts, ensuring completeness, correctness, and coherence before archiving.

docs: Create CLAUDE.md for project guidance

- Added CLAUDE.md to provide an overview of the PCLI project, including build, test commands, architecture, and resource addition guidelines.

chore: Add new change and design documents for project filter in status command

- Created `.openspec.yaml`, `design.md`, `proposal.md`, and `tasks.md` for the `add-project-filter-to-status` change.
- Updated specs for CLI commands and status command to include project filtering functionality.

feat: Expand board included parsing in API client

- Added parsing for `labels`, `cardLabels`, and `cardMemberships` in the `GetBoard` response.
- Updated `ListCardsByBoard` to enrich card output with label names, enhancing usability in kanban sync workflows.
2026-02-18 21:27:02 +00:00
Steve Cliff 94dffdf8fc Updated project info 2026-02-18 20:26:12 +00:00
Steve Cliff 46b03e1a22 Added list management commands, board filtering by project name, and enhanced skill documentation with bootstrap workflow and error handling patterns. Also added plumbing in to "pcli" binary for status syncing with Planka 2026-02-18 20:06:56 +00:00
93 changed files with 5297 additions and 1736 deletions
+45
View File
@@ -0,0 +1,45 @@
---
description: Reconcile Planka board state with OpenSpec changes
allowed-tools: Bash, Read
---
# Planka <-> OpenSpec Reconciliation Sync
Runs the `kanban-project-sync` script to reconcile Planka board state with OpenSpec changes.
## How It Works
The sync is handled by the `kanban-project-sync` bash script (on PATH). It:
1. Checks Planka connectivity
2. Bootstraps project/board/lists/label infrastructure (idempotent)
3. Reads OpenSpec state and maps changes to board lists
4. Creates/moves/updates Planka cards and task checklists
5. Moves orphaned cards to Done
**OpenSpec is the source of truth.** Planka is a read-only projection. Sync is one-directional (OpenSpec -> Planka) and idempotent.
## Running the Sync
Read project config and invoke the script in background mode:
```bash
PROJECT_NAME=$(yq -r '.planka.project' project.yaml)
BOARD_NAME=$(yq -r '.planka.board' project.yaml)
kanban-project-sync --project "$PROJECT_NAME" --board "$BOARD_NAME" --background
```
The `--background` flag makes the script fire-and-forget — it detaches and logs to `/tmp/kanban-project-sync-<project>-<board>.log`.
## Concurrency
The script handles its own concurrency:
- Uses `flock` to ensure only one sync runs per project-board pair
- If a sync is already running, sets a pending flag and exits immediately
- The running sync re-runs after completion if the pending flag is set
- Multiple pending requests coalesce into a single re-run
## Guardrails
- Sync is **best-effort** — if Planka is unreachable or the script fails, log a warning and continue
- Never block agentic work because of sync
- If `kanban-project-sync` is not on PATH, log a warning and skip
+152
View File
@@ -0,0 +1,152 @@
---
name: "OPSX: Apply"
description: Implement tasks from an OpenSpec change (Experimental)
category: Workflow
tags: [workflow, artifacts, 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
+157
View File
@@ -0,0 +1,157 @@
---
name: "OPSX: Archive"
description: Archive a completed change in the experimental workflow
category: Workflow
tags: [workflow, archive, experimental]
---
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
+114
View File
@@ -0,0 +1,114 @@
---
name: "OPSX: Continue"
description: Continue working on a change - create the next artifact (Experimental)
category: Workflow
tags: [workflow, artifacts, experimental]
---
Continue working on a change by creating the next artifact.
**Input**: Optionally specify a change name after `/opsx:continue` (e.g., `/opsx:continue 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 sorted by most recently modified. Then use the **AskUserQuestion tool** to let the user select which change to work on.
Present the top 3-4 most recently modified changes as options, showing:
- Change name
- Schema (from `schema` field if present, otherwise "spec-driven")
- Status (e.g., "0/5 tasks", "complete", "no tasks")
- How recently it was modified (from `lastModified` field)
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to continue.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check current status**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
- `artifacts`: Array of artifacts with their status ("done", "ready", "blocked")
- `isComplete`: Boolean indicating if all artifacts are complete
3. **Act based on status**:
---
**If all artifacts are complete (`isComplete: true`)**:
- Congratulate the user
- Show final status including the schema used
- Suggest: "All artifacts created! You can now implement this change with `/opsx:apply` or archive it with `/opsx:archive`."
- STOP
---
**If artifacts are ready to create** (status shows artifacts with `status: "ready"`):
- Pick the FIRST artifact with `status: "ready"` from the status output
- Get its instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- Parse the JSON. The key fields are:
- `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
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- **Create the artifact file**:
- Read any completed dependency files for context
- Use `template` as the structure - fill in its sections
- Apply `context` and `rules` as constraints when writing - but do NOT copy them into the file
- Write to the output path specified in instructions
- Show what was created and what's now unlocked
- STOP after creating ONE artifact
---
**If no artifacts are ready (all blocked)**:
- This shouldn't happen with a valid schema
- Show status and suggest checking for issues
4. **After creating an artifact, show progress**
```bash
openspec status --change "<name>"
```
**Output**
After each invocation, show:
- Which artifact was created
- Schema workflow being used
- Current progress (N/M complete)
- What artifacts are now unlocked
- Prompt: "Run `/opsx:continue` to create the next artifact"
**Artifact Creation Guidelines**
The artifact types and their purpose depend on the schema. Use the `instruction` field from the instructions output to understand what to create.
Common artifact patterns:
**spec-driven schema** (proposal → specs → design → tasks):
- **proposal.md**: Ask user about the change if not clear. Fill in Why, What Changes, Capabilities, Impact.
- The Capabilities section is critical - each capability listed will need a spec file.
- **specs/<capability>/spec.md**: Create one spec per capability listed in the proposal's Capabilities section (use the capability name, not the change name).
- **design.md**: Document technical decisions, architecture, and implementation approach.
- **tasks.md**: Break down implementation into checkboxed tasks.
For other schemas, follow the `instruction` field from the CLI output.
**Guardrails**
- Create ONE artifact per invocation
- Always read dependency artifacts before creating a new one
- Never skip artifacts or create out of order
- If context is unclear, ask the user before creating
- Verify the artifact file exists after writing before marking progress
- Use the schema's artifact sequence, don't assume specific artifact names
- **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
+173
View File
@@ -0,0 +1,173 @@
---
name: "OPSX: Explore"
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
category: Workflow
tags: [workflow, explore, experimental, thinking]
---
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
+97
View File
@@ -0,0 +1,97 @@
---
name: "OPSX: Fast Forward"
description: Create a change and generate all artifacts needed for implementation in one go
category: Workflow
tags: [workflow, artifacts, experimental]
---
Fast-forward through artifact creation - generate everything needed to start implementation.
**Input**: The argument after `/opsx:ff` 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>/`.
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
+69
View File
@@ -0,0 +1,69 @@
---
name: "OPSX: New"
description: Start a new change using the experimental artifact workflow (OPSX)
category: Workflow
tags: [workflow, artifacts, experimental]
---
Start a new change using the experimental artifact-driven approach.
**Input**: The argument after `/opsx:new` 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. **Determine the workflow schema**
Use the default schema (omit `--schema`) unless the user explicitly requests a different workflow.
**Use a different schema only if the user mentions:**
- A specific schema name → use `--schema <name>`
- "show workflows" or "what workflows" → run `openspec schemas --json` and let them choose
**Otherwise**: Omit `--schema` to use the default.
3. **Create the change directory**
```bash
openspec new change "<name>"
```
Add `--schema <name>` only if the user requested a specific workflow.
This creates a scaffolded change at `openspec/changes/<name>/` with the selected schema.
4. **Show the artifact status**
```bash
openspec status --change "<name>"
```
This shows which artifacts need to be created and which are ready (dependencies satisfied).
5. **Get instructions for the first artifact**
The first artifact depends on the schema. Check the status output to find the first artifact with status "ready".
```bash
openspec instructions <first-artifact-id> --change "<name>"
```
This outputs the template and context for creating the first artifact.
6. **STOP and wait for user direction**
**Output**
After completing the steps, summarize:
- Change name and location
- Schema/workflow being used and its artifact sequence
- Current status (0/N artifacts complete)
- The template for the first artifact
- Prompt: "Ready to create the first artifact? Run `/opsx:continue` or just describe what this change is about and I'll draft it."
**Guardrails**
- Do NOT create any artifacts yet - just show the instructions
- Do NOT advance beyond showing the first artifact template
- If the name is invalid (not kebab-case), ask for a valid name
- If a change with that name already exists, suggest using `/opsx:continue` instead
- Pass --schema if using a non-default workflow
+134
View File
@@ -0,0 +1,134 @@
---
name: "OPSX: Sync"
description: Sync delta specs from a change to main specs
category: Workflow
tags: [workflow, specs, experimental]
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync 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 changes that have delta specs (under `specs/` directory).
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **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)
If no delta specs found, inform user and stop.
3. **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 requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in 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 main spec
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
d. **Create new main spec** if capability doesn't exist yet:
- Create `openspec/specs/<capability>/spec.md`
- Add Purpose section (can be brief, mark as TBD)
- Add Requirements section with the ADDED requirements
4. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
**Delta Spec Format Reference**
```markdown
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**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
**Output On Success**
```
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result
+164
View File
@@ -0,0 +1,164 @@
---
name: "OPSX: Verify"
description: Verify implementation matches change artifacts before archiving
category: Workflow
tags: [workflow, verify, experimental]
---
Verify that an implementation matches the change artifacts (specs, tasks, design).
**Input**: Optionally specify a change name after `/opsx:verify` (e.g., `/opsx:verify 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 changes that have implementation tasks (tasks artifact exists).
Include the schema used for each change if available.
Mark changes with incomplete tasks as "(In Progress)".
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
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 artifacts exist for this change
3. **Get the change directory and load artifacts**
```bash
openspec instructions apply --change "<name>" --json
```
This returns the change directory and context files. Read all available artifacts from `contextFiles`.
4. **Initialize verification report structure**
Create a report structure with three dimensions:
- **Completeness**: Track tasks and spec coverage
- **Correctness**: Track requirement implementation and scenario coverage
- **Coherence**: Track design adherence and pattern consistency
Each dimension can have CRITICAL, WARNING, or SUGGESTION issues.
5. **Verify Completeness**
**Task Completion**:
- If tasks.md exists in contextFiles, read it
- Parse checkboxes: `- [ ]` (incomplete) vs `- [x]` (complete)
- Count complete vs total tasks
- If incomplete tasks exist:
- Add CRITICAL issue for each incomplete task
- Recommendation: "Complete task: <description>" or "Mark as done if already implemented"
**Spec Coverage**:
- If delta specs exist in `openspec/changes/<name>/specs/`:
- Extract all requirements (marked with "### Requirement:")
- For each requirement:
- Search codebase for keywords related to the requirement
- Assess if implementation likely exists
- If requirements appear unimplemented:
- Add CRITICAL issue: "Requirement not found: <requirement name>"
- Recommendation: "Implement requirement X: <description>"
6. **Verify Correctness**
**Requirement Implementation Mapping**:
- For each requirement from delta specs:
- Search codebase for implementation evidence
- If found, note file paths and line ranges
- Assess if implementation matches requirement intent
- If divergence detected:
- Add WARNING: "Implementation may diverge from spec: <details>"
- Recommendation: "Review <file>:<lines> against requirement X"
**Scenario Coverage**:
- For each scenario in delta specs (marked with "#### Scenario:"):
- Check if conditions are handled in code
- Check if tests exist covering the scenario
- If scenario appears uncovered:
- Add WARNING: "Scenario not covered: <scenario name>"
- Recommendation: "Add test or implementation for scenario: <description>"
7. **Verify Coherence**
**Design Adherence**:
- If design.md exists in contextFiles:
- Extract key decisions (look for sections like "Decision:", "Approach:", "Architecture:")
- Verify implementation follows those decisions
- If contradiction detected:
- Add WARNING: "Design decision not followed: <decision>"
- Recommendation: "Update implementation or revise design.md to match reality"
- If no design.md: Skip design adherence check, note "No design.md to verify against"
**Code Pattern Consistency**:
- Review new code for consistency with project patterns
- Check file naming, directory structure, coding style
- If significant deviations found:
- Add SUGGESTION: "Code pattern deviation: <details>"
- Recommendation: "Consider following project pattern: <example>"
8. **Generate Verification Report**
**Summary Scorecard**:
```
## Verification Report: <change-name>
### Summary
| Dimension | Status |
|--------------|------------------|
| Completeness | X/Y tasks, N reqs|
| Correctness | M/N reqs covered |
| Coherence | Followed/Issues |
```
**Issues by Priority**:
1. **CRITICAL** (Must fix before archive):
- Incomplete tasks
- Missing requirement implementations
- Each with specific, actionable recommendation
2. **WARNING** (Should fix):
- Spec/design divergences
- Missing scenario coverage
- Each with specific recommendation
3. **SUGGESTION** (Nice to fix):
- Pattern inconsistencies
- Minor improvements
- Each with specific recommendation
**Final Assessment**:
- If CRITICAL issues: "X critical issue(s) found. Fix before archiving."
- If only warnings: "No critical issues. Y warning(s) to consider. Ready for archive (with noted improvements)."
- If all clear: "All checks passed. Ready for archive."
**Verification Heuristics**
- **Completeness**: Focus on objective checklist items (checkboxes, requirements list)
- **Correctness**: Use keyword search, file path analysis, reasonable inference - don't require perfect certainty
- **Coherence**: Look for glaring inconsistencies, don't nitpick style
- **False Positives**: When uncertain, prefer SUGGESTION over WARNING, WARNING over CRITICAL
- **Actionability**: Every issue must have a specific recommendation with file/line references where applicable
**Graceful Degradation**
- If only tasks.md exists: verify task completion only, skip spec/design checks
- If tasks + specs exist: verify completeness and correctness, skip design
- If full artifacts: verify all three dimensions
- Always note which checks were skipped and why
**Output Format**
Use clear markdown with:
- Table for summary scorecard
- Grouped lists for issues (CRITICAL/WARNING/SUGGESTION)
- Code references in format: `file.ts:123`
- Specific, actionable recommendations
- No vague suggestions like "consider reviewing"
@@ -1,5 +1,5 @@
--- ---
name: example-skill name: planka-skill
description: Manage Planka project boards using the pcli CLI. Use when the user wants to interact with Planka boards, cards, lists, tasks, labels, or comments. description: Manage Planka project boards using the pcli CLI. Use when the user wants to interact with Planka boards, cards, lists, tasks, labels, or comments.
compatibility: Requires pcli binary in PATH and PLANKA_URL + PLANKA_API_KEY environment variables set compatibility: Requires pcli binary in PATH and PLANKA_URL + PLANKA_API_KEY environment variables set
metadata: metadata:
@@ -23,7 +23,7 @@ Ensure `jq` is installed.
## Global Flags ## Global Flags
All commands accept: `--format json|table`, `--url <url>`, `--api-key <key>`, `--log-level debug|info|warn|error` All commands (apart from import/export) accept: `--format json|table`, `--url <url>`, `--api-key <key>`, `--log-level debug|info|warn|error`
## Commands ## Commands
@@ -40,14 +40,38 @@ Returns summary of all boards, lists, and card counts (open/closed per list).
```bash ```bash
pcli project list pcli project list
pcli project get <project-id> pcli project get <project-id>
pcli project create --name "Name" --type private # type: private or shared
pcli project delete <project-id>
# Export/Import
pcli project export <project-id-or-name> [--board <name-or-id>] > backup.json
pcli project import --file backup.json
pcli project import < backup.json
``` ```
Export outputs a portable JSON file (names, not IDs). Import creates all resources with fresh IDs.
Import fails if the project+board name combination already exists on the target.
Comments are exported with `(Original comment by <username>)` prefix for attribution.
**Note:** Export outputs its own envelope format (`{version, exportedAt, project}`) directly — not the standard `{data, error}` envelope. Import progress and errors go to stderr.
### Boards ### Boards
```bash ```bash
pcli board list pcli board list
pcli board get <board-id> # includes lists and cards pcli board get <board-id> # includes lists and cards
pcli board actions <board-id> [--limit N] pcli board actions <board-id> [--limit N]
pcli board create --project <project-id> --name "Board Name" [--position N]
pcli board delete <board-id>
```
### Lists (Board Columns)
```bash
pcli list create --board <board-id> --name "Column Name" [--type active|closed] [--position N]
pcli list get <list-id>
pcli list update <list-id> [--name "..."] [--type active|closed] [--color "..."] [--position N] [--board <board-id>]
pcli list delete <list-id>
``` ```
### Cards ### Cards
@@ -125,6 +149,22 @@ pcli card list --board <id> | jq -r '.data[].id'
## Common Workflows ## Common Workflows
### Create a complete Kanban board
```bash
# Create board
BOARD_ID=$(pcli board create --project <project-id> --name "Development Board" | jq -r '.data.id')
# Create columns
pcli list create --board $BOARD_ID --name "Backlog" --type "active" --position 0
TODO_ID=$(pcli list create --board $BOARD_ID --name "To Do" --type "active" --position 65536 | jq -r '.data.id')
PROGRESS_ID=$(pcli list create --board $BOARD_ID --name "In Progress" --type "active" --position 131072 | jq -r '.data.id')
DONE_ID=$(pcli list create --board $BOARD_ID --name "Done" --type "closed" --position 196608 | jq -r '.data.id')
# View the board
pcli board get $BOARD_ID --format table
```
### Create a card with a checklist ### Create a card with a checklist
```bash ```bash
@@ -141,3 +181,16 @@ pcli card list --list <source-list-id> | jq -r '.data[].id' | while read id; do
pcli card move $id --list <target-list-id> pcli card move $id --list <target-list-id>
done done
``` ```
### Export and import a project
```bash
# Export entire project
pcli project export "My Project" > project-backup.json
# Export single board
pcli project export "My Project" --board "Sprint Board" > board-backup.json
# Import to another instance (or same instance if project+board combo doesn't exist)
pcli project import --file project-backup.json
```
@@ -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
@@ -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
@@ -0,0 +1,118 @@
---
name: openspec-continue-change
description: Continue working on an OpenSpec change by creating the next artifact. Use when the user wants to progress their change, create the next artifact, or continue their workflow.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Continue working on a change by creating the next artifact.
**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 sorted by most recently modified. Then use the **AskUserQuestion tool** to let the user select which change to work on.
Present the top 3-4 most recently modified changes as options, showing:
- Change name
- Schema (from `schema` field if present, otherwise "spec-driven")
- Status (e.g., "0/5 tasks", "complete", "no tasks")
- How recently it was modified (from `lastModified` field)
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to continue.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check current status**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
- `artifacts`: Array of artifacts with their status ("done", "ready", "blocked")
- `isComplete`: Boolean indicating if all artifacts are complete
3. **Act based on status**:
---
**If all artifacts are complete (`isComplete: true`)**:
- Congratulate the user
- Show final status including the schema used
- Suggest: "All artifacts created! You can now implement this change or archive it."
- STOP
---
**If artifacts are ready to create** (status shows artifacts with `status: "ready"`):
- Pick the FIRST artifact with `status: "ready"` from the status output
- Get its instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- Parse the JSON. The key fields are:
- `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
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- **Create the artifact file**:
- Read any completed dependency files for context
- Use `template` as the structure - fill in its sections
- Apply `context` and `rules` as constraints when writing - but do NOT copy them into the file
- Write to the output path specified in instructions
- Show what was created and what's now unlocked
- STOP after creating ONE artifact
---
**If no artifacts are ready (all blocked)**:
- This shouldn't happen with a valid schema
- Show status and suggest checking for issues
4. **After creating an artifact, show progress**
```bash
openspec status --change "<name>"
```
**Output**
After each invocation, show:
- Which artifact was created
- Schema workflow being used
- Current progress (N/M complete)
- What artifacts are now unlocked
- Prompt: "Want to continue? Just ask me to continue or tell me what to do next."
**Artifact Creation Guidelines**
The artifact types and their purpose depend on the schema. Use the `instruction` field from the instructions output to understand what to create.
Common artifact patterns:
**spec-driven schema** (proposal → specs → design → tasks):
- **proposal.md**: Ask user about the change if not clear. Fill in Why, What Changes, Capabilities, Impact.
- The Capabilities section is critical - each capability listed will need a spec file.
- **specs/<capability>/spec.md**: Create one spec per capability listed in the proposal's Capabilities section (use the capability name, not the change name).
- **design.md**: Document technical decisions, architecture, and implementation approach.
- **tasks.md**: Break down implementation into checkboxed tasks.
For other schemas, follow the `instruction` field from the CLI output.
**Guardrails**
- Create ONE artifact per invocation
- Always read dependency artifacts before creating a new one
- Never skip artifacts or create out of order
- If context is unclear, ask the user before creating
- Verify the artifact file exists after writing before marking progress
- Use the schema's artifact sequence, don't assume specific artifact names
- **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
+288
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
+101
View File
@@ -0,0 +1,101 @@
---
name: openspec-ff-change
description: Fast-forward through OpenSpec artifact creation. Use when the user wants to quickly create all artifacts needed for implementation without stepping through each one individually.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Fast-forward through artifact creation - generate everything needed to start implementation in one go.
**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>/`.
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, suggest continuing that change instead
- Verify each artifact file exists after writing before proceeding to next
@@ -0,0 +1,74 @@
---
name: openspec-new-change
description: Start a new OpenSpec change using the experimental artifact workflow. Use when the user wants to create a new feature, fix, or modification with a structured step-by-step approach.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Start a new change using the experimental artifact-driven approach.
**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. **Determine the workflow schema**
Use the default schema (omit `--schema`) unless the user explicitly requests a different workflow.
**Use a different schema only if the user mentions:**
- A specific schema name → use `--schema <name>`
- "show workflows" or "what workflows" → run `openspec schemas --json` and let them choose
**Otherwise**: Omit `--schema` to use the default.
3. **Create the change directory**
```bash
openspec new change "<name>"
```
Add `--schema <name>` only if the user requested a specific workflow.
This creates a scaffolded change at `openspec/changes/<name>/` with the selected schema.
4. **Show the artifact status**
```bash
openspec status --change "<name>"
```
This shows which artifacts need to be created and which are ready (dependencies satisfied).
5. **Get instructions for the first artifact**
The first artifact depends on the schema (e.g., `proposal` for spec-driven).
Check the status output to find the first artifact with status "ready".
```bash
openspec instructions <first-artifact-id> --change "<name>"
```
This outputs the template and context for creating the first artifact.
6. **STOP and wait for user direction**
**Output**
After completing the steps, summarize:
- Change name and location
- Schema/workflow being used and its artifact sequence
- Current status (0/N artifacts complete)
- The template for the first artifact
- Prompt: "Ready to create the first artifact? Just describe what this change is about and I'll draft it, or ask me to continue."
**Guardrails**
- Do NOT create any artifacts yet - just show the instructions
- Do NOT advance beyond showing the first artifact template
- If the name is invalid (not kebab-case), ask for a valid name
- If a change with that name already exists, suggest continuing that change instead
- Pass --schema if using a non-default workflow
+138
View File
@@ -0,0 +1,138 @@
---
name: openspec-sync-specs
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**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 changes that have delta specs (under `specs/` directory).
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **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)
If no delta specs found, inform user and stop.
3. **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 requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in 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 main spec
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
d. **Create new main spec** if capability doesn't exist yet:
- Create `openspec/specs/<capability>/spec.md`
- Add Purpose section (can be brief, mark as TBD)
- Add Requirements section with the ADDED requirements
4. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
**Delta Spec Format Reference**
```markdown
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**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
**Output On Success**
```
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result
@@ -0,0 +1,168 @@
---
name: openspec-verify-change
description: Verify implementation matches change artifacts. Use when the user wants to validate that implementation is complete, correct, and coherent before archiving.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Verify that an implementation matches the change artifacts (specs, tasks, design).
**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 changes that have implementation tasks (tasks artifact exists).
Include the schema used for each change if available.
Mark changes with incomplete tasks as "(In Progress)".
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
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 artifacts exist for this change
3. **Get the change directory and load artifacts**
```bash
openspec instructions apply --change "<name>" --json
```
This returns the change directory and context files. Read all available artifacts from `contextFiles`.
4. **Initialize verification report structure**
Create a report structure with three dimensions:
- **Completeness**: Track tasks and spec coverage
- **Correctness**: Track requirement implementation and scenario coverage
- **Coherence**: Track design adherence and pattern consistency
Each dimension can have CRITICAL, WARNING, or SUGGESTION issues.
5. **Verify Completeness**
**Task Completion**:
- If tasks.md exists in contextFiles, read it
- Parse checkboxes: `- [ ]` (incomplete) vs `- [x]` (complete)
- Count complete vs total tasks
- If incomplete tasks exist:
- Add CRITICAL issue for each incomplete task
- Recommendation: "Complete task: <description>" or "Mark as done if already implemented"
**Spec Coverage**:
- If delta specs exist in `openspec/changes/<name>/specs/`:
- Extract all requirements (marked with "### Requirement:")
- For each requirement:
- Search codebase for keywords related to the requirement
- Assess if implementation likely exists
- If requirements appear unimplemented:
- Add CRITICAL issue: "Requirement not found: <requirement name>"
- Recommendation: "Implement requirement X: <description>"
6. **Verify Correctness**
**Requirement Implementation Mapping**:
- For each requirement from delta specs:
- Search codebase for implementation evidence
- If found, note file paths and line ranges
- Assess if implementation matches requirement intent
- If divergence detected:
- Add WARNING: "Implementation may diverge from spec: <details>"
- Recommendation: "Review <file>:<lines> against requirement X"
**Scenario Coverage**:
- For each scenario in delta specs (marked with "#### Scenario:"):
- Check if conditions are handled in code
- Check if tests exist covering the scenario
- If scenario appears uncovered:
- Add WARNING: "Scenario not covered: <scenario name>"
- Recommendation: "Add test or implementation for scenario: <description>"
7. **Verify Coherence**
**Design Adherence**:
- If design.md exists in contextFiles:
- Extract key decisions (look for sections like "Decision:", "Approach:", "Architecture:")
- Verify implementation follows those decisions
- If contradiction detected:
- Add WARNING: "Design decision not followed: <decision>"
- Recommendation: "Update implementation or revise design.md to match reality"
- If no design.md: Skip design adherence check, note "No design.md to verify against"
**Code Pattern Consistency**:
- Review new code for consistency with project patterns
- Check file naming, directory structure, coding style
- If significant deviations found:
- Add SUGGESTION: "Code pattern deviation: <details>"
- Recommendation: "Consider following project pattern: <example>"
8. **Generate Verification Report**
**Summary Scorecard**:
```
## Verification Report: <change-name>
### Summary
| Dimension | Status |
|--------------|------------------|
| Completeness | X/Y tasks, N reqs|
| Correctness | M/N reqs covered |
| Coherence | Followed/Issues |
```
**Issues by Priority**:
1. **CRITICAL** (Must fix before archive):
- Incomplete tasks
- Missing requirement implementations
- Each with specific, actionable recommendation
2. **WARNING** (Should fix):
- Spec/design divergences
- Missing scenario coverage
- Each with specific recommendation
3. **SUGGESTION** (Nice to fix):
- Pattern inconsistencies
- Minor improvements
- Each with specific recommendation
**Final Assessment**:
- If CRITICAL issues: "X critical issue(s) found. Fix before archiving."
- If only warnings: "No critical issues. Y warning(s) to consider. Ready for archive (with noted improvements)."
- If all clear: "All checks passed. Ready for archive."
**Verification Heuristics**
- **Completeness**: Focus on objective checklist items (checkboxes, requirements list)
- **Correctness**: Use keyword search, file path analysis, reasonable inference - don't require perfect certainty
- **Coherence**: Look for glaring inconsistencies, don't nitpick style
- **False Positives**: When uncertain, prefer SUGGESTION over WARNING, WARNING over CRITICAL
- **Actionability**: Every issue must have a specific recommendation with file/line references where applicable
**Graceful Degradation**
- If only tasks.md exists: verify task completion only, skip spec/design checks
- If tasks + specs exist: verify completeness and correctness, skip design
- If full artifacts: verify all three dimensions
- Always note which checks were skipped and why
**Output Format**
Use clear markdown with:
- Table for summary scorecard
- Grouped lists for issues (CRITICAL/WARNING/SUGGESTION)
- Code references in format: `file.ts:123`
- Specific, actionable recommendations
- No vague suggestions like "consider reviewing"
+20
View File
@@ -0,0 +1,20 @@
---
trigger: always_on
---
## Planka Sync
**IMPORTANT**
After completing any opsx workflow (/opsx:new, /opsx:ff, /opsx:continue,
/opsx:apply, /opsx:verify, /opsx:archive, /opsx:bulk-archive), automatically
reconcile Planka board state by running the sync script:
```bash
PROJECT_NAME=$(yq -r '.planka.project' project.yaml)
BOARD_NAME=$(yq -r '.planka.board' project.yaml)
kanban-project-sync --project "$PROJECT_NAME" --board "$BOARD_NAME" --background
```
The script handles concurrency (flock-based locking with coalescing pending queue).
If the script is not on PATH or fails, log a brief warning and continue.
Never block or retry — Planka sync is best-effort.
+56 -3
View File
@@ -1,5 +1,5 @@
--- ---
name: kanban name: planka-skill
description: Manage Planka project boards using the pcli CLI. Use when the user wants to interact with Planka boards, cards, lists, tasks, labels, or comments. description: Manage Planka project boards using the pcli CLI. Use when the user wants to interact with Planka boards, cards, lists, tasks, labels, or comments.
compatibility: Requires pcli binary in PATH and PLANKA_URL + PLANKA_API_KEY environment variables set compatibility: Requires pcli binary in PATH and PLANKA_URL + PLANKA_API_KEY environment variables set
metadata: metadata:
@@ -19,11 +19,11 @@ export PLANKA_URL="https://planka.example.com"
export PLANKA_API_KEY="your-api-key" export PLANKA_API_KEY="your-api-key"
``` ```
Ensure `jq` and `pcli` are installed and in the path. Ensure `jq` is installed.
## Global Flags ## Global Flags
All commands accept: `--format json|table`, `--url <url>`, `--api-key <key>`, `--log-level debug|info|warn|error` All commands (apart from import/export) accept: `--format json|table`, `--url <url>`, `--api-key <key>`, `--log-level debug|info|warn|error`
## Commands ## Commands
@@ -40,14 +40,38 @@ Returns summary of all boards, lists, and card counts (open/closed per list).
```bash ```bash
pcli project list pcli project list
pcli project get <project-id> pcli project get <project-id>
pcli project create --name "Name" --type private # type: private or shared
pcli project delete <project-id>
# Export/Import
pcli project export <project-id-or-name> [--board <name-or-id>] > backup.json
pcli project import --file backup.json
pcli project import < backup.json
``` ```
Export outputs a portable JSON file (names, not IDs). Import creates all resources with fresh IDs.
Import fails if the project+board name combination already exists on the target.
Comments are exported with `(Original comment by <username>)` prefix for attribution.
**Note:** Export outputs its own envelope format (`{version, exportedAt, project}`) directly — not the standard `{data, error}` envelope. Import progress and errors go to stderr.
### Boards ### Boards
```bash ```bash
pcli board list pcli board list
pcli board get <board-id> # includes lists and cards pcli board get <board-id> # includes lists and cards
pcli board actions <board-id> [--limit N] pcli board actions <board-id> [--limit N]
pcli board create --project <project-id> --name "Board Name" [--position N]
pcli board delete <board-id>
```
### Lists (Board Columns)
```bash
pcli list create --board <board-id> --name "Column Name" [--type active|closed] [--position N]
pcli list get <list-id>
pcli list update <list-id> [--name "..."] [--type active|closed] [--color "..."] [--position N] [--board <board-id>]
pcli list delete <list-id>
``` ```
### Cards ### Cards
@@ -125,6 +149,22 @@ pcli card list --board <id> | jq -r '.data[].id'
## Common Workflows ## Common Workflows
### Create a complete Kanban board
```bash
# Create board
BOARD_ID=$(pcli board create --project <project-id> --name "Development Board" | jq -r '.data.id')
# Create columns
pcli list create --board $BOARD_ID --name "Backlog" --type "active" --position 0
TODO_ID=$(pcli list create --board $BOARD_ID --name "To Do" --type "active" --position 65536 | jq -r '.data.id')
PROGRESS_ID=$(pcli list create --board $BOARD_ID --name "In Progress" --type "active" --position 131072 | jq -r '.data.id')
DONE_ID=$(pcli list create --board $BOARD_ID --name "Done" --type "closed" --position 196608 | jq -r '.data.id')
# View the board
pcli board get $BOARD_ID --format table
```
### Create a card with a checklist ### Create a card with a checklist
```bash ```bash
@@ -141,3 +181,16 @@ pcli card list --list <source-list-id> | jq -r '.data[].id' | while read id; do
pcli card move $id --list <target-list-id> pcli card move $id --list <target-list-id>
done done
``` ```
### Export and import a project
```bash
# Export entire project
pcli project export "My Project" > project-backup.json
# Export single board
pcli project export "My Project" --board "Sprint Board" > board-backup.json
# Import to another instance (or same instance if project+board combo doesn't exist)
pcli project import --file project-backup.json
```
@@ -6,7 +6,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.1.1" generatedBy: "1.2.0"
--- ---
Implement tasks from an OpenSpec change. Implement tasks from an OpenSpec change.
@@ -6,7 +6,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.1.1" generatedBy: "1.2.0"
--- ---
Archive a completed change in the experimental workflow. Archive a completed change in the experimental workflow.
@@ -63,7 +63,7 @@ Archive a completed change in the experimental workflow.
- If changes needed: "Sync now (recommended)", "Archive without syncing" - If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel" - If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, execute /opsx:sync logic (use the openspec-sync-specs skill). Proceed to archive regardless of choice. 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** 5. **Perform the archive**
@@ -1,246 +0,0 @@
---
name: openspec-bulk-archive-change
description: Archive multiple completed changes at once. Use when archiving several parallel changes.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.1.1"
---
Archive multiple completed changes in a single operation.
This skill allows you to batch-archive changes, handling spec conflicts intelligently by checking the codebase to determine what's actually implemented.
**Input**: None required (prompts for selection)
**Steps**
1. **Get active changes**
Run `openspec list --json` to get all active changes.
If no active changes exist, inform user and stop.
2. **Prompt for change selection**
Use **AskUserQuestion tool** with multi-select to let user choose changes:
- Show each change with its schema
- Include an option for "All changes"
- Allow any number of selections (1+ works, 2+ is the typical use case)
**IMPORTANT**: Do NOT auto-select. Always let the user choose.
3. **Batch validation - gather status for all selected changes**
For each selected change, collect:
a. **Artifact status** - Run `openspec status --change "<name>" --json`
- Parse `schemaName` and `artifacts` list
- Note which artifacts are `done` vs other states
b. **Task completion** - Read `openspec/changes/<name>/tasks.md`
- Count `- [ ]` (incomplete) vs `- [x]` (complete)
- If no tasks file exists, note as "No tasks"
c. **Delta specs** - Check `openspec/changes/<name>/specs/` directory
- List which capability specs exist
- For each, extract requirement names (lines matching `### Requirement: <name>`)
4. **Detect spec conflicts**
Build a map of `capability -> [changes that touch it]`:
```
auth -> [change-a, change-b] <- CONFLICT (2+ changes)
api -> [change-c] <- OK (only 1 change)
```
A conflict exists when 2+ selected changes have delta specs for the same capability.
5. **Resolve conflicts agentically**
**For each conflict**, investigate the codebase:
a. **Read the delta specs** from each conflicting change to understand what each claims to add/modify
b. **Search the codebase** for implementation evidence:
- Look for code implementing requirements from each delta spec
- Check for related files, functions, or tests
c. **Determine resolution**:
- If only one change is actually implemented -> sync that one's specs
- If both implemented -> apply in chronological order (older first, newer overwrites)
- If neither implemented -> skip spec sync, warn user
d. **Record resolution** for each conflict:
- Which change's specs to apply
- In what order (if both)
- Rationale (what was found in codebase)
6. **Show consolidated status table**
Display a table summarizing all changes:
```
| Change | Artifacts | Tasks | Specs | Conflicts | Status |
|---------------------|-----------|-------|---------|-----------|--------|
| schema-management | Done | 5/5 | 2 delta | None | Ready |
| project-config | Done | 3/3 | 1 delta | None | Ready |
| add-oauth | Done | 4/4 | 1 delta | auth (!) | Ready* |
| add-verify-skill | 1 left | 2/5 | None | None | Warn |
```
For conflicts, show the resolution:
```
* Conflict resolution:
- auth spec: Will apply add-oauth then add-jwt (both implemented, chronological order)
```
For incomplete changes, show warnings:
```
Warnings:
- add-verify-skill: 1 incomplete artifact, 3 incomplete tasks
```
7. **Confirm batch operation**
Use **AskUserQuestion tool** with a single confirmation:
- "Archive N changes?" with options based on status
- Options might include:
- "Archive all N changes"
- "Archive only N ready changes (skip incomplete)"
- "Cancel"
If there are incomplete changes, make clear they'll be archived with warnings.
8. **Execute archive for each confirmed change**
Process changes in the determined order (respecting conflict resolution):
a. **Sync specs** if delta specs exist:
- Use the openspec-sync-specs approach (agent-driven intelligent merge)
- For conflicts, apply in resolved order
- Track if sync was done
b. **Perform the archive**:
```bash
mkdir -p openspec/changes/archive
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
c. **Track outcome** for each change:
- Success: archived successfully
- Failed: error during archive (record error)
- Skipped: user chose not to archive (if applicable)
9. **Display summary**
Show final results:
```
## Bulk Archive Complete
Archived 3 changes:
- schema-management-cli -> archive/2026-01-19-schema-management-cli/
- project-config -> archive/2026-01-19-project-config/
- add-oauth -> archive/2026-01-19-add-oauth/
Skipped 1 change:
- add-verify-skill (user chose not to archive incomplete)
Spec sync summary:
- 4 delta specs synced to main specs
- 1 conflict resolved (auth: applied both in chronological order)
```
If any failures:
```
Failed 1 change:
- some-change: Archive directory already exists
```
**Conflict Resolution Examples**
Example 1: Only one implemented
```
Conflict: specs/auth/spec.md touched by [add-oauth, add-jwt]
Checking add-oauth:
- Delta adds "OAuth Provider Integration" requirement
- Searching codebase... found src/auth/oauth.ts implementing OAuth flow
Checking add-jwt:
- Delta adds "JWT Token Handling" requirement
- Searching codebase... no JWT implementation found
Resolution: Only add-oauth is implemented. Will sync add-oauth specs only.
```
Example 2: Both implemented
```
Conflict: specs/api/spec.md touched by [add-rest-api, add-graphql]
Checking add-rest-api (created 2026-01-10):
- Delta adds "REST Endpoints" requirement
- Searching codebase... found src/api/rest.ts
Checking add-graphql (created 2026-01-15):
- Delta adds "GraphQL Schema" requirement
- Searching codebase... found src/api/graphql.ts
Resolution: Both implemented. Will apply add-rest-api specs first,
then add-graphql specs (chronological order, newer takes precedence).
```
**Output On Success**
```
## Bulk Archive Complete
Archived N changes:
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
- <change-2> -> archive/YYYY-MM-DD-<change-2>/
Spec sync summary:
- N delta specs synced to main specs
- No conflicts (or: M conflicts resolved)
```
**Output On Partial Success**
```
## Bulk Archive Complete (partial)
Archived N changes:
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
Skipped M changes:
- <change-2> (user chose not to archive incomplete)
Failed K changes:
- <change-3>: Archive directory already exists
```
**Output When No Changes**
```
## No Changes to Archive
No active changes found. Use `/opsx:new` to create a new change.
```
**Guardrails**
- Allow any number of changes (1+ is fine, 2+ is the typical use case)
- Always prompt for selection, never auto-select
- Detect spec conflicts early and resolve by checking codebase
- When both changes are implemented, apply specs in chronological order
- Skip spec sync only when implementation is missing (warn user)
- Show clear per-change status before confirming
- Use single confirmation for entire batch
- Track and report all outcomes (success/skip/fail)
- Preserve .openspec.yaml when moving to archive
- Archive directory target uses current date: YYYY-MM-DD-<name>
- If archive target exists, fail that change but continue with others
@@ -6,7 +6,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.1.1" generatedBy: "1.2.0"
--- ---
Continue working on a change by creating the next artifact. Continue working on a change by creating the next artifact.
+5 -7
View File
@@ -6,12 +6,12 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.1.1" generatedBy: "1.2.0"
--- ---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes. 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 (e.g., start a change with `/opsx:new` or `/opsx:ff`). You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing. **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. **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.
@@ -95,8 +95,7 @@ This tells you:
Think freely. When insights crystallize, you might offer: Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create one?" - "This feels solid enough to start a change. Want me to create a proposal?"
→ Can transition to `/opsx:new` or `/opsx:ff`
- Or keep exploring - no pressure to formalize - Or keep exploring - no pressure to formalize
### When a change exists ### When a change exists
@@ -252,7 +251,7 @@ You: That changes everything.
There's no required ending. Discovery might: There's no required ending. Discovery might:
- **Flow into action**: "Ready to start? /opsx:new or /opsx:ff" - **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions" - **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on - **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime" - **Continue later**: "We can pick this up anytime"
@@ -269,8 +268,7 @@ When it feels like things are crystallizing, you might summarize:
**Open questions**: [if any remain] **Open questions**: [if any remain]
**Next steps** (if ready): **Next steps** (if ready):
- Create a change: /opsx:new <name> - Create a change proposal
- Fast-forward to tasks: /opsx:ff <name>
- Keep exploring: just keep talking - Keep exploring: just keep talking
``` ```
+1 -1
View File
@@ -6,7 +6,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.1.1" generatedBy: "1.2.0"
--- ---
Fast-forward through artifact creation - generate everything needed to start implementation in one go. Fast-forward through artifact creation - generate everything needed to start implementation in one go.
@@ -6,7 +6,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.1.1" generatedBy: "1.2.0"
--- ---
Start a new change using the experimental artifact-driven approach. Start a new change using the experimental artifact-driven approach.
-529
View File
@@ -1,529 +0,0 @@
---
name: openspec-onboard
description: Guided onboarding for OpenSpec - walk through a complete workflow cycle with narration and real codebase work.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.1.1"
---
Guide the user through their first complete OpenSpec workflow cycle. This is a teaching experience—you'll do real work in their codebase while explaining each step.
---
## Preflight
Before starting, check if OpenSpec is initialized:
```bash
openspec status --json 2>&1 || echo "NOT_INITIALIZED"
```
**If not initialized:**
> OpenSpec isn't set up in this project yet. Run `openspec init` first, then come back to `/opsx:onboard`.
Stop here if not initialized.
---
## Phase 1: Welcome
Display:
```
## Welcome to OpenSpec!
I'll walk you through a complete change cycle—from idea to implementation—using a real task in your codebase. Along the way, you'll learn the workflow by doing it.
**What we'll do:**
1. Pick a small, real task in your codebase
2. Explore the problem briefly
3. Create a change (the container for our work)
4. Build the artifacts: proposal → specs → design → tasks
5. Implement the tasks
6. Archive the completed change
**Time:** ~15-20 minutes
Let's start by finding something to work on.
```
---
## Phase 2: Task Selection
### Codebase Analysis
Scan the codebase for small improvement opportunities. Look for:
1. **TODO/FIXME comments** - Search for `TODO`, `FIXME`, `HACK`, `XXX` in code files
2. **Missing error handling** - `catch` blocks that swallow errors, risky operations without try-catch
3. **Functions without tests** - Cross-reference `src/` with test directories
4. **Type issues** - `any` types in TypeScript files (`: any`, `as any`)
5. **Debug artifacts** - `console.log`, `console.debug`, `debugger` statements in non-debug code
6. **Missing validation** - User input handlers without validation
Also check recent git activity:
```bash
git log --oneline -10 2>/dev/null || echo "No git history"
```
### Present Suggestions
From your analysis, present 3-4 specific suggestions:
```
## Task Suggestions
Based on scanning your codebase, here are some good starter tasks:
**1. [Most promising task]**
Location: `src/path/to/file.ts:42`
Scope: ~1-2 files, ~20-30 lines
Why it's good: [brief reason]
**2. [Second task]**
Location: `src/another/file.ts`
Scope: ~1 file, ~15 lines
Why it's good: [brief reason]
**3. [Third task]**
Location: [location]
Scope: [estimate]
Why it's good: [brief reason]
**4. Something else?**
Tell me what you'd like to work on.
Which task interests you? (Pick a number or describe your own)
```
**If nothing found:** Fall back to asking what the user wants to build:
> I didn't find obvious quick wins in your codebase. What's something small you've been meaning to add or fix?
### Scope Guardrail
If the user picks or describes something too large (major feature, multi-day work):
```
That's a valuable task, but it's probably larger than ideal for your first OpenSpec run-through.
For learning the workflow, smaller is better—it lets you see the full cycle without getting stuck in implementation details.
**Options:**
1. **Slice it smaller** - What's the smallest useful piece of [their task]? Maybe just [specific slice]?
2. **Pick something else** - One of the other suggestions, or a different small task?
3. **Do it anyway** - If you really want to tackle this, we can. Just know it'll take longer.
What would you prefer?
```
Let the user override if they insist—this is a soft guardrail.
---
## Phase 3: Explore Demo
Once a task is selected, briefly demonstrate explore mode:
```
Before we create a change, let me quickly show you **explore mode**—it's how you think through problems before committing to a direction.
```
Spend 1-2 minutes investigating the relevant code:
- Read the file(s) involved
- Draw a quick ASCII diagram if it helps
- Note any considerations
```
## Quick Exploration
[Your brief analysis—what you found, any considerations]
┌─────────────────────────────────────────┐
│ [Optional: ASCII diagram if helpful] │
└─────────────────────────────────────────┘
Explore mode (`/opsx:explore`) is for this kind of thinking—investigating before implementing. You can use it anytime you need to think through a problem.
Now let's create a change to hold our work.
```
**PAUSE** - Wait for user acknowledgment before proceeding.
---
## Phase 4: Create the Change
**EXPLAIN:**
```
## Creating a Change
A "change" in OpenSpec is a container for all the thinking and planning around a piece of work. It lives in `openspec/changes/<name>/` and holds your artifacts—proposal, specs, design, tasks.
Let me create one for our task.
```
**DO:** Create the change with a derived kebab-case name:
```bash
openspec new change "<derived-name>"
```
**SHOW:**
```
Created: `openspec/changes/<name>/`
The folder structure:
```
openspec/changes/<name>/
├── proposal.md ← Why we're doing this (empty, we'll fill it)
├── design.md ← How we'll build it (empty)
├── specs/ ← Detailed requirements (empty)
└── tasks.md ← Implementation checklist (empty)
```
Now let's fill in the first artifact—the proposal.
```
---
## Phase 5: Proposal
**EXPLAIN:**
```
## The Proposal
The proposal captures **why** we're making this change and **what** it involves at a high level. It's the "elevator pitch" for the work.
I'll draft one based on our task.
```
**DO:** Draft the proposal content (don't save yet):
```
Here's a draft proposal:
---
## Why
[1-2 sentences explaining the problem/opportunity]
## What Changes
[Bullet points of what will be different]
## Capabilities
### New Capabilities
- `<capability-name>`: [brief description]
### Modified Capabilities
<!-- If modifying existing behavior -->
## Impact
- `src/path/to/file.ts`: [what changes]
- [other files if applicable]
---
Does this capture the intent? I can adjust before we save it.
```
**PAUSE** - Wait for user approval/feedback.
After approval, save the proposal:
```bash
openspec instructions proposal --change "<name>" --json
```
Then write the content to `openspec/changes/<name>/proposal.md`.
```
Proposal saved. This is your "why" document—you can always come back and refine it as understanding evolves.
Next up: specs.
```
---
## Phase 6: Specs
**EXPLAIN:**
```
## Specs
Specs define **what** we're building in precise, testable terms. They use a requirement/scenario format that makes expected behavior crystal clear.
For a small task like this, we might only need one spec file.
```
**DO:** Create the spec file:
```bash
mkdir -p openspec/changes/<name>/specs/<capability-name>
```
Draft the spec content:
```
Here's the spec:
---
## ADDED Requirements
### Requirement: <Name>
<Description of what the system should do>
#### Scenario: <Scenario name>
- **WHEN** <trigger condition>
- **THEN** <expected outcome>
- **AND** <additional outcome if needed>
---
This format—WHEN/THEN/AND—makes requirements testable. You can literally read them as test cases.
```
Save to `openspec/changes/<name>/specs/<capability>/spec.md`.
---
## Phase 7: Design
**EXPLAIN:**
```
## Design
The design captures **how** we'll build it—technical decisions, tradeoffs, approach.
For small changes, this might be brief. That's fine—not every change needs deep design discussion.
```
**DO:** Draft design.md:
```
Here's the design:
---
## Context
[Brief context about the current state]
## Goals / Non-Goals
**Goals:**
- [What we're trying to achieve]
**Non-Goals:**
- [What's explicitly out of scope]
## Decisions
### Decision 1: [Key decision]
[Explanation of approach and rationale]
---
For a small task, this captures the key decisions without over-engineering.
```
Save to `openspec/changes/<name>/design.md`.
---
## Phase 8: Tasks
**EXPLAIN:**
```
## Tasks
Finally, we break the work into implementation tasks—checkboxes that drive the apply phase.
These should be small, clear, and in logical order.
```
**DO:** Generate tasks based on specs and design:
```
Here are the implementation tasks:
---
## 1. [Category or file]
- [ ] 1.1 [Specific task]
- [ ] 1.2 [Specific task]
## 2. Verify
- [ ] 2.1 [Verification step]
---
Each checkbox becomes a unit of work in the apply phase. Ready to implement?
```
**PAUSE** - Wait for user to confirm they're ready to implement.
Save to `openspec/changes/<name>/tasks.md`.
---
## Phase 9: Apply (Implementation)
**EXPLAIN:**
```
## Implementation
Now we implement each task, checking them off as we go. I'll announce each one and occasionally note how the specs/design informed the approach.
```
**DO:** For each task:
1. Announce: "Working on task N: [description]"
2. Implement the change in the codebase
3. Reference specs/design naturally: "The spec says X, so I'm doing Y"
4. Mark complete in tasks.md: `- [ ]``- [x]`
5. Brief status: "✓ Task N complete"
Keep narration light—don't over-explain every line of code.
After all tasks:
```
## Implementation Complete
All tasks done:
- [x] Task 1
- [x] Task 2
- [x] ...
The change is implemented! One more step—let's archive it.
```
---
## Phase 10: Archive
**EXPLAIN:**
```
## Archiving
When a change is complete, we archive it. This moves it from `openspec/changes/` to `openspec/changes/archive/YYYY-MM-DD-<name>/`.
Archived changes become your project's decision history—you can always find them later to understand why something was built a certain way.
```
**DO:**
```bash
openspec archive "<name>"
```
**SHOW:**
```
Archived to: `openspec/changes/archive/YYYY-MM-DD-<name>/`
The change is now part of your project's history. The code is in your codebase, the decision record is preserved.
```
---
## Phase 11: Recap & Next Steps
```
## Congratulations!
You just completed a full OpenSpec cycle:
1. **Explore** - Thought through the problem
2. **New** - Created a change container
3. **Proposal** - Captured WHY
4. **Specs** - Defined WHAT in detail
5. **Design** - Decided HOW
6. **Tasks** - Broke it into steps
7. **Apply** - Implemented the work
8. **Archive** - Preserved the record
This same rhythm works for any size change—a small fix or a major feature.
---
## Command Reference
| Command | What it does |
|---------|--------------|
| `/opsx:explore` | Think through problems before/during work |
| `/opsx:new` | Start a new change, step through artifacts |
| `/opsx:ff` | Fast-forward: create all artifacts at once |
| `/opsx:continue` | Continue working on an existing change |
| `/opsx:apply` | Implement tasks from a change |
| `/opsx:verify` | Verify implementation matches artifacts |
| `/opsx:archive` | Archive a completed change |
---
## What's Next?
Try `/opsx:new` or `/opsx:ff` on something you actually want to build. You've got the rhythm now!
```
---
## Graceful Exit Handling
### User wants to stop mid-way
If the user says they need to stop, want to pause, or seem disengaged:
```
No problem! Your change is saved at `openspec/changes/<name>/`.
To pick up where we left off later:
- `/opsx:continue <name>` - Resume artifact creation
- `/opsx:apply <name>` - Jump to implementation (if tasks exist)
The work won't be lost. Come back whenever you're ready.
```
Exit gracefully without pressure.
### User just wants command reference
If the user says they just want to see the commands or skip the tutorial:
```
## OpenSpec Quick Reference
| Command | What it does |
|---------|--------------|
| `/opsx:explore` | Think through problems (no code changes) |
| `/opsx:new <name>` | Start a new change, step by step |
| `/opsx:ff <name>` | Fast-forward: all artifacts at once |
| `/opsx:continue <name>` | Continue an existing change |
| `/opsx:apply <name>` | Implement tasks |
| `/opsx:verify <name>` | Verify implementation |
| `/opsx:archive <name>` | Archive when done |
Try `/opsx:new` to start your first change, or `/opsx:ff` if you want to move fast.
```
Exit gracefully.
---
## Guardrails
- **Follow the EXPLAIN → DO → SHOW → PAUSE pattern** at key transitions (after explore, after proposal draft, after tasks, after archive)
- **Keep narration light** during implementation—teach without lecturing
- **Don't skip phases** even if the change is small—the goal is teaching the workflow
- **Pause for acknowledgment** at marked points, but don't over-pause
- **Handle exits gracefully**—never pressure the user to continue
- **Use real codebase tasks**—don't simulate or use fake examples
- **Adjust scope gently**—guide toward smaller tasks but respect user choice
@@ -6,7 +6,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.1.1" generatedBy: "1.2.0"
--- ---
Sync delta specs from a change to main specs. Sync delta specs from a change to main specs.
@@ -6,7 +6,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.1.1" generatedBy: "1.2.0"
--- ---
Verify that an implementation matches the change artifacts (specs, tasks, design). Verify that an implementation matches the change artifacts (specs, tasks, design).
+45
View File
@@ -0,0 +1,45 @@
---
description: Reconcile Planka board state with OpenSpec changes
allowed-tools: Bash, Read
---
# Planka <-> OpenSpec Reconciliation Sync
Runs the `kanban-project-sync` script to reconcile Planka board state with OpenSpec changes.
## How It Works
The sync is handled by the `kanban-project-sync` bash script (on PATH). It:
1. Checks Planka connectivity
2. Bootstraps project/board/lists/label infrastructure (idempotent)
3. Reads OpenSpec state and maps changes to board lists
4. Creates/moves/updates Planka cards and task checklists
5. Moves orphaned cards to Done
**OpenSpec is the source of truth.** Planka is a read-only projection. Sync is one-directional (OpenSpec -> Planka) and idempotent.
## Running the Sync
Read project config and invoke the script in background mode:
```bash
PROJECT_NAME=$(yq -r '.planka.project' project.yaml)
BOARD_NAME=$(yq -r '.planka.board' project.yaml)
kanban-project-sync --project "$PROJECT_NAME" --board "$BOARD_NAME" --background
```
The `--background` flag makes the script fire-and-forget — it detaches and logs to `/tmp/kanban-project-sync-<project>-<board>.log`.
## Concurrency
The script handles its own concurrency:
- Uses `flock` to ensure only one sync runs per project-board pair
- If a sync is already running, sets a pending flag and exits immediately
- The running sync re-runs after completion if the pending flag is set
- Multiple pending requests coalesce into a single re-run
## Guardrails
- Sync is **best-effort** — if Planka is unreachable or the script fails, log a warning and continue
- Never block agentic work because of sync
- If `kanban-project-sync` is not on PATH, log a warning and skip
+2 -2
View File
@@ -59,7 +59,7 @@ Archive a completed change in the experimental workflow.
- If changes needed: "Sync now (recommended)", "Archive without syncing" - If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel" - If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, execute `/opsx:sync` logic. Proceed to archive regardless of choice. 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** 5. **Perform the archive**
@@ -153,5 +153,5 @@ Target archive directory already exists.
- Don't block archive on warnings - just inform and confirm - Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory) - Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened - Show clear summary of what happened
- If sync is requested, use /opsx:sync approach (agent-driven) - 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 - If delta specs exist, always run the sync assessment and show the combined summary before prompting
-242
View File
@@ -1,242 +0,0 @@
---
name: "OPSX: Bulk Archive"
description: Archive multiple completed changes at once
category: Workflow
tags: [workflow, archive, experimental, bulk]
---
Archive multiple completed changes in a single operation.
This skill allows you to batch-archive changes, handling spec conflicts intelligently by checking the codebase to determine what's actually implemented.
**Input**: None required (prompts for selection)
**Steps**
1. **Get active changes**
Run `openspec list --json` to get all active changes.
If no active changes exist, inform user and stop.
2. **Prompt for change selection**
Use **AskUserQuestion tool** with multi-select to let user choose changes:
- Show each change with its schema
- Include an option for "All changes"
- Allow any number of selections (1+ works, 2+ is the typical use case)
**IMPORTANT**: Do NOT auto-select. Always let the user choose.
3. **Batch validation - gather status for all selected changes**
For each selected change, collect:
a. **Artifact status** - Run `openspec status --change "<name>" --json`
- Parse `schemaName` and `artifacts` list
- Note which artifacts are `done` vs other states
b. **Task completion** - Read `openspec/changes/<name>/tasks.md`
- Count `- [ ]` (incomplete) vs `- [x]` (complete)
- If no tasks file exists, note as "No tasks"
c. **Delta specs** - Check `openspec/changes/<name>/specs/` directory
- List which capability specs exist
- For each, extract requirement names (lines matching `### Requirement: <name>`)
4. **Detect spec conflicts**
Build a map of `capability -> [changes that touch it]`:
```
auth -> [change-a, change-b] <- CONFLICT (2+ changes)
api -> [change-c] <- OK (only 1 change)
```
A conflict exists when 2+ selected changes have delta specs for the same capability.
5. **Resolve conflicts agentically**
**For each conflict**, investigate the codebase:
a. **Read the delta specs** from each conflicting change to understand what each claims to add/modify
b. **Search the codebase** for implementation evidence:
- Look for code implementing requirements from each delta spec
- Check for related files, functions, or tests
c. **Determine resolution**:
- If only one change is actually implemented -> sync that one's specs
- If both implemented -> apply in chronological order (older first, newer overwrites)
- If neither implemented -> skip spec sync, warn user
d. **Record resolution** for each conflict:
- Which change's specs to apply
- In what order (if both)
- Rationale (what was found in codebase)
6. **Show consolidated status table**
Display a table summarizing all changes:
```
| Change | Artifacts | Tasks | Specs | Conflicts | Status |
|---------------------|-----------|-------|---------|-----------|--------|
| schema-management | Done | 5/5 | 2 delta | None | Ready |
| project-config | Done | 3/3 | 1 delta | None | Ready |
| add-oauth | Done | 4/4 | 1 delta | auth (!) | Ready* |
| add-verify-skill | 1 left | 2/5 | None | None | Warn |
```
For conflicts, show the resolution:
```
* Conflict resolution:
- auth spec: Will apply add-oauth then add-jwt (both implemented, chronological order)
```
For incomplete changes, show warnings:
```
Warnings:
- add-verify-skill: 1 incomplete artifact, 3 incomplete tasks
```
7. **Confirm batch operation**
Use **AskUserQuestion tool** with a single confirmation:
- "Archive N changes?" with options based on status
- Options might include:
- "Archive all N changes"
- "Archive only N ready changes (skip incomplete)"
- "Cancel"
If there are incomplete changes, make clear they'll be archived with warnings.
8. **Execute archive for each confirmed change**
Process changes in the determined order (respecting conflict resolution):
a. **Sync specs** if delta specs exist:
- Use the openspec-sync-specs approach (agent-driven intelligent merge)
- For conflicts, apply in resolved order
- Track if sync was done
b. **Perform the archive**:
```bash
mkdir -p openspec/changes/archive
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
c. **Track outcome** for each change:
- Success: archived successfully
- Failed: error during archive (record error)
- Skipped: user chose not to archive (if applicable)
9. **Display summary**
Show final results:
```
## Bulk Archive Complete
Archived 3 changes:
- schema-management-cli -> archive/2026-01-19-schema-management-cli/
- project-config -> archive/2026-01-19-project-config/
- add-oauth -> archive/2026-01-19-add-oauth/
Skipped 1 change:
- add-verify-skill (user chose not to archive incomplete)
Spec sync summary:
- 4 delta specs synced to main specs
- 1 conflict resolved (auth: applied both in chronological order)
```
If any failures:
```
Failed 1 change:
- some-change: Archive directory already exists
```
**Conflict Resolution Examples**
Example 1: Only one implemented
```
Conflict: specs/auth/spec.md touched by [add-oauth, add-jwt]
Checking add-oauth:
- Delta adds "OAuth Provider Integration" requirement
- Searching codebase... found src/auth/oauth.ts implementing OAuth flow
Checking add-jwt:
- Delta adds "JWT Token Handling" requirement
- Searching codebase... no JWT implementation found
Resolution: Only add-oauth is implemented. Will sync add-oauth specs only.
```
Example 2: Both implemented
```
Conflict: specs/api/spec.md touched by [add-rest-api, add-graphql]
Checking add-rest-api (created 2026-01-10):
- Delta adds "REST Endpoints" requirement
- Searching codebase... found src/api/rest.ts
Checking add-graphql (created 2026-01-15):
- Delta adds "GraphQL Schema" requirement
- Searching codebase... found src/api/graphql.ts
Resolution: Both implemented. Will apply add-rest-api specs first,
then add-graphql specs (chronological order, newer takes precedence).
```
**Output On Success**
```
## Bulk Archive Complete
Archived N changes:
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
- <change-2> -> archive/YYYY-MM-DD-<change-2>/
Spec sync summary:
- N delta specs synced to main specs
- No conflicts (or: M conflicts resolved)
```
**Output On Partial Success**
```
## Bulk Archive Complete (partial)
Archived N changes:
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
Skipped M changes:
- <change-2> (user chose not to archive incomplete)
Failed K changes:
- <change-3>: Archive directory already exists
```
**Output When No Changes**
```
## No Changes to Archive
No active changes found. Use `/opsx:new` to create a new change.
```
**Guardrails**
- Allow any number of changes (1+ is fine, 2+ is the typical use case)
- Always prompt for selection, never auto-select
- Detect spec conflicts early and resolve by checking codebase
- When both changes are implemented, apply specs in chronological order
- Skip spec sync only when implementation is missing (warn user)
- Show clear per-change status before confirming
- Use single confirmation for entire batch
- Track and report all outcomes (success/skip/fail)
- Preserve .openspec.yaml when moving to archive
- Archive directory target uses current date: YYYY-MM-DD-<name>
- If archive target exists, fail that change but continue with others
+3 -4
View File
@@ -7,7 +7,7 @@ tags: [workflow, explore, experimental, thinking]
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes. 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 (e.g., start a change with `/opsx:new` or `/opsx:ff`). You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing. **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. **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.
@@ -100,8 +100,7 @@ If the user mentioned a specific change name, read its artifacts for context.
Think freely. When insights crystallize, you might offer: Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create one?" - "This feels solid enough to start a change. Want me to create a proposal?"
→ Can transition to `/opsx:new` or `/opsx:ff`
- Or keep exploring - no pressure to formalize - Or keep exploring - no pressure to formalize
### When a change exists ### When a change exists
@@ -153,7 +152,7 @@ If the user mentions a change or you detect one is relevant:
There's no required ending. Discovery might: There's no required ending. Discovery might:
- **Flow into action**: "Ready to start? `/opsx:new` or `/opsx:ff`" - **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions" - **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on - **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime" - **Continue later**: "We can pick this up anytime"
+4 -1
View File
@@ -84,7 +84,10 @@ After completing all artifacts, summarize:
- Follow the `instruction` field from `openspec instructions` for each artifact type - Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it - The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones - Read dependency artifacts for context before creating new ones
- Use the `template` as a starting point, filling in based on context - 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** **Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`) - Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
-525
View File
@@ -1,525 +0,0 @@
---
name: "OPSX: Onboard"
description: Guided onboarding - walk through a complete OpenSpec workflow cycle with narration
category: Workflow
tags: [workflow, onboarding, tutorial, learning]
---
Guide the user through their first complete OpenSpec workflow cycle. This is a teaching experience—you'll do real work in their codebase while explaining each step.
---
## Preflight
Before starting, check if OpenSpec is initialized:
```bash
openspec status --json 2>&1 || echo "NOT_INITIALIZED"
```
**If not initialized:**
> OpenSpec isn't set up in this project yet. Run `openspec init` first, then come back to `/opsx:onboard`.
Stop here if not initialized.
---
## Phase 1: Welcome
Display:
```
## Welcome to OpenSpec!
I'll walk you through a complete change cycle—from idea to implementation—using a real task in your codebase. Along the way, you'll learn the workflow by doing it.
**What we'll do:**
1. Pick a small, real task in your codebase
2. Explore the problem briefly
3. Create a change (the container for our work)
4. Build the artifacts: proposal → specs → design → tasks
5. Implement the tasks
6. Archive the completed change
**Time:** ~15-20 minutes
Let's start by finding something to work on.
```
---
## Phase 2: Task Selection
### Codebase Analysis
Scan the codebase for small improvement opportunities. Look for:
1. **TODO/FIXME comments** - Search for `TODO`, `FIXME`, `HACK`, `XXX` in code files
2. **Missing error handling** - `catch` blocks that swallow errors, risky operations without try-catch
3. **Functions without tests** - Cross-reference `src/` with test directories
4. **Type issues** - `any` types in TypeScript files (`: any`, `as any`)
5. **Debug artifacts** - `console.log`, `console.debug`, `debugger` statements in non-debug code
6. **Missing validation** - User input handlers without validation
Also check recent git activity:
```bash
git log --oneline -10 2>/dev/null || echo "No git history"
```
### Present Suggestions
From your analysis, present 3-4 specific suggestions:
```
## Task Suggestions
Based on scanning your codebase, here are some good starter tasks:
**1. [Most promising task]**
Location: `src/path/to/file.ts:42`
Scope: ~1-2 files, ~20-30 lines
Why it's good: [brief reason]
**2. [Second task]**
Location: `src/another/file.ts`
Scope: ~1 file, ~15 lines
Why it's good: [brief reason]
**3. [Third task]**
Location: [location]
Scope: [estimate]
Why it's good: [brief reason]
**4. Something else?**
Tell me what you'd like to work on.
Which task interests you? (Pick a number or describe your own)
```
**If nothing found:** Fall back to asking what the user wants to build:
> I didn't find obvious quick wins in your codebase. What's something small you've been meaning to add or fix?
### Scope Guardrail
If the user picks or describes something too large (major feature, multi-day work):
```
That's a valuable task, but it's probably larger than ideal for your first OpenSpec run-through.
For learning the workflow, smaller is better—it lets you see the full cycle without getting stuck in implementation details.
**Options:**
1. **Slice it smaller** - What's the smallest useful piece of [their task]? Maybe just [specific slice]?
2. **Pick something else** - One of the other suggestions, or a different small task?
3. **Do it anyway** - If you really want to tackle this, we can. Just know it'll take longer.
What would you prefer?
```
Let the user override if they insist—this is a soft guardrail.
---
## Phase 3: Explore Demo
Once a task is selected, briefly demonstrate explore mode:
```
Before we create a change, let me quickly show you **explore mode**—it's how you think through problems before committing to a direction.
```
Spend 1-2 minutes investigating the relevant code:
- Read the file(s) involved
- Draw a quick ASCII diagram if it helps
- Note any considerations
```
## Quick Exploration
[Your brief analysis—what you found, any considerations]
┌─────────────────────────────────────────┐
│ [Optional: ASCII diagram if helpful] │
└─────────────────────────────────────────┘
Explore mode (`/opsx:explore`) is for this kind of thinking—investigating before implementing. You can use it anytime you need to think through a problem.
Now let's create a change to hold our work.
```
**PAUSE** - Wait for user acknowledgment before proceeding.
---
## Phase 4: Create the Change
**EXPLAIN:**
```
## Creating a Change
A "change" in OpenSpec is a container for all the thinking and planning around a piece of work. It lives in `openspec/changes/<name>/` and holds your artifacts—proposal, specs, design, tasks.
Let me create one for our task.
```
**DO:** Create the change with a derived kebab-case name:
```bash
openspec new change "<derived-name>"
```
**SHOW:**
```
Created: `openspec/changes/<name>/`
The folder structure:
```
openspec/changes/<name>/
├── proposal.md ← Why we're doing this (empty, we'll fill it)
├── design.md ← How we'll build it (empty)
├── specs/ ← Detailed requirements (empty)
└── tasks.md ← Implementation checklist (empty)
```
Now let's fill in the first artifact—the proposal.
```
---
## Phase 5: Proposal
**EXPLAIN:**
```
## The Proposal
The proposal captures **why** we're making this change and **what** it involves at a high level. It's the "elevator pitch" for the work.
I'll draft one based on our task.
```
**DO:** Draft the proposal content (don't save yet):
```
Here's a draft proposal:
---
## Why
[1-2 sentences explaining the problem/opportunity]
## What Changes
[Bullet points of what will be different]
## Capabilities
### New Capabilities
- `<capability-name>`: [brief description]
### Modified Capabilities
<!-- If modifying existing behavior -->
## Impact
- `src/path/to/file.ts`: [what changes]
- [other files if applicable]
---
Does this capture the intent? I can adjust before we save it.
```
**PAUSE** - Wait for user approval/feedback.
After approval, save the proposal:
```bash
openspec instructions proposal --change "<name>" --json
```
Then write the content to `openspec/changes/<name>/proposal.md`.
```
Proposal saved. This is your "why" document—you can always come back and refine it as understanding evolves.
Next up: specs.
```
---
## Phase 6: Specs
**EXPLAIN:**
```
## Specs
Specs define **what** we're building in precise, testable terms. They use a requirement/scenario format that makes expected behavior crystal clear.
For a small task like this, we might only need one spec file.
```
**DO:** Create the spec file:
```bash
mkdir -p openspec/changes/<name>/specs/<capability-name>
```
Draft the spec content:
```
Here's the spec:
---
## ADDED Requirements
### Requirement: <Name>
<Description of what the system should do>
#### Scenario: <Scenario name>
- **WHEN** <trigger condition>
- **THEN** <expected outcome>
- **AND** <additional outcome if needed>
---
This format—WHEN/THEN/AND—makes requirements testable. You can literally read them as test cases.
```
Save to `openspec/changes/<name>/specs/<capability>/spec.md`.
---
## Phase 7: Design
**EXPLAIN:**
```
## Design
The design captures **how** we'll build it—technical decisions, tradeoffs, approach.
For small changes, this might be brief. That's fine—not every change needs deep design discussion.
```
**DO:** Draft design.md:
```
Here's the design:
---
## Context
[Brief context about the current state]
## Goals / Non-Goals
**Goals:**
- [What we're trying to achieve]
**Non-Goals:**
- [What's explicitly out of scope]
## Decisions
### Decision 1: [Key decision]
[Explanation of approach and rationale]
---
For a small task, this captures the key decisions without over-engineering.
```
Save to `openspec/changes/<name>/design.md`.
---
## Phase 8: Tasks
**EXPLAIN:**
```
## Tasks
Finally, we break the work into implementation tasks—checkboxes that drive the apply phase.
These should be small, clear, and in logical order.
```
**DO:** Generate tasks based on specs and design:
```
Here are the implementation tasks:
---
## 1. [Category or file]
- [ ] 1.1 [Specific task]
- [ ] 1.2 [Specific task]
## 2. Verify
- [ ] 2.1 [Verification step]
---
Each checkbox becomes a unit of work in the apply phase. Ready to implement?
```
**PAUSE** - Wait for user to confirm they're ready to implement.
Save to `openspec/changes/<name>/tasks.md`.
---
## Phase 9: Apply (Implementation)
**EXPLAIN:**
```
## Implementation
Now we implement each task, checking them off as we go. I'll announce each one and occasionally note how the specs/design informed the approach.
```
**DO:** For each task:
1. Announce: "Working on task N: [description]"
2. Implement the change in the codebase
3. Reference specs/design naturally: "The spec says X, so I'm doing Y"
4. Mark complete in tasks.md: `- [ ]``- [x]`
5. Brief status: "✓ Task N complete"
Keep narration light—don't over-explain every line of code.
After all tasks:
```
## Implementation Complete
All tasks done:
- [x] Task 1
- [x] Task 2
- [x] ...
The change is implemented! One more step—let's archive it.
```
---
## Phase 10: Archive
**EXPLAIN:**
```
## Archiving
When a change is complete, we archive it. This moves it from `openspec/changes/` to `openspec/changes/archive/YYYY-MM-DD-<name>/`.
Archived changes become your project's decision history—you can always find them later to understand why something was built a certain way.
```
**DO:**
```bash
openspec archive "<name>"
```
**SHOW:**
```
Archived to: `openspec/changes/archive/YYYY-MM-DD-<name>/`
The change is now part of your project's history. The code is in your codebase, the decision record is preserved.
```
---
## Phase 11: Recap & Next Steps
```
## Congratulations!
You just completed a full OpenSpec cycle:
1. **Explore** - Thought through the problem
2. **New** - Created a change container
3. **Proposal** - Captured WHY
4. **Specs** - Defined WHAT in detail
5. **Design** - Decided HOW
6. **Tasks** - Broke it into steps
7. **Apply** - Implemented the work
8. **Archive** - Preserved the record
This same rhythm works for any size change—a small fix or a major feature.
---
## Command Reference
| Command | What it does |
|---------|--------------|
| `/opsx:explore` | Think through problems before/during work |
| `/opsx:new` | Start a new change, step through artifacts |
| `/opsx:ff` | Fast-forward: create all artifacts at once |
| `/opsx:continue` | Continue working on an existing change |
| `/opsx:apply` | Implement tasks from a change |
| `/opsx:verify` | Verify implementation matches artifacts |
| `/opsx:archive` | Archive a completed change |
---
## What's Next?
Try `/opsx:new` or `/opsx:ff` on something you actually want to build. You've got the rhythm now!
```
---
## Graceful Exit Handling
### User wants to stop mid-way
If the user says they need to stop, want to pause, or seem disengaged:
```
No problem! Your change is saved at `openspec/changes/<name>/`.
To pick up where we left off later:
- `/opsx:continue <name>` - Resume artifact creation
- `/opsx:apply <name>` - Jump to implementation (if tasks exist)
The work won't be lost. Come back whenever you're ready.
```
Exit gracefully without pressure.
### User just wants command reference
If the user says they just want to see the commands or skip the tutorial:
```
## OpenSpec Quick Reference
| Command | What it does |
|---------|--------------|
| `/opsx:explore` | Think through problems (no code changes) |
| `/opsx:new <name>` | Start a new change, step by step |
| `/opsx:ff <name>` | Fast-forward: all artifacts at once |
| `/opsx:continue <name>` | Continue an existing change |
| `/opsx:apply <name>` | Implement tasks |
| `/opsx:verify <name>` | Verify implementation |
| `/opsx:archive <name>` | Archive when done |
Try `/opsx:new` to start your first change, or `/opsx:ff` if you want to move fast.
```
Exit gracefully.
---
## Guardrails
- **Follow the EXPLAIN → DO → SHOW → PAUSE pattern** at key transitions (after explore, after proposal draft, after tasks, after archive)
- **Keep narration light** during implementation—teach without lecturing
- **Don't skip phases** even if the change is small—the goal is teaching the workflow
- **Pause for acknowledgment** at marked points, but don't over-pause
- **Handle exits gracefully**—never pressure the user to continue
- **Use real codebase tasks**—don't simulate or use fake examples
- **Adjust scope gently**—guide toward smaller tasks but respect user choice
+66
View File
@@ -0,0 +1,66 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
PCLI is a Go CLI tool for interacting with the Planka (v2.0) project management API. It uses the Cobra framework with minimal dependencies (only Cobra + standard library).
## Build & Test Commands
```bash
go build -o pcli . # Build for development
./build.sh # Multi-platform release build (linux/darwin/windows)
./test.sh # Integration tests (requires live Planka instance)
```
Integration tests require `PLANKA_URL` and `PLANKA_API_KEY` environment variables pointing to a running Planka instance.
There is no unit test suite or linter configured — tests are shell-based integration tests in `test.sh`.
## Architecture
**Entry point**: `main.go``cmd.Execute()`
**Package layout**:
- `cmd/` — Cobra command definitions, one file per resource (project.go, board.go, card.go, etc.)
- `client/` — HTTP API client, one file per resource matching cmd/ structure
- `model/types.go` — All domain types (Project, Board, Card, List, Label, Task, Comment, etc.)
- `output/output.go` — Dual-format output: JSON envelope (`{data, error}`) or human-readable table via tabwriter
- `logging/logging.go` — slog-based structured JSON logging to stderr
**Command hierarchy**: `pcli <resource> <action>` (e.g., `pcli card create --list <id> --name "task"`)
**Key patterns**:
- Global flags (`--format`, `--url`, `--api-key`, `--log-level`) set in `cmd/root.go` PersistentPreRunE, which validates config and initializes the API client
- Client methods follow `List*/Get*/Create*/Update*/Delete*` naming
- API responses use typed structs with included relationships (e.g., board responses include lists and cards)
- `friendlyAPIError()` in `cmd/errors.go` translates HTTP status codes to contextual messages
- `DoWithFallback` in client supports trying alternate API endpoint patterns
- Output uses reflection-based table rendering per type
**Configuration**: Environment variables `PLANKA_URL` and `PLANKA_API_KEY`, overridable via CLI flags.
## Adding a New Resource
1. Define model structs in `model/types.go`
2. Add client methods in `client/<resource>.go`
3. Add command definitions in `cmd/<resource>.go` with subcommands (list, get, create, update, delete)
4. Wire the parent command into `root.go` init()
## Planka Sync
**IMPORTANT**
After completing any opsx workflow (/opsx:new, /opsx:ff, /opsx:continue,
/opsx:apply, /opsx:verify, /opsx:archive, /opsx:bulk-archive), automatically
reconcile Planka board state by running the sync script:
```bash
PROJECT_NAME=$(yq -r '.planka.project' project.yaml)
BOARD_NAME=$(yq -r '.planka.board' project.yaml)
kanban-project-sync --project "$PROJECT_NAME" --board "$BOARD_NAME" --background
```
The script handles concurrency (flock-based locking with coalescing pending queue).
If the script is not on PATH or fails, log a brief warning and continue.
Never block or retry — Planka sync is best-effort.
+34 -5
View File
@@ -8,6 +8,7 @@ A command-line interface for interacting with the [Planka](https://planka.app/)
- **JSON-first output** - Machine-parseable by default, with optional table format for humans - **JSON-first output** - Machine-parseable by default, with optional table format for humans
- **Environment-based auth** - Configure once via environment variables - **Environment-based auth** - Configure once via environment variables
- **Full CRUD operations** - Manage cards, comments, tasks, labels, and more - **Full CRUD operations** - Manage cards, comments, tasks, labels, and more
- **Project export/import** - Portable JSON backup and migration between instances
- **Cursor-based pagination** - Automatic handling of paginated API responses - **Cursor-based pagination** - Automatic handling of paginated API responses
- **Structured logging** - Debug-level HTTP request/response logging available - **Structured logging** - Debug-level HTTP request/response logging available
@@ -67,14 +68,30 @@ pcli project list
# Get a specific project # Get a specific project
pcli project get <project-id> pcli project get <project-id>
# Create a project (type: private or shared)
pcli project create --name "My Project" --type private
# Export a project (all boards, or filter by board)
pcli project export <project-id-or-name> > backup.json
pcli project export "My Project" --board "Sprint Board" > board-backup.json
# Import a project from JSON
pcli project import --file backup.json
pcli project import < backup.json
``` ```
**Note on project types:** Planka v2 accepts `private` or `shared` (not `public`). Use `private` for projects visible only to members, `shared` for projects visible to all users.
### Boards ### Boards
```bash ```bash
# List all accessible boards # List all accessible boards
pcli board list pcli board list
# List boards filtered by project name
pcli board list --project "project1"
# Get a board # Get a board
pcli board get <board-id> pcli board get <board-id>
@@ -184,6 +201,9 @@ pcli label delete <label-id>
```bash ```bash
# Show status summary of all boards and their lists # Show status summary of all boards and their lists
pcli status pcli status
# Show status filtered by project name
pcli status --project "MyProject"
``` ```
## Output Formats ## Output Formats
@@ -257,16 +277,23 @@ pcli card list --list <source-list-id> | jq -r '.data[].id' | while read card_id
done done
``` ```
### Export board structure ### Export and import a project
```bash ```bash
# Get board with all lists # Export entire project to portable JSON
pcli board get <board-id> > board.json pcli project export "My Project" > project-backup.json
# Get all cards for the board # Export a single board
pcli card list --board <board-id> > cards.json pcli project export "My Project" --board "Sprint Board" > board-backup.json
# Import to another instance
PLANKA_URL=https://other.planka.example pcli project import --file project-backup.json
``` ```
Export uses names (not IDs) so the file is portable across instances. Import creates all resources with fresh IDs. If the project already exists on the target, boards are added to it — but import fails if a board with the same name already exists under that project.
Comments are exported with a `(Original comment by <username>)` text prefix to preserve attribution, since user IDs are not portable.
## Future Enhancements ## Future Enhancements
The following improvements are planned for future releases: The following improvements are planned for future releases:
@@ -281,6 +308,8 @@ The following improvements are planned for future releases:
Built against Planka v2.0 API. See `planka-api.json` for the full OpenAPI specification. Built against Planka v2.0 API. See `planka-api.json` for the full OpenAPI specification.
**Note:** Planka v2 project types are `private` and `shared` (not `public` as in earlier versions).
## Contributing ## Contributing
Contributions welcome! Please open an issue or pull request on [GitLab](https://git.franklin.lab/steve.cliff/pcli). Contributions welcome! Please open an issue or pull request on [GitLab](https://git.franklin.lab/steve.cliff/pcli).
+8 -2
View File
@@ -43,8 +43,11 @@ func (c *Client) GetBoard(ctx context.Context, id string) (*model.Board, error)
var response struct { var response struct {
Item model.Board `json:"item"` Item model.Board `json:"item"`
Included struct { Included struct {
Lists []model.List `json:"lists"` Lists []model.List `json:"lists"`
Cards []model.Card `json:"cards"` Cards []model.Card `json:"cards"`
Labels []model.Label `json:"labels"`
CardLabels []model.CardLabel `json:"cardLabels"`
CardMemberships []model.CardMembership `json:"cardMemberships"`
} `json:"included"` } `json:"included"`
} }
@@ -54,6 +57,9 @@ func (c *Client) GetBoard(ctx context.Context, id string) (*model.Board, error)
response.Item.Lists = response.Included.Lists response.Item.Lists = response.Included.Lists
response.Item.Cards = response.Included.Cards response.Item.Cards = response.Included.Cards
response.Item.Labels = response.Included.Labels
response.Item.CardLabels = response.Included.CardLabels
response.Item.CardMemberships = response.Included.CardMemberships
return &response.Item, nil return &response.Item, nil
} }
+36 -3
View File
@@ -9,21 +9,31 @@ import (
"git.franklin.lab/steve.cliff/pcli/model" "git.franklin.lab/steve.cliff/pcli/model"
) )
func (c *Client) GetCard(ctx context.Context, id string) (*model.Card, error) { func (c *Client) GetCard(ctx context.Context, id string) (*model.CardDetail, error) {
data, err := c.DoNoBody(ctx, "GET", fmt.Sprintf("/api/cards/%s", id)) data, err := c.DoNoBody(ctx, "GET", fmt.Sprintf("/api/cards/%s", id))
if err != nil { if err != nil {
return nil, err return nil, err
} }
var response struct { var response struct {
Item model.Card `json:"item"` Item model.Card `json:"item"`
Included struct {
TaskLists []model.TaskList `json:"taskLists"`
Tasks []model.Task `json:"tasks"`
} `json:"included"`
} }
if err := json.Unmarshal(data, &response); err != nil { if err := json.Unmarshal(data, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal card response: %w", err) return nil, fmt.Errorf("failed to unmarshal card response: %w", err)
} }
return &response.Item, nil result := &model.CardDetail{
Card: response.Item,
TaskLists: response.Included.TaskLists,
Tasks: response.Included.Tasks,
}
return result, nil
} }
func (c *Client) CreateCard(ctx context.Context, listId string, fields map[string]any) (*model.Card, error) { func (c *Client) CreateCard(ctx context.Context, listId string, fields map[string]any) (*model.Card, error) {
@@ -195,11 +205,34 @@ func (c *Client) ListCardsByBoard(ctx context.Context, boardId string, limit int
listNames[list.ID] = name listNames[list.ID] = name
} }
// Build label ID -> name map
labelNames := make(map[string]string)
for _, label := range board.Labels {
name := ""
if label.Name != nil {
name = *label.Name
}
labelNames[label.ID] = name
}
// Build card ID -> label names map
cardLabelNames := make(map[string][]string)
for _, cl := range board.CardLabels {
if name, ok := labelNames[cl.LabelID]; ok {
cardLabelNames[cl.CardID] = append(cardLabelNames[cl.CardID], name)
}
}
var allCards []model.CardWithList var allCards []model.CardWithList
for _, card := range board.Cards { for _, card := range board.Cards {
labels := cardLabelNames[card.ID]
if labels == nil {
labels = []string{}
}
cardWithList := model.CardWithList{ cardWithList := model.CardWithList{
Card: card, Card: card,
ListName: listNames[card.ListID], ListName: listNames[card.ListID],
Labels: labels,
} }
allCards = append(allCards, cardWithList) allCards = append(allCards, cardWithList)
+249
View File
@@ -0,0 +1,249 @@
package client
import (
"context"
"fmt"
"log/slog"
"time"
"git.franklin.lab/steve.cliff/pcli/model"
)
func (c *Client) ExportProject(ctx context.Context, projectID string, boardFilter string) (*model.ExportEnvelope, error) {
// Fetch users for comment attribution
userMap, err := c.buildUserMap(ctx)
if err != nil {
c.Logger.Warn("Failed to fetch users for comment attribution, will use 'unknown user'",
slog.String("error", err.Error()),
)
userMap = make(map[string]string)
}
// Get project details
project, err := c.GetProject(ctx, projectID)
if err != nil {
return nil, fmt.Errorf("failed to get project: %w", err)
}
// Get all boards for the project
boards, err := c.ListBoards(ctx)
if err != nil {
return nil, fmt.Errorf("failed to list boards: %w", err)
}
// Filter boards to this project
var projectBoards []model.Board
for _, b := range boards {
if b.ProjectID == projectID {
projectBoards = append(projectBoards, b)
}
}
// Apply board filter if specified
if boardFilter != "" {
var filtered []model.Board
for _, b := range projectBoards {
if b.ID == boardFilter || b.Name == boardFilter {
filtered = append(filtered, b)
}
}
if len(filtered) == 0 {
return nil, fmt.Errorf("board %q not found in project %q", boardFilter, project.Name)
}
projectBoards = filtered
}
// Export each board
var exportBoards []model.ExportBoard
for _, b := range projectBoards {
c.Logger.Info("Exporting board", slog.String("board", b.Name))
eb, err := c.exportBoard(ctx, b.ID, userMap)
if err != nil {
return nil, fmt.Errorf("failed to export board %q: %w", b.Name, err)
}
exportBoards = append(exportBoards, *eb)
}
return &model.ExportEnvelope{
Version: 1,
ExportedAt: time.Now().UTC().Format(time.RFC3339),
Project: model.ExportProject{
Name: project.Name,
Description: project.Description,
Boards: exportBoards,
},
}, nil
}
func (c *Client) buildUserMap(ctx context.Context) (map[string]string, error) {
users, err := c.ListUsers(ctx)
if err != nil {
return nil, err
}
userMap := make(map[string]string, len(users))
for _, u := range users {
userMap[u.ID] = u.Name
}
return userMap, nil
}
func (c *Client) exportBoard(ctx context.Context, boardID string, userMap map[string]string) (*model.ExportBoard, error) {
board, err := c.GetBoard(ctx, boardID)
if err != nil {
return nil, err
}
// Build lookup maps from board included data
listMap := make(map[string]string) // id -> name
systemListIDs := make(map[string]bool)
for _, l := range board.Lists {
if l.Type == "archive" || l.Type == "trash" {
systemListIDs[l.ID] = true
continue
}
name := ""
if l.Name != nil {
name = *l.Name
}
listMap[l.ID] = name
}
labelMap := make(map[string]string) // id -> name
for _, l := range board.Labels {
name := ""
if l.Name != nil {
name = *l.Name
}
labelMap[l.ID] = name
}
// Build card -> label names map
cardLabels := make(map[string][]string)
for _, cl := range board.CardLabels {
if name, ok := labelMap[cl.LabelID]; ok {
cardLabels[cl.CardID] = append(cardLabels[cl.CardID], name)
}
}
// Export lists (skip system lists like archive and trash)
var exportLists []model.ExportList
for _, l := range board.Lists {
if l.Type == "archive" || l.Type == "trash" {
continue
}
name := ""
if l.Name != nil {
name = *l.Name
}
pos := float64(0)
if l.Position != nil {
pos = *l.Position
}
exportLists = append(exportLists, model.ExportList{
Name: name,
Position: pos,
Type: l.Type,
Color: l.Color,
})
}
// Export labels
var exportLabels []model.ExportLabel
for _, l := range board.Labels {
exportLabels = append(exportLabels, model.ExportLabel{
Name: l.Name,
Position: l.Position,
Color: l.Color,
})
}
// Export cards with per-card details (skip cards in archive/trash lists)
var exportCards []model.ExportCard
for _, card := range board.Cards {
if systemListIDs[card.ListID] {
continue
}
c.Logger.Debug("Exporting card", slog.String("card", card.Name))
ec, err := c.exportCard(ctx, card, listMap[card.ListID], cardLabels[card.ID], userMap)
if err != nil {
return nil, fmt.Errorf("failed to export card %q: %w", card.Name, err)
}
exportCards = append(exportCards, *ec)
}
return &model.ExportBoard{
Name: board.Name,
Position: board.Position,
Lists: exportLists,
Labels: exportLabels,
Cards: exportCards,
}, nil
}
func (c *Client) exportCard(ctx context.Context, card model.Card, listName string, labelNames []string, userMap map[string]string) (*model.ExportCard, error) {
// Fetch card details (task lists + tasks)
detail, err := c.GetCard(ctx, card.ID)
if err != nil {
return nil, fmt.Errorf("failed to get card details: %w", err)
}
// Fetch comments
comments, err := c.ListComments(ctx, card.ID, 0)
if err != nil {
return nil, fmt.Errorf("failed to get card comments: %w", err)
}
// Build task list ID -> tasks map
tasksByList := make(map[string][]model.Task)
for _, t := range detail.Tasks {
tasksByList[t.TaskListID] = append(tasksByList[t.TaskListID], t)
}
// Export task lists
var exportTaskLists []model.ExportTaskList
for _, tl := range detail.TaskLists {
var exportTasks []model.ExportTask
for _, t := range tasksByList[tl.ID] {
exportTasks = append(exportTasks, model.ExportTask{
Name: t.Name,
Position: t.Position,
IsCompleted: t.IsCompleted,
})
}
exportTaskLists = append(exportTaskLists, model.ExportTaskList{
Name: tl.Name,
Position: tl.Position,
Tasks: exportTasks,
})
}
// Export comments with attribution
var exportComments []model.ExportComment
for _, cm := range comments {
author := "unknown user"
if cm.UserID != nil {
if name, ok := userMap[*cm.UserID]; ok {
author = name
}
}
exportComments = append(exportComments, model.ExportComment{
Text: fmt.Sprintf("(Original comment by %s)\n%s", author, cm.Text),
})
}
return &model.ExportCard{
Name: card.Name,
Position: card.Position,
ListName: listName,
LabelNames: labelNames,
Description: card.Description,
DueDate: card.DueDate,
IsClosed: card.IsClosed,
Type: card.Type,
TaskLists: exportTaskLists,
Comments: exportComments,
}, nil
}
+244
View File
@@ -0,0 +1,244 @@
package client
import (
"context"
"fmt"
"io"
"log/slog"
"strings"
"git.franklin.lab/steve.cliff/pcli/model"
)
// ImportProgress tracks creation counts during import.
type ImportProgress struct {
Boards int
Lists int
Labels int
Cards int
TaskLists int
Tasks int
Comments int
}
func (p ImportProgress) String() string {
return fmt.Sprintf("boards: %d, lists: %d, labels: %d, cards: %d, task lists: %d, tasks: %d, comments: %d",
p.Boards, p.Lists, p.Labels, p.Cards, p.TaskLists, p.Tasks, p.Comments)
}
func (c *Client) ImportProject(ctx context.Context, export *model.ExportEnvelope, stderr io.Writer) (*ImportProgress, error) {
progress := &ImportProgress{}
// Resolve or create project
projectID, err := c.resolveOrCreateProject(ctx, export.Project.Name, export.Project.Description)
if err != nil {
return nil, fmt.Errorf("failed to resolve/create project: %w", err)
}
// Check for board name conflicts before creating anything
if err := c.checkBoardConflicts(ctx, projectID, export.Project); err != nil {
return nil, err
}
// Import each board
for _, board := range export.Project.Boards {
fmt.Fprintf(stderr, "Importing board %q...\n", board.Name)
if err := c.importBoard(ctx, projectID, board, progress); err != nil {
return progress, fmt.Errorf("failed to import board %q: %w", board.Name, err)
}
}
return progress, nil
}
func (c *Client) resolveOrCreateProject(ctx context.Context, name string, description *string) (string, error) {
projects, err := c.ListProjects(ctx)
if err != nil {
return "", fmt.Errorf("failed to list projects: %w", err)
}
for _, p := range projects {
if strings.EqualFold(p.Name, name) {
c.Logger.Info("Using existing project", slog.String("project", name), slog.String("id", p.ID))
return p.ID, nil
}
}
// Create new project
fields := ProjectCreateFields{
Type: "private",
Name: name,
}
if description != nil {
fields.Description = description
}
project, err := c.CreateProject(ctx, fields)
if err != nil {
return "", fmt.Errorf("failed to create project: %w", err)
}
c.Logger.Info("Created project", slog.String("project", name), slog.String("id", project.ID))
return project.ID, nil
}
func (c *Client) checkBoardConflicts(ctx context.Context, projectID string, export model.ExportProject) error {
boards, err := c.ListBoards(ctx)
if err != nil {
return fmt.Errorf("failed to list boards: %w", err)
}
existingNames := make(map[string]bool)
for _, b := range boards {
if b.ProjectID == projectID {
existingNames[strings.ToLower(b.Name)] = true
}
}
var conflicts []string
for _, b := range export.Boards {
if existingNames[strings.ToLower(b.Name)] {
conflicts = append(conflicts, b.Name)
}
}
if len(conflicts) > 0 {
return fmt.Errorf("board(s) already exist in project %q: %s", export.Name, strings.Join(conflicts, ", "))
}
return nil
}
func (c *Client) importBoard(ctx context.Context, projectID string, board model.ExportBoard, progress *ImportProgress) error {
// Create board
createdBoard, err := c.CreateBoard(ctx, projectID, BoardCreateFields{
Name: board.Name,
Position: board.Position,
})
if err != nil {
return fmt.Errorf("failed to create board: %w", err)
}
progress.Boards++
// Create lists, build name -> ID map (skip system lists)
listMap := make(map[string]string)
for _, l := range board.Lists {
if l.Type == "archive" || l.Type == "trash" {
continue
}
created, err := c.CreateList(ctx, createdBoard.ID, ListCreateFields{
Name: l.Name,
Position: l.Position,
Type: l.Type,
})
if err != nil {
return fmt.Errorf("failed to create list %q: %w", l.Name, err)
}
listMap[l.Name] = created.ID
progress.Lists++
}
// Create labels, build name -> ID map
// Labels are keyed by name only (Planka scopes labels to a board)
labelMap := make(map[string]string)
for _, l := range board.Labels {
fields := map[string]any{
"position": l.Position,
"color": l.Color,
}
if l.Name != nil {
fields["name"] = *l.Name
}
created, err := c.CreateLabel(ctx, createdBoard.ID, fields)
if err != nil {
return fmt.Errorf("failed to create label: %w", err)
}
name := ""
if l.Name != nil {
name = *l.Name
}
labelMap[name] = created.ID
progress.Labels++
}
// Create cards
for _, card := range board.Cards {
listID, ok := listMap[card.ListName]
if !ok {
return fmt.Errorf("card %q references unknown list %q", card.Name, card.ListName)
}
cardFields := map[string]any{
"name": card.Name,
"type": card.Type,
}
if card.Position != nil {
cardFields["position"] = *card.Position
}
if card.Description != nil {
cardFields["description"] = *card.Description
}
if card.DueDate != nil {
cardFields["dueDate"] = *card.DueDate
}
if card.IsClosed {
cardFields["isClosed"] = true
}
createdCard, err := c.CreateCard(ctx, listID, cardFields)
if err != nil {
return fmt.Errorf("failed to create card %q: %w", card.Name, err)
}
progress.Cards++
// Add card labels
for _, labelName := range card.LabelNames {
labelID, ok := labelMap[labelName]
if !ok {
c.Logger.Warn("Label not found for card, skipping",
slog.String("card", card.Name),
slog.String("label", labelName),
)
continue
}
if err := c.AddCardLabel(ctx, createdCard.ID, labelID); err != nil {
return fmt.Errorf("failed to add label %q to card %q: %w", labelName, card.Name, err)
}
}
// Create task lists and tasks
for _, tl := range card.TaskLists {
tlFields := map[string]any{
"name": tl.Name,
"position": tl.Position,
}
createdTL, err := c.CreateTaskList(ctx, createdCard.ID, tlFields)
if err != nil {
return fmt.Errorf("failed to create task list %q: %w", tl.Name, err)
}
progress.TaskLists++
for _, t := range tl.Tasks {
tFields := map[string]any{
"name": t.Name,
"position": t.Position,
"isCompleted": t.IsCompleted,
}
if _, err := c.CreateTask(ctx, createdTL.ID, tFields); err != nil {
return fmt.Errorf("failed to create task %q: %w", t.Name, err)
}
progress.Tasks++
}
}
// Create comments
for _, cm := range card.Comments {
if _, err := c.CreateComment(ctx, createdCard.ID, cm.Text); err != nil {
return fmt.Errorf("failed to create comment on card %q: %w", card.Name, err)
}
progress.Comments++
}
}
return nil
}
+81
View File
@@ -0,0 +1,81 @@
package client
import (
"context"
"encoding/json"
"fmt"
"git.franklin.lab/steve.cliff/pcli/model"
)
// ListCreateFields represents the fields required to create a list
type ListCreateFields struct {
Name string `json:"name"`
Position float64 `json:"position"`
Type string `json:"type"`
}
// ListUpdateFields represents the fields that can be updated for a list
type ListUpdateFields struct {
Name *string `json:"name,omitempty"`
Position *float64 `json:"position,omitempty"`
Type *string `json:"type,omitempty"`
Color *string `json:"color,omitempty"`
BoardID *string `json:"boardId,omitempty"`
}
func (c *Client) CreateList(ctx context.Context, boardId string, fields ListCreateFields) (*model.List, error) {
data, err := c.Do(ctx, "POST", fmt.Sprintf("/api/boards/%s/lists", boardId), fields)
if err != nil {
return nil, err
}
var response struct {
Item model.List `json:"item"`
}
if err := json.Unmarshal(data, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal list response: %w", err)
}
return &response.Item, nil
}
func (c *Client) GetList(ctx context.Context, id string) (*model.List, error) {
data, err := c.DoNoBody(ctx, "GET", fmt.Sprintf("/api/lists/%s", id))
if err != nil {
return nil, err
}
var response struct {
Item model.List `json:"item"`
}
if err := json.Unmarshal(data, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal list response: %w", err)
}
return &response.Item, nil
}
func (c *Client) UpdateList(ctx context.Context, id string, fields ListUpdateFields) (*model.List, error) {
data, err := c.Do(ctx, "PATCH", fmt.Sprintf("/api/lists/%s", id), fields)
if err != nil {
return nil, err
}
var response struct {
Item model.List `json:"item"`
}
if err := json.Unmarshal(data, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal list response: %w", err)
}
return &response.Item, nil
}
func (c *Client) DeleteList(ctx context.Context, id string) error {
_, err := c.DoNoBody(ctx, "DELETE", fmt.Sprintf("/api/lists/%s", id))
return err
}
+26
View File
@@ -0,0 +1,26 @@
package client
import (
"context"
"encoding/json"
"fmt"
"git.franklin.lab/steve.cliff/pcli/model"
)
func (c *Client) ListUsers(ctx context.Context) ([]model.User, error) {
data, err := c.DoNoBody(ctx, "GET", "/api/users")
if err != nil {
return nil, err
}
var response struct {
Items []model.User `json:"items"`
}
if err := json.Unmarshal(data, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal users response: %w", err)
}
return response.Items, nil
}
+42
View File
@@ -0,0 +1,42 @@
package cmd
import (
"encoding/json"
"fmt"
"os"
"github.com/spf13/cobra"
)
var projectExportCmd = &cobra.Command{
Use: "export <project-id-or-name>",
Short: "Export a project to JSON",
Long: "Export a project (or a specific board) as a portable JSON file to stdout",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
boardFilter, _ := cmd.Flags().GetString("board")
projectID, err := resolveProject(args[0])
if err != nil {
return err
}
envelope, err := getClient().ExportProject(getContext(), projectID, boardFilter)
if err != nil {
return friendlyAPIError(err, "export project", "")
}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
if err := encoder.Encode(envelope); err != nil {
return fmt.Errorf("failed to encode export: %w", err)
}
return nil
},
}
func init() {
projectCmd.AddCommand(projectExportCmd)
projectExportCmd.Flags().String("board", "", "Filter to a specific board (name or ID)")
}
+62
View File
@@ -0,0 +1,62 @@
package cmd
import (
"encoding/json"
"fmt"
"io"
"os"
"git.franklin.lab/steve.cliff/pcli/model"
"github.com/spf13/cobra"
)
var projectImportCmd = &cobra.Command{
Use: "import",
Short: "Import a project from JSON",
Long: "Import a project from a JSON export file, creating all resources with new IDs",
RunE: func(cmd *cobra.Command, args []string) error {
filePath, _ := cmd.Flags().GetString("file")
var reader io.Reader
if filePath != "" {
f, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer f.Close()
reader = f
} else {
// Check if stdin has data
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) != 0 {
return fmt.Errorf("no input provided — use --file or pipe JSON via stdin")
}
reader = os.Stdin
}
var envelope model.ExportEnvelope
if err := json.NewDecoder(reader).Decode(&envelope); err != nil {
return fmt.Errorf("failed to parse export JSON: %w", err)
}
if envelope.Version != 1 {
return fmt.Errorf("unsupported export version %d (supported: 1)", envelope.Version)
}
progress, err := getClient().ImportProject(getContext(), &envelope, os.Stderr)
if err != nil {
if progress != nil {
fmt.Fprintf(os.Stderr, "Partial import before error: %s\n", progress)
}
return friendlyAPIError(err, "import project", "")
}
fmt.Fprintf(os.Stderr, "Import complete: %s\n", progress)
return nil
},
}
func init() {
projectCmd.AddCommand(projectImportCmd)
projectImportCmd.Flags().String("file", "", "Path to export JSON file (alternative to stdin)")
}
+141
View File
@@ -0,0 +1,141 @@
package cmd
import (
"fmt"
"os"
"git.franklin.lab/steve.cliff/pcli/client"
"git.franklin.lab/steve.cliff/pcli/output"
"github.com/spf13/cobra"
)
var listCmd = &cobra.Command{
Use: "list",
Short: "Manage lists (board columns)",
Long: "Commands for managing Planka lists (board columns)",
}
var listCreateCmd = &cobra.Command{
Use: "create",
Short: "Create a new list",
RunE: func(cmd *cobra.Command, args []string) error {
board, _ := cmd.Flags().GetString("board")
name, _ := cmd.Flags().GetString("name")
listType, _ := cmd.Flags().GetString("type")
position, _ := cmd.Flags().GetFloat64("position")
// Validate required flags
if board == "" {
return cmd.Usage()
}
if name == "" {
return cmd.Usage()
}
if listType == "" {
listType = "active" // default to active
}
fields := client.ListCreateFields{
Name: name,
Type: listType,
Position: position,
}
list, err := getClient().CreateList(getContext(), board, fields)
if err != nil {
return friendlyAPIError(err, "create list", "requires board editor role")
}
return output.Print(list, getFormat(), os.Stdout)
},
}
var listGetCmd = &cobra.Command{
Use: "get <id>",
Short: "Get a list by ID",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
list, err := getClient().GetList(getContext(), args[0])
if err != nil {
return err
}
return output.Print(list, getFormat(), os.Stdout)
},
}
var listUpdateCmd = &cobra.Command{
Use: "update <id>",
Short: "Update a list",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
fields := client.ListUpdateFields{}
if name, _ := cmd.Flags().GetString("name"); cmd.Flags().Changed("name") {
fields.Name = &name
}
if listType, _ := cmd.Flags().GetString("type"); cmd.Flags().Changed("type") {
fields.Type = &listType
}
if color, _ := cmd.Flags().GetString("color"); cmd.Flags().Changed("color") {
fields.Color = &color
}
if pos, _ := cmd.Flags().GetFloat64("position"); cmd.Flags().Changed("position") {
fields.Position = &pos
}
if board, _ := cmd.Flags().GetString("board"); cmd.Flags().Changed("board") {
fields.BoardID = &board
}
// Check if at least one field is being updated
if fields.Name == nil && fields.Type == nil && fields.Color == nil && fields.Position == nil && fields.BoardID == nil {
return fmt.Errorf("at least one field must be specified for update")
}
list, err := getClient().UpdateList(getContext(), args[0], fields)
if err != nil {
return friendlyAPIError(err, "update list", "requires board editor role")
}
return output.Print(list, getFormat(), os.Stdout)
},
}
var listDeleteCmd = &cobra.Command{
Use: "delete <id>",
Short: "Delete a list",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
err := getClient().DeleteList(getContext(), args[0])
if err != nil {
return friendlyAPIError(err, "delete list", "requires board editor role")
}
fmt.Println("List deleted successfully")
return nil
},
}
func init() {
rootCmd.AddCommand(listCmd)
listCmd.AddCommand(listCreateCmd)
listCmd.AddCommand(listGetCmd)
listCmd.AddCommand(listUpdateCmd)
listCmd.AddCommand(listDeleteCmd)
// Flags for list create
listCreateCmd.Flags().String("board", "", "Board ID (required)")
listCreateCmd.Flags().String("name", "", "List name (required)")
listCreateCmd.Flags().String("type", "active", "List type (active|closed, default: active)")
listCreateCmd.Flags().Float64("position", 65536, "List position (optional, default 65536)")
listCreateCmd.MarkFlagRequired("board")
listCreateCmd.MarkFlagRequired("name")
// Flags for list update
listUpdateCmd.Flags().String("name", "", "List name")
listUpdateCmd.Flags().String("type", "", "List type (active|closed)")
listUpdateCmd.Flags().String("color", "", "List color")
listUpdateCmd.Flags().Float64("position", 0, "List position")
listUpdateCmd.Flags().String("board", "", "Move list to different board (Board ID)")
}
+43
View File
@@ -0,0 +1,43 @@
package cmd
import (
"fmt"
"strings"
)
// resolveProject takes a project ID or name and returns the project ID.
// If the input matches a project ID exactly, it's returned directly.
// If it matches project name(s), it returns the ID if exactly one matches.
func resolveProject(idOrName string) (string, error) {
// First try as an ID
project, err := getClient().GetProject(getContext(), idOrName)
if err == nil {
return project.ID, nil
}
// Fall back to name lookup
projects, err := getClient().ListProjects(getContext())
if err != nil {
return "", fmt.Errorf("failed to list projects: %w", err)
}
var matches []struct{ id, name string }
for _, p := range projects {
if strings.EqualFold(p.Name, idOrName) {
matches = append(matches, struct{ id, name string }{p.ID, p.Name})
}
}
switch len(matches) {
case 0:
return "", fmt.Errorf("project %q not found", idOrName)
case 1:
return matches[0].id, nil
default:
var names []string
for _, m := range matches {
names = append(names, fmt.Sprintf("%s (%s)", m.name, m.id))
}
return "", fmt.Errorf("ambiguous project name %q matches multiple projects: %s", idOrName, strings.Join(names, ", "))
}
}
+2 -2
View File
@@ -11,8 +11,8 @@ import (
var statusCmd = &cobra.Command{ var statusCmd = &cobra.Command{
Use: "status", Use: "status",
Short: "Show status summary of all boards and their lists", Short: "Show status summary of boards and their lists",
Long: "Displays a summary of all boards, their lists, and the number of cards in each list", Long: "Displays a summary of boards, their lists, and the number of cards in each list.",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
// Get all boards // Get all boards
boards, err := getClient().ListBoards(getContext()) boards, err := getClient().ListBoards(getContext())
-121
View File
@@ -1,121 +0,0 @@
---
name: "Kanban"
description: "Manage Planka project boards using the pcli CLI"
category: Workflow
tags: [workflow, kanban, planka, project-management]
---
Manage Planka project boards using the `pcli` CLI. Use the kanban skill for detailed command reference.
## Prerequisites
Before running any commands, verify the environment is ready:
```bash
// turbo
pcli status
```
If this fails, ensure `PLANKA_URL` and `PLANKA_API_KEY` environment variables are set and `pcli` is in PATH.
---
## How to Use
**Input**: The argument after `/kanban` is what the user wants to do. Could be:
- A status check: "show me all boards" or "what's on my board"
- A card operation: "create a card for fixing the login bug"
- A board query: "list all cards in the backlog"
- A move: "move card X to done"
- A bulk operation: "move all cards from In Progress to Done"
- Nothing (show overall status)
---
## Responding to Requests
### 1. Understand the request
Map the user's intent to `pcli` commands. Use `pcli status` for overview requests. For specific operations, identify the resource (project, board, card, list, label, task, comment) and action (list, get, create, update, delete, move).
### 2. Discover IDs when needed
Most commands require IDs. Discover them by querying first:
```bash
# Find boards
pcli board list | jq '.data[] | {id, title}'
# Find lists on a board
pcli board get <board-id> | jq '.data.included.lists[] | {id, title}'
# Find cards on a list or board
pcli card list --board <board-id> | jq '.data[] | {id, name}'
pcli card list --list <list-id> | jq '.data[] | {id, name}'
```
Always use `jq` to extract and format output for readability.
### 3. Execute the operation
Run the appropriate `pcli` command. For create/update/delete operations, confirm with the user before executing unless the intent is unambiguous.
### 4. Report results
Show the user a concise summary of what happened. Use tables or formatted output when listing multiple items.
---
## Command Quick Reference
| Resource | Commands |
|----------|----------|
| **Status** | `pcli status` |
| **Projects** | `list`, `get` |
| **Boards** | `list`, `get`, `actions` |
| **Cards** | `list`, `get`, `create`, `update`, `delete`, `duplicate`, `move`, `assign`, `unassign`, `add-label`, `remove-label`, `actions` |
| **Comments** | `list`, `create`, `update`, `delete` |
| **Task Lists** | `create`, `get`, `update`, `delete` |
| **Tasks** | `create`, `update`, `delete` |
| **Labels** | `create`, `update`, `delete` |
---
## Common Patterns
### Create a card with a checklist
```bash
CARD_ID=$(pcli card create --list <list-id> --name "Task" | jq -r '.data.id')
TL_ID=$(pcli task-list create --card $CARD_ID --name "Steps" | jq -r '.data.id')
pcli task create --task-list $TL_ID --name "Step 1"
pcli task create --task-list $TL_ID --name "Step 2"
```
### Move all cards between lists
```bash
pcli card list --list <source-list-id> | jq -r '.data[].id' | while read id; do
pcli card move $id --list <target-list-id>
done
```
### Extract IDs from output
```bash
# Single object
pcli card create --list <id> --name "X" | jq -r '.data.id'
# Array
pcli card list --board <id> | jq -r '.data[].id'
```
---
## Guardrails
- **Discover before acting** - Always query for IDs rather than guessing
- **Confirm destructive actions** - Ask before delete or bulk move operations
- **Use jq for output** - Parse JSON responses with `jq` for clean, readable results
- **Show context** - When listing cards, include the list/board name for context
- **Global flags** - All commands accept `--format json|table` for output format
+196
View File
@@ -0,0 +1,196 @@
---
name: planka-skill
description: Manage Planka project boards using the pcli CLI. Use when the user wants to interact with Planka boards, cards, lists, tasks, labels, or comments.
compatibility: Requires pcli binary in PATH and PLANKA_URL + PLANKA_API_KEY environment variables set
metadata:
author: steve-cliff
version: "1.0"
---
# pcli - Planka CLI
CLI for the Planka project management API. All commands return JSON by default with envelope `{"data": ..., "error": null}`. Use `jq` to extract fields.
## Prerequisites
Ensure environment variables are set:
```bash
export PLANKA_URL="https://planka.example.com"
export PLANKA_API_KEY="your-api-key"
```
Ensure `jq` is installed.
## Global Flags
All commands (apart from import/export) accept: `--format json|table`, `--url <url>`, `--api-key <key>`, `--log-level debug|info|warn|error`
## Commands
### Status Overview
```bash
pcli status
```
Returns summary of all boards, lists, and card counts (open/closed per list).
### Projects
```bash
pcli project list
pcli project get <project-id>
pcli project create --name "Name" --type private # type: private or shared
pcli project delete <project-id>
# Export/Import
pcli project export <project-id-or-name> [--board <name-or-id>] > backup.json
pcli project import --file backup.json
pcli project import < backup.json
```
Export outputs a portable JSON file (names, not IDs). Import creates all resources with fresh IDs.
Import fails if the project+board name combination already exists on the target.
Comments are exported with `(Original comment by <username>)` prefix for attribution.
**Note:** Export outputs its own envelope format (`{version, exportedAt, project}`) directly — not the standard `{data, error}` envelope. Import progress and errors go to stderr.
### Boards
```bash
pcli board list
pcli board get <board-id> # includes lists and cards
pcli board actions <board-id> [--limit N]
pcli board create --project <project-id> --name "Board Name" [--position N]
pcli board delete <board-id>
```
### Lists (Board Columns)
```bash
pcli list create --board <board-id> --name "Column Name" [--type active|closed] [--position N]
pcli list get <list-id>
pcli list update <list-id> [--name "..."] [--type active|closed] [--color "..."] [--position N] [--board <board-id>]
pcli list delete <list-id>
```
### Cards
```bash
# List (one of --board or --list required, mutually exclusive)
pcli card list --board <board-id> [--limit N]
pcli card list --list <list-id> [--limit N]
# CRUD
pcli card get <card-id>
pcli card create --list <list-id> --name "Name" [--description "..."] [--type project|story] [--position N] [--due-date "ISO8601"] [--due-completed]
pcli card update <card-id> [--name "..."] [--description "..."] [--type ...] [--position N] [--due-date "..."] [--due-completed]
pcli card delete <card-id>
pcli card duplicate <card-id> --name "Copy" [--position N]
pcli card move <card-id> --list <target-list-id> [--position N]
# Members
pcli card assign <card-id> --user <user-id>
pcli card unassign <card-id> --user <user-id>
# Labels
pcli card add-label <card-id> --label <label-id>
pcli card remove-label <card-id> --label <label-id>
# Actions
pcli card actions <card-id> [--limit N]
```
### Comments
```bash
pcli comment list --card <card-id> [--limit N]
pcli comment create --card <card-id> --text "..."
pcli comment update <comment-id> --text "..."
pcli comment delete <comment-id>
```
### Task Lists
```bash
pcli task-list create --card <card-id> --name "Checklist" [--position N] [--show-on-front] [--hide-completed]
pcli task-list get <task-list-id>
pcli task-list update <task-list-id> [--name "..."] [--position N] [--show-on-front] [--hide-completed]
pcli task-list delete <task-list-id>
```
### Tasks
```bash
pcli task create --task-list <task-list-id> --name "Item" [--position N] [--completed]
pcli task update <task-id> [--name "..."] [--position N] [--completed]
pcli task delete <task-id>
```
### Labels
```bash
pcli label create --board <board-id> --name "Bug" --color "berry-red" [--position N]
pcli label update <label-id> [--name "..."] [--color "..."] [--position N]
pcli label delete <label-id>
```
## Extracting IDs from Output
All responses use `{"data": ..., "error": null}`. Extract IDs with jq:
```bash
# Single object
pcli card create --list <id> --name "X" | jq -r '.data.id'
# Array
pcli card list --board <id> | jq -r '.data[].id'
```
## Common Workflows
### Create a complete Kanban board
```bash
# Create board
BOARD_ID=$(pcli board create --project <project-id> --name "Development Board" | jq -r '.data.id')
# Create columns
pcli list create --board $BOARD_ID --name "Backlog" --type "active" --position 0
TODO_ID=$(pcli list create --board $BOARD_ID --name "To Do" --type "active" --position 65536 | jq -r '.data.id')
PROGRESS_ID=$(pcli list create --board $BOARD_ID --name "In Progress" --type "active" --position 131072 | jq -r '.data.id')
DONE_ID=$(pcli list create --board $BOARD_ID --name "Done" --type "closed" --position 196608 | jq -r '.data.id')
# View the board
pcli board get $BOARD_ID --format table
```
### Create a card with a checklist
```bash
CARD_ID=$(pcli card create --list <list-id> --name "Task" | jq -r '.data.id')
TL_ID=$(pcli task-list create --card $CARD_ID --name "Steps" | jq -r '.data.id')
pcli task create --task-list $TL_ID --name "Step 1"
pcli task create --task-list $TL_ID --name "Step 2"
```
### Move all cards between lists
```bash
pcli card list --list <source-list-id> | jq -r '.data[].id' | while read id; do
pcli card move $id --list <target-list-id>
done
```
### Export and import a project
```bash
# Export entire project
pcli project export "My Project" > project-backup.json
# Export single board
pcli project export "My Project" --board "Sprint Board" > board-backup.json
# Import to another instance (or same instance if project+board combo doesn't exist)
pcli project import --file project-backup.json
```
@@ -24,6 +24,8 @@ If this fails, ensure `PLANKA_URL` and `PLANKA_API_KEY` environment variables ar
**Input**: The argument after `/kanban` is what the user wants to do. Could be: **Input**: The argument after `/kanban` is what the user wants to do. Could be:
- A status check: "show me all boards" or "what's on my board" - A status check: "show me all boards" or "what's on my board"
- A board setup: "create a kanban board with todo, in progress, done columns"
- A list operation: "add a 'testing' column to my board" or "rename the done column"
- A card operation: "create a card for fixing the login bug" - A card operation: "create a card for fixing the login bug"
- A board query: "list all cards in the backlog" - A board query: "list all cards in the backlog"
- A move: "move card X to done" - A move: "move card X to done"
@@ -47,7 +49,7 @@ Most commands require IDs. Discover them by querying first:
pcli board list | jq '.data[] | {id, title}' pcli board list | jq '.data[] | {id, title}'
# Find lists on a board # Find lists on a board
pcli board get <board-id> | jq '.data.included.lists[] | {id, title}' pcli board get <board-id> | jq '.data.lists[] | {id, name}'
# Find cards on a list or board # Find cards on a list or board
pcli card list --board <board-id> | jq '.data[] | {id, name}' pcli card list --board <board-id> | jq '.data[] | {id, name}'
@@ -71,8 +73,9 @@ Show the user a concise summary of what happened. Use tables or formatted output
| Resource | Commands | | Resource | Commands |
|----------|----------| |----------|----------|
| **Status** | `pcli status` | | **Status** | `pcli status` |
| **Projects** | `list`, `get` | | **Projects** | `list`, `get`, `create`, `delete` |
| **Boards** | `list`, `get`, `actions` | | **Boards** | `list`, `get`, `actions`, `create`, `delete` |
| **Lists** | `create`, `get`, `update`, `delete` |
| **Cards** | `list`, `get`, `create`, `update`, `delete`, `duplicate`, `move`, `assign`, `unassign`, `add-label`, `remove-label`, `actions` | | **Cards** | `list`, `get`, `create`, `update`, `delete`, `duplicate`, `move`, `assign`, `unassign`, `add-label`, `remove-label`, `actions` |
| **Comments** | `list`, `create`, `update`, `delete` | | **Comments** | `list`, `create`, `update`, `delete` |
| **Task Lists** | `create`, `get`, `update`, `delete` | | **Task Lists** | `create`, `get`, `update`, `delete` |
@@ -83,6 +86,32 @@ Show the user a concise summary of what happened. Use tables or formatted output
## Common Patterns ## Common Patterns
### Create a complete Kanban board
```bash
# Create board
BOARD_ID=$(pcli board create --project <project-id> --name "Development Board" | jq -r '.data.id')
# Create standard columns
pcli list create --board $BOARD_ID --name "Backlog" --type "active" --position 0
TODO_ID=$(pcli list create --board $BOARD_ID --name "To Do" --type "active" --position 65536 | jq -r '.data.id')
PROGRESS_ID=$(pcli list create --board $BOARD_ID --name "In Progress" --type "active" --position 131072 | jq -r '.data.id')
DONE_ID=$(pcli list create --board $BOARD_ID --name "Done" --type "closed" --position 196608 | jq -r '.data.id')
# View the completed board
pcli board get $BOARD_ID --format table
```
### Add a new column to existing board
```bash
# Find the board
BOARD_ID=$(pcli board list | jq -r '.data[] | select(.name == "Development Board") | .id')
# Add new column
pcli list create --board $BOARD_ID --name "Testing" --type "active" --position 163840
```
### Create a card with a checklist ### Create a card with a checklist
```bash ```bash
+84 -3
View File
@@ -30,8 +30,11 @@ type Board struct {
ExpandTaskListsByDefault bool `json:"expandTaskListsByDefault"` ExpandTaskListsByDefault bool `json:"expandTaskListsByDefault"`
CreatedAt *string `json:"createdAt"` CreatedAt *string `json:"createdAt"`
UpdatedAt *string `json:"updatedAt"` UpdatedAt *string `json:"updatedAt"`
Lists []List `json:"lists,omitempty"` Lists []List `json:"lists,omitempty"`
Cards []Card `json:"cards,omitempty"` Cards []Card `json:"cards,omitempty"`
Labels []Label `json:"labels,omitempty"`
CardLabels []CardLabel `json:"cardLabels,omitempty"`
CardMemberships []CardMembership `json:"cardMemberships,omitempty"`
} }
type List struct { type List struct {
@@ -71,9 +74,16 @@ type Card struct {
UpdatedAt *string `json:"updatedAt"` UpdatedAt *string `json:"updatedAt"`
} }
type CardDetail struct {
Card
TaskLists []TaskList `json:"taskLists,omitempty"`
Tasks []Task `json:"tasks,omitempty"`
}
type CardWithList struct { type CardWithList struct {
Card Card
ListName string `json:"listName"` ListName string `json:"listName"`
Labels []string `json:"labels"`
} }
type Comment struct { type Comment struct {
@@ -168,6 +178,77 @@ type ListSummary struct {
ClosedCards int `json:"closedCards"` ClosedCards int `json:"closedCards"`
} }
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Username *string `json:"username"`
Email string `json:"email"`
}
// Export types - portable structs without Planka IDs
type ExportEnvelope struct {
Version int `json:"version"`
ExportedAt string `json:"exportedAt"`
Project ExportProject `json:"project"`
}
type ExportProject struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
Boards []ExportBoard `json:"boards"`
}
type ExportBoard struct {
Name string `json:"name"`
Position float64 `json:"position"`
Lists []ExportList `json:"lists"`
Labels []ExportLabel `json:"labels"`
Cards []ExportCard `json:"cards"`
}
type ExportList struct {
Name string `json:"name"`
Position float64 `json:"position"`
Type string `json:"type"`
Color *string `json:"color,omitempty"`
}
type ExportLabel struct {
Name *string `json:"name,omitempty"`
Position float64 `json:"position"`
Color string `json:"color"`
}
type ExportCard struct {
Name string `json:"name"`
Position *float64 `json:"position,omitempty"`
ListName string `json:"listName"`
LabelNames []string `json:"labelNames,omitempty"`
Description *string `json:"description,omitempty"`
DueDate *string `json:"dueDate,omitempty"`
IsClosed bool `json:"isClosed,omitempty"`
Type string `json:"type"`
TaskLists []ExportTaskList `json:"taskLists,omitempty"`
Comments []ExportComment `json:"comments,omitempty"`
}
type ExportTaskList struct {
Name string `json:"name"`
Position float64 `json:"position"`
Tasks []ExportTask `json:"tasks"`
}
type ExportTask struct {
Name string `json:"name"`
Position float64 `json:"position"`
IsCompleted bool `json:"isCompleted"`
}
type ExportComment struct {
Text string `json:"text"`
}
type APIError struct { type APIError struct {
StatusCode int StatusCode int
Message string Message string
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-02-18
@@ -0,0 +1,71 @@
## Context
The `pcli board list` command currently calls `client.ListBoards()` which returns all boards accessible to the user across all projects. There's no filtering capability at the CLI level. The kanban-sync workflow needs to check if a board exists within a specific project before creating it, but without filtering, it risks creating duplicates.
The Planka API returns boards with a `projectId` field. Projects can be listed via `client.ListProjects()` which returns project objects with `id` and `name` fields. We need to bridge project names (user-friendly) to project IDs (API-level) for filtering.
## Goals / Non-Goals
**Goals:**
- Add `--project <name>` flag to `pcli board list` command
- Filter boards by project name using case-insensitive matching
- Maintain backward compatibility (no flag = list all boards)
- Provide clear error message if project name doesn't match any accessible project
**Non-Goals:**
- Filtering by multiple projects simultaneously
- Fuzzy matching or partial name matching (exact case-insensitive match only)
- Adding project filtering to other board commands (get, actions, etc.)
- Caching project lookups across commands
## Decisions
### Decision 1: Filter client-side, not API-side
**Choice:** Fetch all boards via `ListBoards()`, then filter in CLI code based on `projectId`.
**Rationale:** The Planka API's `ListBoards()` endpoint doesn't support project filtering. Adding API-level filtering would require changes to the Planka server or a different endpoint. Client-side filtering is simpler and keeps changes contained to pcli.
**Alternatives considered:**
- Use a different API endpoint: No suitable endpoint exists in the Planka API
- Modify Planka API: Out of scope for this change
**Trade-off:** Fetches all boards even when filtering, but acceptable given typical board counts.
### Decision 2: Accept project name, not project ID
**Choice:** The `--project` flag accepts a project name string and resolves it to an ID internally.
**Rationale:** Project names are more user-friendly and memorable than UUIDs. Users working with kanban-sync know project names, not IDs.
**Alternatives considered:**
- Accept project ID: Less user-friendly, requires users to look up IDs first
- Accept both name and ID: Adds complexity for minimal benefit
**Trade-off:** Requires an additional API call to `ListProjects()` to resolve the name, but this is a one-time cost per command execution.
### Decision 3: Case-insensitive exact match
**Choice:** Match project name case-insensitively but require exact match (no partial/fuzzy matching).
**Rationale:** Case-insensitive matching improves usability (users don't need to remember exact casing). Exact matching avoids ambiguity when multiple projects have similar names.
**Alternatives considered:**
- Case-sensitive matching: Too strict, poor UX
- Fuzzy/partial matching: Could match multiple projects, requires disambiguation logic
**Trade-off:** Users must know the exact project name, but this is acceptable for the target use case.
### Decision 4: Error on no match
**Choice:** If `--project` is provided but no accessible project matches the name, return an error and exit with code 1.
**Rationale:** Silent failure or empty results could confuse users. Explicit error makes it clear the project name is wrong or inaccessible.
**Alternatives considered:**
- Return empty list: Ambiguous (no boards vs. wrong project name)
- List similar project names: Adds complexity
## Risks / Trade-offs
**[Risk: Performance with many boards]** → Acceptable: Client-side filtering requires fetching all boards. For users with hundreds of boards, this could be slow. However, typical Planka instances have <100 boards, making this acceptable. If performance becomes an issue, we can optimize later with API-level filtering.
**[Risk: Project name collisions]** → Mitigated: If multiple projects have the same name (case-insensitive), the first match wins. This is unlikely in practice since project names are typically unique within an organization. If needed, users can use `pcli project list` to identify the correct project.
**[Risk: Additional API call overhead]** → Acceptable: Resolving project name to ID requires calling `ListProjects()`. This adds ~100-200ms latency but is necessary for the user-friendly interface. The call is made only once per command execution.
@@ -0,0 +1,34 @@
## Why
The `pcli board list` command currently returns all accessible boards across all projects, making it difficult to find boards within a specific project. When working with the kanban-sync workflow, we need to filter boards by project name to avoid creating duplicate boards. This change adds a `--project` flag to enable project-scoped board listing.
## What Changes
- Add `--project <name>` flag to `pcli board list` command
- When `--project` is provided, filter boards to only show those belonging to the specified project
- When `--project` is omitted, maintain current behavior (list all boards)
- The flag accepts a project name (not ID) and performs case-insensitive matching
## Capabilities
### New Capabilities
- `board-list-filtering`: Filter board list results by project name
### Modified Capabilities
- `cli-commands`: Add `--project` flag to the `board list` command specification
## Impact
**Code:**
- `cmd/board.go`: Add `--project` flag to `boardListCmd` and implement filtering logic
- `client/boards.go`: May need to add project name resolution if not already available
**APIs:**
- Uses existing `ListBoards()` and `ListProjects()` client methods
- No new API endpoints required
**Dependencies:**
- No new dependencies
**Workflows:**
- Enables kanban-sync workflow to check for existing boards within a specific project before creating new ones
@@ -0,0 +1,32 @@
## ADDED Requirements
### Requirement: Board list project filtering
The system SHALL provide a `--project <name>` flag for the `board list` command. When the flag is provided, the system SHALL resolve the project name to a project ID by calling `ListProjects()` and performing a case-insensitive exact match on the project name. If no matching project is found, the system SHALL output an error message "project not found: <name>" and exit with code 1. If a matching project is found, the system SHALL filter the board list to include only boards where `projectId` matches the resolved project ID. When the `--project` flag is omitted, the system SHALL list all accessible boards without filtering.
#### Scenario: List boards without project filter
- **WHEN** `pcli board list` is executed without the `--project` flag
- **THEN** the system SHALL output all accessible boards across all projects
#### Scenario: List boards filtered by project name
- **WHEN** `pcli board list --project "project1"` is executed
- **THEN** the system SHALL resolve "project1" to a project ID
- **AND** the system SHALL output only boards belonging to that project
#### Scenario: List boards with case-insensitive project match
- **WHEN** `pcli board list --project "PROJECT1"` is executed and a project named "project1" exists
- **THEN** the system SHALL match the project case-insensitively
- **AND** the system SHALL output boards belonging to the matched project
#### Scenario: Project name not found
- **WHEN** `pcli board list --project "nonexistent"` is executed
- **THEN** the system SHALL output "project not found: nonexistent"
- **AND** the system SHALL exit with code 1
#### Scenario: Project exists but has no boards
- **WHEN** `pcli board list --project "empty-project"` is executed for a project with no boards
- **THEN** the system SHALL output an empty list (or empty JSON array in JSON format)
#### Scenario: User lacks access to project
- **WHEN** `pcli board list --project "restricted"` is executed for a project the user cannot access
- **THEN** the system SHALL output "project not found: restricted"
- **AND** the system SHALL exit with code 1
@@ -0,0 +1,57 @@
## ADDED Requirements
### Requirement: Board list command
The system SHALL provide a `board list` subcommand. `pcli board list` SHALL call the client's ListBoards method and output all accessible boards. The command SHALL accept an optional `--project <name>` flag (string). When `--project` is provided, the system SHALL filter boards to only those belonging to the specified project (see board-list-filtering spec for filtering behavior).
#### Scenario: List all boards
- **WHEN** `pcli board list` is executed without flags
- **THEN** the system SHALL output all accessible boards
#### Scenario: List boards filtered by project
- **WHEN** `pcli board list --project "project1"` is executed
- **THEN** the system SHALL output only boards belonging to the specified project
## MODIFIED Requirements
### Requirement: Board commands
The system SHALL provide a `board` command group with subcommands `list`, `get`, `actions`, `create`, and `delete`. `pcli board list` SHALL list all accessible boards and accept an optional `--project <name>` flag for filtering. `pcli board get <id>` SHALL accept a board ID as a positional argument and output the board details. `pcli board actions <id>` SHALL accept a board ID and an optional `--limit` flag (int, default 0) and output the board's action history. `pcli board create` SHALL create a new board. `pcli board delete <id>` SHALL delete a board.
#### Scenario: Get board
- **WHEN** `pcli board get <id>` is executed
- **THEN** the system SHALL output the board details including its lists
#### Scenario: List board actions
- **WHEN** `pcli board actions <id>` is executed
- **THEN** the system SHALL output the board's action history
#### Scenario: List board actions with limit
- **WHEN** `pcli board actions <id> --limit 10` is executed
- **THEN** the system SHALL output at most 10 action entries
#### Scenario: Create board
- **WHEN** `pcli board create --project <id> --name "Development Board" --position 65536` is executed
- **THEN** the system SHALL create the board and output the created board
#### Scenario: Create board missing required flags
- **WHEN** `pcli board create` is executed without `--project` or `--name`
- **THEN** the system SHALL print an error indicating the required flags and exit with code 1
#### Scenario: Create board with insufficient permissions
- **WHEN** `pcli board create --project <id> --name "Board"` is executed by a user without project manager permissions on the project
- **THEN** the system SHALL output "create board: permission denied (requires project manager role)"
#### Scenario: Create board project not found
- **WHEN** `pcli board create --project <id> --name "Board"` is executed with a project the user cannot access
- **THEN** the system SHALL output "create board: not found — the resource may not exist or you may not have access to it"
#### Scenario: Delete board
- **WHEN** `pcli board delete <id>` is executed with a valid board ID
- **THEN** the system SHALL delete the board and output a success confirmation
#### Scenario: Delete board with insufficient permissions
- **WHEN** `pcli board delete <id>` is executed by a user without project manager permissions
- **THEN** the system SHALL output "delete board: permission denied (requires project manager role)"
#### Scenario: Delete board not found
- **WHEN** `pcli board delete <id>` is executed with a non-existent board ID
- **THEN** the system SHALL output "delete board: not found — the resource may not exist or you may not have access to it"
@@ -0,0 +1,24 @@
## 1. Add project name resolution helper
- [x] 1.1 Add helper function in cmd/board.go to resolve project name to ID by calling ListProjects() and performing case-insensitive match
- [x] 1.2 Add error handling for project not found case with appropriate error message
## 2. Implement board list filtering
- [x] 2.1 Add --project flag to boardListCmd in cmd/board.go
- [x] 2.2 Implement filtering logic: when --project is provided, resolve name to ID and filter boards by projectId
- [x] 2.3 Maintain backward compatibility: when --project is omitted, list all boards
## 3. Update tests and documentation
- [x] 3.1 Add test cases for board list with project filter
- [x] 3.2 Add test cases for project not found error
- [x] 3.3 Add test cases for case-insensitive project matching
- [x] 3.4 Update README or help text if needed
## 4. Verify integration
- [x] 4.1 Test board list without --project flag (should list all boards)
- [x] 4.2 Test board list with valid --project flag (should filter correctly)
- [x] 4.3 Test board list with invalid --project flag (should error appropriately)
- [x] 4.4 Test board list with case variations in project name
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-02-18
@@ -0,0 +1,38 @@
## Context
The `pcli status` command fetches all boards and aggregates card counts per list. It has no filtering capability. The `board list` command already supports `--project <name>` filtering via a `resolveProjectNameToID()` helper in `cmd/board.go` that does case-insensitive name matching against all projects. The Board model already contains a `ProjectID` field.
## Goals / Non-Goals
**Goals:**
- Add `--project` flag to `pcli status` that filters boards by project name
- Reuse the existing `resolveProjectNameToID()` pattern from `cmd/board.go`
- Update help text and README to document the new flag
**Non-Goals:**
- Filtering by project ID (only name-based, consistent with `board list`)
- Multiple project filtering (single project only)
- Caching project lookups across commands
- Changing the status output structure or adding new fields
## Decisions
### Filter boards before fetching details
**Decision**: Apply the project filter on the initial `ListBoards()` result, before calling `GetBoard()` for each board. This avoids unnecessary API calls for boards that will be filtered out.
**Alternative**: Filter after fetching all board details. Rejected because it wastes API calls and time for boards not in the target project.
### Reuse resolveProjectNameToID from board.go
**Decision**: Call the existing `resolveProjectNameToID()` function directly — it is already exported within the `cmd` package.
**Alternative**: Extract to a shared utility. Rejected as premature — two call sites within the same package doesn't warrant a new abstraction.
### totalBoards reflects filtered count
**Decision**: When `--project` is used, `totalBoards` in the output reflects only the matching boards, not all boards. This matches the semantics of "how many boards am I looking at."
**Alternative**: Show total and filtered counts separately. Rejected — adds complexity for minimal value.
## Risks / Trade-offs
- **[Extra API call]** → When `--project` is used, an additional `ListProjects()` call is made to resolve the name. This is lightweight and consistent with `board list --project`.
- **[No partial match]** → Project name must match exactly (case-insensitive). Consistent with existing `board list` behavior. Users who misspell get a clear "project not found" error.
@@ -0,0 +1,30 @@
## Why
The `pcli status` command currently shows a summary of **all** boards across all projects. In instances with many projects, this produces noisy output and makes it difficult to focus on a specific project's boards. The `board list` command already supports `--project` filtering — the status command should offer the same capability for consistency and usability.
## What Changes
- Add an optional `--project` flag to `pcli status` that filters the status summary to boards belonging to the named project
- When `--project` is provided, only boards matching that project are included; `totalBoards` reflects the filtered count
- When `--project` is omitted, behavior is unchanged (all boards shown)
- Update command help text (`Short`, `Long`) to mention the filtering capability
- Update README status section with `--project` usage example
- Reuse the existing `resolveProjectNameToID()` helper from `cmd/board.go`
## Capabilities
### New Capabilities
_None — this enhances existing capabilities._
### Modified Capabilities
- `status-command`: Add optional `--project` flag for project-scoped filtering
- `cli-commands`: Update status command documentation to include `--project` flag
## Impact
- **Code**: `cmd/status.go` (add flag, filter logic), `cmd/board.go` (no change — reuses existing helper)
- **Documentation**: `README.md` status section, command help strings
- **API**: No new API calls — uses existing `ListProjects()` for name resolution, same `ListBoards()` + `GetBoard()` flow
- **Breaking changes**: None — flag is optional, default behavior preserved
@@ -0,0 +1,20 @@
## MODIFIED Requirements
### Requirement: Status command
The system SHALL provide a top-level `status` command registered directly on the root command (not as a subcommand of any resource group). `pcli status` SHALL take no positional arguments. The command SHALL accept an optional `--project <name>` flag (string) to filter boards by project name. The command SHALL fetch all boards via `ListBoards`, optionally filter by project, then fetch each board's details via `GetBoard` sequentially, aggregate card counts per list, and output the result via the standard `output.Print` mechanism respecting the global `--format` flag.
#### Scenario: Run status command
- **WHEN** `pcli status` is executed
- **THEN** the system SHALL output a summary of all boards with their lists and card counts
#### Scenario: Run status command with project filter
- **WHEN** `pcli status --project "MyProject"` is executed
- **THEN** the system SHALL output a summary of only boards belonging to "MyProject"
#### Scenario: Status command respects format flag
- **WHEN** `pcli status --format table` is executed
- **THEN** the output SHALL be in table format
#### Scenario: Status command default format
- **WHEN** `pcli status` is executed without a `--format` flag
- **THEN** the output SHALL be in JSON envelope format
@@ -0,0 +1,49 @@
## ADDED Requirements
### Requirement: Status command project filtering
The system SHALL accept an optional `--project <name>` flag on the `pcli status` command. When `--project` is provided, the system SHALL resolve the project name to a project ID using case-insensitive exact matching against all accessible projects. The system SHALL then filter the board list to include only boards whose `projectId` matches the resolved project ID. The `totalBoards` count in the output SHALL reflect the filtered board count. When `--project` is omitted, behavior SHALL be unchanged (all boards shown).
#### Scenario: Status filtered by project name
- **WHEN** `pcli status --project "MyProject"` is executed and the project exists with 2 boards
- **THEN** the output SHALL include only the 2 boards belonging to "MyProject"
- **AND** `totalBoards` SHALL be 2
#### Scenario: Status filtered by project name case-insensitive
- **WHEN** `pcli status --project "myproject"` is executed and a project named "MyProject" exists
- **THEN** the output SHALL include boards belonging to "MyProject"
#### Scenario: Status with project filter and no matching boards
- **WHEN** `pcli status --project "EmptyProject"` is executed and the project exists but has no boards
- **THEN** the output SHALL show `totalBoards` as 0 and an empty boards array
#### Scenario: Status with project not found
- **WHEN** `pcli status --project "NonExistent"` is executed and no project with that name exists
- **THEN** the system SHALL output an error "project not found: NonExistent"
- **AND** the system SHALL exit with code 1
#### Scenario: Status without project flag
- **WHEN** `pcli status` is executed without `--project`
- **THEN** the output SHALL include all boards across all projects (unchanged behavior)
## MODIFIED Requirements
### Requirement: Status command summary output
The system SHALL provide a top-level `pcli status` command that outputs a summary of all boards (or boards filtered by `--project`), their lists, and card counts. The summary SHALL include the total number of boards. For each board, the summary SHALL include the board name and a breakdown of each list within that board showing the list name, the number of open cards (where `isClosed` is false), and the number of closed cards (where `isClosed` is true). Empty lists SHALL be included in the output with 0 open and 0 closed cards.
#### Scenario: Status with multiple boards and lists
- **WHEN** `pcli status` is executed and there are boards with lists containing cards
- **THEN** the output SHALL include the total board count
- **AND** each board SHALL list all its lists with open and closed card counts
#### Scenario: Status with empty lists
- **WHEN** a board contains a list with no cards
- **THEN** that list SHALL appear in the output with 0 open cards and 0 closed cards
#### Scenario: Status with no boards
- **WHEN** `pcli status` is executed and there are no boards
- **THEN** the output SHALL indicate 0 boards
#### Scenario: Status with closed cards
- **WHEN** a list contains both open and closed cards
- **THEN** the open card count SHALL exclude closed cards
- **AND** the closed card count SHALL be shown separately
@@ -0,0 +1,19 @@
## 1. Core Implementation
- [x] 1.1 Add `--project` flag to `statusCmd` in `cmd/status.go`
- [x] 1.2 Add project filtering logic: resolve name via `resolveProjectNameToID()`, filter boards by `ProjectID` before fetching details
- [x] 1.3 Update `totalBoards` count to reflect filtered results
## 2. Command Help Text
- [x] 2.1 Update `Short` and `Long` descriptions on `statusCmd` to mention `--project` filtering
## 3. Documentation
- [x] 3.1 Update README.md status section with `--project` usage example
## 4. Verification
- [x] 4.1 Build and manually test `pcli status --project <name>` with an existing project
- [x] 4.2 Test error case: `pcli status --project "nonexistent"` returns "project not found" error
- [x] 4.3 Test default behavior: `pcli status` without `--project` still shows all boards
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-02-18
@@ -0,0 +1,37 @@
## Context
The Planka v2 API `GET /api/boards/:id` response includes an `included` object with: `users`, `boardMemberships`, `labels`, `lists`, `cards`, `cardMemberships`, `cardLabels`, `taskLists`, `tasks`, `attachments`, `customFieldGroups`, `customFields`, `customFieldValues`. Currently `GetBoard` only parses `lists` and `cards`, discarding everything else.
The `CardLabel` and `Label` types already exist in `model/types.go`. The `Board` struct has `Lists` and `Cards` fields but not `Labels`, `CardLabels`, or `CardMemberships`.
## Goals / Non-Goals
**Goals:**
- Parse `labels`, `cardLabels`, and `cardMemberships` from the `GetBoard` response
- Make label data available on the `Board` struct for downstream consumers
- Enrich `ListCardsByBoard` output so `card list --board` includes label names per card
**Non-Goals:**
- Parsing all included fields (users, taskLists, attachments, customFields, etc.) — only what's needed now
- Adding label data to `card list --list` (uses a different API endpoint that doesn't include labels)
- Changing the `card get` response (already returns card-level data via a different endpoint)
## Decisions
### Add fields to Board struct rather than creating a separate BoardDetail type
**Decision**: Add `Labels`, `CardLabels`, and `CardMemberships` as optional fields on the existing `Board` struct with `omitempty`.
**Alternative**: Create a `BoardDetail` struct for the enriched response. Rejected — the fields are simply absent when not fetched (e.g., `ListBoards`), and `omitempty` handles this cleanly without a type split.
### Add Labels field to CardWithList for card list --board output
**Decision**: Add a `Labels` field (`[]string` of label names) to the `CardWithList` struct. `ListCardsByBoard` will resolve card→label associations via the `cardLabels` join table and `labels` list from the board response.
**Alternative**: Return full `Label` objects per card. Rejected — label names are sufficient for display and filtering; full objects add noise to output.
### Use join-table approach matching the API structure
**Decision**: Keep `CardLabel` as the join entity (cardId + labelId), and resolve to label names at the point of use (in `ListCardsByBoard`). This mirrors the Planka API's relational structure.
## Risks / Trade-offs
- **[Additive JSON fields]** → `card list --board` output will include a new `labels` array per card. Existing consumers that don't use this field are unaffected. Scripts using strict JSON parsing may need updating.
- **[Partial included parsing]** → We still skip users, taskLists, attachments, etc. This is intentional — parse only what's needed. Future changes can add more fields incrementally.
@@ -0,0 +1,26 @@
## Why
The `GetBoard` API response includes `cardLabels`, `labels`, and `cardMemberships` in its `included` data, but `pcli` only parses `lists` and `cards` — silently discarding the rest. This means there is no way to determine which labels are attached to which cards without making per-card API calls. The kanban sync workflow needs to identify agent-labelled cards from a board listing, and currently must fall back to name-matching because label data is unavailable.
## What Changes
- Expand the `Board` struct in `model/types.go` to include `Labels`, `CardLabels`, and `CardMemberships` fields
- Update `GetBoard` in `client/boards.go` to parse these additional `included` fields from the API response
- Update `ListCardsByBoard` to enrich card output with label names (via `cardLabels` join table + `labels`)
## Capabilities
### New Capabilities
_None — this enhances existing capabilities._
### Modified Capabilities
- `api-client`: `GetBoard` SHALL parse `labels`, `cardLabels`, and `cardMemberships` from the board response `included` data
- `card-operations`: `ListCardsByBoard` (card list --board) SHALL include label names on each card
## Impact
- **Code**: `model/types.go` (Board struct), `client/boards.go` (GetBoard parsing), `client/cards.go` (ListCardsByBoard enrichment)
- **API**: No new API calls — parsing data already returned by `GET /api/boards/:id`
- **Breaking changes**: None — new fields are additive; JSON output gains new fields but existing fields unchanged
@@ -0,0 +1,25 @@
## MODIFIED Requirements
### Requirement: Board operations
The client SHALL provide a method to get a single board by ID (`GET /boards/{id}`), list board actions (`GET /boards/{boardId}/actions`) with pagination support, create a board (`POST /projects/{projectId}/boards`), and delete a board (`DELETE /boards/{id}`). `GetBoard` SHALL parse the `included` object from the response and populate the Board model with `lists`, `cards`, `labels`, `cardLabels`, and `cardMemberships`.
#### Scenario: Get board
- **WHEN** `GetBoard` is called with a board ID
- **THEN** the client SHALL send `GET /boards/{id}` and return a Board model including its included lists, cards, labels, cardLabels, and cardMemberships
#### Scenario: Get board includes labels
- **WHEN** `GetBoard` is called and the board has labels defined
- **THEN** the returned Board SHALL contain a `Labels` slice with all board labels
#### Scenario: Get board includes card-label associations
- **WHEN** `GetBoard` is called and cards on the board have labels attached
- **THEN** the returned Board SHALL contain a `CardLabels` slice with all card-label associations
- **AND** each `CardLabel` entry SHALL contain `cardId` and `labelId` fields
#### Scenario: Get board includes card memberships
- **WHEN** `GetBoard` is called and cards on the board have members assigned
- **THEN** the returned Board SHALL contain a `CardMemberships` slice with all card-membership associations
#### Scenario: List board actions
- **WHEN** `ListBoardActions` is called with a board ID and limit
- **THEN** the client SHALL paginate through `GET /boards/{boardId}/actions` and return action items
@@ -0,0 +1,23 @@
## MODIFIED Requirements
### Requirement: Enriched board-level card listing
The system SHALL provide a `card list --board <id>` operation that returns all cards across all lists in a board, with each card enriched with the `listName` field and a `labels` field. The operation SHALL: (1) call `GET /boards/{id}` to retrieve the board and its included lists, cards, labels, and cardLabels, (2) build a card-to-label-names map by joining `cardLabels` with `labels`, (3) inject `listName` and `labels` into each card. The `labels` field SHALL be an array of label name strings. The `--limit` flag SHALL apply to the total number of cards returned across all lists.
#### Scenario: List all cards on a board
- **WHEN** `pcli card list --board <id>` is executed
- **THEN** the system SHALL return all cards from all lists in the board
- **AND** each card SHALL include a `listName` field with the name of its containing list
- **AND** each card SHALL include a `labels` field with an array of label names attached to that card
#### Scenario: Card with multiple labels
- **WHEN** a card has two labels ("bug" and "urgent") attached
- **THEN** the `labels` array for that card SHALL contain both "bug" and "urgent"
#### Scenario: Card with no labels
- **WHEN** a card has no labels attached
- **THEN** the `labels` array for that card SHALL be an empty array (not null)
#### Scenario: Board card listing with limit
- **WHEN** `pcli card list --board <id> --limit 10` is executed
- **THEN** the system SHALL return at most 10 cards total across all lists
- **AND** each card SHALL include the `listName` and `labels` fields
@@ -0,0 +1,15 @@
## 1. Model Changes
- [x] 1.1 Add `Labels []Label`, `CardLabels []CardLabel`, and `CardMemberships []CardMembership` fields to `Board` struct in `model/types.go` (with `json:",omitempty"`)
- [x] 1.2 Add `Labels []string` field to `CardWithList` struct in `model/types.go`
## 2. Client Changes
- [x] 2.1 Update `GetBoard` in `client/boards.go` to parse `labels`, `cardLabels`, and `cardMemberships` from `included` response
- [x] 2.2 Update `ListCardsByBoard` in `client/cards.go` to build label-name map from board's `CardLabels` and `Labels`, and populate `Labels` on each `CardWithList`
## 3. Verification
- [x] 3.1 Build and test `pcli board get <id>` — verify JSON output includes labels and cardLabels when present
- [x] 3.2 Test `pcli card list --board <id>` — verify each card includes a `labels` array
- [x] 3.3 Test card with no labels returns empty array (not null)
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-02-19
@@ -0,0 +1,86 @@
## Context
The kanban sync workflow is currently a 280-line markdown document (`.claude/commands/kanban-sync.md`) that the LLM reads and interprets each time sync is triggered. The sync logic is deterministic — it reads OpenSpec state, compares it with Planka board state, and reconciles. No LLM judgment is needed. The overhead is significant: each sync consumes tokens for reasoning through ~10 phases and executing ~15-30 shell commands.
There is also no concurrency protection. If two opsx workflows complete in quick succession, two syncs could run simultaneously and produce conflicting Planka API calls.
## Goals / Non-Goals
**Goals:**
- Replace LLM-interpreted sync with a standalone bash script
- Implement concurrency control so only one sync runs at a time
- Support coalescing: if sync is requested while one runs, queue exactly one follow-up
- Support foreground (default, for humans) and background (for LLM/skill invocation) modes
- Keep the existing sync logic and board structure unchanged
**Non-Goals:**
- Changing the sync algorithm or board layout
- Adding bidirectional sync (Planka → OpenSpec)
- Supporting multiple simultaneous boards
- Adding a daemon/service mode — this remains an on-demand script
## Decisions
### 1. Externally deployed bash script (`kanban-project-sync`)
**Rationale**: The sync logic uses `pcli`, `jq`, `yq`, and `openspec` CLI tools — all shell-native. A bash script is the natural fit. The script is deployed to developer instances via existing tooling and placed on PATH, like other shared scripts. It does not live in the project repo.
**Convention**: The script assumes it is run from the project root directory (uses `pwd` to locate `openspec/` directory). This is consistent with how `openspec` and `pcli` already work.
**Alternative considered**: A Go subcommand in pcli (`pcli sync`). Rejected because the sync orchestrates `openspec` (a separate tool) and would require shelling out anyway. The script approach keeps concerns separated.
**Alternative considered**: Placing the script in the project root alongside `build.sh`. Rejected — the script is a shared developer tool, not project-specific. External deployment keeps it consistent with other tooling.
### 2. `flock` for locking with pending file for coalescing
**Rationale**: `flock` is the standard POSIX advisory locking mechanism. It's atomic, handles process crashes (lock auto-releases), and avoids manual PID-file management. The pending flag file is a simple touch/rm mechanism that coalesces multiple queued requests into one re-run.
**Lock file**: `/tmp/kanban-project-sync-<project>-<board>.lock` — scoped per project-board to allow independent syncs for different boards.
**Pending file**: `/tmp/kanban-project-sync-<project>-<board>.pending` — touched by callers that can't acquire the lock.
**Flow**:
```
Caller:
Try flock (non-blocking)
├── Got lock:
│ loop:
│ run_sync()
│ if pending file exists: rm pending, continue loop
│ else: break
│ release lock (fd close)
└── Lock held:
touch pending file
exit 0
```
**Alternative considered**: PID file with `kill -0` checks. Rejected — racy, doesn't handle crashes cleanly, more complex than `flock`.
### 3. Foreground default, `--background` flag for detached mode
**Rationale**: Humans running the script manually want to see output. The LLM/skill always passes `--background` to avoid blocking. Background mode uses `nohup` + `&` with output redirected to a log file at `/tmp/kanban-project-sync-<project>-<board>.log`.
### 4. Script reads `project.yaml` for defaults but CLI args override
**Rationale**: `--project` and `--board` are required arguments. The script does NOT read `project.yaml` itself — that's the caller's concern. This keeps the script generic. The kanban-sync command/skill reads `project.yaml` and passes the values. A human can pass whatever project/board they want.
### 5. Exit codes
| Code | Meaning |
|------|---------|
| 0 | Success (sync completed) or queued (pending flag set) |
| 1 | Error (sync failed) |
| 2 | Skipped (Planka offline / connectivity check failed) |
When a caller can't acquire the lock and sets the pending flag, it exits 0 — from the caller's perspective, the sync will happen.
## Risks / Trade-offs
**[`flock` availability on macOS]** → macOS doesn't ship `flock` by default. Mitigation: document that `brew install util-linux` is needed. This is a dev tooling script, not a production binary — acceptable friction.
**[Background mode log management]** → Log files in `/tmp` accumulate. Mitigation: Each run overwrites the log file (not appends), so only the last run's output is kept per project-board pair.
**[Pending flag race window]** → Tiny window between "check pending" and "release lock" where a new pending could be missed. Mitigation: The check-and-release happens while still holding the flock, so no other process can set pending between check and release. The lock holder is the only one that reads/clears the pending file.
**[Script drift from sync logic]** → If the sync algorithm changes, the script must be updated manually (no longer auto-follows the markdown doc). Mitigation: The sync logic has been stable. The kanban-sync.md doc will reference the script, making it clear where changes go.
@@ -0,0 +1,30 @@
## Why
The kanban sync is currently implemented as a detailed workflow document that the LLM interprets and executes command-by-command. Each sync burns significant tokens as the LLM reasons through ~10 phases and executes ~15-30 `pcli` commands. The sync logic is entirely deterministic — there are no decisions that require LLM judgment. Moving this to a standalone bash script eliminates the overhead and makes sync near-instant. Additionally, there is no concurrency protection — two syncs could run simultaneously and clash on Planka API state.
## What Changes
- New `kanban-project-sync` bash script (deployed externally, on PATH) that performs the full 10-phase Planka board reconciliation
- Script accepts `--project` and `--board` as required inputs, with optional `--background` flag
- Script assumes it is run from the project root (uses `pwd` to locate `openspec/` directory)
- Implements `flock`-based concurrency control with a coalescing pending flag (depth-1 queue)
- Default mode is foreground (human-friendly); `--background` detaches for fire-and-forget use
- `.claude/commands/kanban-sync.md` simplified to just invoke the script with `--background`
- `CLAUDE.md` sync instructions updated to reference the script
## Capabilities
### New Capabilities
- `kanban-sync-concurrency`: Concurrency control for sync execution — flock-based locking with a pending flag that coalesces multiple requests, and automatic re-run after completion if a sync was requested during execution
### Modified Capabilities
_(none — no existing spec-level requirements change)_
## Impact
- **New external script**: `kanban-project-sync` — deployed to developer instances via existing tooling, placed on PATH
- **Modified**: `.claude/commands/kanban-sync.md` — reduced from full workflow to script invocation
- **Modified**: `CLAUDE.md` — updated Planka Sync section
- **Dependencies**: Requires `flock` (standard on Linux, available on macOS via `brew install util-linux`), `jq`, `yq`, `pcli`, `openspec` on PATH
- **No Go code changes** — this is entirely in the tooling/workflow layer
- **Convention**: Script must be run from the project root directory (same as `openspec` and `pcli`)
@@ -0,0 +1,59 @@
## ADDED Requirements
### Requirement: Exclusive sync execution
The sync script SHALL use `flock` advisory locking to ensure only one sync instance runs at a time per project-board pair. The lock file SHALL be located at `/tmp/kanban-project-sync-<project>-<board>.lock`.
#### Scenario: First sync acquires lock
- **WHEN** kanban-project-sync is invoked and no other sync is running for the same project-board
- **THEN** the script acquires the flock and executes the full sync
#### Scenario: Second sync finds lock held
- **WHEN** kanban-project-sync is invoked while another sync is running for the same project-board
- **THEN** the script SHALL NOT execute the sync, SHALL touch the pending flag file, and SHALL exit with code 0
### Requirement: Coalescing pending queue
The sync script SHALL implement a depth-1 coalescing queue using a pending flag file at `/tmp/kanban-project-sync-<project>-<board>.pending`. Multiple pending requests SHALL coalesce into a single re-run.
#### Scenario: Pending flag set during sync
- **WHEN** a sync completes and the pending flag file exists
- **THEN** the script SHALL clear the pending flag and re-run the sync before releasing the lock
#### Scenario: No pending flag after sync
- **WHEN** a sync completes and no pending flag file exists
- **THEN** the script SHALL release the lock and exit
#### Scenario: Multiple pending requests coalesce
- **WHEN** three sync requests arrive while a sync is running
- **THEN** only one additional sync SHALL run after the current one completes (not three)
### Requirement: Foreground and background modes
The sync script SHALL default to foreground execution (output to stdout/stderr). When `--background` is passed, the script SHALL detach and redirect output to a log file at `/tmp/kanban-project-sync-<project>-<board>.log`.
#### Scenario: Foreground execution
- **WHEN** kanban-project-sync is invoked without `--background`
- **THEN** sync output SHALL be written to stdout/stderr and the script SHALL block until complete
#### Scenario: Background execution
- **WHEN** kanban-project-sync is invoked with `--background`
- **THEN** the script SHALL detach from the terminal, redirect output to the log file, and return immediately
### Requirement: Required arguments
The sync script SHALL require `--project <name>` and `--board <name>` arguments. The script SHALL NOT read `project.yaml` directly.
#### Scenario: Missing arguments
- **WHEN** kanban-project-sync is invoked without `--project` or `--board`
- **THEN** the script SHALL print usage information and exit with code 1
### Requirement: Connectivity check
The sync script SHALL run `pcli status` before syncing. If the check fails, the script SHALL exit with code 2.
#### Scenario: Planka offline
- **WHEN** `pcli status` returns a non-zero exit code
- **THEN** the script SHALL print a message indicating Planka is unreachable and exit with code 2
### Requirement: Idempotent sync phases
The sync script SHALL implement all 10 phases of the existing kanban-sync workflow: connectivity check, bootstrap infrastructure (find-or-create project, board, lists, label), gather OpenSpec state, determine target lists, gather Planka agent cards, create missing cards, move cards to correct lists, sync task checklists, handle archived changes, and report. Each phase SHALL be idempotent — running the script twice with no state changes SHALL produce no Planka API mutations on the second run.
#### Scenario: Clean re-run with no changes
- **WHEN** the sync script runs twice in succession with no OpenSpec or Planka state changes between runs
- **THEN** the second run SHALL make no create/update/move API calls and SHALL report zero changes
@@ -0,0 +1,32 @@
## 1. Script Skeleton and Concurrency
- [x] 1.1 Create `kanban-project-sync` script with argument parsing (`--project`, `--board`, `--background`), usage help, and exit code constants
- [x] 1.2 Implement `flock`-based locking with pending flag file and re-run loop
- [x] 1.3 Implement `--background` mode (re-exec self detached with output to log file)
- [x] 1.4 Add connectivity check (`pcli status`) with exit code 2 on failure
## 2. Bootstrap Phase
- [x] 2.1 Implement find-or-create project by name
- [x] 2.2 Implement find-or-create board by name within project
- [x] 2.3 Implement find-or-create lists (Backlog, To Do, Planning, In Progress, Review, Done) with correct positions
- [x] 2.4 Implement find-or-create `agent` label on the board
## 3. Reconciliation Phases
- [x] 3.1 Gather OpenSpec state — list active changes, parse artifact completion and task checkbox state
- [x] 3.2 Determine target list for each change based on OpenSpec state (Planning / In Progress / Review)
- [x] 3.3 Gather existing Planka agent-labelled cards and build name→card map
- [x] 3.4 Create missing cards (new OpenSpec changes without a Planka card) with agent label
- [x] 3.5 Move cards to correct list when current list doesn't match target
- [x] 3.6 Sync task checklists — create/update task lists and tasks on cards from `tasks.md`
- [x] 3.7 Move orphaned agent cards (no matching active change) to Done
## 4. Reporting and Summary
- [x] 4.1 Add summary output — infrastructure created, cards created/moved, tasks synced, errors
## 5. Skill and Documentation Updates
- [x] 5.1 Simplify `.claude/commands/kanban-sync.md` to invoke `kanban-project-sync --background`
- [x] 5.2 Update `CLAUDE.md` Planka Sync section to reference the script
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-03-04
@@ -0,0 +1,93 @@
## Context
pcli currently supports CRUD operations on individual Planka resources but has no way to bulk export or import project data. The Planka API returns nested data for boards (lists, cards, labels, card-labels, memberships) but requires per-card fetches for comments, task lists, and tasks. There is no existing user client — we need one to resolve comment author userIds to names.
## Goals / Non-Goals
**Goals:**
- Export an entire project (or single board) to a portable JSON file via stdout
- Import from that JSON file, creating all resources with fresh IDs on the target instance
- Use names (not IDs) as portable identity throughout the export format
- Preserve comment authorship textually via `(Original comment by <username>)` prefix
- Fail safely on import if project+board combination already exists
**Non-Goals:**
- Attachments/file export (binary assets — out of scope)
- Merge/update import (replace-only for now)
- Multi-board filter on export (single `--board` flag only)
- User/membership migration (not portable across instances)
- Incremental/differential export
## Decisions
### 1. Export format: flat nested JSON, no ID references
**Decision**: Export uses a fully nested structure where child objects are inline under their parent. Cards reference lists and labels by name, not ID.
**Rationale**: Avoids needing an ID remapping table in the export file. Makes the format human-readable and trivially parseable. Names are the natural portable identifier.
**Alternative considered**: Flat arrays with ID cross-references (like the Planka API response format). Rejected — adds complexity for both export and import with no benefit since IDs are regenerated anyway.
### 2. User resolution: one-time fetch during export
**Decision**: Export fetches the full user list once at the start, builds a userId→name map, and uses it to prefix comments.
**Rationale**: Comment API returns userId but not the user's name. A single bulk fetch is more efficient than per-comment lookups. Falls back to "unknown user" for unresolvable IDs.
**Implementation**: New `client/users.go` with `ListUsers()` method hitting `GET /api/users` (Planka v2 endpoint).
### 3. Import conflict detection: project+board name pair
**Decision**: Import checks if the target Planka instance already has a board with the same name under the same project. If so, it fails immediately before creating anything.
**Rationale**: This is the simplest safe behavior. Project existing alone is fine (we add the board to it). Board name collision means data would overlap, so we fail rather than risk duplicates.
**Implementation flow**:
1. List projects, find by name → use existing or create new
2. Get project's boards (via board list filtered by project)
3. For each board in export: check name against existing boards → fail if collision
4. Proceed with creation only after all boards pass the check
### 4. Export data gathering strategy
**Decision**: Use the existing board GET response (includes lists, cards, labels, card-labels) as the base, then fetch per-card details (comments, task lists, tasks) individually.
**Rationale**: Board GET already returns most of what we need in one call. Only comments and task lists/tasks require additional fetches. This minimizes API calls while getting complete data.
**Sequence per board**:
1. `GET /api/boards/<id>` → lists, cards, labels, card-labels
2. For each card: `GET /api/cards/<id>` → task lists, tasks
3. For each card: `GET /api/cards/<id>/comments` → comments
### 5. Command structure: subcommands under project
**Decision**: `pcli project export` and `pcli project import` as subcommands of the existing project command.
**Rationale**: Export/import are project-level operations. Keeps the CLI hierarchy clean and discoverable.
### 6. Import input: stdin and --file flag
**Decision**: Support both `pcli project import < file.json` and `pcli project import --file file.json`.
**Rationale**: stdin is natural for piping; `--file` is explicit and clearer in scripts. Minimal implementation cost to support both.
### 7. Import creation order
**Decision**: Create resources top-down: project → board → lists → labels → cards → card-labels → task lists → tasks → comments. Build name→ID maps as each level is created.
**Rationale**: Each child resource needs its parent's ID. Creating top-down and maintaining maps (e.g., listName→listID) lets us resolve references as we go.
**ID mapping during import**:
- `listName → listID` (created when lists are created)
- `labelName+color → labelID` (created when labels are created)
- Cards are created with the resolved listID, then card-label associations are created separately
## Risks / Trade-offs
**[Slow export for large projects]** → Accept the cost. Per-card fetches for comments/tasks could be slow with hundreds of cards. Could be optimized later with concurrency but keeping it simple (sequential) for now.
**[Comment attribution may be inaccurate]** → If users have been deleted or the user list endpoint requires admin permissions, some comments may show "unknown user". This is acceptable — textual attribution is best-effort.
**[No atomicity on import]** → If import fails partway through (e.g., API error on card 50 of 100), partial data will exist on the target. Mitigation: the conflict check happens upfront before any creation starts, so the most likely failure mode (name collision) is caught early. For API failures mid-import, the user would need to manually clean up or re-run after fixing the issue.
**[Label matching by name+color]** → Two labels with the same name but different colors would be treated as distinct. This matches Planka's model where labels are board-scoped and identified by name+color.
@@ -0,0 +1,92 @@
## Why
There's no way to backup, migrate, or clone project data between Planka instances using pcli. Users need to export a project (or specific board) to a portable file and import it elsewhere — useful for backups, instance migration, and sharing project templates.
## What Changes
- Add `pcli project export` command: exports a project (optionally filtered to a specific board) as a self-contained JSON file to stdout
- Add `pcli project import` command: reads a JSON export file and creates the project/board(s) on the target instance
- Export uses **names** (not IDs) as the portable identity — IDs are Planka-instance-specific and regenerated on import
- Export includes the full hierarchy: project → boards → lists → labels → cards → card-labels → task lists → tasks → comments
- Import uses **fail-if-exists** strategy: if the project+board name combination already exists on the target, import stops with an error. Project existing alone is fine (board gets added to it).
- User-specific references (cardMemberships, creatorUserId) are **excluded** from export — these are instance-specific and not portable
- Comments are exported with **text attribution**: each comment is prefixed with `(Original comment by <username>)` so authorship is preserved textually even though the userId is not portable. This requires a one-time user list fetch during export to resolve userId→name.
### Export format
Single JSON object to stdout. Structure:
```json
{
"version": 1,
"exportedAt": "2026-03-04T...",
"project": {
"name": "...",
"description": "...",
"boards": [
{
"name": "...",
"position": 1,
"lists": [...],
"labels": [...],
"cards": [
{
"name": "...",
"listName": "...",
"labelNames": ["..."],
"description": "...",
"taskLists": [
{
"name": "...",
"tasks": [{ "name": "...", "isCompleted": false }]
}
],
"comments": [{ "text": "(Original comment by jsmith)\nActual comment text here" }]
}
]
}
]
}
}
```
Key design choices:
- **Name-based references**: cards reference `listName` and `labelNames` instead of IDs
- **Nested hierarchy**: no ID cross-references to resolve — everything is inline
- **Version field**: allows future format changes
- Positions preserved to maintain ordering
- User fields stripped (not portable) except for textual attribution on comments
- Comments prefixed with `(Original comment by <username>)` — requires fetching user list during export to resolve userIds to names. If a userId can't be resolved, falls back to `(Original comment by unknown user)`
### Import behavior
1. Look up project by name — create if it doesn't exist
2. For each board in the export: check if project already has a board with that name → **fail with error** if so
3. Create board, then lists, labels, cards (mapping listName→list ID, labelNames→label IDs), task lists, tasks, comments — all with fresh Planka IDs
4. Ordering maintained via position fields from the export
### CLI interface
```
pcli project export <project-id-or-name> [--board <name-or-id>] > backup.json
pcli project import < backup.json
# or
pcli project import --file backup.json
```
## Capabilities
### New Capabilities
- `project-export`: Export project hierarchy to portable JSON (project → boards → lists → labels → cards → task lists → tasks → comments)
- `project-import`: Import project hierarchy from JSON export file, creating all resources with new IDs
### Modified Capabilities
_(none — these are new commands added to the existing project resource)_
## Impact
- **New files**: `client/export.go`, `client/import.go`, `client/users.go`, `cmd/export.go`, `cmd/import.go`
- **Model changes**: new export-specific types in `model/types.go` (portable structs without IDs/user references), new User type
- **API usage**: export requires multiple API calls (user list for name resolution, board GET for bulk data, then per-card fetches for comments/tasks) — could be slow for large projects
- **No breaking changes**: purely additive new subcommands
- **Dependencies**: none new (standard library JSON encoding)
@@ -0,0 +1,79 @@
## ADDED Requirements
### Requirement: Export project hierarchy to JSON
The system SHALL export a complete project hierarchy as a JSON object to stdout. The export SHALL include: project metadata, boards, lists, labels, cards (with list and label name references), task lists, tasks, and comments.
#### Scenario: Export entire project
- **WHEN** user runs `pcli project export <project-id-or-name>`
- **THEN** the system outputs a JSON object to stdout containing the project and all its boards with their full hierarchy
#### Scenario: Export with board filter
- **WHEN** user runs `pcli project export <project-id-or-name> --board <board-name-or-id>`
- **THEN** the system outputs a JSON object containing only the specified board (and its full hierarchy) under the project
#### Scenario: Board filter does not match
- **WHEN** user runs `pcli project export <project> --board <nonexistent>`
- **THEN** the system exits with an error indicating the board was not found
### Requirement: Export format uses version envelope
The export JSON SHALL contain a `version` field (integer, currently `1`), an `exportedAt` timestamp (ISO 8601), and a `project` object.
#### Scenario: Export envelope structure
- **WHEN** an export is generated
- **THEN** the root JSON object contains exactly `version`, `exportedAt`, and `project` keys
- **THEN** `version` is `1`
- **THEN** `exportedAt` is a valid ISO 8601 timestamp
### Requirement: Export uses name-based references
The export SHALL use names instead of IDs for all cross-references. Cards SHALL reference their list by `listName` and their labels by `labelNames` (array of label name strings). No Planka IDs SHALL appear in the export.
#### Scenario: Card references list by name
- **WHEN** a card belongs to a list named "In Progress"
- **THEN** the exported card has `"listName": "In Progress"` instead of a list ID
#### Scenario: Card references labels by name
- **WHEN** a card has labels "Bug" and "Urgent"
- **THEN** the exported card has `"labelNames": ["Bug", "Urgent"]`
### Requirement: Export preserves ordering
The export SHALL include `position` fields for boards, lists, labels, and cards to maintain their display ordering on import.
#### Scenario: List ordering preserved
- **WHEN** a board has lists "Todo" (position 1), "Doing" (position 2), "Done" (position 3)
- **THEN** the exported lists include their position values
### Requirement: Export includes comment attribution
Each exported comment SHALL have its text prefixed with `(Original comment by <username>)\n` where `<username>` is resolved from the comment's userId. If the userId cannot be resolved, the prefix SHALL use `unknown user`.
#### Scenario: Comment with known author
- **WHEN** a comment was authored by user "jsmith"
- **THEN** the exported comment text starts with `(Original comment by jsmith)\n`
#### Scenario: Comment with unresolvable author
- **WHEN** a comment's userId does not match any known user
- **THEN** the exported comment text starts with `(Original comment by unknown user)\n`
### Requirement: Export excludes user-specific data
The export SHALL NOT include cardMemberships, creatorUserId, or userId fields. Only textual comment attribution (as a text prefix) SHALL preserve user information.
#### Scenario: Card memberships excluded
- **WHEN** a card has members assigned
- **THEN** the exported card does not contain membership data
### Requirement: Export includes task lists and tasks
The export SHALL include task lists and their tasks for each card. Each task list SHALL contain its tasks inline. Tasks SHALL include `name` and `isCompleted` fields.
#### Scenario: Card with task lists
- **WHEN** a card has a task list "Checklist" with tasks "Item 1" (complete) and "Item 2" (incomplete)
- **THEN** the exported card includes the task list with both tasks and their completion status
### Requirement: Project identified by name or ID
The `<project-id-or-name>` argument SHALL accept either a Planka project ID or a project name. If a name is provided, the system SHALL look up the project by name. If multiple projects match the name, the system SHALL exit with an error.
#### Scenario: Project by name
- **WHEN** user provides a project name that matches exactly one project
- **THEN** the system exports that project
#### Scenario: Ambiguous project name
- **WHEN** user provides a project name that matches multiple projects
- **THEN** the system exits with an error listing the matches
@@ -0,0 +1,83 @@
## ADDED Requirements
### Requirement: Import project hierarchy from JSON
The system SHALL read a JSON export file and create all resources (project, boards, lists, labels, cards, card-labels, task lists, tasks, comments) on the target Planka instance with fresh IDs.
#### Scenario: Import from stdin
- **WHEN** user runs `pcli project import < backup.json`
- **THEN** the system reads the JSON from stdin and creates all resources
#### Scenario: Import from file flag
- **WHEN** user runs `pcli project import --file backup.json`
- **THEN** the system reads the JSON from the specified file and creates all resources
#### Scenario: No input provided
- **WHEN** user runs `pcli project import` with no stdin and no --file flag
- **THEN** the system exits with an error indicating input is required
### Requirement: Import creates project if not exists
The system SHALL look up the project by name. If no project with that name exists, the system SHALL create it. If the project already exists, the system SHALL use the existing project.
#### Scenario: Project does not exist
- **WHEN** importing a project named "proj1" and no project with that name exists
- **THEN** the system creates a new project named "proj1"
#### Scenario: Project already exists
- **WHEN** importing a project named "proj1" and a project with that name already exists
- **THEN** the system uses the existing project (does not create a duplicate)
### Requirement: Import fails if board name conflicts
Before creating any resources, the system SHALL check that none of the boards in the export file have names that conflict with existing boards in the target project. If any board name already exists under the target project, the system SHALL exit with an error naming the conflicting board(s) and create nothing.
#### Scenario: No board conflict
- **WHEN** importing boards "board1" and "board2" into project "proj1" which has no boards
- **THEN** the import proceeds and creates both boards
#### Scenario: Board name conflict
- **WHEN** importing board "board1" into project "proj1" which already has a board named "board1"
- **THEN** the system exits with an error: board "board1" already exists in project "proj1"
- **THEN** no resources are created
#### Scenario: Partial conflict
- **WHEN** importing boards "board1" and "board2" into project "proj1" which already has "board2"
- **THEN** the system exits with an error about "board2" conflicting
- **THEN** no resources are created (not even "board1")
### Requirement: Import creates resources in dependency order
The system SHALL create resources top-down: board → lists → labels → cards → card-label associations → task lists → tasks → comments. Name-to-ID maps SHALL be maintained at each level to resolve references for child resources.
#### Scenario: Card references resolved on import
- **WHEN** a card in the export has `"listName": "In Progress"` and `"labelNames": ["Bug"]`
- **THEN** the system creates the card in the list named "In Progress" and associates it with the label named "Bug" using the IDs generated during import
### Requirement: Import preserves ordering
The system SHALL use position values from the export to maintain the original display ordering of boards, lists, labels, and cards.
#### Scenario: List positions preserved
- **WHEN** the export contains lists with positions 1, 2, 3
- **THEN** the imported lists are created with those same position values
### Requirement: Import validates export version
The system SHALL check the `version` field of the export JSON. If the version is not supported (currently only version `1`), the system SHALL exit with an error.
#### Scenario: Supported version
- **WHEN** the export file has `"version": 1`
- **THEN** the import proceeds normally
#### Scenario: Unsupported version
- **WHEN** the export file has `"version": 99`
- **THEN** the system exits with an error indicating the version is not supported
### Requirement: Import reports progress
The system SHALL output progress information to stderr as it creates resources, including the count of each resource type created.
#### Scenario: Progress reporting
- **WHEN** an import completes successfully
- **THEN** stderr shows a summary: boards created, lists created, cards created, etc.
### Requirement: Import handles missing list reference
If a card references a `listName` that does not exist in the board's lists, the system SHALL exit with an error identifying the card and the missing list name.
#### Scenario: Invalid list reference
- **WHEN** a card references `"listName": "Nonexistent"` and no list with that name exists in the board
- **THEN** the system exits with an error: card "<name>" references unknown list "Nonexistent"
@@ -0,0 +1,24 @@
## 1. Model & Types
- [x] 1.1 Add User struct to `model/types.go` (id, name, username, email)
- [x] 1.2 Add export-specific portable types to `model/types.go`: ExportEnvelope, ExportProject, ExportBoard, ExportList, ExportLabel, ExportCard, ExportTaskList, ExportTask, ExportComment
## 2. User Client
- [x] 2.1 Create `client/users.go` with `ListUsers()` method (GET /api/users)
## 3. Project Export
- [x] 3.1 Create `client/export.go` with `ExportProject(ctx, projectID, boardFilter)` method that orchestrates data gathering: fetch users (build userId→name map), fetch board(s) with included data, fetch per-card comments/task lists/tasks, assemble into portable export types
- [x] 3.2 Create `cmd/export.go` with `project export <project-id-or-name> [--board <name-or-id>]` command: resolve project by name or ID, call ExportProject, marshal JSON to stdout
- [x] 3.3 Add project name/ID resolution helper: list projects, match by ID or exact name, error on ambiguous match
## 4. Project Import
- [x] 4.1 Create `client/import.go` with `ImportProject(ctx, export)` method that: resolves/creates project by name, checks board name conflicts (fail-fast), creates boards → lists → labels → cards → card-labels → task lists → tasks → comments in order, maintains name→ID maps at each level, reports progress to stderr
- [x] 4.2 Create `cmd/import.go` with `project import [--file <path>]` command: read JSON from stdin or file, unmarshal, validate version, call ImportProject
## 5. Wire Up & Integration
- [x] 5.1 Register export and import subcommands under project command in `cmd/root.go` or `cmd/project.go`
- [x] 5.2 End-to-end test: export a project, import to same instance under different project name, verify structure matches
-20
View File
@@ -1,20 +0,0 @@
schema: spec-driven
# Project context (optional)
# This is shown to AI when creating artifacts.
# Add your tech stack, conventions, style guides, domain knowledge, etc.
# Example:
# context: |
# Tech stack: TypeScript, React, Node.js
# We use conventional commits
# Domain: e-commerce platform
# Per-artifact rules (optional)
# Add custom rules for specific artifacts.
# Example:
# rules:
# proposal:
# - Keep proposals under 500 words
# - Always include a "Non-goals" section
# tasks:
# - Break tasks into chunks of max 2 hours
+15 -2
View File
@@ -71,11 +71,24 @@ The client SHALL provide methods to list all accessible projects (`GET /projects
- **THEN** the client SHALL send `DELETE /projects/{id}` - **THEN** the client SHALL send `DELETE /projects/{id}`
### Requirement: Board operations ### Requirement: Board operations
The client SHALL provide a method to get a single board by ID (`GET /boards/{id}`), list board actions (`GET /boards/{boardId}/actions`) with pagination support, create a board (`POST /projects/{projectId}/boards`), and delete a board (`DELETE /boards/{id}`). The client SHALL provide a method to get a single board by ID (`GET /boards/{id}`), list board actions (`GET /boards/{boardId}/actions`) with pagination support, create a board (`POST /projects/{projectId}/boards`), and delete a board (`DELETE /boards/{id}`). `GetBoard` SHALL parse the `included` object from the response and populate the Board model with `lists`, `cards`, `labels`, `cardLabels`, and `cardMemberships`.
#### Scenario: Get board #### Scenario: Get board
- **WHEN** `GetBoard` is called with a board ID - **WHEN** `GetBoard` is called with a board ID
- **THEN** the client SHALL send `GET /boards/{id}` and return a Board model including its included lists - **THEN** the client SHALL send `GET /boards/{id}` and return a Board model including its included lists, cards, labels, cardLabels, and cardMemberships
#### Scenario: Get board includes labels
- **WHEN** `GetBoard` is called and the board has labels defined
- **THEN** the returned Board SHALL contain a `Labels` slice with all board labels
#### Scenario: Get board includes card-label associations
- **WHEN** `GetBoard` is called and cards on the board have labels attached
- **THEN** the returned Board SHALL contain a `CardLabels` slice with all card-label associations
- **AND** each `CardLabel` entry SHALL contain `cardId` and `labelId` fields
#### Scenario: Get board includes card memberships
- **WHEN** `GetBoard` is called and cards on the board have members assigned
- **THEN** the returned Board SHALL contain a `CardMemberships` slice with all card-membership associations
#### Scenario: List board actions #### Scenario: List board actions
- **WHEN** `ListBoardActions` is called with a board ID and limit - **WHEN** `ListBoardActions` is called with a board ID and limit
@@ -0,0 +1,38 @@
# Board List Filtering
## Purpose
Provides filtering capabilities for the `board list` command to scope results by project name.
## Requirements
### Requirement: Board list project filtering
The system SHALL provide a `--project <name>` flag for the `board list` command. When the flag is provided, the system SHALL resolve the project name to a project ID by calling `ListProjects()` and performing a case-insensitive exact match on the project name. If no matching project is found, the system SHALL output an error message "project not found: <name>" and exit with code 1. If a matching project is found, the system SHALL filter the board list to include only boards where `projectId` matches the resolved project ID. When the `--project` flag is omitted, the system SHALL list all accessible boards without filtering.
#### Scenario: List boards without project filter
- **WHEN** `pcli board list` is executed without the `--project` flag
- **THEN** the system SHALL output all accessible boards across all projects
#### Scenario: List boards filtered by project name
- **WHEN** `pcli board list --project "project1"` is executed
- **THEN** the system SHALL resolve "project1" to a project ID
- **AND** the system SHALL output only boards belonging to that project
#### Scenario: List boards with case-insensitive project match
- **WHEN** `pcli board list --project "PROJECT1"` is executed and a project named "project1" exists
- **THEN** the system SHALL match the project case-insensitively
- **AND** the system SHALL output boards belonging to the matched project
#### Scenario: Project name not found
- **WHEN** `pcli board list --project "nonexistent"` is executed
- **THEN** the system SHALL output "project not found: nonexistent"
- **AND** the system SHALL exit with code 1
#### Scenario: Project exists but has no boards
- **WHEN** `pcli board list --project "empty-project"` is executed for a project with no boards
- **THEN** the system SHALL output an empty list (or empty JSON array in JSON format)
#### Scenario: User lacks access to project
- **WHEN** `pcli board list --project "restricted"` is executed for a project the user cannot access
- **THEN** the system SHALL output "project not found: restricted"
- **AND** the system SHALL exit with code 1
+11 -3
View File
@@ -65,18 +65,26 @@ The system SHALL provide `card add-label` and `card remove-label` operations to
- **THEN** the system SHALL print an error indicating `--label` is required and exit with code 1 - **THEN** the system SHALL print an error indicating `--label` is required and exit with code 1
### Requirement: Enriched board-level card listing ### Requirement: Enriched board-level card listing
The system SHALL provide a `card list --board <id>` operation that returns all cards across all lists in a board, with each card enriched with the `listName` field. The operation SHALL: (1) call `GET /boards/{id}` to retrieve the board and its included lists, (2) call `GET /lists/{listId}/cards` for each list to retrieve cards (with pagination support), (3) inject `listName` into each card based on the list it belongs to. The `--limit` flag SHALL apply to the total number of cards returned across all lists. The system SHALL provide a `card list --board <id>` operation that returns all cards across all lists in a board, with each card enriched with the `listName` field and a `labels` field. The operation SHALL: (1) call `GET /boards/{id}` to retrieve the board and its included lists, cards, labels, and cardLabels, (2) build a card-to-label-names map by joining `cardLabels` with `labels`, (3) inject `listName` and `labels` into each card. The `labels` field SHALL be an array of label name strings. The `--limit` flag SHALL apply to the total number of cards returned across all lists.
#### Scenario: List all cards on a board #### Scenario: List all cards on a board
- **WHEN** `pcli card list --board <id>` is executed - **WHEN** `pcli card list --board <id>` is executed
- **THEN** the system SHALL return all cards from all lists in the board - **THEN** the system SHALL return all cards from all lists in the board
- **AND** each card SHALL include a `listName` field with the name of its containing list - **AND** each card SHALL include a `listName` field with the name of its containing list
- **AND** each card SHALL include a `listId` field - **AND** each card SHALL include a `labels` field with an array of label names attached to that card
#### Scenario: Card with multiple labels
- **WHEN** a card has two labels ("bug" and "urgent") attached
- **THEN** the `labels` array for that card SHALL contain both "bug" and "urgent"
#### Scenario: Card with no labels
- **WHEN** a card has no labels attached
- **THEN** the `labels` array for that card SHALL be an empty array (not null)
#### Scenario: Board card listing with limit #### Scenario: Board card listing with limit
- **WHEN** `pcli card list --board <id> --limit 10` is executed - **WHEN** `pcli card list --board <id> --limit 10` is executed
- **THEN** the system SHALL return at most 10 cards total across all lists - **THEN** the system SHALL return at most 10 cards total across all lists
- **AND** each card SHALL include the `listName` field - **AND** each card SHALL include the `listName` and `labels` fields
#### Scenario: Board with no cards #### Scenario: Board with no cards
- **WHEN** `pcli card list --board <id>` is executed on a board with empty lists - **WHEN** `pcli card list --board <id>` is executed on a board with empty lists
+17 -2
View File
@@ -60,8 +60,19 @@ The system SHALL provide a `project` command group with subcommands `list`, `get
- **WHEN** `pcli project delete <id>` is executed with a non-existent project ID - **WHEN** `pcli project delete <id>` is executed with a non-existent project ID
- **THEN** the system SHALL output "delete project: not found — the resource may not exist or you may not have access to it" - **THEN** the system SHALL output "delete project: not found — the resource may not exist or you may not have access to it"
### Requirement: Board list command
The system SHALL provide a `board list` subcommand. `pcli board list` SHALL call the client's ListBoards method and output all accessible boards. The command SHALL accept an optional `--project <name>` flag (string). When `--project` is provided, the system SHALL filter boards to only those belonging to the specified project (see board-list-filtering spec for filtering behavior).
#### Scenario: List all boards
- **WHEN** `pcli board list` is executed without flags
- **THEN** the system SHALL output all accessible boards
#### Scenario: List boards filtered by project
- **WHEN** `pcli board list --project "project1"` is executed
- **THEN** the system SHALL output only boards belonging to the specified project
### Requirement: Board commands ### Requirement: Board commands
The system SHALL provide a `board` command group with subcommands `get`, `actions`, `create`, and `delete`. `pcli board get <id>` SHALL accept a board ID as a positional argument and output the board details. `pcli board actions <id>` SHALL accept a board ID and an optional `--limit` flag (int, default 0) and output the board's action history. `pcli board create` SHALL create a new board. `pcli board delete <id>` SHALL delete a board. The system SHALL provide a `board` command group with subcommands `list`, `get`, `actions`, `create`, and `delete`. `pcli board list` SHALL list all accessible boards and accept an optional `--project <name>` flag for filtering. `pcli board get <id>` SHALL accept a board ID as a positional argument and output the board details. `pcli board actions <id>` SHALL accept a board ID and an optional `--limit` flag (int, default 0) and output the board's action history. `pcli board create` SHALL create a new board. `pcli board delete <id>` SHALL delete a board.
#### Scenario: Get board #### Scenario: Get board
- **WHEN** `pcli board get <id>` is executed - **WHEN** `pcli board get <id>` is executed
@@ -230,12 +241,16 @@ The system SHALL provide a `task` command group with subcommands: `create`, `upd
- **THEN** the system SHALL delete the task and output a success confirmation - **THEN** the system SHALL delete the task and output a success confirmation
### Requirement: Status command ### Requirement: Status command
The system SHALL provide a top-level `status` command registered directly on the root command (not as a subcommand of any resource group). `pcli status` SHALL take no positional arguments. The command SHALL fetch all boards via `ListBoards`, then fetch each board's details via `GetBoard` sequentially, aggregate card counts per list, and output the result via the standard `output.Print` mechanism respecting the global `--format` flag. The system SHALL provide a top-level `status` command registered directly on the root command (not as a subcommand of any resource group). `pcli status` SHALL take no positional arguments. The command SHALL accept an optional `--project <name>` flag (string) to filter boards by project name. The command SHALL fetch all boards via `ListBoards`, optionally filter by project, then fetch each board's details via `GetBoard` sequentially, aggregate card counts per list, and output the result via the standard `output.Print` mechanism respecting the global `--format` flag.
#### Scenario: Run status command #### Scenario: Run status command
- **WHEN** `pcli status` is executed - **WHEN** `pcli status` is executed
- **THEN** the system SHALL output a summary of all boards with their lists and card counts - **THEN** the system SHALL output a summary of all boards with their lists and card counts
#### Scenario: Run status command with project filter
- **WHEN** `pcli status --project "MyProject"` is executed
- **THEN** the system SHALL output a summary of only boards belonging to "MyProject"
#### Scenario: Status command respects format flag #### Scenario: Status command respects format flag
- **WHEN** `pcli status --format table` is executed - **WHEN** `pcli status --format table` is executed
- **THEN** the output SHALL be in table format - **THEN** the output SHALL be in table format
@@ -0,0 +1,57 @@
### Requirement: Exclusive sync execution
The sync script SHALL use `flock` advisory locking to ensure only one sync instance runs at a time per project-board pair. The lock file SHALL be located at `/tmp/kanban-project-sync-<project>-<board>.lock`.
#### Scenario: First sync acquires lock
- **WHEN** kanban-project-sync is invoked and no other sync is running for the same project-board
- **THEN** the script acquires the flock and executes the full sync
#### Scenario: Second sync finds lock held
- **WHEN** kanban-project-sync is invoked while another sync is running for the same project-board
- **THEN** the script SHALL NOT execute the sync, SHALL touch the pending flag file, and SHALL exit with code 0
### Requirement: Coalescing pending queue
The sync script SHALL implement a depth-1 coalescing queue using a pending flag file at `/tmp/kanban-project-sync-<project>-<board>.pending`. Multiple pending requests SHALL coalesce into a single re-run.
#### Scenario: Pending flag set during sync
- **WHEN** a sync completes and the pending flag file exists
- **THEN** the script SHALL clear the pending flag and re-run the sync before releasing the lock
#### Scenario: No pending flag after sync
- **WHEN** a sync completes and no pending flag file exists
- **THEN** the script SHALL release the lock and exit
#### Scenario: Multiple pending requests coalesce
- **WHEN** three sync requests arrive while a sync is running
- **THEN** only one additional sync SHALL run after the current one completes (not three)
### Requirement: Foreground and background modes
The sync script SHALL default to foreground execution (output to stdout/stderr). When `--background` is passed, the script SHALL detach and redirect output to a log file at `/tmp/kanban-project-sync-<project>-<board>.log`.
#### Scenario: Foreground execution
- **WHEN** kanban-project-sync is invoked without `--background`
- **THEN** sync output SHALL be written to stdout/stderr and the script SHALL block until complete
#### Scenario: Background execution
- **WHEN** kanban-project-sync is invoked with `--background`
- **THEN** the script SHALL detach from the terminal, redirect output to the log file, and return immediately
### Requirement: Required arguments
The sync script SHALL require `--project <name>` and `--board <name>` arguments. The script SHALL NOT read `project.yaml` directly.
#### Scenario: Missing arguments
- **WHEN** kanban-project-sync is invoked without `--project` or `--board`
- **THEN** the script SHALL print usage information and exit with code 1
### Requirement: Connectivity check
The sync script SHALL run `pcli status` before syncing. If the check fails, the script SHALL exit with code 2.
#### Scenario: Planka offline
- **WHEN** `pcli status` returns a non-zero exit code
- **THEN** the script SHALL print a message indicating Planka is unreachable and exit with code 2
### Requirement: Idempotent sync phases
The sync script SHALL implement all 10 phases of the existing kanban-sync workflow: connectivity check, bootstrap infrastructure (find-or-create project, board, lists, label), gather OpenSpec state, determine target lists, gather Planka agent cards, create missing cards, move cards to correct lists, sync task checklists, handle archived changes, and report. Each phase SHALL be idempotent — running the script twice with no state changes SHALL produce no Planka API mutations on the second run.
#### Scenario: Clean re-run with no changes
- **WHEN** the sync script runs twice in succession with no OpenSpec or Planka state changes between runs
- **THEN** the second run SHALL make no create/update/move API calls and SHALL report zero changes
+85
View File
@@ -0,0 +1,85 @@
# project-export Spec
## Purpose
Enable users to export a complete Planka project hierarchy (boards, lists, cards, labels, tasks, comments) to a portable JSON format for backup, migration, or documentation purposes.
## Requirements
### Requirement: Export project hierarchy to JSON
The system SHALL export a complete project hierarchy as a JSON object to stdout. The export SHALL include: project metadata, boards, lists, labels, cards (with list and label name references), task lists, tasks, and comments.
#### Scenario: Export entire project
- **WHEN** user runs `pcli project export <project-id-or-name>`
- **THEN** the system outputs a JSON object to stdout containing the project and all its boards with their full hierarchy
#### Scenario: Export with board filter
- **WHEN** user runs `pcli project export <project-id-or-name> --board <board-name-or-id>`
- **THEN** the system outputs a JSON object containing only the specified board (and its full hierarchy) under the project
#### Scenario: Board filter does not match
- **WHEN** user runs `pcli project export <project> --board <nonexistent>`
- **THEN** the system exits with an error indicating the board was not found
### Requirement: Export format uses version envelope
The export JSON SHALL contain a `version` field (integer, currently `1`), an `exportedAt` timestamp (ISO 8601), and a `project` object.
#### Scenario: Export envelope structure
- **WHEN** an export is generated
- **THEN** the root JSON object contains exactly `version`, `exportedAt`, and `project` keys
- **THEN** `version` is `1`
- **THEN** `exportedAt` is a valid ISO 8601 timestamp
### Requirement: Export uses name-based references
The export SHALL use names instead of IDs for all cross-references. Cards SHALL reference their list by `listName` and their labels by `labelNames` (array of label name strings). No Planka IDs SHALL appear in the export.
#### Scenario: Card references list by name
- **WHEN** a card belongs to a list named "In Progress"
- **THEN** the exported card has `"listName": "In Progress"` instead of a list ID
#### Scenario: Card references labels by name
- **WHEN** a card has labels "Bug" and "Urgent"
- **THEN** the exported card has `"labelNames": ["Bug", "Urgent"]`
### Requirement: Export preserves ordering
The export SHALL include `position` fields for boards, lists, labels, and cards to maintain their display ordering on import.
#### Scenario: List ordering preserved
- **WHEN** a board has lists "Todo" (position 1), "Doing" (position 2), "Done" (position 3)
- **THEN** the exported lists include their position values
### Requirement: Export includes comment attribution
Each exported comment SHALL have its text prefixed with `(Original comment by <username>)\n` where `<username>` is resolved from the comment's userId. If the userId cannot be resolved, the prefix SHALL use `unknown user`.
#### Scenario: Comment with known author
- **WHEN** a comment was authored by user "jsmith"
- **THEN** the exported comment text starts with `(Original comment by jsmith)\n`
#### Scenario: Comment with unresolvable author
- **WHEN** a comment's userId does not match any known user
- **THEN** the exported comment text starts with `(Original comment by unknown user)\n`
### Requirement: Export excludes user-specific data
The export SHALL NOT include cardMemberships, creatorUserId, or userId fields. Only textual comment attribution (as a text prefix) SHALL preserve user information.
#### Scenario: Card memberships excluded
- **WHEN** a card has members assigned
- **THEN** the exported card does not contain membership data
### Requirement: Export includes task lists and tasks
The export SHALL include task lists and their tasks for each card. Each task list SHALL contain its tasks inline. Tasks SHALL include `name` and `isCompleted` fields.
#### Scenario: Card with task lists
- **WHEN** a card has a task list "Checklist" with tasks "Item 1" (complete) and "Item 2" (incomplete)
- **THEN** the exported card includes the task list with both tasks and their completion status
### Requirement: Project identified by name or ID
The `<project-id-or-name>` argument SHALL accept either a Planka project ID or a project name. If a name is provided, the system SHALL look up the project by name. If multiple projects match the name, the system SHALL exit with an error.
#### Scenario: Project by name
- **WHEN** user provides a project name that matches exactly one project
- **THEN** the system exports that project
#### Scenario: Ambiguous project name
- **WHEN** user provides a project name that matches multiple projects
- **THEN** the system exits with an error listing the matches
+89
View File
@@ -0,0 +1,89 @@
# project-import Spec
## Purpose
Enable users to import a Planka project hierarchy from a JSON export file, creating all resources (boards, lists, cards, labels, tasks, comments) on the target Planka instance with fresh IDs while preserving structure and ordering.
## Requirements
### Requirement: Import project hierarchy from JSON
The system SHALL read a JSON export file and create all resources (project, boards, lists, labels, cards, card-labels, task lists, tasks, comments) on the target Planka instance with fresh IDs.
#### Scenario: Import from stdin
- **WHEN** user runs `pcli project import < backup.json`
- **THEN** the system reads the JSON from stdin and creates all resources
#### Scenario: Import from file flag
- **WHEN** user runs `pcli project import --file backup.json`
- **THEN** the system reads the JSON from the specified file and creates all resources
#### Scenario: No input provided
- **WHEN** user runs `pcli project import` with no stdin and no --file flag
- **THEN** the system exits with an error indicating input is required
### Requirement: Import creates project if not exists
The system SHALL look up the project by name. If no project with that name exists, the system SHALL create it. If the project already exists, the system SHALL use the existing project.
#### Scenario: Project does not exist
- **WHEN** importing a project named "proj1" and no project with that name exists
- **THEN** the system creates a new project named "proj1"
#### Scenario: Project already exists
- **WHEN** importing a project named "proj1" and a project with that name already exists
- **THEN** the system uses the existing project (does not create a duplicate)
### Requirement: Import fails if board name conflicts
Before creating any resources, the system SHALL check that none of the boards in the export file have names that conflict with existing boards in the target project. If any board name already exists under the target project, the system SHALL exit with an error naming the conflicting board(s) and create nothing.
#### Scenario: No board conflict
- **WHEN** importing boards "board1" and "board2" into project "proj1" which has no boards
- **THEN** the import proceeds and creates both boards
#### Scenario: Board name conflict
- **WHEN** importing board "board1" into project "proj1" which already has a board named "board1"
- **THEN** the system exits with an error: board "board1" already exists in project "proj1"
- **THEN** no resources are created
#### Scenario: Partial conflict
- **WHEN** importing boards "board1" and "board2" into project "proj1" which already has "board2"
- **THEN** the system exits with an error about "board2" conflicting
- **THEN** no resources are created (not even "board1")
### Requirement: Import creates resources in dependency order
The system SHALL create resources top-down: board → lists → labels → cards → card-label associations → task lists → tasks → comments. Name-to-ID maps SHALL be maintained at each level to resolve references for child resources.
#### Scenario: Card references resolved on import
- **WHEN** a card in the export has `"listName": "In Progress"` and `"labelNames": ["Bug"]`
- **THEN** the system creates the card in the list named "In Progress" and associates it with the label named "Bug" using the IDs generated during import
### Requirement: Import preserves ordering
The system SHALL use position values from the export to maintain the original display ordering of boards, lists, labels, and cards.
#### Scenario: List positions preserved
- **WHEN** the export contains lists with positions 1, 2, 3
- **THEN** the imported lists are created with those same position values
### Requirement: Import validates export version
The system SHALL check the `version` field of the export JSON. If the version is not supported (currently only version `1`), the system SHALL exit with an error.
#### Scenario: Supported version
- **WHEN** the export file has `"version": 1`
- **THEN** the import proceeds normally
#### Scenario: Unsupported version
- **WHEN** the export file has `"version": 99`
- **THEN** the system exits with an error indicating the version is not supported
### Requirement: Import reports progress
The system SHALL output progress information to stderr as it creates resources, including the count of each resource type created.
#### Scenario: Progress reporting
- **WHEN** an import completes successfully
- **THEN** stderr shows a summary: boards created, lists created, cards created, etc.
### Requirement: Import handles missing list reference
If a card references a `listName` that does not exist in the board's lists, the system SHALL exit with an error identifying the card and the missing list name.
#### Scenario: Invalid list reference
- **WHEN** a card references `"listName": "Nonexistent"` and no list with that name exists in the board
- **THEN** the system exits with an error: card "<name>" references unknown list "Nonexistent"
+26 -1
View File
@@ -1,7 +1,32 @@
## ADDED Requirements ## ADDED Requirements
### Requirement: Status command project filtering
The system SHALL accept an optional `--project <name>` flag on the `pcli status` command. When `--project` is provided, the system SHALL resolve the project name to a project ID using case-insensitive exact matching against all accessible projects. The system SHALL then filter the board list to include only boards whose `projectId` matches the resolved project ID. The `totalBoards` count in the output SHALL reflect the filtered board count. When `--project` is omitted, behavior SHALL be unchanged (all boards shown).
#### Scenario: Status filtered by project name
- **WHEN** `pcli status --project "MyProject"` is executed and the project exists with 2 boards
- **THEN** the output SHALL include only the 2 boards belonging to "MyProject"
- **AND** `totalBoards` SHALL be 2
#### Scenario: Status filtered by project name case-insensitive
- **WHEN** `pcli status --project "myproject"` is executed and a project named "MyProject" exists
- **THEN** the output SHALL include boards belonging to "MyProject"
#### Scenario: Status with project filter and no matching boards
- **WHEN** `pcli status --project "EmptyProject"` is executed and the project exists but has no boards
- **THEN** the output SHALL show `totalBoards` as 0 and an empty boards array
#### Scenario: Status with project not found
- **WHEN** `pcli status --project "NonExistent"` is executed and no project with that name exists
- **THEN** the system SHALL output an error "project not found: NonExistent"
- **AND** the system SHALL exit with code 1
#### Scenario: Status without project flag
- **WHEN** `pcli status` is executed without `--project`
- **THEN** the output SHALL include all boards across all projects (unchanged behavior)
### Requirement: Status command summary output ### Requirement: Status command summary output
The system SHALL provide a top-level `pcli status` command that outputs a summary of all boards, their lists, and card counts. The summary SHALL include the total number of boards. For each board, the summary SHALL include the board name and a breakdown of each list within that board showing the list name, the number of open cards (where `isClosed` is false), and the number of closed cards (where `isClosed` is true). Empty lists SHALL be included in the output with 0 open and 0 closed cards. The system SHALL provide a top-level `pcli status` command that outputs a summary of all boards (or boards filtered by `--project`), their lists, and card counts. The summary SHALL include the total number of boards. For each board, the summary SHALL include the board name and a breakdown of each list within that board showing the list name, the number of open cards (where `isClosed` is false), and the number of closed cards (where `isClosed` is true). Empty lists SHALL be included in the output with 0 open and 0 closed cards.
#### Scenario: Status with multiple boards and lists #### Scenario: Status with multiple boards and lists
- **WHEN** `pcli status` is executed and there are boards with lists containing cards - **WHEN** `pcli status` is executed and there are boards with lists containing cards
+49
View File
@@ -93,6 +93,8 @@ func printTable(data any, w io.Writer) error {
return printTaskTable(data.([]model.Task), tw) return printTaskTable(data.([]model.Task), tw)
case "Label": case "Label":
return printLabelTable(data.([]model.Label), tw) return printLabelTable(data.([]model.Label), tw)
case "List":
return printListTable(data.([]model.List), tw)
case "Action": case "Action":
return printActionTable(data.([]model.Action), tw) return printActionTable(data.([]model.Action), tw)
default: default:
@@ -107,6 +109,8 @@ func printTable(data any, w io.Writer) error {
return printBoardTable([]model.Board{*data}, tw) return printBoardTable([]model.Board{*data}, tw)
case *model.Card: case *model.Card:
return printCardTable([]model.Card{*data}, tw) return printCardTable([]model.Card{*data}, tw)
case *model.CardDetail:
return printCardDetailTable(data, tw)
case *model.Comment: case *model.Comment:
return printCommentTable([]model.Comment{*data}, tw) return printCommentTable([]model.Comment{*data}, tw)
case *model.TaskList: case *model.TaskList:
@@ -115,6 +119,8 @@ func printTable(data any, w io.Writer) error {
return printTaskTable([]model.Task{*data}, tw) return printTaskTable([]model.Task{*data}, tw)
case *model.Label: case *model.Label:
return printLabelTable([]model.Label{*data}, tw) return printLabelTable([]model.Label{*data}, tw)
case *model.List:
return printListTable([]model.List{*data}, tw)
case model.StatusSummary: case model.StatusSummary:
return printStatusTable(data, tw) return printStatusTable(data, tw)
case *model.StatusSummary: case *model.StatusSummary:
@@ -160,6 +166,29 @@ func printCardWithListTable(cards []model.CardWithList, tw *tabwriter.Writer) er
return nil return nil
} }
func printCardDetailTable(card *model.CardDetail, tw *tabwriter.Writer) error {
fmt.Fprintln(tw, "ID\tNAME\tLIST_ID\tTYPE\tCLOSED")
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%v\n", card.ID, card.Name, card.ListID, card.Type, card.IsClosed)
if len(card.TaskLists) > 0 {
fmt.Fprintln(tw)
fmt.Fprintln(tw, "TASK_LIST_ID\tTASK_LIST_NAME\tPOSITION")
for _, tl := range card.TaskLists {
fmt.Fprintf(tw, "%s\t%s\t%.0f\n", tl.ID, tl.Name, tl.Position)
}
}
if len(card.Tasks) > 0 {
fmt.Fprintln(tw)
fmt.Fprintln(tw, "TASK_ID\tTASK_NAME\tTASK_LIST_ID\tCOMPLETED")
for _, t := range card.Tasks {
fmt.Fprintf(tw, "%s\t%s\t%s\t%v\n", t.ID, t.Name, t.TaskListID, t.IsCompleted)
}
}
return nil
}
func printCommentTable(comments []model.Comment, tw *tabwriter.Writer) error { func printCommentTable(comments []model.Comment, tw *tabwriter.Writer) error {
fmt.Fprintln(tw, "ID\tCARD_ID\tTEXT\tCREATED_AT") fmt.Fprintln(tw, "ID\tCARD_ID\tTEXT\tCREATED_AT")
for _, c := range comments { for _, c := range comments {
@@ -200,6 +229,26 @@ func printLabelTable(labels []model.Label, tw *tabwriter.Writer) error {
return nil return nil
} }
func printListTable(lists []model.List, tw *tabwriter.Writer) error {
fmt.Fprintln(tw, "ID\tNAME\tTYPE\tBOARD_ID\tPOSITION\tCOLOR")
for _, l := range lists {
name := ""
if l.Name != nil {
name = *l.Name
}
color := ""
if l.Color != nil {
color = *l.Color
}
position := ""
if l.Position != nil {
position = fmt.Sprintf("%.0f", *l.Position)
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\n", l.ID, name, l.Type, l.BoardID, position, color)
}
return nil
}
func printActionTable(actions []model.Action, tw *tabwriter.Writer) error { func printActionTable(actions []model.Action, tw *tabwriter.Writer) error {
fmt.Fprintln(tw, "ID\tTYPE\tCARD_ID\tCREATED_AT") fmt.Fprintln(tw, "ID\tTYPE\tCARD_ID\tCREATED_AT")
for _, a := range actions { for _, a := range actions {
+16
View File
@@ -0,0 +1,16 @@
# Project configuration
# This file is read by workflows and agents for project-level settings.
planka:
# Planka project name
project: "agentic"
# Planka board name to sync with
board: "pcli"
# Future sections can be added here, e.g.:
# openspec:
# default-schema: "spec-driven"
# team:
# members: [...]