mirror of
https://github.com/Fission-AI/OpenSpec.git
synced 2026-10-04 06:18:24 +08:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ea48c5eaa | ||
|
|
4715138927 | ||
|
|
940898c1c5 | ||
|
|
d49a88c3bb | ||
|
|
bb9f6ce0ea | ||
|
|
ae85a7229d | ||
|
|
504c93bdf1 | ||
|
|
c4a54a8d54 |
@@ -26,6 +26,10 @@
|
||||
Follow <a href="https://x.com/0xTab">@0xTab on X</a> for updates · Join the <a href="https://discord.gg/YctCnvvshC">OpenSpec Discord</a> for help and questions.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<sub>🧪 <strong>New:</strong> <a href="docs/experimental-workflow.md">Experimental Workflow (OPSX)</a> — schema-driven, hackable, fluid. Iterate on workflows without code changes.</sub>
|
||||
</p>
|
||||
|
||||
# OpenSpec
|
||||
|
||||
OpenSpec aligns humans and AI coding assistants with spec-driven development so you agree on what to build before any code is written. **No API keys required.**
|
||||
@@ -368,6 +372,53 @@ Run `openspec update` whenever someone switches tools so your agents pick up the
|
||||
2. **Refresh agent instructions**
|
||||
- Run `openspec update` inside each project to regenerate AI guidance and ensure the latest slash commands are active.
|
||||
|
||||
## Experimental Features
|
||||
|
||||
<details>
|
||||
<summary><strong>🧪 OPSX: Fluid, Iterative Workflow</strong> (Claude Code only)</summary>
|
||||
|
||||
**Why this exists:**
|
||||
- Standard workflow is locked down — you can't tweak instructions or customize
|
||||
- When AI output is bad, you can't improve the prompts yourself
|
||||
- Same workflow for everyone, no way to match how your team works
|
||||
|
||||
**What's different:**
|
||||
- **Hackable** — edit templates and schemas yourself, test immediately, no rebuild
|
||||
- **Granular** — each artifact has its own instructions, test and tweak individually
|
||||
- **Customizable** — define your own workflows, artifacts, and dependencies
|
||||
- **Fluid** — no phase gates, update any artifact anytime
|
||||
|
||||
```
|
||||
You can always go back:
|
||||
|
||||
proposal ──→ specs ──→ design ──→ tasks ──→ implement
|
||||
▲ ▲ ▲ │
|
||||
└───────────┴──────────┴────────────────────┘
|
||||
```
|
||||
|
||||
| Command | What it does |
|
||||
|---------|--------------|
|
||||
| `/opsx:new` | Start a new change |
|
||||
| `/opsx:continue` | Create the next artifact (based on what's ready) |
|
||||
| `/opsx:ff` | Fast-forward (all planning artifacts at once) |
|
||||
| `/opsx:apply` | Implement tasks, updating artifacts as needed |
|
||||
| `/opsx:archive` | Archive when done |
|
||||
|
||||
**Setup:** `openspec artifact-experimental-setup`
|
||||
|
||||
[Full documentation →](docs/experimental-workflow.md)
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Telemetry</strong> – OpenSpec collects anonymous usage stats (opt-out: <code>OPENSPEC_TELEMETRY=0</code>)</summary>
|
||||
|
||||
We collect only command names and version to understand usage patterns. No arguments, paths, content, or PII. Automatically disabled in CI.
|
||||
|
||||
**Opt-out:** `export OPENSPEC_TELEMETRY=0` or `export DO_NOT_TRACK=1`
|
||||
|
||||
</details>
|
||||
|
||||
## Contributing
|
||||
|
||||
- Install dependencies: `pnpm install`
|
||||
|
||||
+460
-27
@@ -6,13 +6,65 @@
|
||||
|
||||
## What Is It?
|
||||
|
||||
OPSX is a new way to work with OpenSpec changes. Instead of one big proposal, you build **artifacts** step-by-step:
|
||||
OPSX is a **fluid, iterative workflow** for OpenSpec changes. No more rigid phases — just actions you can take anytime.
|
||||
|
||||
## Why This Exists
|
||||
|
||||
The standard OpenSpec workflow works, but it's **locked down**:
|
||||
|
||||
- **Instructions are hardcoded** — buried in TypeScript, you can't change them
|
||||
- **All-or-nothing** — one big command creates everything, can't test individual pieces
|
||||
- **Fixed structure** — same workflow for everyone, no customization
|
||||
- **Black box** — when AI output is bad, you can't tweak the prompts
|
||||
|
||||
**OPSX opens it up.** Now anyone can:
|
||||
|
||||
1. **Experiment with instructions** — edit a template, see if the AI does better
|
||||
2. **Test granularly** — validate each artifact's instructions independently
|
||||
3. **Customize workflows** — define your own artifacts and dependencies
|
||||
4. **Iterate quickly** — change a template, test immediately, no rebuild
|
||||
|
||||
```
|
||||
proposal → specs → design → tasks → implementation → archive
|
||||
Standard workflow: OPSX:
|
||||
┌────────────────────────┐ ┌────────────────────────┐
|
||||
│ Hardcoded in package │ │ schema.yaml │◄── You edit this
|
||||
│ (can't change) │ │ templates/*.md │◄── Or this
|
||||
│ ↓ │ │ ↓ │
|
||||
│ Wait for new release │ │ Instant effect │
|
||||
│ ↓ │ │ ↓ │
|
||||
│ Hope it's better │ │ Test it yourself │
|
||||
└────────────────────────┘ └────────────────────────┘
|
||||
```
|
||||
|
||||
Each artifact has dependencies. Can't write tasks until you have specs. Can't implement until you have tasks. The system tracks what's ready and what's blocked.
|
||||
**This is for everyone:**
|
||||
- **Teams** — create workflows that match how you actually work
|
||||
- **Power users** — tweak prompts to get better AI outputs for your codebase
|
||||
- **OpenSpec contributors** — experiment with new approaches without releases
|
||||
|
||||
We're all still learning what works best. OPSX lets us learn together.
|
||||
|
||||
## The User Experience
|
||||
|
||||
**The problem with linear workflows:**
|
||||
You're "in planning phase", then "in implementation phase", then "done". But real work doesn't work that way. You implement something, realize your design was wrong, need to update specs, continue implementing. Linear phases fight against how work actually happens.
|
||||
|
||||
**OPSX approach:**
|
||||
- **Actions, not phases** — create, implement, update, archive — do any of them anytime
|
||||
- **Dependencies are enablers** — they show what's possible, not what's required next
|
||||
- **Update as you learn** — halfway through implementation? Go back and fix the design. That's normal.
|
||||
|
||||
```
|
||||
You can always go back:
|
||||
|
||||
┌────────────────────────────────────┐
|
||||
│ │
|
||||
▼ │
|
||||
proposal ──→ specs ──→ design ──→ tasks ──→ implement
|
||||
▲ ▲ ▲ │
|
||||
│ │ │ │
|
||||
└───────────┴──────────┴───────────────┘
|
||||
update as you learn
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
@@ -30,59 +82,439 @@ This creates skills in `.claude/skills/` that Claude Code auto-detects.
|
||||
|
||||
| Command | What it does |
|
||||
|---------|--------------|
|
||||
| `/opsx:explore` | Think through ideas, investigate problems, clarify requirements |
|
||||
| `/opsx:new` | Start a new change |
|
||||
| `/opsx:continue` | Create the next artifact |
|
||||
| `/opsx:ff` | Fast-forward (create all artifacts at once) |
|
||||
| `/opsx:apply` | Implement the tasks |
|
||||
| `/opsx:continue` | Create the next artifact (based on what's ready) |
|
||||
| `/opsx:ff` | Fast-forward — create all planning artifacts at once |
|
||||
| `/opsx:apply` | Implement tasks, updating artifacts as needed |
|
||||
| `/opsx:sync` | Sync delta specs to main specs |
|
||||
| `/opsx:archive` | Archive when done |
|
||||
|
||||
## Usage
|
||||
|
||||
### Explore an idea
|
||||
```
|
||||
/opsx:explore
|
||||
```
|
||||
Think through ideas, investigate problems, compare options. No structure required - just a thinking partner. When insights crystallize, transition to `/opsx:new` or `/opsx:ff`.
|
||||
|
||||
### Start a new change
|
||||
```
|
||||
/opsx:new
|
||||
```
|
||||
You'll be asked what you want to build and which workflow schema to use.
|
||||
|
||||
### Build artifacts step-by-step
|
||||
### Create artifacts
|
||||
```
|
||||
/opsx:continue
|
||||
```
|
||||
Creates one artifact at a time. Good for reviewing each step.
|
||||
Shows what's ready to create based on dependencies, then creates one artifact. Use repeatedly to build up your change incrementally.
|
||||
|
||||
### Or fast-forward
|
||||
```
|
||||
/opsx:ff add-dark-mode
|
||||
```
|
||||
Creates all artifacts in one go. Good when you know what you want.
|
||||
Creates all planning artifacts at once. Use when you have a clear picture of what you're building.
|
||||
|
||||
### Implement
|
||||
### Implement (the fluid part)
|
||||
```
|
||||
/opsx:apply
|
||||
```
|
||||
Works through tasks, checking them off as you go.
|
||||
Works through tasks, checking them off as you go. **Key difference:** if you discover issues during implementation, you can update your specs, design, or tasks — then continue. No phase gates.
|
||||
|
||||
### Sync specs and archive
|
||||
### Finish up
|
||||
```
|
||||
/opsx:sync # Update main specs with your delta specs
|
||||
/opsx:archive # Move to archive when done
|
||||
```
|
||||
|
||||
## When to Update vs. Start Fresh
|
||||
|
||||
OPSX lets you update artifacts anytime. But when does "update as you learn" become "this is different work"?
|
||||
|
||||
### What a Proposal Captures
|
||||
|
||||
A proposal defines three things:
|
||||
1. **Intent** — What problem are you solving?
|
||||
2. **Scope** — What's in/out of bounds?
|
||||
3. **Approach** — How will you solve it?
|
||||
|
||||
The question is: which changed, and by how much?
|
||||
|
||||
### Update the Existing Change When:
|
||||
|
||||
**Same intent, refined execution**
|
||||
- You discover edge cases you didn't consider
|
||||
- The approach needs tweaking but the goal is unchanged
|
||||
- Implementation reveals the design was slightly off
|
||||
|
||||
**Scope narrows**
|
||||
- You realize full scope is too big, want to ship MVP first
|
||||
- "Add dark mode" → "Add dark mode toggle (system preference in v2)"
|
||||
|
||||
**Learning-driven corrections**
|
||||
- Codebase isn't structured how you thought
|
||||
- A dependency doesn't work as expected
|
||||
- "Use CSS variables" → "Use Tailwind's dark: prefix instead"
|
||||
|
||||
### Start a New Change When:
|
||||
|
||||
**Intent fundamentally changed**
|
||||
- The problem itself is different now
|
||||
- "Add dark mode" → "Add comprehensive theme system with custom colors, fonts, spacing"
|
||||
|
||||
**Scope exploded**
|
||||
- Change grew so much it's essentially different work
|
||||
- Original proposal would be unrecognizable after updates
|
||||
- "Fix login bug" → "Rewrite auth system"
|
||||
|
||||
**Original is completable**
|
||||
- The original change can be marked "done"
|
||||
- New work stands alone, not a refinement
|
||||
- Complete "Add dark mode MVP" → Archive → New change "Enhance dark mode"
|
||||
|
||||
### The Heuristics
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Is this the same work? │
|
||||
└──────────────┬──────────────────────┘
|
||||
│
|
||||
┌──────────────────┼──────────────────┐
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
Same intent? >50% overlap? Can original
|
||||
Same problem? Same scope? be "done" without
|
||||
│ │ these changes?
|
||||
│ │ │
|
||||
┌────────┴────────┐ ┌──────┴──────┐ ┌───────┴───────┐
|
||||
│ │ │ │ │ │
|
||||
YES NO YES NO NO YES
|
||||
│ │ │ │ │ │
|
||||
▼ ▼ ▼ ▼ ▼ ▼
|
||||
UPDATE NEW UPDATE NEW UPDATE NEW
|
||||
```
|
||||
|
||||
| Test | Update | New Change |
|
||||
|------|--------|------------|
|
||||
| **Identity** | "Same thing, refined" | "Different work" |
|
||||
| **Scope overlap** | >50% overlaps | <50% overlaps |
|
||||
| **Completion** | Can't be "done" without changes | Can finish original, new work stands alone |
|
||||
| **Story** | Update chain tells coherent story | Patches would confuse more than clarify |
|
||||
|
||||
### The Principle
|
||||
|
||||
> **Update preserves context. New change provides clarity.**
|
||||
>
|
||||
> Choose update when the history of your thinking is valuable.
|
||||
> Choose new when starting fresh would be clearer than patching.
|
||||
|
||||
Think of it like git branches:
|
||||
- Keep committing while working on the same feature
|
||||
- Start a new branch when it's genuinely new work
|
||||
- Sometimes merge a partial feature and start fresh for phase 2
|
||||
|
||||
## What's Different?
|
||||
|
||||
**Standard workflow** (`/openspec:proposal`):
|
||||
- One big proposal document
|
||||
- Linear phases: plan → implement → archive
|
||||
- All-or-nothing artifact creation
|
||||
| | Standard (`/openspec:proposal`) | Experimental (`/opsx:*`) |
|
||||
|---|---|---|
|
||||
| **Structure** | One big proposal document | Discrete artifacts with dependencies |
|
||||
| **Workflow** | Linear phases: plan → implement → archive | Fluid actions — do anything anytime |
|
||||
| **Iteration** | Awkward to go back | Update artifacts as you learn |
|
||||
| **Customization** | Fixed structure | Schema-driven (define your own artifacts) |
|
||||
|
||||
**Experimental workflow** (`/opsx:*`):
|
||||
- Discrete artifacts with dependencies
|
||||
- Fluid actions (not phases) - update artifacts anytime
|
||||
- Step-by-step or fast-forward
|
||||
- Schema-driven (can customize the workflow)
|
||||
**The key insight:** work isn't linear. OPSX stops pretending it is.
|
||||
|
||||
The key insight: work isn't linear. You implement, realize the design is wrong, update it, continue. OPSX supports this.
|
||||
## Architecture Deep Dive
|
||||
|
||||
This section explains how OPSX works under the hood and how it compares to the standard workflow.
|
||||
|
||||
### Philosophy: Phases vs Actions
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────────┐
|
||||
│ STANDARD WORKFLOW │
|
||||
│ (Phase-Locked, All-or-Nothing) │
|
||||
├─────────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ PLANNING │ ───► │ IMPLEMENTING │ ───► │ ARCHIVING │ │
|
||||
│ │ PHASE │ │ PHASE │ │ PHASE │ │
|
||||
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ ▼ ▼ ▼ │
|
||||
│ /openspec:proposal /openspec:apply /openspec:archive │
|
||||
│ │
|
||||
│ • Creates ALL artifacts at once │
|
||||
│ • Can't go back to update specs during implementation │
|
||||
│ • Phase gates enforce linear progression │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
|
||||
┌─────────────────────────────────────────────────────────────────────────────┐
|
||||
│ OPSX WORKFLOW │
|
||||
│ (Fluid Actions, Iterative) │
|
||||
├─────────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────┐ │
|
||||
│ │ ACTIONS (not phases) │ │
|
||||
│ │ │ │
|
||||
│ │ new ◄──► continue ◄──► apply ◄──► sync │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ └──────────┴───────────┴──────────┘ │ │
|
||||
│ │ any order │ │
|
||||
│ └────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ • Create artifacts one at a time OR fast-forward │
|
||||
│ • Update specs/design/tasks during implementation │
|
||||
│ • Dependencies enable progress, phases don't exist │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Component Architecture
|
||||
|
||||
**Standard workflow** uses hardcoded templates in TypeScript:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────────┐
|
||||
│ STANDARD WORKFLOW COMPONENTS │
|
||||
├─────────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Hardcoded Templates (TypeScript strings) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ Configurators (18+ classes, one per editor) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ Generated Command Files (.claude/commands/openspec/*.md) │
|
||||
│ │
|
||||
│ • Fixed structure, no artifact awareness │
|
||||
│ • Change requires code modification + rebuild │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**OPSX** uses external schemas and a dependency graph engine:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────────┐
|
||||
│ OPSX COMPONENTS │
|
||||
├─────────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Schema Definitions (YAML) │
|
||||
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ name: spec-driven │ │
|
||||
│ │ artifacts: │ │
|
||||
│ │ - id: proposal │ │
|
||||
│ │ generates: proposal.md │ │
|
||||
│ │ requires: [] ◄── Dependencies │ │
|
||||
│ │ - id: specs │ │
|
||||
│ │ generates: specs/**/*.md ◄── Glob patterns │ │
|
||||
│ │ requires: [proposal] ◄── Enables after proposal │ │
|
||||
│ └─────────────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ Artifact Graph Engine │
|
||||
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ • Topological sort (dependency ordering) │ │
|
||||
│ │ • State detection (filesystem existence) │ │
|
||||
│ │ • Rich instruction generation (templates + context) │ │
|
||||
│ └─────────────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ Skill Files (.claude/skills/openspec-*/SKILL.md) │
|
||||
│ │
|
||||
│ • Cross-editor compatible (Claude Code, Cursor, Windsurf) │
|
||||
│ • Skills query CLI for structured data │
|
||||
│ • Fully customizable via schema files │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Dependency Graph Model
|
||||
|
||||
Artifacts form a directed acyclic graph (DAG). Dependencies are **enablers**, not gates:
|
||||
|
||||
```
|
||||
proposal
|
||||
(root node)
|
||||
│
|
||||
┌─────────────┴─────────────┐
|
||||
│ │
|
||||
▼ ▼
|
||||
specs design
|
||||
(requires: (requires:
|
||||
proposal) proposal)
|
||||
│ │
|
||||
└─────────────┬─────────────┘
|
||||
│
|
||||
▼
|
||||
tasks
|
||||
(requires:
|
||||
specs, design)
|
||||
│
|
||||
▼
|
||||
┌──────────────┐
|
||||
│ APPLY PHASE │
|
||||
│ (requires: │
|
||||
│ tasks) │
|
||||
└──────────────┘
|
||||
```
|
||||
|
||||
**State transitions:**
|
||||
|
||||
```
|
||||
BLOCKED ────────────────► READY ────────────────► DONE
|
||||
│ │ │
|
||||
Missing All deps File exists
|
||||
dependencies are DONE on filesystem
|
||||
```
|
||||
|
||||
### Information Flow
|
||||
|
||||
**Standard workflow** — agent receives static instructions:
|
||||
|
||||
```
|
||||
User: "/openspec:proposal"
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Static instructions: │
|
||||
│ • Create proposal.md │
|
||||
│ • Create tasks.md │
|
||||
│ • Create design.md │
|
||||
│ • Create specs/*.md │
|
||||
│ │
|
||||
│ No awareness of what exists or │
|
||||
│ dependencies between artifacts │
|
||||
└─────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
Agent creates ALL artifacts in one go
|
||||
```
|
||||
|
||||
**OPSX** — agent queries for rich context:
|
||||
|
||||
```
|
||||
User: "/opsx:continue"
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────────────────────┐
|
||||
│ Step 1: Query current state │
|
||||
│ ┌────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ $ openspec status --change "add-auth" --json │ │
|
||||
│ │ │ │
|
||||
│ │ { │ │
|
||||
│ │ "artifacts": [ │ │
|
||||
│ │ {"id": "proposal", "status": "done"}, │ │
|
||||
│ │ {"id": "specs", "status": "ready"}, ◄── First ready │ │
|
||||
│ │ {"id": "design", "status": "ready"}, │ │
|
||||
│ │ {"id": "tasks", "status": "blocked", "missingDeps": ["specs"]}│ │
|
||||
│ │ ] │ │
|
||||
│ │ } │ │
|
||||
│ └────────────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Step 2: Get rich instructions for ready artifact │
|
||||
│ ┌────────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ $ openspec instructions specs --change "add-auth" --json │ │
|
||||
│ │ │ │
|
||||
│ │ { │ │
|
||||
│ │ "template": "# Specification\n\n## ADDED Requirements...", │ │
|
||||
│ │ "dependencies": [{"id": "proposal", "path": "...", "done": true}│ │
|
||||
│ │ "unlocks": ["tasks"] │ │
|
||||
│ │ } │ │
|
||||
│ └────────────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Step 3: Read dependencies → Create ONE artifact → Show what's unlocked │
|
||||
└──────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Iteration Model
|
||||
|
||||
**Standard workflow** — awkward to iterate:
|
||||
|
||||
```
|
||||
┌─────────┐ ┌─────────┐ ┌─────────┐
|
||||
│/proposal│ ──► │ /apply │ ──► │/archive │
|
||||
└─────────┘ └─────────┘ └─────────┘
|
||||
│ │
|
||||
│ ├── "Wait, the design is wrong"
|
||||
│ │
|
||||
│ ├── Options:
|
||||
│ │ • Edit files manually (breaks context)
|
||||
│ │ • Abandon and start over
|
||||
│ │ • Push through and fix later
|
||||
│ │
|
||||
│ └── No official "go back" mechanism
|
||||
│
|
||||
└── Creates ALL artifacts at once
|
||||
```
|
||||
|
||||
**OPSX** — natural iteration:
|
||||
|
||||
```
|
||||
/opsx:new ───► /opsx:continue ───► /opsx:apply ───► /opsx:archive
|
||||
│ │ │
|
||||
│ │ ├── "The design is wrong"
|
||||
│ │ │
|
||||
│ │ ▼
|
||||
│ │ Just edit design.md
|
||||
│ │ and continue!
|
||||
│ │ │
|
||||
│ │ ▼
|
||||
│ │ /opsx:apply picks up
|
||||
│ │ where you left off
|
||||
│ │
|
||||
│ └── Creates ONE artifact, shows what's unlocked
|
||||
│
|
||||
└── Scaffolds change, waits for direction
|
||||
```
|
||||
|
||||
### Custom Schemas
|
||||
|
||||
Create your own workflow by adding a schema to `~/.local/share/openspec/schemas/`:
|
||||
|
||||
```
|
||||
~/.local/share/openspec/schemas/research-first/
|
||||
├── schema.yaml
|
||||
└── templates/
|
||||
├── research.md
|
||||
├── proposal.md
|
||||
└── tasks.md
|
||||
|
||||
schema.yaml:
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ name: research-first │
|
||||
│ artifacts: │
|
||||
│ - id: research # Added before proposal │
|
||||
│ generates: research.md │
|
||||
│ requires: [] │
|
||||
│ │
|
||||
│ - id: proposal │
|
||||
│ generates: proposal.md │
|
||||
│ requires: [research] # Now depends on research │
|
||||
│ │
|
||||
│ - id: tasks │
|
||||
│ generates: tasks.md │
|
||||
│ requires: [proposal] │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
|
||||
Dependency Graph:
|
||||
|
||||
research ──► proposal ──► tasks
|
||||
```
|
||||
|
||||
### Summary
|
||||
|
||||
| Aspect | Standard | OPSX |
|
||||
|--------|----------|------|
|
||||
| **Templates** | Hardcoded TypeScript | External YAML + Markdown |
|
||||
| **Dependencies** | None (all at once) | DAG with topological sort |
|
||||
| **State** | Phase-based mental model | Filesystem existence |
|
||||
| **Customization** | Edit source, rebuild | Create schema.yaml |
|
||||
| **Iteration** | Phase-locked | Fluid, edit anything |
|
||||
| **Editor Support** | 18+ configurator classes | Single skills directory |
|
||||
|
||||
## Schemas
|
||||
|
||||
@@ -95,13 +527,14 @@ Run `openspec schemas` to see available schemas.
|
||||
|
||||
## Tips
|
||||
|
||||
- Use `/opsx:ff` when you have a clear idea, `/opsx:continue` when exploring
|
||||
- Use `/opsx:explore` to think through an idea before committing to a change
|
||||
- `/opsx:ff` when you know what you want, `/opsx:continue` when exploring
|
||||
- During `/opsx:apply`, if something's wrong — fix the artifact, then continue
|
||||
- Tasks track progress via checkboxes in `tasks.md`
|
||||
- Delta specs (in `specs/`) get synced to main specs with `/opsx:sync`
|
||||
- If you get stuck, the status command shows what's blocked: `openspec status --change "name"`
|
||||
- Check status anytime: `openspec status --change "name"`
|
||||
|
||||
## Feedback
|
||||
|
||||
This is rough. That's intentional - we're learning what works.
|
||||
This is rough. That's intentional — we're learning what works.
|
||||
|
||||
Found a bug? Have ideas? Join us on [Discord](https://discord.gg/BYjPaKbqMt) or open an issue on [GitHub](https://github.com/Fission-AI/openspec/issues).
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-01-10
|
||||
@@ -0,0 +1,175 @@
|
||||
## Context
|
||||
|
||||
OpenSpec needs usage analytics to understand adoption and inform product decisions. PostHog provides a privacy-conscious analytics platform suitable for open source projects.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Track daily/weekly/monthly active usage
|
||||
- Understand command usage patterns
|
||||
- Keep implementation minimal and privacy-respecting
|
||||
- Enable opt-out with minimal friction
|
||||
|
||||
**Non-Goals:**
|
||||
- Detailed error tracking or diagnostics
|
||||
- User identification or profiling
|
||||
- Complex event hierarchies
|
||||
- Full CLI command for telemetry management (env var sufficient for now)
|
||||
|
||||
## Decisions
|
||||
|
||||
### Opt-Out Model
|
||||
|
||||
**Decision:** Telemetry enabled by default, opt-out via environment variable.
|
||||
|
||||
```bash
|
||||
OPENSPEC_TELEMETRY=0 # Disable telemetry
|
||||
DO_NOT_TRACK=1 # Industry standard, also respected
|
||||
```
|
||||
|
||||
Auto-disabled when `CI=true` is detected.
|
||||
|
||||
**Rationale:**
|
||||
- Opt-in typically yields ~3% participation—not enough for meaningful data
|
||||
- Understanding usage patterns requires statistically significant sample sizes
|
||||
- Environment variable opt-out is simple and immediate
|
||||
- Respecting `DO_NOT_TRACK` follows industry convention
|
||||
|
||||
**Alternatives considered:**
|
||||
- Opt-in only - Insufficient data for product decisions
|
||||
- Config file setting - More complex, env var sufficient for MVP
|
||||
- Full `openspec telemetry` command - Can add later if users request
|
||||
|
||||
### Event Design
|
||||
|
||||
**Decision:** Single event type with minimal properties.
|
||||
|
||||
```typescript
|
||||
{
|
||||
event: 'command_executed',
|
||||
properties: {
|
||||
command: 'init', // Command name only
|
||||
version: '1.2.3' // OpenSpec version
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Rationale:**
|
||||
- Answers the core questions: how much usage, which commands are popular
|
||||
- PostHog derives DAU/WAU/MAU from anonymous user counts over time
|
||||
- No arguments, paths, or content—clean privacy story
|
||||
- Easy to explain in disclosure notice
|
||||
|
||||
**Not tracked:**
|
||||
- Command arguments
|
||||
- File paths or contents
|
||||
- Error messages or stack traces
|
||||
- Project names or spec content
|
||||
- IP addresses (`$ip: null` explicitly set)
|
||||
|
||||
### Anonymous ID
|
||||
|
||||
**Decision:** Random UUID, lazily generated on first telemetry send, stored in global config.
|
||||
|
||||
```typescript
|
||||
// ~/.config/openspec/config.json
|
||||
{
|
||||
"telemetry": {
|
||||
"anonymousId": "f47ac10b-58cc-4372-a567-0e02b2c3d479"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Rationale:**
|
||||
- Random UUID has no relation to the person—can't be reversed
|
||||
- Stored in config so same user = same ID across sessions (needed for DAU/WAU/MAU)
|
||||
- Lazy generation means no ID created if user opts out before first command
|
||||
- User can delete config to reset identity
|
||||
|
||||
**Alternatives considered:**
|
||||
- Machine-derived hash (hostname, MAC) - Feels invasive, fingerprint-like
|
||||
- Per-session UUID - Breaks user counting metrics entirely
|
||||
|
||||
### SDK Configuration
|
||||
|
||||
**Decision:** PostHog Node SDK with immediate flush, shutdown on exit.
|
||||
|
||||
```typescript
|
||||
const posthog = new PostHog(API_KEY, {
|
||||
flushAt: 1, // Send immediately, don't batch
|
||||
flushInterval: 0 // No timer-based flushing
|
||||
});
|
||||
|
||||
// Before CLI exits
|
||||
await posthog.shutdown();
|
||||
```
|
||||
|
||||
**Rationale:**
|
||||
- CLI processes are short-lived; batching would lose events
|
||||
- `flushAt: 1` ensures each event sends immediately
|
||||
- `shutdown()` guarantees flush before process exit
|
||||
- Adds ~100-300ms to exit—negligible for typical CLI workflows
|
||||
|
||||
**Error handling:**
|
||||
- Network failures silently ignored (telemetry shouldn't break CLI)
|
||||
- `shutdown()` wrapped in try/catch
|
||||
|
||||
### Hook Location
|
||||
|
||||
**Decision:** Commander.js `preAction` and `postAction` hooks.
|
||||
|
||||
```typescript
|
||||
program
|
||||
.hook('preAction', (thisCommand) => {
|
||||
maybeShowTelemetryNotice();
|
||||
trackCommand(thisCommand.name(), VERSION);
|
||||
})
|
||||
.hook('postAction', async () => {
|
||||
await shutdown();
|
||||
});
|
||||
```
|
||||
|
||||
**Rationale:**
|
||||
- Centralized—one place for all telemetry logic
|
||||
- Automatic—new commands get tracked without code changes
|
||||
- Clean separation—command handlers don't know about telemetry
|
||||
|
||||
**Subcommand handling:**
|
||||
- Track full command path for nested commands (e.g., `change:apply`)
|
||||
|
||||
### First-Run Notice
|
||||
|
||||
**Decision:** One-liner on first command ever, stored "seen" flag in config.
|
||||
|
||||
```
|
||||
Note: OpenSpec collects anonymous usage stats. Opt out: OPENSPEC_TELEMETRY=0
|
||||
```
|
||||
|
||||
**Rationale:**
|
||||
- First command (not just `init`) ensures notice is always seen
|
||||
- Non-blocking—no prompt, just informational
|
||||
- One-liner is visible but not intrusive
|
||||
- Storing "seen" in config prevents repeated display
|
||||
|
||||
**Config after first run:**
|
||||
```json
|
||||
{
|
||||
"telemetry": {
|
||||
"anonymousId": "...",
|
||||
"noticeSeen": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Users prefer opt-in | Clear disclosure, trivial opt-out, transparent about what's collected |
|
||||
| GDPR concerns | No personal data, no IP, user can delete config |
|
||||
| Slows CLI exit by ~200ms | Negligible for most workflows; can optimize if needed |
|
||||
| PostHog outage affects CLI | Fire-and-forget with timeout; failures are silent |
|
||||
|
||||
## Open Questions
|
||||
|
||||
None—design is intentionally minimal. Future enhancements (dedicated command, workflow tracking) can be added based on user feedback.
|
||||
@@ -0,0 +1,37 @@
|
||||
## Why
|
||||
|
||||
OpenSpec currently has no visibility into how the tool is being used. Without analytics, we cannot:
|
||||
- Understand which commands and features are most valuable to users
|
||||
- Measure adoption and usage patterns
|
||||
- Make data-driven decisions about product development
|
||||
|
||||
Adding PostHog analytics enables product insights while respecting user privacy through transparent, opt-out telemetry.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Add PostHog Node.js SDK as a dependency
|
||||
- Implement telemetry system with environment variable opt-out
|
||||
- Track command usage (command name and version only)
|
||||
- Show first-run notice informing users about telemetry
|
||||
- Store anonymous ID in global config (`~/.config/openspec/config.json`)
|
||||
- Respect `DO_NOT_TRACK` and `OPENSPEC_TELEMETRY=0` environment variables
|
||||
- Auto-disable in CI environments
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `telemetry`: Anonymous usage analytics using PostHog. Covers command tracking, opt-out controls, and first-run disclosure notice.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `global-config`: Add telemetry state storage (anonymous ID, notice seen flag)
|
||||
|
||||
## Impact
|
||||
|
||||
- **Dependencies**: Add `posthog-node` package
|
||||
- **Privacy**: Opt-out via env var, no personal data collected, clear disclosure
|
||||
- **Configuration**: New global config fields for telemetry state
|
||||
- **Network**: Async event sending with flush on exit (~100-300ms added)
|
||||
- **CI/CD**: Telemetry auto-disabled when `CI=true`
|
||||
- **Documentation**: Update README with telemetry disclosure
|
||||
@@ -0,0 +1,21 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Global configuration storage
|
||||
The system SHALL store global configuration in `~/.config/openspec/config.json`, including telemetry state with `anonymousId` and `noticeSeen` fields.
|
||||
|
||||
#### Scenario: Initial config creation
|
||||
- **WHEN** no global config file exists
|
||||
- **AND** the first telemetry event is about to be sent
|
||||
- **THEN** the system creates `~/.config/openspec/config.json` with telemetry configuration
|
||||
|
||||
#### Scenario: Telemetry config structure
|
||||
- **WHEN** reading or writing telemetry configuration
|
||||
- **THEN** the config contains a `telemetry` object with `anonymousId` (string UUID) and `noticeSeen` (boolean) fields
|
||||
|
||||
#### Scenario: Config file format
|
||||
- **WHEN** storing configuration
|
||||
- **THEN** the system writes valid JSON that can be read and modified by users
|
||||
|
||||
#### Scenario: Existing config preservation
|
||||
- **WHEN** adding telemetry fields to an existing config file
|
||||
- **THEN** the system preserves all existing configuration fields
|
||||
@@ -0,0 +1,116 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Command execution tracking
|
||||
The system SHALL send a `command_executed` event to PostHog when any CLI command executes, including only the command name and OpenSpec version as properties.
|
||||
|
||||
#### Scenario: Standard command execution
|
||||
- **WHEN** a user runs any openspec command
|
||||
- **THEN** the system sends a `command_executed` event with `command` and `version` properties
|
||||
|
||||
#### Scenario: Subcommand execution
|
||||
- **WHEN** a user runs a nested command like `openspec change apply`
|
||||
- **THEN** the system sends a `command_executed` event with the full command path (e.g., `change:apply`)
|
||||
|
||||
### Requirement: Privacy-preserving event design
|
||||
The system SHALL NOT include command arguments, file paths, project names, spec content, error messages, or IP addresses in telemetry events.
|
||||
|
||||
#### Scenario: Command with arguments
|
||||
- **WHEN** a user runs `openspec init my-project --force`
|
||||
- **THEN** the telemetry event contains only `command: "init"` and `version: "<version>"` without arguments
|
||||
|
||||
#### Scenario: IP address exclusion
|
||||
- **WHEN** the system sends a telemetry event
|
||||
- **THEN** the event explicitly sets `$ip: null` to prevent IP tracking
|
||||
|
||||
### Requirement: Environment variable opt-out
|
||||
The system SHALL disable telemetry when `OPENSPEC_TELEMETRY=0` or `DO_NOT_TRACK=1` environment variables are set.
|
||||
|
||||
#### Scenario: OPENSPEC_TELEMETRY opt-out
|
||||
- **WHEN** `OPENSPEC_TELEMETRY=0` is set in the environment
|
||||
- **THEN** the system sends no telemetry events
|
||||
|
||||
#### Scenario: DO_NOT_TRACK opt-out
|
||||
- **WHEN** `DO_NOT_TRACK=1` is set in the environment
|
||||
- **THEN** the system sends no telemetry events
|
||||
|
||||
#### Scenario: Environment variable takes precedence
|
||||
- **WHEN** the user has previously used the CLI (config exists)
|
||||
- **AND** the user sets `OPENSPEC_TELEMETRY=0`
|
||||
- **THEN** telemetry is disabled regardless of config state
|
||||
|
||||
### Requirement: CI environment auto-disable
|
||||
The system SHALL automatically disable telemetry when `CI=true` environment variable is detected.
|
||||
|
||||
#### Scenario: CI environment detection
|
||||
- **WHEN** `CI=true` is set in the environment
|
||||
- **THEN** the system sends no telemetry events
|
||||
|
||||
#### Scenario: CI with explicit enable
|
||||
- **WHEN** `CI=true` is set
|
||||
- **AND** `OPENSPEC_TELEMETRY=1` is explicitly set
|
||||
- **THEN** telemetry remains disabled (CI takes precedence for privacy)
|
||||
|
||||
### Requirement: First-run telemetry notice
|
||||
The system SHALL display a one-line telemetry disclosure notice on the first command execution, before any telemetry is sent.
|
||||
|
||||
#### Scenario: First command execution
|
||||
- **WHEN** a user runs their first openspec command
|
||||
- **AND** telemetry is enabled
|
||||
- **THEN** the system displays: "Note: OpenSpec collects anonymous usage stats. Opt out: OPENSPEC_TELEMETRY=0"
|
||||
|
||||
#### Scenario: Subsequent command execution
|
||||
- **WHEN** a user has already seen the notice (noticeSeen: true in config)
|
||||
- **THEN** the system does not display the notice
|
||||
|
||||
#### Scenario: Notice before telemetry
|
||||
- **WHEN** displaying the first-run notice
|
||||
- **THEN** the notice appears before any telemetry event is sent
|
||||
|
||||
### Requirement: Anonymous user identification
|
||||
The system SHALL generate a random UUID as an anonymous identifier on first telemetry send, stored in global config.
|
||||
|
||||
#### Scenario: First telemetry event
|
||||
- **WHEN** the first telemetry event is sent
|
||||
- **AND** no anonymousId exists in config
|
||||
- **THEN** the system generates a random UUID v4 and stores it in config
|
||||
|
||||
#### Scenario: Persistent identity
|
||||
- **WHEN** a user runs multiple commands across sessions
|
||||
- **THEN** the same anonymousId is used for all events
|
||||
|
||||
#### Scenario: Lazy generation with opt-out
|
||||
- **WHEN** a user opts out before running any command
|
||||
- **THEN** no anonymousId is ever generated or stored
|
||||
|
||||
### Requirement: Immediate event sending
|
||||
The system SHALL send telemetry events immediately without batching, using `flushAt: 1` and `flushInterval: 0` configuration.
|
||||
|
||||
#### Scenario: Event transmission timing
|
||||
- **WHEN** a command executes
|
||||
- **THEN** the telemetry event is sent immediately, not queued for batch transmission
|
||||
|
||||
### Requirement: Graceful shutdown
|
||||
The system SHALL call `posthog.shutdown()` before CLI exit to ensure pending events are flushed.
|
||||
|
||||
#### Scenario: Normal exit
|
||||
- **WHEN** a command completes successfully
|
||||
- **THEN** the system awaits `shutdown()` before exiting
|
||||
|
||||
#### Scenario: Error exit
|
||||
- **WHEN** a command fails with an error
|
||||
- **THEN** the system still awaits `shutdown()` before exiting
|
||||
|
||||
### Requirement: Silent failure handling
|
||||
The system SHALL silently ignore telemetry failures without affecting CLI functionality.
|
||||
|
||||
#### Scenario: Network failure
|
||||
- **WHEN** the telemetry request fails due to network error
|
||||
- **THEN** the CLI command completes normally without error message
|
||||
|
||||
#### Scenario: PostHog outage
|
||||
- **WHEN** PostHog service is unavailable
|
||||
- **THEN** the CLI command completes normally without error message
|
||||
|
||||
#### Scenario: Shutdown failure
|
||||
- **WHEN** `shutdown()` fails or times out
|
||||
- **THEN** the CLI exits normally without error message
|
||||
@@ -0,0 +1,47 @@
|
||||
## 1. Setup
|
||||
|
||||
- [x] 1.1 Add `posthog-node` package as a dependency
|
||||
- [x] 1.2 Create `src/telemetry/` module directory
|
||||
- [x] 1.3 Add PostHog API key configuration (environment variable or embedded)
|
||||
|
||||
## 2. Global Config
|
||||
|
||||
- [x] 2.1 Create or extend global config module for `~/.config/openspec/config.json`
|
||||
- [x] 2.2 Implement read/write functions that preserve existing config fields
|
||||
- [x] 2.3 Define telemetry config structure (`anonymousId`, `noticeSeen`)
|
||||
|
||||
## 3. Core Telemetry Module
|
||||
|
||||
- [x] 3.1 Implement `isTelemetryEnabled()` checking `OPENSPEC_TELEMETRY`, `DO_NOT_TRACK`, and `CI` env vars
|
||||
- [x] 3.2 Implement `getOrCreateAnonymousId()` with lazy UUID generation
|
||||
- [x] 3.3 Initialize PostHog client with `flushAt: 1` and `flushInterval: 0`
|
||||
- [x] 3.4 Implement `trackCommand(commandName, version)` with `$ip: null`
|
||||
- [x] 3.5 Implement `shutdown()` with try/catch for silent failure handling
|
||||
|
||||
## 4. First-Run Notice
|
||||
|
||||
- [x] 4.1 Implement `maybeShowTelemetryNotice()` function
|
||||
- [x] 4.2 Check `noticeSeen` flag before displaying notice
|
||||
- [x] 4.3 Display notice text: "Note: OpenSpec collects anonymous usage stats. Opt out: OPENSPEC_TELEMETRY=0"
|
||||
- [x] 4.4 Update `noticeSeen` in config after first display
|
||||
|
||||
## 5. CLI Integration
|
||||
|
||||
- [x] 5.1 Add Commander.js `preAction` hook to show notice and track command
|
||||
- [x] 5.2 Add Commander.js `postAction` hook to call shutdown
|
||||
- [x] 5.3 Handle subcommand path extraction (e.g., `change:apply`)
|
||||
|
||||
## 6. Testing
|
||||
|
||||
- [x] 6.1 Test opt-out via `OPENSPEC_TELEMETRY=0`
|
||||
- [x] 6.2 Test opt-out via `DO_NOT_TRACK=1`
|
||||
- [x] 6.3 Test auto-disable in CI environment
|
||||
- [x] 6.4 Test first-run notice display and noticeSeen persistence
|
||||
- [x] 6.5 Test anonymous ID generation and persistence
|
||||
- [x] 6.6 Test silent failure on network error (mock PostHog)
|
||||
|
||||
## 7. Documentation
|
||||
|
||||
- [x] 7.1 Add telemetry disclosure section to README
|
||||
- [x] 7.2 Document opt-out methods (`OPENSPEC_TELEMETRY=0`, `DO_NOT_TRACK=1`)
|
||||
- [x] 7.3 Document what data is collected and not collected
|
||||
@@ -4,6 +4,26 @@
|
||||
|
||||
This spec defines how OpenSpec resolves, reads, and writes user-level global configuration. It governs the `src/core/global-config.ts` module, which provides the foundation for storing user preferences, feature flags, and settings that persist across projects. The spec ensures cross-platform compatibility by following XDG Base Directory Specification with platform-specific fallbacks, and guarantees forward/backward compatibility through schema evolution rules.
|
||||
## Requirements
|
||||
### Requirement: Global configuration storage
|
||||
The system SHALL store global configuration in `~/.config/openspec/config.json`, including telemetry state with `anonymousId` and `noticeSeen` fields.
|
||||
|
||||
#### Scenario: Initial config creation
|
||||
- **WHEN** no global config file exists
|
||||
- **AND** the first telemetry event is about to be sent
|
||||
- **THEN** the system creates `~/.config/openspec/config.json` with telemetry configuration
|
||||
|
||||
#### Scenario: Telemetry config structure
|
||||
- **WHEN** reading or writing telemetry configuration
|
||||
- **THEN** the config contains a `telemetry` object with `anonymousId` (string UUID) and `noticeSeen` (boolean) fields
|
||||
|
||||
#### Scenario: Config file format
|
||||
- **WHEN** storing configuration
|
||||
- **THEN** the system writes valid JSON that can be read and modified by users
|
||||
|
||||
#### Scenario: Existing config preservation
|
||||
- **WHEN** adding telemetry fields to an existing config file
|
||||
- **THEN** the system preserves all existing configuration fields
|
||||
|
||||
### Requirement: Global Config Directory Path
|
||||
|
||||
The system SHALL resolve the global configuration directory path following XDG Base Directory Specification with platform-specific fallbacks.
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# telemetry Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
This spec defines how OpenSpec collects anonymous usage telemetry to help improve the tool. It governs the `src/telemetry/` module, which handles PostHog integration, privacy-preserving event design, user opt-out mechanisms, and first-run notice display. The spec ensures telemetry is minimal, transparent, and respects user privacy.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Command execution tracking
|
||||
The system SHALL send a `command_executed` event to PostHog when any CLI command executes, including only the command name and OpenSpec version as properties.
|
||||
|
||||
#### Scenario: Standard command execution
|
||||
- **WHEN** a user runs any openspec command
|
||||
- **THEN** the system sends a `command_executed` event with `command` and `version` properties
|
||||
|
||||
#### Scenario: Subcommand execution
|
||||
- **WHEN** a user runs a nested command like `openspec change apply`
|
||||
- **THEN** the system sends a `command_executed` event with the full command path (e.g., `change:apply`)
|
||||
|
||||
### Requirement: Privacy-preserving event design
|
||||
The system SHALL NOT include command arguments, file paths, project names, spec content, error messages, or IP addresses in telemetry events.
|
||||
|
||||
#### Scenario: Command with arguments
|
||||
- **WHEN** a user runs `openspec init my-project --force`
|
||||
- **THEN** the telemetry event contains only `command: "init"` and `version: "<version>"` without arguments
|
||||
|
||||
#### Scenario: IP address exclusion
|
||||
- **WHEN** the system sends a telemetry event
|
||||
- **THEN** the event explicitly sets `$ip: null` to prevent IP tracking
|
||||
|
||||
### Requirement: Environment variable opt-out
|
||||
The system SHALL disable telemetry when `OPENSPEC_TELEMETRY=0` or `DO_NOT_TRACK=1` environment variables are set.
|
||||
|
||||
#### Scenario: OPENSPEC_TELEMETRY opt-out
|
||||
- **WHEN** `OPENSPEC_TELEMETRY=0` is set in the environment
|
||||
- **THEN** the system sends no telemetry events
|
||||
|
||||
#### Scenario: DO_NOT_TRACK opt-out
|
||||
- **WHEN** `DO_NOT_TRACK=1` is set in the environment
|
||||
- **THEN** the system sends no telemetry events
|
||||
|
||||
#### Scenario: Environment variable takes precedence
|
||||
- **WHEN** the user has previously used the CLI (config exists)
|
||||
- **AND** the user sets `OPENSPEC_TELEMETRY=0`
|
||||
- **THEN** telemetry is disabled regardless of config state
|
||||
|
||||
### Requirement: CI environment auto-disable
|
||||
The system SHALL automatically disable telemetry when `CI=true` environment variable is detected.
|
||||
|
||||
#### Scenario: CI environment detection
|
||||
- **WHEN** `CI=true` is set in the environment
|
||||
- **THEN** the system sends no telemetry events
|
||||
|
||||
#### Scenario: CI with explicit enable
|
||||
- **WHEN** `CI=true` is set
|
||||
- **AND** `OPENSPEC_TELEMETRY=1` is explicitly set
|
||||
- **THEN** telemetry remains disabled (CI takes precedence for privacy)
|
||||
|
||||
### Requirement: First-run telemetry notice
|
||||
The system SHALL display a one-line telemetry disclosure notice on the first command execution, before any telemetry is sent.
|
||||
|
||||
#### Scenario: First command execution
|
||||
- **WHEN** a user runs their first openspec command
|
||||
- **AND** telemetry is enabled
|
||||
- **THEN** the system displays: "Note: OpenSpec collects anonymous usage stats. Opt out: OPENSPEC_TELEMETRY=0"
|
||||
|
||||
#### Scenario: Subsequent command execution
|
||||
- **WHEN** a user has already seen the notice (noticeSeen: true in config)
|
||||
- **THEN** the system does not display the notice
|
||||
|
||||
#### Scenario: Notice before telemetry
|
||||
- **WHEN** displaying the first-run notice
|
||||
- **THEN** the notice appears before any telemetry event is sent
|
||||
|
||||
### Requirement: Anonymous user identification
|
||||
The system SHALL generate a random UUID as an anonymous identifier on first telemetry send, stored in global config.
|
||||
|
||||
#### Scenario: First telemetry event
|
||||
- **WHEN** the first telemetry event is sent
|
||||
- **AND** no anonymousId exists in config
|
||||
- **THEN** the system generates a random UUID v4 and stores it in config
|
||||
|
||||
#### Scenario: Persistent identity
|
||||
- **WHEN** a user runs multiple commands across sessions
|
||||
- **THEN** the same anonymousId is used for all events
|
||||
|
||||
#### Scenario: Lazy generation with opt-out
|
||||
- **WHEN** a user opts out before running any command
|
||||
- **THEN** no anonymousId is ever generated or stored
|
||||
|
||||
### Requirement: Immediate event sending
|
||||
The system SHALL send telemetry events immediately without batching, using `flushAt: 1` and `flushInterval: 0` configuration.
|
||||
|
||||
#### Scenario: Event transmission timing
|
||||
- **WHEN** a command executes
|
||||
- **THEN** the telemetry event is sent immediately, not queued for batch transmission
|
||||
|
||||
### Requirement: Graceful shutdown
|
||||
The system SHALL call `posthog.shutdown()` before CLI exit to ensure pending events are flushed.
|
||||
|
||||
#### Scenario: Normal exit
|
||||
- **WHEN** a command completes successfully
|
||||
- **THEN** the system awaits `shutdown()` before exiting
|
||||
|
||||
#### Scenario: Error exit
|
||||
- **WHEN** a command fails with an error
|
||||
- **THEN** the system still awaits `shutdown()` before exiting
|
||||
|
||||
### Requirement: Silent failure handling
|
||||
The system SHALL silently ignore telemetry failures without affecting CLI functionality.
|
||||
|
||||
#### Scenario: Network failure
|
||||
- **WHEN** the telemetry request fails due to network error
|
||||
- **THEN** the CLI command completes normally without error message
|
||||
|
||||
#### Scenario: PostHog outage
|
||||
- **WHEN** PostHog service is unavailable
|
||||
- **THEN** the CLI command completes normally without error message
|
||||
|
||||
#### Scenario: Shutdown failure
|
||||
- **WHEN** `shutdown()` fails or times out
|
||||
- **THEN** the CLI exits normally without error message
|
||||
@@ -76,6 +76,7 @@
|
||||
"commander": "^14.0.0",
|
||||
"fast-glob": "^3.3.3",
|
||||
"ora": "^8.2.0",
|
||||
"posthog-node": "^5.20.0",
|
||||
"yaml": "^2.8.2",
|
||||
"zod": "^4.0.17"
|
||||
}
|
||||
|
||||
Generated
+18
@@ -26,6 +26,9 @@ importers:
|
||||
ora:
|
||||
specifier: ^8.2.0
|
||||
version: 8.2.0
|
||||
posthog-node:
|
||||
specifier: ^5.20.0
|
||||
version: 5.20.0
|
||||
yaml:
|
||||
specifier: ^2.8.2
|
||||
version: 2.8.2
|
||||
@@ -484,6 +487,9 @@ packages:
|
||||
'@polka/url@1.0.0-next.29':
|
||||
resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
|
||||
|
||||
'@posthog/core@1.9.1':
|
||||
resolution: {integrity: sha512-kRb1ch2dhQjsAapZmu6V66551IF2LnCbc1rnrQqnR7ArooVyJN9KOPXre16AJ3ObJz2eTfuP7x25BMyS2Y5Exw==}
|
||||
|
||||
'@rollup/rollup-android-arm-eabi@4.46.2':
|
||||
resolution: {integrity: sha512-Zj3Hl6sN34xJtMv7Anwb5Gu01yujyE/cLBDB2gnHTAHaWS1Z38L7kuSG+oAh0giZMqG060f/YBStXtMH6FvPMA==}
|
||||
cpu: [arm]
|
||||
@@ -1284,6 +1290,10 @@ packages:
|
||||
resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
|
||||
posthog-node@5.20.0:
|
||||
resolution: {integrity: sha512-LkR5KfrvEQTnUtNKN97VxFB00KcYG1Iz8iKg8r0e/i7f1eQhg1WSZO+Jp1B4bvtHCmdpIE4HwYbvCCzFoCyjVg==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
prelude-ls@1.2.1:
|
||||
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
@@ -2038,6 +2048,10 @@ snapshots:
|
||||
|
||||
'@polka/url@1.0.0-next.29': {}
|
||||
|
||||
'@posthog/core@1.9.1':
|
||||
dependencies:
|
||||
cross-spawn: 7.0.6
|
||||
|
||||
'@rollup/rollup-android-arm-eabi@4.46.2':
|
||||
optional: true
|
||||
|
||||
@@ -2808,6 +2822,10 @@ snapshots:
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.1
|
||||
|
||||
posthog-node@5.20.0:
|
||||
dependencies:
|
||||
'@posthog/core': 1.9.1
|
||||
|
||||
prelude-ls@1.2.1: {}
|
||||
|
||||
prettier@2.8.8: {}
|
||||
|
||||
+38
-2
@@ -15,11 +15,32 @@ import { ShowCommand } from '../commands/show.js';
|
||||
import { CompletionCommand } from '../commands/completion.js';
|
||||
import { registerConfigCommand } from '../commands/config.js';
|
||||
import { registerArtifactWorkflowCommands } from '../commands/artifact-workflow.js';
|
||||
import { maybeShowTelemetryNotice, trackCommand, shutdown } from '../telemetry/index.js';
|
||||
|
||||
const program = new Command();
|
||||
const require = createRequire(import.meta.url);
|
||||
const { version } = require('../../package.json');
|
||||
|
||||
/**
|
||||
* Get the full command path for nested commands.
|
||||
* For example: 'change show' -> 'change:show'
|
||||
*/
|
||||
function getCommandPath(command: Command): string {
|
||||
const names: string[] = [];
|
||||
let current: Command | null = command;
|
||||
|
||||
while (current) {
|
||||
const name = current.name();
|
||||
// Skip the root 'openspec' command
|
||||
if (name && name !== 'openspec') {
|
||||
names.unshift(name);
|
||||
}
|
||||
current = current.parent;
|
||||
}
|
||||
|
||||
return names.join(':') || 'openspec';
|
||||
}
|
||||
|
||||
program
|
||||
.name('openspec')
|
||||
.description('AI-native system for spec-driven development')
|
||||
@@ -28,12 +49,27 @@ program
|
||||
// Global options
|
||||
program.option('--no-color', 'Disable color output');
|
||||
|
||||
// Apply global flags before any command runs
|
||||
program.hook('preAction', (thisCommand) => {
|
||||
// Apply global flags and telemetry before any command runs
|
||||
// Note: preAction receives (thisCommand, actionCommand) where:
|
||||
// - thisCommand: the command where hook was added (root program)
|
||||
// - actionCommand: the command actually being executed (subcommand)
|
||||
program.hook('preAction', async (thisCommand, actionCommand) => {
|
||||
const opts = thisCommand.opts();
|
||||
if (opts.color === false) {
|
||||
process.env.NO_COLOR = '1';
|
||||
}
|
||||
|
||||
// Show first-run telemetry notice (if not seen)
|
||||
await maybeShowTelemetryNotice();
|
||||
|
||||
// Track command execution (use actionCommand to get the actual subcommand)
|
||||
const commandPath = getCommandPath(actionCommand);
|
||||
await trackCommand(commandPath, version);
|
||||
});
|
||||
|
||||
// Shutdown telemetry after command completes
|
||||
program.hook('postAction', async () => {
|
||||
await shutdown();
|
||||
});
|
||||
|
||||
const availableToolIds = AI_TOOLS.filter((tool) => tool.available).map((tool) => tool.value);
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
type SchemaInfo,
|
||||
} from '../core/artifact-graph/index.js';
|
||||
import { createChange, validateChangeName } from '../utils/change-utils.js';
|
||||
import { getNewChangeSkillTemplate, getContinueChangeSkillTemplate, getApplyChangeSkillTemplate, getFfChangeSkillTemplate, getSyncSpecsSkillTemplate, getArchiveChangeSkillTemplate, getOpsxNewCommandTemplate, getOpsxContinueCommandTemplate, getOpsxApplyCommandTemplate, getOpsxFfCommandTemplate, getOpsxSyncCommandTemplate, getOpsxArchiveCommandTemplate } from '../core/templates/skill-templates.js';
|
||||
import { getExploreSkillTemplate, getNewChangeSkillTemplate, getContinueChangeSkillTemplate, getApplyChangeSkillTemplate, getFfChangeSkillTemplate, getSyncSpecsSkillTemplate, getArchiveChangeSkillTemplate, getOpsxExploreCommandTemplate, getOpsxNewCommandTemplate, getOpsxContinueCommandTemplate, getOpsxApplyCommandTemplate, getOpsxFfCommandTemplate, getOpsxSyncCommandTemplate, getOpsxArchiveCommandTemplate } from '../core/templates/skill-templates.js';
|
||||
import { FileSystemUtils } from '../utils/file-system.js';
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
@@ -793,6 +793,7 @@ async function artifactExperimentalSetupCommand(): Promise<void> {
|
||||
const commandsDir = path.join(projectRoot, '.claude', 'commands', 'opsx');
|
||||
|
||||
// Get skill templates
|
||||
const exploreSkill = getExploreSkillTemplate();
|
||||
const newChangeSkill = getNewChangeSkillTemplate();
|
||||
const continueChangeSkill = getContinueChangeSkillTemplate();
|
||||
const applyChangeSkill = getApplyChangeSkillTemplate();
|
||||
@@ -801,6 +802,7 @@ async function artifactExperimentalSetupCommand(): Promise<void> {
|
||||
const archiveChangeSkill = getArchiveChangeSkillTemplate();
|
||||
|
||||
// Get command templates
|
||||
const exploreCommand = getOpsxExploreCommandTemplate();
|
||||
const newCommand = getOpsxNewCommandTemplate();
|
||||
const continueCommand = getOpsxContinueCommandTemplate();
|
||||
const applyCommand = getOpsxApplyCommandTemplate();
|
||||
@@ -810,6 +812,7 @@ async function artifactExperimentalSetupCommand(): Promise<void> {
|
||||
|
||||
// Create skill directories and SKILL.md files
|
||||
const skills = [
|
||||
{ template: exploreSkill, dirName: 'openspec-explore' },
|
||||
{ template: newChangeSkill, dirName: 'openspec-new-change' },
|
||||
{ template: continueChangeSkill, dirName: 'openspec-continue-change' },
|
||||
{ template: applyChangeSkill, dirName: 'openspec-apply-change' },
|
||||
@@ -840,6 +843,7 @@ ${template.instructions}
|
||||
|
||||
// Create slash command files
|
||||
const commands = [
|
||||
{ template: exploreCommand, fileName: 'explore.md' },
|
||||
{ template: newCommand, fileName: 'new.md' },
|
||||
{ template: continueCommand, fileName: 'continue.md' },
|
||||
{ template: applyCommand, fileName: 'apply.md' },
|
||||
@@ -898,6 +902,7 @@ ${template.content}
|
||||
console.log(' • "Implement the tasks for this change"');
|
||||
console.log();
|
||||
console.log(' ' + chalk.cyan('Slash Commands') + ' for explicit invocation:');
|
||||
console.log(' • /opsx:explore - Think through ideas, investigate problems');
|
||||
console.log(' • /opsx:new - Start a new change');
|
||||
console.log(' • /opsx:continue - Create the next artifact');
|
||||
console.log(' • /opsx:apply - Implement tasks');
|
||||
|
||||
@@ -83,6 +83,22 @@ complete -F _openspec_completion openspec
|
||||
|
||||
// Handle subcommands
|
||||
if (cmd.subcommands && cmd.subcommands.length > 0) {
|
||||
// First, check if user is typing a flag for the parent command
|
||||
if (cmd.flags.length > 0) {
|
||||
lines.push(`${indent}if [[ "$cur" == -* ]]; then`);
|
||||
const flags = cmd.flags.map(f => {
|
||||
const parts: string[] = [];
|
||||
if (f.short) parts.push(`-${f.short}`);
|
||||
parts.push(`--${f.name}`);
|
||||
return parts.join(' ');
|
||||
}).join(' ');
|
||||
lines.push(`${indent} local flags="${flags}"`);
|
||||
lines.push(`${indent} COMPREPLY=($(compgen -W "$flags" -- "$cur"))`);
|
||||
lines.push(`${indent} return 0`);
|
||||
lines.push(`${indent}fi`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
lines.push(`${indent}if [[ $cword -eq 2 ]]; then`);
|
||||
lines.push(`${indent} local subcommands="` + cmd.subcommands.map(s => this.escapeCommandName(s.name)).join(' ') + '"');
|
||||
lines.push(`${indent} COMPREPLY=($(compgen -W "$subcommands" -- "$cur"))`);
|
||||
|
||||
@@ -74,6 +74,29 @@ Register-ArgumentCompleter -CommandName openspec -ScriptBlock $openspecCompleter
|
||||
const lines: string[] = [];
|
||||
|
||||
if (cmd.subcommands && cmd.subcommands.length > 0) {
|
||||
// First, check if user is typing a flag for the parent command
|
||||
if (cmd.flags.length > 0) {
|
||||
lines.push(`${indent}if ($wordToComplete -like "-*") {`);
|
||||
lines.push(`${indent} $flags = @(`);
|
||||
for (const flag of cmd.flags) {
|
||||
const longFlag = `--${flag.name}`;
|
||||
const shortFlag = flag.short ? `-${flag.short}` : undefined;
|
||||
if (shortFlag) {
|
||||
lines.push(`${indent} @{Name="${longFlag}"; Description="${this.escapeDescription(flag.description)}"},`);
|
||||
lines.push(`${indent} @{Name="${shortFlag}"; Description="${this.escapeDescription(flag.description)}"},`);
|
||||
} else {
|
||||
lines.push(`${indent} @{Name="${longFlag}"; Description="${this.escapeDescription(flag.description)}"},`);
|
||||
}
|
||||
}
|
||||
lines.push(`${indent} )`);
|
||||
lines.push(`${indent} $flags | Where-Object { $_.Name -like "$wordToComplete*" } | ForEach-Object {`);
|
||||
lines.push(`${indent} [System.Management.Automation.CompletionResult]::new($_.Name, $_.Name, "ParameterName", $_.Description)`);
|
||||
lines.push(`${indent} }`);
|
||||
lines.push(`${indent} return`);
|
||||
lines.push(`${indent}}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
// Handle subcommands
|
||||
lines.push(`${indent}if ($commandCount -eq 2 -or ($commandCount -eq 3 -and $wordToComplete)) {`);
|
||||
lines.push(`${indent} $subcommands = @(`);
|
||||
|
||||
@@ -14,6 +14,292 @@ export interface SkillTemplate {
|
||||
instructions: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
||||
**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
|
||||
- **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/<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 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 <name>
|
||||
- Fast-forward to tasks: /opsx:ff <name>
|
||||
- Keep exploring: just keep talking
|
||||
\`\`\`
|
||||
|
||||
But this summary is optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **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`
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Template for openspec-new-change skill
|
||||
* Based on /opsx:new command
|
||||
@@ -37,21 +323,22 @@ export function getNewChangeSkillTemplate(): SkillTemplate {
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Select a workflow schema**
|
||||
2. **Determine the workflow schema**
|
||||
|
||||
Run \`openspec schemas --json\` to get available schemas with descriptions.
|
||||
Use the default schema (omit \`--schema\`) unless the user explicitly requests a different workflow.
|
||||
|
||||
Use the **AskUserQuestion tool** to let the user choose a workflow:
|
||||
- Present each schema with its description
|
||||
- Mark \`spec-driven\` as "(default)" if it's available
|
||||
- Example options: "spec-driven - proposal → specs → design → tasks (default)", "tdd - tests → implementation → docs"
|
||||
**Use a different schema only if the user mentions:**
|
||||
- "tdd" or "test-driven" → use \`--schema tdd\`
|
||||
- A specific schema name → use \`--schema <name>\`
|
||||
- "show workflows" or "what workflows" → run \`openspec schemas --json\` and let them choose
|
||||
|
||||
If user doesn't have a preference, default to \`spec-driven\`.
|
||||
**Otherwise**: Omit \`--schema\` to use the default.
|
||||
|
||||
3. **Create the change directory**
|
||||
\`\`\`bash
|
||||
openspec new change "<name>" --schema "<selected-schema>"
|
||||
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**
|
||||
@@ -74,7 +361,7 @@ export function getNewChangeSkillTemplate(): SkillTemplate {
|
||||
|
||||
After completing the steps, summarize:
|
||||
- Change name and location
|
||||
- Selected schema/workflow and its artifact sequence
|
||||
- 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."
|
||||
@@ -84,7 +371,7 @@ After completing the steps, summarize:
|
||||
- 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
|
||||
- Always pass --schema to preserve the user's workflow choice`
|
||||
- Pass --schema if using a non-default workflow`
|
||||
};
|
||||
}
|
||||
|
||||
@@ -605,6 +892,182 @@ export interface CommandTemplate {
|
||||
content: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Template for /opsx:explore slash command
|
||||
* Explore mode - adaptive thinking partner
|
||||
*/
|
||||
export function getOpsxExploreCommandTemplate(): CommandTemplate {
|
||||
return {
|
||||
name: 'OPSX: Explore',
|
||||
description: 'Enter explore mode - think through ideas, investigate problems, clarify requirements',
|
||||
category: 'Workflow',
|
||||
tags: ['workflow', 'explore', 'experimental', 'thinking'],
|
||||
content: `Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||
|
||||
**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
|
||||
- **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 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/<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 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 things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
|
||||
|
||||
---
|
||||
|
||||
## Guardrails
|
||||
|
||||
- **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`
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Template for /opsx:new slash command
|
||||
*/
|
||||
@@ -629,21 +1092,22 @@ export function getOpsxNewCommandTemplate(): CommandTemplate {
|
||||
|
||||
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||
|
||||
2. **Select a workflow schema**
|
||||
2. **Determine the workflow schema**
|
||||
|
||||
Run \`openspec schemas --json\` to get available schemas with descriptions.
|
||||
Use the default schema (omit \`--schema\`) unless the user explicitly requests a different workflow.
|
||||
|
||||
Use the **AskUserQuestion tool** to let the user choose a workflow:
|
||||
- Present each schema with its description
|
||||
- Mark \`spec-driven\` as "(default)" if it's available
|
||||
- Example options: "spec-driven - proposal → specs → design → tasks (default)", "tdd - tests → implementation → docs"
|
||||
**Use a different schema only if the user mentions:**
|
||||
- "tdd" or "test-driven" → use \`--schema tdd\`
|
||||
- A specific schema name → use \`--schema <name>\`
|
||||
- "show workflows" or "what workflows" → run \`openspec schemas --json\` and let them choose
|
||||
|
||||
If user doesn't have a preference, default to \`spec-driven\`.
|
||||
**Otherwise**: Omit \`--schema\` to use the default.
|
||||
|
||||
3. **Create the change directory**
|
||||
\`\`\`bash
|
||||
openspec new change "<name>" --schema "<selected-schema>"
|
||||
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**
|
||||
@@ -665,7 +1129,7 @@ export function getOpsxNewCommandTemplate(): CommandTemplate {
|
||||
|
||||
After completing the steps, summarize:
|
||||
- Change name and location
|
||||
- Selected schema/workflow and its artifact sequence
|
||||
- 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."
|
||||
@@ -675,7 +1139,7 @@ After completing the steps, summarize:
|
||||
- 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
|
||||
- Always pass --schema to preserve the user's workflow choice`
|
||||
- Pass --schema if using a non-default workflow`
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Global configuration for telemetry state.
|
||||
* Stores anonymous ID and notice-seen flag in ~/.config/openspec/config.json
|
||||
*/
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
|
||||
export interface TelemetryConfig {
|
||||
anonymousId?: string;
|
||||
noticeSeen?: boolean;
|
||||
}
|
||||
|
||||
export interface GlobalConfig {
|
||||
telemetry?: TelemetryConfig;
|
||||
[key: string]: unknown; // Preserve other fields
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the global config file.
|
||||
* Uses ~/.config/openspec/config.json on all platforms.
|
||||
*/
|
||||
export function getConfigPath(): string {
|
||||
const configDir = path.join(os.homedir(), '.config', 'openspec');
|
||||
return path.join(configDir, 'config.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the global config file.
|
||||
* Returns an empty object if the file doesn't exist.
|
||||
*/
|
||||
export async function readConfig(): Promise<GlobalConfig> {
|
||||
const configPath = getConfigPath();
|
||||
try {
|
||||
const content = await fs.readFile(configPath, 'utf-8');
|
||||
return JSON.parse(content) as GlobalConfig;
|
||||
} catch (error: unknown) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return {};
|
||||
}
|
||||
// If parse fails or other error, return empty config
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write to the global config file.
|
||||
* Preserves existing fields and merges in new values.
|
||||
*/
|
||||
export async function writeConfig(updates: Partial<GlobalConfig>): Promise<void> {
|
||||
const configPath = getConfigPath();
|
||||
const configDir = path.dirname(configPath);
|
||||
|
||||
// Ensure directory exists
|
||||
await fs.mkdir(configDir, { recursive: true });
|
||||
|
||||
// Read existing config and merge
|
||||
const existing = await readConfig();
|
||||
const merged = { ...existing, ...updates };
|
||||
|
||||
// Deep merge for telemetry object
|
||||
if (updates.telemetry && existing.telemetry) {
|
||||
merged.telemetry = { ...existing.telemetry, ...updates.telemetry };
|
||||
}
|
||||
|
||||
await fs.writeFile(configPath, JSON.stringify(merged, null, 2) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the telemetry config section.
|
||||
*/
|
||||
export async function getTelemetryConfig(): Promise<TelemetryConfig> {
|
||||
const config = await readConfig();
|
||||
return config.telemetry ?? {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the telemetry config section.
|
||||
*/
|
||||
export async function updateTelemetryConfig(updates: Partial<TelemetryConfig>): Promise<void> {
|
||||
const existing = await getTelemetryConfig();
|
||||
await writeConfig({
|
||||
telemetry: { ...existing, ...updates },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* Telemetry module for anonymous usage analytics.
|
||||
*
|
||||
* Privacy-first design:
|
||||
* - Only tracks command name and version
|
||||
* - No arguments, file paths, or content
|
||||
* - Opt-out via OPENSPEC_TELEMETRY=0 or DO_NOT_TRACK=1
|
||||
* - Auto-disabled in CI environments
|
||||
* - Anonymous ID is a random UUID with no relation to the user
|
||||
*/
|
||||
import { PostHog } from 'posthog-node';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { getTelemetryConfig, updateTelemetryConfig } from './config.js';
|
||||
|
||||
// PostHog API key - public key for client-side analytics
|
||||
// This is safe to embed as it only allows sending events, not reading data
|
||||
const POSTHOG_API_KEY = 'phc_Hthu8YvaIJ9QaFKyTG4TbVwkbd5ktcAFzVTKeMmoW2g';
|
||||
// Using reverse proxy to avoid ad blockers and keep traffic on our domain
|
||||
const POSTHOG_HOST = 'https://edge.openspec.dev';
|
||||
|
||||
let posthogClient: PostHog | null = null;
|
||||
let anonymousId: string | null = null;
|
||||
|
||||
/**
|
||||
* Check if telemetry is enabled.
|
||||
*
|
||||
* Disabled when:
|
||||
* - OPENSPEC_TELEMETRY=0
|
||||
* - DO_NOT_TRACK=1
|
||||
* - CI=true (any CI environment)
|
||||
*/
|
||||
export function isTelemetryEnabled(): boolean {
|
||||
// Check explicit opt-out
|
||||
if (process.env.OPENSPEC_TELEMETRY === '0') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Respect DO_NOT_TRACK standard
|
||||
if (process.env.DO_NOT_TRACK === '1') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Auto-disable in CI environments
|
||||
if (process.env.CI === 'true') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create the anonymous user ID.
|
||||
* Lazily generates a UUID on first call and persists it.
|
||||
*/
|
||||
export async function getOrCreateAnonymousId(): Promise<string> {
|
||||
// Return cached value if available
|
||||
if (anonymousId) {
|
||||
return anonymousId;
|
||||
}
|
||||
|
||||
// Try to load from config
|
||||
const config = await getTelemetryConfig();
|
||||
if (config.anonymousId) {
|
||||
anonymousId = config.anonymousId;
|
||||
return anonymousId;
|
||||
}
|
||||
|
||||
// Generate new UUID and persist
|
||||
anonymousId = randomUUID();
|
||||
await updateTelemetryConfig({ anonymousId });
|
||||
return anonymousId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PostHog client instance.
|
||||
* Creates it on first call with CLI-optimized settings.
|
||||
*/
|
||||
function getClient(): PostHog {
|
||||
if (!posthogClient) {
|
||||
posthogClient = new PostHog(POSTHOG_API_KEY, {
|
||||
host: POSTHOG_HOST,
|
||||
flushAt: 1, // Send immediately, don't batch
|
||||
flushInterval: 0, // No timer-based flushing
|
||||
});
|
||||
}
|
||||
return posthogClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Track a command execution.
|
||||
*
|
||||
* @param commandName - The command name (e.g., 'init', 'change:apply')
|
||||
* @param version - The OpenSpec version
|
||||
*/
|
||||
export async function trackCommand(commandName: string, version: string): Promise<void> {
|
||||
if (!isTelemetryEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const userId = await getOrCreateAnonymousId();
|
||||
const client = getClient();
|
||||
|
||||
client.capture({
|
||||
distinctId: userId,
|
||||
event: 'command_executed',
|
||||
properties: {
|
||||
command: commandName,
|
||||
version: version,
|
||||
surface: 'cli',
|
||||
$ip: null, // Explicitly disable IP tracking
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// Silent failure - telemetry should never break CLI
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show first-run telemetry notice if not already seen.
|
||||
*/
|
||||
export async function maybeShowTelemetryNotice(): Promise<void> {
|
||||
if (!isTelemetryEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await getTelemetryConfig();
|
||||
if (config.noticeSeen) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Display notice
|
||||
console.log(
|
||||
'Note: OpenSpec collects anonymous usage stats. Opt out: OPENSPEC_TELEMETRY=0'
|
||||
);
|
||||
|
||||
// Mark as seen
|
||||
await updateTelemetryConfig({ noticeSeen: true });
|
||||
} catch {
|
||||
// Silent failure - telemetry should never break CLI
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown the PostHog client and flush pending events.
|
||||
* Call this before CLI exit.
|
||||
*/
|
||||
export async function shutdown(): Promise<void> {
|
||||
if (!posthogClient) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await posthogClient.shutdown();
|
||||
} catch {
|
||||
// Silent failure - telemetry should never break CLI exit
|
||||
} finally {
|
||||
posthogClient = null;
|
||||
}
|
||||
}
|
||||
@@ -205,6 +205,50 @@ describe('BashGenerator', () => {
|
||||
expect(script).toContain('list');
|
||||
});
|
||||
|
||||
it('should offer parent flags when command has both flags and subcommands', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'config',
|
||||
description: 'Manage configuration',
|
||||
flags: [
|
||||
{
|
||||
name: 'scope',
|
||||
short: 's',
|
||||
description: 'Configuration scope',
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
description: 'Output as JSON',
|
||||
},
|
||||
],
|
||||
subcommands: [
|
||||
{
|
||||
name: 'set',
|
||||
description: 'Set a config value',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'get',
|
||||
description: 'Get a config value',
|
||||
flags: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
// Should check for flag prefix before offering subcommands
|
||||
expect(script).toContain('if [[ "$cur" == -* ]]; then');
|
||||
// Should include parent command flags
|
||||
expect(script).toContain('-s');
|
||||
expect(script).toContain('--scope');
|
||||
expect(script).toContain('--json');
|
||||
// Should also include subcommands
|
||||
expect(script).toContain('set');
|
||||
expect(script).toContain('get');
|
||||
});
|
||||
|
||||
it('should handle positional arguments for change-id', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
|
||||
@@ -224,6 +224,50 @@ describe('PowerShellGenerator', () => {
|
||||
expect(script).toContain('List changes');
|
||||
});
|
||||
|
||||
it('should offer parent flags when command has both flags and subcommands', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
name: 'config',
|
||||
description: 'Manage configuration',
|
||||
flags: [
|
||||
{
|
||||
name: 'scope',
|
||||
short: 's',
|
||||
description: 'Configuration scope',
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
description: 'Output as JSON',
|
||||
},
|
||||
],
|
||||
subcommands: [
|
||||
{
|
||||
name: 'set',
|
||||
description: 'Set a config value',
|
||||
flags: [],
|
||||
},
|
||||
{
|
||||
name: 'get',
|
||||
description: 'Get a config value',
|
||||
flags: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const script = generator.generate(commands);
|
||||
|
||||
// Should check for flag prefix before offering subcommands
|
||||
expect(script).toContain('if ($wordToComplete -like "-*")');
|
||||
// Should include parent command flags
|
||||
expect(script).toContain('-s');
|
||||
expect(script).toContain('--scope');
|
||||
expect(script).toContain('--json');
|
||||
// Should also include subcommands
|
||||
expect(script).toContain('"set"');
|
||||
expect(script).toContain('"get"');
|
||||
});
|
||||
|
||||
it('should handle positional arguments for change-id', () => {
|
||||
const commands: CommandDefinition[] = [
|
||||
{
|
||||
|
||||
@@ -139,8 +139,11 @@ describe('BashInstaller', () => {
|
||||
});
|
||||
|
||||
it('should handle installation errors gracefully', async () => {
|
||||
// Create installer with non-existent/invalid home directory
|
||||
const invalidInstaller = new BashInstaller('/root/invalid/nonexistent/path');
|
||||
// Create a temporary file and use its path as homeDir
|
||||
// This guarantees ENOTDIR when trying to create subdirectories (cross-platform)
|
||||
const blockingFile = path.join(testHomeDir, 'blocking-file');
|
||||
await fs.writeFile(blockingFile, 'blocking content');
|
||||
const invalidInstaller = new BashInstaller(blockingFile);
|
||||
|
||||
const result = await invalidInstaller.install(testScript);
|
||||
|
||||
@@ -373,8 +376,11 @@ describe('BashInstaller', () => {
|
||||
});
|
||||
|
||||
it('should handle write permission errors gracefully', async () => {
|
||||
// Create installer with path that can't be written
|
||||
const invalidInstaller = new BashInstaller('/root/invalid/path');
|
||||
// Create a temporary file and use its path as homeDir
|
||||
// This guarantees ENOTDIR when trying to write .bashrc (cross-platform)
|
||||
const blockingFile = path.join(testHomeDir, 'blocking-file');
|
||||
await fs.writeFile(blockingFile, 'blocking content');
|
||||
const invalidInstaller = new BashInstaller(blockingFile);
|
||||
|
||||
const result = await invalidInstaller.configureBashrc(completionsDir);
|
||||
|
||||
|
||||
@@ -192,7 +192,9 @@ complete -c openspec -a 'validate' -d 'Validate specs'
|
||||
await fs.rm(spacedHomeDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should return failure on permission error', async () => {
|
||||
// Skip on Windows: fs.chmod() on directories doesn't restrict write access on Windows
|
||||
// Windows uses ACLs which Node.js chmod doesn't control
|
||||
it.skipIf(process.platform === 'win32')('should return failure on permission error', async () => {
|
||||
// Create a read-only directory to simulate permission error
|
||||
const restrictedDir = path.join(testHomeDir, '.config', 'fish', 'completions');
|
||||
await fs.mkdir(restrictedDir, { recursive: true });
|
||||
@@ -284,7 +286,9 @@ complete -c openspec -a 'init'
|
||||
expect(result.message).toBe('Completion script uninstalled successfully');
|
||||
});
|
||||
|
||||
it('should return failure on permission error', async () => {
|
||||
// Skip on Windows: fs.chmod() on directories doesn't restrict write access on Windows
|
||||
// Windows uses ACLs which Node.js chmod doesn't control
|
||||
it.skipIf(process.platform === 'win32')('should return failure on permission error', async () => {
|
||||
await installer.install(mockCompletionScript);
|
||||
const targetPath = path.join(testHomeDir, '.config', 'fish', 'completions', 'openspec.fish');
|
||||
const parentDir = path.dirname(targetPath);
|
||||
|
||||
@@ -171,7 +171,9 @@ describe('PowerShellInstaller', () => {
|
||||
expect(content).toContain('Write-Host "Hello"');
|
||||
});
|
||||
|
||||
it('should skip configuration when script line already exists', async () => {
|
||||
// Skip on Windows: Windows has dual profile paths (PowerShell Core + Windows PowerShell 5.1),
|
||||
// so even if one profile is already configured, the second one will be configured and return true
|
||||
it.skipIf(process.platform === 'win32')('should skip configuration when script line already exists', async () => {
|
||||
delete process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
const profilePath = installer.getProfilePath();
|
||||
await fs.mkdir(path.dirname(profilePath), { recursive: true });
|
||||
@@ -237,7 +239,9 @@ describe('PowerShellInstaller', () => {
|
||||
expect(content).toContain('# OPENSPEC:END');
|
||||
});
|
||||
|
||||
it('should return false on write permission error', async () => {
|
||||
// Skip on Windows: fs.chmod() doesn't reliably restrict write access on Windows
|
||||
// (admin users can bypass read-only attribute, and CI runners often have elevated privileges)
|
||||
it.skipIf(process.platform === 'win32')('should return false on write permission error', async () => {
|
||||
delete process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
const profilePath = installer.getProfilePath();
|
||||
await fs.mkdir(path.dirname(profilePath), { recursive: true });
|
||||
@@ -451,7 +455,9 @@ Register-ArgumentCompleter -CommandName openspec -ScriptBlock $openspecCompleter
|
||||
// Note: OPENSPEC_NO_AUTO_CONFIG support was removed from PowerShell installer
|
||||
// Profile is now always auto-configured if possible
|
||||
|
||||
it('should provide instructions when profile cannot be configured', async () => {
|
||||
// Skip on Windows: fs.chmod() doesn't reliably restrict write access on Windows
|
||||
// (admin users can bypass read-only attribute, and CI runners often have elevated privileges)
|
||||
it.skipIf(process.platform === 'win32')('should provide instructions when profile cannot be configured', async () => {
|
||||
delete process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
// Make profile directory read-only to prevent configuration
|
||||
const profilePath = installer.getProfilePath();
|
||||
@@ -496,7 +502,9 @@ Register-ArgumentCompleter -CommandName openspec -ScriptBlock $openspecCompleter
|
||||
await fs.rm(spacedHomeDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('should return failure on permission error', async () => {
|
||||
// Skip on Windows: fs.chmod() on directories doesn't restrict write access on Windows
|
||||
// Windows uses ACLs which Node.js chmod doesn't control
|
||||
it.skipIf(process.platform === 'win32')('should return failure on permission error', async () => {
|
||||
const targetPath = installer.getInstallationPath();
|
||||
const targetDir = path.dirname(targetPath);
|
||||
await fs.mkdir(targetDir, { recursive: true });
|
||||
@@ -614,7 +622,9 @@ Register-ArgumentCompleter -CommandName openspec -ScriptBlock $openspecCompleter
|
||||
expect(profileContentAfter).not.toContain('# OPENSPEC:START');
|
||||
});
|
||||
|
||||
it('should return failure on permission error', async () => {
|
||||
// Skip on Windows: fs.chmod() on directories doesn't restrict write access on Windows
|
||||
// Windows uses ACLs which Node.js chmod doesn't control
|
||||
it.skipIf(process.platform === 'win32')('should return failure on permission error', async () => {
|
||||
delete process.env.OPENSPEC_NO_AUTO_CONFIG;
|
||||
await installer.install(mockCompletionScript);
|
||||
const targetPath = installer.getInstallationPath();
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
|
||||
import {
|
||||
getConfigPath,
|
||||
readConfig,
|
||||
writeConfig,
|
||||
getTelemetryConfig,
|
||||
updateTelemetryConfig,
|
||||
} from '../../src/telemetry/config.js';
|
||||
|
||||
describe('telemetry/config', () => {
|
||||
let tempDir: string;
|
||||
let originalHome: string | undefined;
|
||||
let originalUserProfile: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create temp directory for tests
|
||||
tempDir = path.join(os.tmpdir(), `openspec-telemetry-test-${Date.now()}`);
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
// Mock HOME/USERPROFILE to point to temp dir
|
||||
// On POSIX, os.homedir() uses HOME; on Windows it uses USERPROFILE
|
||||
originalHome = process.env.HOME;
|
||||
originalUserProfile = process.env.USERPROFILE;
|
||||
process.env.HOME = tempDir;
|
||||
process.env.USERPROFILE = tempDir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore HOME/USERPROFILE
|
||||
process.env.HOME = originalHome;
|
||||
process.env.USERPROFILE = originalUserProfile;
|
||||
|
||||
// Clean up temp directory
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('getConfigPath', () => {
|
||||
it('should return path to config.json in .config/openspec', () => {
|
||||
const result = getConfigPath();
|
||||
expect(result).toBe(path.join(tempDir, '.config', 'openspec', 'config.json'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('readConfig', () => {
|
||||
it('should return empty object when config file does not exist', async () => {
|
||||
const config = await readConfig();
|
||||
expect(config).toEqual({});
|
||||
});
|
||||
|
||||
it('should load valid config from file', async () => {
|
||||
const configDir = path.join(tempDir, '.config', 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({
|
||||
telemetry: { anonymousId: 'test-id', noticeSeen: true }
|
||||
}));
|
||||
|
||||
const config = await readConfig();
|
||||
expect(config.telemetry).toEqual({ anonymousId: 'test-id', noticeSeen: true });
|
||||
});
|
||||
|
||||
it('should return empty object for invalid JSON', async () => {
|
||||
const configDir = path.join(tempDir, '.config', 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, '{ invalid json }');
|
||||
|
||||
const config = await readConfig();
|
||||
expect(config).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeConfig', () => {
|
||||
it('should create directory if it does not exist', async () => {
|
||||
const configDir = path.join(tempDir, '.config', 'openspec');
|
||||
|
||||
await writeConfig({ telemetry: { noticeSeen: true } });
|
||||
|
||||
expect(fs.existsSync(configDir)).toBe(true);
|
||||
});
|
||||
|
||||
it('should write config to file', async () => {
|
||||
const configPath = path.join(tempDir, '.config', 'openspec', 'config.json');
|
||||
|
||||
await writeConfig({ telemetry: { anonymousId: 'test-123' } });
|
||||
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
expect(parsed.telemetry.anonymousId).toBe('test-123');
|
||||
});
|
||||
|
||||
it('should preserve existing fields when updating', async () => {
|
||||
const configDir = path.join(tempDir, '.config', 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
// Create initial config with other fields
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({
|
||||
existingField: 'preserved',
|
||||
telemetry: { anonymousId: 'old-id' }
|
||||
}));
|
||||
|
||||
// Update telemetry
|
||||
await writeConfig({ telemetry: { noticeSeen: true } });
|
||||
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
expect(parsed.existingField).toBe('preserved');
|
||||
expect(parsed.telemetry.noticeSeen).toBe(true);
|
||||
});
|
||||
|
||||
it('should deep merge telemetry fields', async () => {
|
||||
const configDir = path.join(tempDir, '.config', 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
// Create initial config
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({
|
||||
telemetry: { anonymousId: 'existing-id' }
|
||||
}));
|
||||
|
||||
// Update with noticeSeen only
|
||||
await writeConfig({ telemetry: { noticeSeen: true } });
|
||||
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
expect(parsed.telemetry.anonymousId).toBe('existing-id');
|
||||
expect(parsed.telemetry.noticeSeen).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTelemetryConfig', () => {
|
||||
it('should return empty object when no config exists', async () => {
|
||||
const config = await getTelemetryConfig();
|
||||
expect(config).toEqual({});
|
||||
});
|
||||
|
||||
it('should return telemetry section from config', async () => {
|
||||
const configDir = path.join(tempDir, '.config', 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({
|
||||
telemetry: { anonymousId: 'my-id', noticeSeen: false }
|
||||
}));
|
||||
|
||||
const config = await getTelemetryConfig();
|
||||
expect(config).toEqual({ anonymousId: 'my-id', noticeSeen: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateTelemetryConfig', () => {
|
||||
it('should create telemetry config when none exists', async () => {
|
||||
await updateTelemetryConfig({ anonymousId: 'new-id' });
|
||||
|
||||
const configPath = path.join(tempDir, '.config', 'openspec', 'config.json');
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
expect(parsed.telemetry.anonymousId).toBe('new-id');
|
||||
});
|
||||
|
||||
it('should merge with existing telemetry config', async () => {
|
||||
const configDir = path.join(tempDir, '.config', 'openspec');
|
||||
const configPath = path.join(configDir, 'config.json');
|
||||
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
fs.writeFileSync(configPath, JSON.stringify({
|
||||
telemetry: { anonymousId: 'existing-id' }
|
||||
}));
|
||||
|
||||
await updateTelemetryConfig({ noticeSeen: true });
|
||||
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const parsed = JSON.parse(content);
|
||||
expect(parsed.telemetry.anonymousId).toBe('existing-id');
|
||||
expect(parsed.telemetry.noticeSeen).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
// Mock posthog-node before importing the module
|
||||
vi.mock('posthog-node', () => {
|
||||
return {
|
||||
PostHog: vi.fn().mockImplementation(() => ({
|
||||
capture: vi.fn(),
|
||||
shutdown: vi.fn().mockResolvedValue(undefined),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
// Import after mocking
|
||||
import { isTelemetryEnabled, maybeShowTelemetryNotice, shutdown, trackCommand } from '../../src/telemetry/index.js';
|
||||
import { PostHog } from 'posthog-node';
|
||||
|
||||
describe('telemetry/index', () => {
|
||||
let tempDir: string;
|
||||
let originalEnv: NodeJS.ProcessEnv;
|
||||
let consoleLogSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create unique temp directory for each test using UUID
|
||||
tempDir = path.join(os.tmpdir(), `openspec-telemetry-test-${randomUUID()}`);
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
// Save original env
|
||||
originalEnv = { ...process.env };
|
||||
|
||||
// Mock HOME to point to temp dir
|
||||
process.env.HOME = tempDir;
|
||||
|
||||
// Clear all mocks
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Spy on console.log for notice tests
|
||||
consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original env
|
||||
process.env = originalEnv;
|
||||
|
||||
// Clean up temp directory
|
||||
try {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
|
||||
// Restore all mocks
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('isTelemetryEnabled', () => {
|
||||
it('should return false when OPENSPEC_TELEMETRY=0', () => {
|
||||
process.env.OPENSPEC_TELEMETRY = '0';
|
||||
expect(isTelemetryEnabled()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when DO_NOT_TRACK=1', () => {
|
||||
process.env.DO_NOT_TRACK = '1';
|
||||
expect(isTelemetryEnabled()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when CI=true', () => {
|
||||
process.env.CI = 'true';
|
||||
expect(isTelemetryEnabled()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true when no opt-out is set', () => {
|
||||
delete process.env.OPENSPEC_TELEMETRY;
|
||||
delete process.env.DO_NOT_TRACK;
|
||||
delete process.env.CI;
|
||||
expect(isTelemetryEnabled()).toBe(true);
|
||||
});
|
||||
|
||||
it('should prioritize OPENSPEC_TELEMETRY=0 over other settings', () => {
|
||||
process.env.OPENSPEC_TELEMETRY = '0';
|
||||
delete process.env.DO_NOT_TRACK;
|
||||
delete process.env.CI;
|
||||
expect(isTelemetryEnabled()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('maybeShowTelemetryNotice', () => {
|
||||
it('should not show notice when telemetry is disabled', async () => {
|
||||
process.env.OPENSPEC_TELEMETRY = '0';
|
||||
|
||||
await maybeShowTelemetryNotice();
|
||||
|
||||
expect(consoleLogSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('trackCommand', () => {
|
||||
it('should not track when telemetry is disabled', async () => {
|
||||
process.env.OPENSPEC_TELEMETRY = '0';
|
||||
|
||||
await trackCommand('test', '1.0.0');
|
||||
|
||||
expect(PostHog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should track when telemetry is enabled', async () => {
|
||||
delete process.env.OPENSPEC_TELEMETRY;
|
||||
delete process.env.DO_NOT_TRACK;
|
||||
delete process.env.CI;
|
||||
|
||||
await trackCommand('test', '1.0.0');
|
||||
|
||||
expect(PostHog).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('shutdown', () => {
|
||||
it('should not throw when no client exists', async () => {
|
||||
await expect(shutdown()).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
it('should handle shutdown errors silently', async () => {
|
||||
const mockPostHog = {
|
||||
capture: vi.fn(),
|
||||
shutdown: vi.fn().mockRejectedValue(new Error('Network error')),
|
||||
};
|
||||
(PostHog as any).mockImplementation(() => mockPostHog);
|
||||
|
||||
await expect(shutdown()).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -196,7 +196,9 @@ describe('FileSystemUtils', () => {
|
||||
expect(canWrite).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-existent file in read-only directory', async () => {
|
||||
// Skip on Windows: fs.chmod() on directories doesn't restrict write access on Windows
|
||||
// Windows uses ACLs which Node.js chmod doesn't control
|
||||
it.skipIf(process.platform === 'win32')('should return false for non-existent file in read-only directory', async () => {
|
||||
const readOnlyDir = path.join(testDir, 'readonly-dir');
|
||||
await fs.mkdir(readOnlyDir);
|
||||
await fs.chmod(readOnlyDir, 0o555); // Read-only + execute
|
||||
|
||||
Reference in New Issue
Block a user