diff --git a/openspec/changes/unify-template-generation-pipeline/.openspec.yaml b/openspec/changes/unify-template-generation-pipeline/.openspec.yaml new file mode 100644 index 000000000..a5571c189 --- /dev/null +++ b/openspec/changes/unify-template-generation-pipeline/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-02-16 diff --git a/openspec/changes/unify-template-generation-pipeline/design.md b/openspec/changes/unify-template-generation-pipeline/design.md new file mode 100644 index 000000000..88228f326 --- /dev/null +++ b/openspec/changes/unify-template-generation-pipeline/design.md @@ -0,0 +1,149 @@ +## Context + +OpenSpec currently has strong building blocks (workflow templates, command adapters, generation helpers), but orchestration concerns are distributed: + +- Workflow definitions and projection lists are maintained separately +- Tool support is represented in multiple places with partial overlap +- Transforms can happen at template rendering time and inside individual adapters +- `init`/`update`/legacy-upgrade each run similar write pipelines with slight differences + +The design goal is to preserve current behavior while making extension points explicit and deterministic. + +## Goals / Non-Goals + +**Goals:** +- Define one canonical source for workflow content and metadata +- Make tool/agent-specific behavior explicit and centrally discoverable +- Keep command adapters as the formatting boundary for tool syntax differences +- Consolidate artifact generation/write orchestration into one reusable engine +- Improve correctness with enforceable validation and parity tests + +**Non-Goals:** +- Redesigning command semantics or workflow instruction content +- Changing user-facing CLI command names/flags in this proposal +- Merging unrelated legacy cleanup behavior beyond artifact generation reuse + +## Decisions + +### 1. Canonical `WorkflowManifest` + +**Decision**: Represent each workflow once in a manifest entry containing canonical skill and command definitions plus metadata defaults. + +Suggested shape: + +```ts +interface WorkflowManifestEntry { + workflowId: string; // e.g. 'explore', 'ff', 'onboard' + skillDirName: string; // e.g. 'openspec-explore' + skill: SkillTemplate; + command?: CommandTemplate; + commandId?: string; + tags: string[]; + compatibility: string; +} +``` + +**Rationale**: +- Eliminates drift between multiple hand-maintained arrays +- Makes workflow completeness testable in one place +- Keeps split workflow modules while centralizing registration + +### 2. `ToolProfileRegistry` for capability wiring + +**Decision**: Add a tool profile layer that maps tool IDs to generation capabilities and behavior. + +Suggested shape: + +```ts +interface ToolProfile { + toolId: string; + skillsDir?: string; + commandAdapterId?: string; + transforms: string[]; +} +``` + +**Rationale**: +- Prevents capability drift between `AI_TOOLS`, adapter registry, and detection logic +- Allows intentional "skills-only" tools without implicit special casing +- Provides one place to answer "what does this tool support?" + +### 3. First-class transform pipeline + +**Decision**: Model transforms as ordered plugins with scope + phase + applicability. + +Suggested shape: + +```ts +interface ArtifactTransform { + id: string; + scope: 'skill' | 'command' | 'both'; + phase: 'preAdapter' | 'postAdapter'; + priority: number; + applies(ctx: GenerationContext): boolean; + transform(content: string, ctx: GenerationContext): string; +} +``` + +Execution order: +1. Render canonical content from manifest +2. Apply matching `preAdapter` transforms +3. For commands, run adapter formatting +4. Apply matching `postAdapter` transforms +5. Validate and write + +**Rationale**: +- Keeps adapters focused on tool formatting, not scattered behavioral rewrites +- Makes agent-specific modifications explicit and testable +- Replaces ad-hoc transform calls in `init`/`update` + +### 4. Shared `ArtifactSyncEngine` + +**Decision**: Introduce a single orchestration engine used by all generation entry points. + +Responsibilities: +- Build generation plan from `(workflows × selected tools × artifact kinds)` +- Run render/transform/adapter pipeline +- Validate outputs +- Write files and return result summary + +**Rationale**: +- Removes duplicated loops and divergent behavior across init/update paths +- Enables dry-run and future preview features without re-implementing logic +- Improves reliability of updates and legacy migrations + +### 5. Validation + parity guardrails + +**Decision**: Add strict checks in tests (and optional runtime assertions in dev builds) for: + +- Required skill metadata fields (`license`, `compatibility`, `metadata`) present for all manifest entries +- Projection consistency (skills, commands, detection names derived from manifest) +- Tool profile consistency (adapter existence, expected capabilities) +- Golden/parity output for key workflows/tools + +**Rationale**: +- Converts prior review issues into enforced invariants +- Preserves output fidelity while enabling internal refactors +- Makes regressions obvious during CI + +## Risks / Trade-offs + +**Risk: Migration complexity** +A broad refactor can destabilize generation paths. +→ Mitigation: introduce in phases with parity tests before cutover. + +**Risk: Over-abstraction** +Too many layers can obscure simple flows. +→ Mitigation: keep interfaces minimal and colocate registries with generation code. + +**Trade-off: More upfront structure** +Adding manifest/profile/transform registries increases conceptual surface area. +→ Accepted: this cost is offset by reduced drift and easier extension. + +## Implementation Approach + +1. Build manifest + profile + transform types and registries behind current public API +2. Rewire `getSkillTemplates`/`getCommandContents` to derive from manifest +3. Introduce `ArtifactSyncEngine` and switch `init` to use it with parity checks +4. Switch `update` and legacy upgrade flows to same engine +5. Remove duplicate/hardcoded lists after parity is green diff --git a/openspec/changes/unify-template-generation-pipeline/proposal.md b/openspec/changes/unify-template-generation-pipeline/proposal.md new file mode 100644 index 000000000..fc7dde577 --- /dev/null +++ b/openspec/changes/unify-template-generation-pipeline/proposal.md @@ -0,0 +1,47 @@ +## Why + +The recent split of `skill-templates.ts` into workflow modules improved readability, but the generation pipeline is still fragmented across multiple layers: + +- Workflow definitions are split from projection logic (`getSkillTemplates`, `getCommandTemplates`, `getCommandContents`) +- Tool capability and compatibility are spread across `AI_TOOLS`, `CommandAdapterRegistry`, and hardcoded lists like `SKILL_NAMES` +- Agent/tool-specific transformations (for example OpenCode command reference rewrites) are applied in different places (`init`, `update`, and adapter code) +- Artifact writing logic is duplicated across `init`, `update`, and legacy-upgrade flow + +This fragmentation creates drift risk (missing exports, missing metadata parity, mismatched counts/support) and makes future workflow/tool additions slower and less predictable. + +## What Changes + +- Introduce a canonical `WorkflowManifest` as the single source of truth for all workflow artifacts +- Introduce a `ToolProfileRegistry` to centralize tool capabilities (skills path, command adapter, transforms) +- Introduce a first-class transform pipeline with explicit phases (`preAdapter`, `postAdapter`) and scopes (`skill`, `command`, `both`) +- Introduce a shared `ArtifactSyncEngine` used by `init`, `update`, and legacy upgrade paths +- Add strict validation and test guardrails to preserve fidelity during migration and future changes + +## Capabilities + +### New Capabilities + +- `template-artifact-pipeline`: Unified workflow manifest, tool profile registry, transform pipeline, and sync engine for skill/command generation + +### Modified Capabilities + +- `command-generation`: Extended to support ordered transform phases around adapter rendering +- `cli-init`: Uses shared artifact sync orchestration instead of bespoke loops +- `cli-update`: Uses shared artifact sync orchestration instead of bespoke loops + +## Impact + +- **Primary refactor area**: + - `src/core/templates/*` + - `src/core/shared/skill-generation.ts` + - `src/core/command-generation/*` + - `src/core/init.ts` + - `src/core/update.ts` + - `src/core/shared/tool-detection.ts` +- **Testing additions**: + - Manifest completeness tests (workflows, required metadata, projection parity) + - Transform ordering and applicability tests + - End-to-end parity tests for generated skill/command outputs across tools +- **User-facing behavior**: + - No new CLI surface area required + - Existing generated artifacts remain behaviorally equivalent unless explicitly changed in future deltas diff --git a/openspec/changes/unify-template-generation-pipeline/specs/template-artifact-pipeline/spec.md b/openspec/changes/unify-template-generation-pipeline/specs/template-artifact-pipeline/spec.md new file mode 100644 index 000000000..71986cc84 --- /dev/null +++ b/openspec/changes/unify-template-generation-pipeline/specs/template-artifact-pipeline/spec.md @@ -0,0 +1,89 @@ +# template-artifact-pipeline Specification + +## Purpose + +Define a unified architecture for workflow template generation that centralizes workflow definitions, tool capability wiring, transform execution, and artifact synchronization while preserving output fidelity. + +## ADDED Requirements + +### Requirement: Canonical Workflow Manifest + +The system SHALL define a canonical workflow manifest as the single source of truth for generated skill and command artifacts. + +#### Scenario: Register workflow once + +- **WHEN** a workflow (for example `explore`, `ff`, or `onboard`) is added or modified +- **THEN** its canonical definition SHALL be registered once in the workflow manifest +- **AND** skill/command projections SHALL be derived from that manifest +- **AND** duplicate hand-maintained lists SHALL NOT be required + +#### Scenario: Required skill metadata + +- **WHEN** defining a workflow skill entry in the manifest +- **THEN** it SHALL include required metadata fields (`license`, `compatibility`, and `metadata`) +- **AND** generation SHALL use those values or explicit defaults in a consistent way for all workflows + +### Requirement: Tool Profile Registry + +The system SHALL define a tool profile registry that captures generation capabilities per tool. + +#### Scenario: Resolve tool capabilities + +- **WHEN** generating artifacts for a selected tool +- **THEN** the system SHALL resolve a tool profile that declares skill path capability, command adapter linkage, and transform set +- **AND** tools with skills support but no command adapter SHALL be handled explicitly without implicit fallback behavior + +#### Scenario: Capability consistency validation + +- **WHEN** running validation checks +- **THEN** the system SHALL detect mismatches between configured tools, profile definitions, and registered adapters +- **AND** fail with actionable errors in development/CI + +### Requirement: Ordered Transform Pipeline + +The system SHALL support ordered artifact transforms with explicit scope and phase semantics. + +#### Scenario: Execute pre-adapter and post-adapter transforms + +- **WHEN** generating an artifact +- **THEN** matching transforms SHALL execute in deterministic order based on phase and priority +- **AND** `preAdapter` transforms SHALL run before command adapter formatting +- **AND** `postAdapter` transforms SHALL run after adapter formatting + +#### Scenario: Apply tool-specific rewrites declaratively + +- **WHEN** a tool requires instruction rewrites (for example command reference syntax changes) +- **THEN** those rewrites SHALL be implemented as registered transforms with explicit applicability predicates +- **AND** generation entry points SHALL NOT implement ad-hoc rewrite logic + +### Requirement: Shared Artifact Sync Engine + +The system SHALL provide a shared artifact sync engine used by all generation entry points. + +#### Scenario: Init and update use same engine + +- **WHEN** `openspec init` or `openspec update` writes skills/commands +- **THEN** both flows SHALL use the same orchestration engine for planning, rendering, validating, and writing artifacts +- **AND** behavior differences SHALL be configuration-driven rather than separate duplicated loops + +#### Scenario: Legacy upgrade path reuses engine + +- **WHEN** legacy cleanup triggers artifact regeneration +- **THEN** the regeneration path SHALL use the same shared engine +- **AND** generated outputs SHALL follow the same transform and validation rules + +### Requirement: Fidelity Guardrails + +The system SHALL enforce guardrails that prevent output drift during refactors. + +#### Scenario: Projection parity checks + +- **WHEN** CI runs template generation tests +- **THEN** it SHALL verify manifest-derived projections remain consistent (workflows, command IDs, skill directories) +- **AND** detect missing exports or missing workflow registration + +#### Scenario: Output parity checks + +- **WHEN** running parity tests for representative workflow/tool combinations +- **THEN** generated artifacts SHALL remain behaviorally equivalent to approved baselines unless intentionally changed +- **AND** intentional changes SHALL be captured in explicit spec/proposal updates diff --git a/openspec/changes/unify-template-generation-pipeline/tasks.md b/openspec/changes/unify-template-generation-pipeline/tasks.md new file mode 100644 index 000000000..a587503d4 --- /dev/null +++ b/openspec/changes/unify-template-generation-pipeline/tasks.md @@ -0,0 +1,41 @@ +## 1. Manifest Foundation + +- [ ] 1.1 Create canonical workflow manifest registry under `src/core/templates/` +- [ ] 1.2 Define shared manifest types for workflow IDs, skill metadata, and optional command descriptors +- [ ] 1.3 Migrate existing workflow registration (`getSkillTemplates`, `getCommandTemplates`, `getCommandContents`) to derive from the manifest +- [ ] 1.4 Preserve existing external exports/API compatibility for `src/core/templates/skill-templates.ts` + +## 2. Tool Profile Layer + +- [ ] 2.1 Add `ToolProfile` types and `ToolProfileRegistry` +- [ ] 2.2 Map all currently supported tools to explicit profile entries +- [ ] 2.3 Wire profile lookups to command adapter resolution and skills path resolution +- [ ] 2.4 Replace hardcoded detection arrays (for example `SKILL_NAMES`) with manifest-derived values + +## 3. Transform Pipeline + +- [ ] 3.1 Introduce transform interfaces (`scope`, `phase`, `priority`, `applies`, `transform`) +- [ ] 3.2 Implement transform runner with deterministic ordering +- [ ] 3.3 Migrate OpenCode command reference rewrite to transform pipeline +- [ ] 3.4 Remove ad-hoc transform invocation from `init` and `update` + +## 4. Artifact Sync Engine + +- [ ] 4.1 Create shared artifact sync engine for generation planning + rendering + writing +- [ ] 4.2 Integrate engine into `init` flow +- [ ] 4.3 Integrate engine into `update` flow +- [ ] 4.4 Integrate engine into legacy-upgrade artifact generation path + +## 5. Validation and Tests + +- [ ] 5.1 Add manifest completeness tests (metadata required fields, command IDs, dir names) +- [ ] 5.2 Add tool-profile consistency tests (skillsDir support and adapter/profile alignment) +- [ ] 5.3 Add transform applicability/order tests +- [ ] 5.4 Expand parity tests for representative workflow/tool matrix +- [ ] 5.5 Run full test suite and verify generated artifacts remain stable + +## 6. Cleanup and Documentation + +- [ ] 6.1 Remove superseded helper code and duplicate write loops after cutover +- [ ] 6.2 Update internal developer docs for template generation architecture +- [ ] 6.3 Document migration guardrails for future workflow/tool additions diff --git a/src/core/templates/index.ts b/src/core/templates/index.ts index 1bcc205b4..6bf5d712c 100644 --- a/src/core/templates/index.ts +++ b/src/core/templates/index.ts @@ -5,24 +5,5 @@ * have been removed. The skill-based workflow uses skill-templates.ts directly. */ -// Re-export skill templates for convenience -export { - getExploreSkillTemplate, - getNewChangeSkillTemplate, - getContinueChangeSkillTemplate, - getApplyChangeSkillTemplate, - getFfChangeSkillTemplate, - getSyncSpecsSkillTemplate, - getArchiveChangeSkillTemplate, - getBulkArchiveChangeSkillTemplate, - getVerifyChangeSkillTemplate, - getOpsxExploreCommandTemplate, - getOpsxNewCommandTemplate, - getOpsxContinueCommandTemplate, - getOpsxApplyCommandTemplate, - getOpsxFfCommandTemplate, - getOpsxSyncCommandTemplate, - getOpsxArchiveCommandTemplate, - getOpsxBulkArchiveCommandTemplate, - getOpsxVerifyCommandTemplate, -} from './skill-templates.js'; +// Re-export all skill templates and related types through the compatibility facade. +export * from './skill-templates.js'; diff --git a/src/core/templates/skill-templates.ts b/src/core/templates/skill-templates.ts index 481611930..3bf7a1c42 100644 --- a/src/core/templates/skill-templates.ts +++ b/src/core/templates/skill-templates.ts @@ -1,3479 +1,19 @@ /** * Agent Skill Templates * - * Templates for generating Agent Skills compatible with: - * - Claude Code - * - Cursor (Settings → Rules → Import Settings) - * - Windsurf - * - Other Agent Skills-compatible editors - */ - -export interface SkillTemplate { - name: string; - description: string; - instructions: string; - license?: string; - compatibility?: string; - metadata?: Record; -} - -/** - * Template for openspec-explore skill - * Explore mode - adaptive thinking partner for exploring ideas and problems - */ -export function getExploreSkillTemplate(): SkillTemplate { - return { - 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.', - instructions: `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. - -**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 one?" - → Can transition to \`/opsx:new\` or \`/opsx:ff\` -- 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//proposal.md\` - - \`openspec/changes//design.md\` - - \`openspec/changes//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//spec.md\` | - | Requirement changed | \`specs//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 action**: "Ready to start? /opsx:new or /opsx:ff" -- **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: /opsx:new -- Fast-forward to tasks: /opsx:ff -- 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`, - license: 'MIT', - compatibility: 'Requires openspec CLI.', - metadata: { author: 'openspec', version: '1.0' }, - }; -} - -/** - * Template for openspec-new-change skill - * Based on /opsx:new command - */ -export function getNewChangeSkillTemplate(): SkillTemplate { - return { - 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.', - instructions: `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 \` - - "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 "" - \`\`\` - Add \`--schema \` only if the user requested a specific workflow. - This creates a scaffolded change at \`openspec/changes//\` with the selected schema. - -4. **Show the artifact status** - \`\`\`bash - openspec status --change "" - \`\`\` - 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 --change "" - \`\`\` - 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`, - license: 'MIT', - compatibility: 'Requires openspec CLI.', - metadata: { author: 'openspec', version: '1.0' }, - }; -} - -/** - * Template for openspec-continue-change skill - * Based on /opsx:continue command - */ -export function getContinueChangeSkillTemplate(): SkillTemplate { - return { - 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.', - instructions: `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 "" --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 --change "" --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 "" - \`\`\` - -**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//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 \`\`, \`\`, \`\` blocks into the artifact - - These guide what you write, but should never appear in the output`, - license: 'MIT', - compatibility: 'Requires openspec CLI.', - metadata: { author: 'openspec', version: '1.0' }, - }; -} - -/** - * Template for openspec-apply-change skill - * For implementing tasks from a completed (or in-progress) change - */ -export function getApplyChangeSkillTemplate(): SkillTemplate { - return { - 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.', - instructions: `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: " and how to override (e.g., \`/opsx:apply \`). - -2. **Check status to understand the schema** - \`\`\`bash - openspec status --change "" --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 "" --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: (schema: ) - -Working on task 3/7: -[...implementation happening...] -✓ Task complete - -Working on task 4/7: -[...implementation happening...] -✓ Task complete -\`\`\` - -**Output On Completion** - -\`\`\` -## Implementation Complete - -**Change:** -**Schema:** -**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:** -**Schema:** -**Progress:** 4/7 tasks complete - -### Issue Encountered - - -**Options:** -1.