specrails-core 3.5.3 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1565 @@
1
+ # Enrich: Agent Workflow System
2
+
3
+ Interactive wizard to configure the full agent workflow system for this repository. Analyzes the codebase, discovers target users, generates VPC personas, and creates all agents, commands, rules, and configuration adapted to this project. Supports config-driven mode for direct installation from a pre-built config file.
4
+
5
+ **Prerequisites:** Run `specrails/install.sh` first to install templates.
6
+
7
+ ### Hub Checkpoint Protocol
8
+
9
+ When running inside specrails-hub, emit checkpoint markers at key transitions so the hub `CheckpointTracker` can display progress. Each checkpoint is a single line printed to stdout:
10
+
11
+ ```
12
+ [checkpoint:phase_1_analysis] Codebase analysis complete
13
+ [checkpoint:phase_2_personas] VPC personas generated
14
+ [checkpoint:phase_3_commands] Commands and rules generated
15
+ [checkpoint:phase_4_agents] Agent files generated
16
+ [checkpoint:phase_5_cleanup] Cleanup and summary complete
17
+ ```
18
+
19
+ The hub parses these via `detectCheckpointFromText()` regex patterns. Always emit checkpoints at the end of each phase, even in `--from-config` and `--quick` modes.
20
+
21
+ ---
22
+
23
+ ## Mode Detection
24
+
25
+ Check `$ARGUMENTS` in this order:
26
+
27
+ 1. If `--update` is present → execute **Update Mode** (below), then stop.
28
+ 2. If `--from-config` is present → execute **From-Config Mode** (below), then stop.
29
+ 3. If `--quick` or `--lite` is present → execute **Quick Mode** (below), then stop.
30
+ 4. Otherwise (no flags) → skip directly to **Phase 1** and execute the full 5-phase wizard.
31
+
32
+ **Default is the full wizard.** Quick Mode only runs when `--quick` or `--lite` is explicitly passed.
33
+
34
+ ---
35
+
36
+ ## From-Config Mode
37
+
38
+ When `--from-config` is passed, execute a fully automated installation using `.specrails/install-config.yaml`. No interactive prompts — all decisions come from the config file.
39
+
40
+ ### FC1: Read and Validate Config
41
+
42
+ Read `.specrails/install-config.yaml`. If it does not exist, display:
43
+ > "`.specrails/install-config.yaml` not found. Run the TUI installer first (`npx specrails-core@latest init`) or use `/specrails:enrich` without `--from-config` for the interactive wizard."
44
+ Then stop.
45
+
46
+ Parse the YAML and extract:
47
+ - `config.version` — must be `1`; if not, warn and proceed
48
+ - `config.provider` — `claude` or `codex`; default `claude`
49
+ - `config.tier` — `full` or `quick`; default `full`
50
+ - `config.agents.selected` — list of agent names to install
51
+ - `config.agents.excluded` — list of agent names to skip (for reference only)
52
+ - `config.models.preset` — `balanced`, `budget`, or `max` (see Model Presets below)
53
+ - `config.models.defaults.model` — default model override (overrides preset)
54
+ - `config.models.overrides` — per-agent model overrides (highest priority)
55
+ - `config.quick_context.product_description` — product description seed
56
+ - `config.quick_context.target_users` — target users seed
57
+ - `config.agent_teams` — boolean; whether to install team-review/team-debug commands
58
+
59
+ Store all values in variables prefixed `FC_`.
60
+
61
+ **Model Presets** (applied when `config.models.defaults` is not set):
62
+ - `balanced` (default): sr-architect=opus, sr-product-manager=opus, all others=sonnet
63
+ - `budget`: all agents=haiku
64
+ - `max`: all agents=opus
65
+
66
+ To resolve the model for any given agent:
67
+ 1. Check `config.models.overrides.<agent-name>` — if present, use it
68
+ 2. Check `config.models.defaults.model` — if present, use it
69
+ 3. Apply preset defaults based on `config.models.preset`
70
+ 4. Fallback to model in template frontmatter
71
+
72
+ ### FC2: Provider Setup
73
+
74
+ Read `.specrails/setup-templates/.provider-detection.json` if present, to get `cli_provider` and `specrails_dir`. If `FC_provider` differs from the detected value, use `FC_provider` (config takes precedence).
75
+
76
+ Set `SPECRAILS_DIR` and `CLI_PROVIDER` from resolved provider.
77
+
78
+ ### FC3: If tier is `quick` — run Quick Mode with config context
79
+
80
+ If `FC_tier == "quick"`:
81
+ - Set `QS_PROJECT_DESCRIPTION = FC_quick_context.product_description`
82
+ - Set `QS_TARGET_USERS = FC_quick_context.target_users`
83
+ - Set `FC_AGENTS_SELECTED` as the list of agents to generate (instead of defaults)
84
+ - Execute Quick Mode (QS1–QS4) with these values injected, generating all `FC_AGENTS_SELECTED` agents (not just defaults)
85
+ - Then stop.
86
+
87
+ ### FC4: If tier is `full` — run automated full wizard
88
+
89
+ **Phase 1 (Silent):** Run the full Phase 1 analysis (1.1–1.4) without any user prompts. Store all detected values internally.
90
+
91
+ **Phase 2 (Seeded VPC Discovery):** Run VPC persona generation using `FC_quick_context` as seeds:
92
+ - Treat `FC_quick_context.product_description` as the answer to "Describe your product"
93
+ - Treat `FC_quick_context.target_users` as the answer to "Who are your users"
94
+ - Use AI to expand these seeds into full VPC personas (3 primary, 3 secondary)
95
+ - Do not ask the user any questions — infer all answers from seeds + codebase analysis
96
+
97
+ **Phase 3 (Silent):** Run Phase 3 normally without user prompts.
98
+
99
+ **Phase 4 (Config-Driven Agent Generation):**
100
+ - Generate only agents in `FC_AGENTS_SELECTED` (skip any not in the list)
101
+ - Apply model resolution (FC1 preset/override logic) to each agent's frontmatter
102
+ - Run all Phase 4 sub-phases (4.1, 4.2, 4.3, 4.4) normally but without interactive prompts
103
+ - If `FC_agent_teams == true`, also install team-review and team-debug commands
104
+
105
+ **Phase 5 (Normal):** Run Phase 5 cleanup normally.
106
+
107
+ ### FC5: Completion
108
+
109
+ Display:
110
+ ```
111
+ ✅ Enrich complete (from-config).
112
+
113
+ Agents generated: <count> of <total selected>
114
+ Models applied:
115
+ sr-architect: <resolved-model>
116
+ sr-developer: <resolved-model>
117
+ [... one line per generated agent ...]
118
+
119
+ Next steps:
120
+ > /specrails:implement <feature>
121
+ ```
122
+
123
+ ---
124
+
125
+ ## Update Mode
126
+
127
+ When `--update` is passed, execute this streamlined flow instead of the full wizard. Do not run any phases from the full wizard. When Phase U7 is complete, stop.
128
+
129
+ ### Phase U1: Read Update Context
130
+
131
+ Read the following files to understand the current installation state:
132
+
133
+ 1. Read `.specrails/specrails-manifest.json` — contains agent template checksums from the last install/update. Structure:
134
+ ```json
135
+ {
136
+ "version": "0.2.0",
137
+ "installed_at": "2025-01-15T10:00:00Z",
138
+ "artifacts": {
139
+ "templates/agents/architect.md": "sha256:<checksum>",
140
+ "templates/agents/developer.md": "sha256:<checksum>",
141
+ "templates/agents/reviewer.md": "sha256:<checksum>"
142
+ }
143
+ }
144
+ ```
145
+ If this file does not exist, inform the user:
146
+ > "No `.specrails/specrails-manifest.json` found. This looks like a pre-versioning installation. Run `update.sh` first to initialize the manifest, then re-run `/specrails:enrich --update`."
147
+ Then stop.
148
+
149
+ 2. Read `.specrails/specrails-version` — contains the current version string (e.g., `0.2.0`). If it does not exist, treat version as `0.1.0 (legacy)`.
150
+
151
+ 3. Determine `$SPECRAILS_DIR` by reading `.specrails/setup-templates/.provider-detection.json`. Extract `cli_provider` and `specrails_dir`. If not found, default to `cli_provider = "claude"`, `specrails_dir = ".claude"`.
152
+
153
+ 4. List all template files in `.specrails/setup-templates/agents/` — these are the NEW agent templates from the update:
154
+ ```bash
155
+ ls .specrails/setup-templates/agents/
156
+ ```
157
+ Template files are named with `sr-` prefix (e.g., `sr-architect.md`, `sr-developer.md`).
158
+
159
+ 5. List all template files in `.specrails/setup-templates/commands/specrails/` — these are the NEW command templates from the update:
160
+ ```bash
161
+ ls .specrails/setup-templates/commands/specrails/
162
+ ```
163
+ Command template files include `implement.md`, `batch-implement.md`, `compat-check.md`, `refactor-recommender.md`, `why.md`, `get-backlog-specs.md`, `auto-propose-backlog-specs.md`.
164
+ If this directory does not exist, skip command template checking for this update.
165
+
166
+ 6. Read `.specrails/backlog-config.json` if it exists — contains stored provider configuration needed for command placeholder substitution.
167
+
168
+ ### Phase U2: Quick Codebase Re-Analysis
169
+
170
+ Perform the same analysis as Phase 1 of the full setup wizard, but silently — do not prompt the user and do not show the findings table. Just execute and store results internally.
171
+
172
+ Detect:
173
+ - **Languages**: Check for `*.py`, `*.ts`, `*.tsx`, `*.go`, `*.rs`, `*.java`, `*.kt`, `*.rb`, `*.cs`
174
+ - **Frameworks**: Search for imports (`fastapi`, `express`, `react`, `vue`, `angular`, `django`, `spring`, `gin`, `actix`, `rails`)
175
+ - **Directory structure**: Identify backend/frontend/core/test directories
176
+ - **Database**: Check for SQL files, ORM configs, migration directories
177
+ - **CI/CD**: Parse `.github/workflows/*.yml` for lint/test/build commands
178
+ - **Naming conventions**: Read 2-3 source files per detected layer
179
+
180
+ Read:
181
+ - `README.md` (if exists)
182
+ - `package.json` / `pyproject.toml` / `Cargo.toml` / `go.mod` / `pom.xml` (detect stack)
183
+ - `.github/workflows/*.yml` (detect CI commands)
184
+
185
+ Store all results for use in Phases U4 and U5.
186
+
187
+ ### Phase U3: Identify What Needs Regeneration
188
+
189
+ **Agent templates:** For each agent template, find its entry in the manifest's `artifacts` map (keyed as `templates/agents/sr-<name>.md`). Compute the SHA-256 checksum of the corresponding file in `.specrails/setup-templates/agents/`:
190
+
191
+ ```bash
192
+ sha256sum .specrails/setup-templates/agents/sr-<name>.md
193
+ ```
194
+
195
+ Build three lists for agents:
196
+
197
+ 1. **Changed agents**: agent name exists in manifest AND the current template checksum differs from the manifest checksum → mark for regeneration
198
+ 2. **New agents**: template file exists in `.specrails/setup-templates/agents/` but the agent name is NOT in the manifest → mark for evaluation
199
+ 3. **Unchanged agents**: agent name exists in manifest AND checksum matches → skip
200
+
201
+ **Command templates:** If `.specrails/setup-templates/commands/specrails/` exists, for each command template file, find its entry in the manifest's `artifacts` map (keyed as `templates/commands/specrails/<name>.md`). Compute the SHA-256 checksum of the corresponding file in `.specrails/setup-templates/commands/specrails/`:
202
+
203
+ ```bash
204
+ sha256sum .specrails/setup-templates/commands/specrails/<name>.md
205
+ ```
206
+
207
+ Build three lists for commands:
208
+
209
+ 1. **Changed commands**: command name exists in manifest AND the current template checksum differs from the manifest checksum → mark for update
210
+ 2. **New commands**: template file exists in `.specrails/setup-templates/commands/specrails/` but the command name is NOT in the manifest → mark for evaluation
211
+ 3. **Unchanged commands**: command name exists in manifest AND checksum matches → skip
212
+
213
+ Display the combined analysis to the user:
214
+
215
+ ```
216
+ ## Update Analysis
217
+
218
+ ### Agents — Changed Templates (will be regenerated)
219
+ - sr-architect.md (template modified)
220
+ - sr-developer.md (template modified)
221
+
222
+ ### Agents — New Templates Available
223
+ - sr-frontend-developer.md
224
+ - sr-backend-developer.md
225
+
226
+ ### Agents — Unchanged (keeping current)
227
+ - sr-reviewer.md
228
+ - sr-product-manager.md
229
+
230
+ ### Commands — Changed Templates (will be updated)
231
+ - implement.md (template modified)
232
+
233
+ ### Commands — New Templates Available
234
+ - refactor-recommender.md
235
+
236
+ ### Commands — Unchanged (keeping current)
237
+ - compat-check.md
238
+ - why.md
239
+ ```
240
+
241
+ If there are no changed agents, no new agents, no changed commands, and no new commands, display:
242
+ ```
243
+ All agents and commands are already up to date. Nothing to regenerate.
244
+ ```
245
+ Then jump to Phase U7.
246
+
247
+ ### Phase U4: Regenerate Changed Agents
248
+
249
+ For each agent in the "changed" list:
250
+
251
+ 1. Read the NEW template from `.specrails/setup-templates/agents/sr-<name>.md`
252
+ 2. Use the codebase analysis from Phase U2 to fill in all `{{PLACEHOLDER}}` values, using the same substitution rules as Phase 4.1 of the full setup:
253
+ - `{{PROJECT_NAME}}` → project name (from README.md or directory name)
254
+ - `{{ARCHITECTURE_DIAGRAM}}` → detected architecture layers
255
+ - `{{LAYER_TAGS}}` → detected layer tags (e.g., `[backend]`, `[frontend]`, `[api]`)
256
+ - `{{CI_COMMANDS_BACKEND}}` → backend CI commands
257
+ - `{{CI_COMMANDS_FRONTEND}}` → frontend CI commands
258
+ - `{{LAYER_CONVENTIONS}}` → detected conventions per layer
259
+ - `{{PERSONA_NAMES}}` → read existing persona names from `$SPECRAILS_DIR/agents/personas/` filenames
260
+ - `{{PERSONA_FILES}}` → paths to existing persona files in `$SPECRAILS_DIR/agents/personas/`
261
+ - `{{DOMAIN_EXPERTISE}}` → infer from detected stack and README
262
+ - `{{KEY_FILE_PATHS}}` → important file paths detected in Phase U2
263
+ - `{{WARNINGS}}` → read from existing `CLAUDE.md` if present
264
+ - `{{MEMORY_PATH}}` → `$SPECRAILS_DIR/agent-memory/sr-<agent-name>/`
265
+ 3. Write the adapted agent using the format for the active provider (same dual-format rules as Phase 4.1):
266
+ - `cli_provider == "claude"`: write to `$SPECRAILS_DIR/agents/sr-<name>.md` (Markdown with YAML frontmatter)
267
+ - `cli_provider == "codex"`: write to `$SPECRAILS_DIR/agents/sr-<name>.toml` (TOML format with `name`, `description`, `model`, `prompt` fields)
268
+ 4. Show: `✓ Regenerated sr-<name>`
269
+
270
+ After regenerating all changed agents, verify no unresolved placeholders remain:
271
+ ```bash
272
+ # Claude Code
273
+ grep -r '{{[A-Z_]*}}' .claude/agents/sr-*.md 2>/dev/null || echo "OK: no broken placeholders"
274
+ # Codex
275
+ grep -r '{{[A-Z_]*}}' .codex/agents/sr-*.toml 2>/dev/null || echo "OK: no broken placeholders"
276
+ ```
277
+
278
+ ### Phase U4b: Update Changed Commands
279
+
280
+ For each command in the "changed commands" list from Phase U3:
281
+
282
+ 1. Read the NEW template:
283
+ - If `cli_provider == "claude"`: from `.specrails/setup-templates/commands/specrails/<name>.md`
284
+ - If `cli_provider == "codex"`: from `.specrails/setup-templates/skills/sr-<name>/SKILL.md`
285
+ 2. Read stored backlog configuration from `.specrails/backlog-config.json` (if it exists) to resolve provider-specific placeholders:
286
+ - `BACKLOG_PROVIDER` → `provider` field (`github`, `jira`, or `none`)
287
+ - `BACKLOG_WRITE` → `write_access` field
288
+ - `JIRA_BASE_URL` → `jira_base_url` field
289
+ - `JIRA_PROJECT_KEY` → `jira_project_key` field
290
+ 3. Substitute all `{{PLACEHOLDER}}` values using the same rules as Phase 4.3 of the full setup:
291
+ - `{{CI_COMMANDS_BACKEND}}` → backend CI commands detected in Phase U2
292
+ - `{{CI_COMMANDS_FRONTEND}}` → frontend CI commands detected in Phase U2
293
+ - `{{DEPENDENCY_CHECK_COMMANDS}}` → stack-specific dependency check commands from Phase U2
294
+ - `{{TEST_RUNNER_CHECK}}` → test runner commands from Phase U2
295
+ - `{{BACKLOG_FETCH_CMD}}` → provider-specific fetch command from backlog config
296
+ - `{{BACKLOG_CREATE_CMD}}` → provider-specific create command from backlog config
297
+ - `{{BACKLOG_VIEW_CMD}}` → provider-specific view command from backlog config
298
+ - `{{BACKLOG_PREFLIGHT}}` → provider-specific preflight check from backlog config
299
+ - Any other `{{PLACEHOLDER}}` values → use Phase U2 analysis data
300
+ 4. Write the updated file:
301
+ - If `cli_provider == "claude"`: to `.claude/commands/specrails/<name>.md`
302
+ - If `cli_provider == "codex"`: to `.agents/skills/sr-<name>/SKILL.md`
303
+ 5. Show:
304
+ - If `cli_provider == "claude"`: `✓ Updated /specrails:<name>`
305
+ - If `cli_provider == "codex"`: `✓ Updated $sr-<name>`
306
+
307
+ After updating all changed commands/skills, verify no unresolved placeholders remain:
308
+ ```bash
309
+ # If cli_provider == "claude":
310
+ grep -l '{{[A-Z_]*}}' .claude/commands/specrails/*.md 2>/dev/null || echo "OK: no broken placeholders"
311
+ # If cli_provider == "codex":
312
+ grep -rl '{{[A-Z_]*}}' .agents/skills/sr-*/SKILL.md 2>/dev/null || echo "OK: no broken placeholders"
313
+ ```
314
+ If any placeholders remain unresolved, warn the user:
315
+ > "⚠ Some placeholders in `<filename>` could not be resolved automatically. Please review the file and fill them in manually."
316
+
317
+ ### Phase U5: Evaluate New Agents
318
+
319
+ For each agent in the "new" list:
320
+
321
+ 1. Read the template from `.specrails/setup-templates/agents/sr-<name>.md` to understand what stack or layer it targets (read its description and any layer-specific comments)
322
+ 2. Match against the codebase detected in Phase U2:
323
+ - If the template targets a layer/stack that IS present (e.g., `sr-frontend-developer` and React was detected), prompt:
324
+ > "New agent available: `sr-<name>` — your project uses [detected tech]. Add it? [Y/n]"
325
+ - If the template targets a layer/stack that is NOT present (e.g., `sr-backend-developer` and no backend was detected), prompt:
326
+ > "New agent available: `sr-<name>` — no [layer] detected in your project. Skip? [Y/n]"
327
+ 3. If the user accepts (or presses Enter on a pre-selected default):
328
+ - Generate the agent using the same template adaptation as Phase U4
329
+ - Create memory directory if it does not exist: `$SPECRAILS_DIR/agent-memory/sr-<name>/`
330
+ - Show: `✓ Added sr-<name>`
331
+ 4. If the user declines:
332
+ - Show: `→ Skipped sr-<name>`
333
+
334
+ For each command in the "new commands" list from Phase U3:
335
+
336
+ 1. Read the template:
337
+ - If `cli_provider == "claude"`: from `.specrails/setup-templates/commands/specrails/<name>.md`
338
+ - If `cli_provider == "codex"`: from `.specrails/setup-templates/skills/sr-<name>/SKILL.md`
339
+ 2. Prompt the user:
340
+ - If `cli_provider == "claude"`: `"New command available: /specrails:<name> — [one-line description]. Install it? [Y/n]"`
341
+ - If `cli_provider == "codex"`: `"New skill available: $sr-<name> — [one-line description]. Install it? [Y/n]"`
342
+ 3. If the user accepts (or presses Enter):
343
+ - Apply placeholder substitution using the same rules as Phase U4b (backlog config + codebase analysis)
344
+ - If `cli_provider == "claude"`: write to `.claude/commands/specrails/<name>.md` — show `✓ Added /specrails:<name>`
345
+ - If `cli_provider == "codex"`: write to `.agents/skills/sr-<name>/SKILL.md` — show `✓ Added $sr-<name>`
346
+ 4. If the user declines:
347
+ - If `cli_provider == "claude"`: show `→ Skipped /specrails:<name>`
348
+ - If `cli_provider == "codex"`: show `→ Skipped $sr-<name>`
349
+
350
+ ### Phase U6: Update Workflow Commands
351
+
352
+ If any new agents were added in Phase U5:
353
+
354
+ 1. Read the implement command/skill:
355
+ - If `cli_provider == "claude"`: `.claude/commands/specrails/implement.md`
356
+ - If `cli_provider == "codex"`: `.agents/skills/sr-implement/SKILL.md`
357
+ 2. Check if the file references agent names in its orchestration steps (look for `sr-architect`, `sr-developer`, `sr-reviewer` etc.)
358
+ 3. If newly added agents belong in the implementation pipeline (i.e., they are layer-specific developers such as `sr-frontend-developer` or `sr-backend-developer`), add them to the appropriate step in the implement command — specifically where parallel developer agents are launched
359
+ 4. Write the updated file if any changes were made:
360
+ - If `cli_provider == "claude"`: `.claude/commands/specrails/implement.md`
361
+ - If `cli_provider == "codex"`: `.agents/skills/sr-implement/SKILL.md`
362
+ 5. Show which commands were updated, or "No command updates needed" if nothing changed
363
+
364
+ This is a lightweight check — only update commands where the sr- agent clearly belongs. Do not restructure the entire command.
365
+
366
+ ### Phase U7: Summary
367
+
368
+ Display the final summary and stop. Do not continue to Phase 1 of the full setup wizard.
369
+
370
+ ```
371
+ ## Update Complete
372
+
373
+ specrails updated from v<previous> to v<new>.
374
+
375
+ | Action | Count |
376
+ |---------------------|-------|
377
+ | Agents regenerated | N |
378
+ | Agents added | N |
379
+ | Agents skipped | N |
380
+ | Commands updated | N |
381
+ | Commands added | N |
382
+ | Commands skipped | N |
383
+
384
+ All agents and commands are now up to date.
385
+
386
+ ### Agents Regenerated
387
+ [list agent names, or "(none)"]
388
+
389
+ ### Agents Added
390
+ [list agent names, or "(none)"]
391
+
392
+ ### Agents Skipped
393
+ [list agent names, or "(none)"]
394
+
395
+ ### Commands Updated
396
+ [list command names, or "(none)"]
397
+
398
+ ### Commands Added
399
+ [list command names, or "(none)"]
400
+
401
+ ### Commands Skipped
402
+ [list command names, or "(none)"]
403
+ ```
404
+
405
+ Update `.specrails/specrails-manifest.json` to reflect the new checksums for all regenerated/updated and added agents and commands:
406
+ - For each regenerated agent: update its checksum entry to the new template's checksum (keyed as `templates/agents/sr-<name>.md`)
407
+ - For each added agent: add a new entry with its checksum
408
+ - For each updated command: update its checksum entry to the new template's checksum (keyed as `templates/commands/specrails/<name>.md`)
409
+ - For each added command: add a new entry with its checksum
410
+ - Update the `version` field to the version read from `.specrails/specrails-version`
411
+
412
+ ---
413
+
414
+ ## Quick Mode
415
+
416
+ When `--quick` or `--lite` is passed, run this streamlined 3-question setup. Do NOT run Phase 1–5. When QS4 is complete, stop.
417
+
418
+ ### QS1: Ask the 3 questions
419
+
420
+ Display the following prompt EXACTLY ONCE and then wait for the user's responses. Do NOT repeat the questions — output them a single time only.
421
+
422
+ Welcome to specrails! Let's get your AI agent team set up in 3 quick questions.
423
+
424
+ 1. What is this project? (one sentence)
425
+ 2. Who are the target users?
426
+ 3. Git access for agents — read-only or read-write?
427
+ (read-only = agents can read and suggest; read-write = agents can commit)
428
+
429
+ Store the answers as:
430
+ - `QS_PROJECT_DESCRIPTION` — answer to question 1
431
+ - `QS_TARGET_USERS` — answer to question 2
432
+ - `QS_GIT_ACCESS` — "read-only" or "read-write" (normalize if user types "ro", "rw", "readonly", etc.)
433
+
434
+ ### QS2: Apply opinionated defaults
435
+
436
+ Use these defaults for all configuration not asked in QS1:
437
+
438
+ | Setting | Quick Mode Default |
439
+ |---------|------------------|
440
+ | Agents enabled | sr-architect, sr-developer, sr-reviewer, sr-product-manager |
441
+ | Git mode | Derived from QS_GIT_ACCESS |
442
+ | CLAUDE.md template | `templates/CLAUDE-quickstart.md` |
443
+ | OpenSpec enabled | Yes if `openspec` CLI is detected in PATH, No otherwise |
444
+ | Telemetry | Not configured (deferred to PRD-002) |
445
+ | Backlog provider | local (lightweight JSON-based, no external tools needed) |
446
+
447
+ Detect whether this is an existing codebase or new project:
448
+ - **Existing codebase**: `package.json`, `Gemfile`, `pyproject.toml`, `go.mod`, or `pom.xml` found in the repo root
449
+ - **New project**: none of the above found
450
+
451
+ Store as `QS_IS_EXISTING_CODEBASE=true/false`.
452
+
453
+ ### QS2.5: Re-run Detection
454
+
455
+ Before generating files, check if this is a re-run:
456
+
457
+ 1. Check if commands/skills already exist:
458
+ - If `cli_provider == "claude"`: check if `.claude/commands/specrails/` directory exists with any `.md` files:
459
+ ```bash
460
+ ls .claude/commands/specrails/*.md 2>/dev/null
461
+ ```
462
+ - If `cli_provider == "codex"`: check if `.agents/skills/sr-*/SKILL.md` files exist:
463
+ ```bash
464
+ ls .agents/skills/sr-*/SKILL.md 2>/dev/null
465
+ ```
466
+ 2. If files are found → this is a **re-run**. Store `QS_IS_RERUN=true`.
467
+ 3. If the directory does not exist or is empty → this is a **fresh install**. Store `QS_IS_RERUN=false`.
468
+
469
+ In re-run mode, QS3 executes in **gap-fill mode** for command/skill files:
470
+ - For each command in the list, check if it already exists:
471
+ - If `cli_provider == "claude"`: at `.claude/commands/specrails/<name>.md`
472
+ - If `cli_provider == "codex"`: at `.agents/skills/sr-<name>/SKILL.md`
473
+ - If it exists: skip it and show:
474
+ - Claude: `✓ Already installed: /specrails:<name>`
475
+ - Codex: `✓ Already installed: $sr-<name>`
476
+ - If it does NOT exist: install it and show:
477
+ - Claude: `✓ Added /specrails:<name> (was missing)`
478
+ - Codex: `✓ Added $sr-<name> (was missing)`
479
+ - Do NOT prompt the user for confirmation on missing files — install them automatically
480
+
481
+ For CLAUDE.md/AGENTS.md and agent files, the existing per-file prompts already handle re-runs (user is asked before overwriting). No change needed there.
482
+
483
+ ### QS3: Generate files
484
+
485
+ Generate files using the Quick Mode defaults.
486
+
487
+ **1. CLAUDE.md**
488
+
489
+ Read `.specrails/setup-templates/claude-md/CLAUDE-quickstart.md` (or fall back to `.specrails/setup-templates/claude-md/default.md` if quickstart template is not found).
490
+
491
+ Replace placeholders:
492
+ - `{{PROJECT_NAME}}` → derive from directory name or README.md first heading
493
+ - `{{PROJECT_DESCRIPTION}}` → `QS_PROJECT_DESCRIPTION`
494
+ - `{{TARGET_USERS}}` → `QS_TARGET_USERS`
495
+ - `{{GIT_ACCESS}}` → `QS_GIT_ACCESS`
496
+
497
+ Write to `CLAUDE.md` in the repo root. If `CLAUDE.md` already exists, ask:
498
+ > "CLAUDE.md already exists. Overwrite? [Y/n]"
499
+ Skip if user says no.
500
+
501
+ **2. Agent files**
502
+
503
+ For each default agent (sr-architect, sr-developer, sr-reviewer, sr-product-manager), read the template from `.specrails/setup-templates/agents/<name>.md` and generate the adapted agent file using the dual-format rules from Phase 4.1:
504
+ - `cli_provider == "claude"`: write to `.claude/agents/<name>.md` (Markdown with frontmatter)
505
+ - `cli_provider == "codex"`: write to `.codex/agents/<name>.toml` (TOML format)
506
+
507
+ Fill placeholders with best-effort values from the limited context available:
508
+ - `{{PROJECT_NAME}}` → directory name or README first heading
509
+ - `{{PROJECT_DESCRIPTION}}` → `QS_PROJECT_DESCRIPTION`
510
+ - `{{TARGET_USERS}}` → `QS_TARGET_USERS`
511
+ - `{{GIT_ACCESS}}` → `QS_GIT_ACCESS`
512
+ - `{{ARCHITECTURE_DIAGRAM}}` → "(Quick Mode — run `/specrails:enrich` for full architecture analysis)"
513
+ - `{{TECH_EXPERTISE}}` → "(Quick Mode — run `/specrails:enrich` for codebase-specific expertise)"
514
+ - `{{LAYER_TAGS}}` → detect from package.json / Gemfile / go.mod if present; otherwise leave empty
515
+ - All other placeholders → "(not configured — run `/specrails:enrich`)"
516
+
517
+ Create memory directories: `$SPECRAILS_DIR/agent-memory/sr-<name>/`
518
+
519
+ **3. Command files**
520
+
521
+ Core commands (always install if missing):
522
+ - `implement.md`
523
+ - `batch-implement.md`
524
+ - `propose-spec.md`
525
+ - `compat-check.md`
526
+ - `why.md`
527
+ - `get-backlog-specs.md`
528
+ - `auto-propose-backlog-specs.md`
529
+
530
+ **Initialize local ticket storage** (backlog provider defaults to `local`):
531
+ 1. Copy `templates/local-tickets-schema.json` to `.specrails/local-tickets.json` and set `last_updated` to the current ISO-8601 timestamp. Skip if the file already exists.
532
+ 2. Write `.specrails/backlog-config.json` (skip if already exists):
533
+ ```json
534
+ {
535
+ "provider": "local",
536
+ "write_access": true,
537
+ "git_auto": true
538
+ }
539
+ ```
540
+
541
+ **If `cli_provider == "claude"`:**
542
+
543
+ If `QS_IS_RERUN=false` (fresh install): for each core command, read the template from `.specrails/setup-templates/commands/specrails/<name>.md`, substitute the backlog placeholders with local values (using the same table as Phase 4.3 "Local Tickets"), stub all persona placeholders with `(Quick Mode — run /specrails:enrich to configure personas)`, then write to `.claude/commands/specrails/<name>.md`.
544
+
545
+ If `QS_IS_RERUN=true` (gap-fill mode): for each command in the list above, check if `.claude/commands/specrails/<name>.md` already exists:
546
+ - If it exists: skip it — show `✓ Already installed: /specrails:<name>`
547
+ - If it does NOT exist: read template, substitute placeholders as above, write to `.claude/commands/specrails/<name>.md` — show `✓ Added /specrails:<name> (was missing)`
548
+
549
+ **If `cli_provider == "codex"`:**
550
+
551
+ If `QS_IS_RERUN=false` (fresh install): for each core command, read the corresponding skill template from `.specrails/setup-templates/skills/sr-<name>/SKILL.md`, substitute the backlog placeholders with local values and stub persona placeholders with `(Quick Mode — run /specrails:enrich to configure personas)`, then write to `.agents/skills/sr-<name>/SKILL.md` (create the directory first).
552
+
553
+ If `QS_IS_RERUN=true` (gap-fill mode): for each command in the list above, check if `.agents/skills/sr-<name>/SKILL.md` already exists:
554
+ - If it exists: skip it — show `✓ Already installed: $sr-<name>`
555
+ - If it does NOT exist: read template, substitute placeholders as above, write to `.agents/skills/sr-<name>/SKILL.md` — show `✓ Added $sr-<name> (was missing)`
556
+
557
+ **4. Cleanup**
558
+
559
+ Remove `.specrails/setup-templates/` (same as full wizard cleanup in Phase 5).
560
+
561
+ Remove `commands/enrich.md` from `.claude/commands/` if it was copied there by the installer.
562
+
563
+ ### QS4: First Task Prompt
564
+
565
+ After generating all files, display the setup complete message.
566
+
567
+ Then, based on `QS_IS_EXISTING_CODEBASE`:
568
+ - **Existing codebase** (`true`): recommend `/specrails:refactor-recommender`
569
+ - **New project** (`false`): recommend `/specrails:get-backlog-specs`
570
+
571
+ If `QS_IS_RERUN=false`, display:
572
+ ```
573
+ ✅ Setup complete.
574
+
575
+ Try your first command:
576
+ > /specrails:get-backlog-specs
577
+ ```
578
+ (Replace `/specrails:get-backlog-specs` with `/specrails:refactor-recommender` for existing codebases.)
579
+
580
+ If `QS_IS_RERUN=true`, display the gap-fill summary and stop:
581
+ ```
582
+ ✅ Re-run complete.
583
+
584
+ Commands status:
585
+ ✓ Already installed: /specrails:<name>
586
+ ✓ Added /specrails:<name> (was missing)
587
+ [... one line per command ...]
588
+
589
+ All commands are up to date.
590
+ ```
591
+ If all commands were already present, display:
592
+ ```
593
+ ✅ Re-run complete. All commands already installed — nothing to add.
594
+ ```
595
+
596
+ Then stop. Do not execute Phase 1.
597
+
598
+ ---
599
+
600
+ ## Phase 1: Codebase Analysis
601
+
602
+ Analyze the repository to understand its architecture, stack, and conventions.
603
+
604
+ ### 1.1 Read project structure
605
+
606
+ ```bash
607
+ # Get the repo root and basic info
608
+ git rev-parse --show-toplevel
609
+ ls -la
610
+ ```
611
+
612
+ Read the following to understand the project:
613
+ - `README.md` (if exists)
614
+ - `CLAUDE.md` (if exists — don't overwrite, merge later)
615
+ - `package.json` or `pyproject.toml` or `Cargo.toml` or `go.mod` or `pom.xml` (detect stack)
616
+ - `.github/workflows/*.yml` (detect CI commands)
617
+ - `docker-compose.yml` or `Dockerfile` (detect infra)
618
+
619
+ ### 1.2 Detect architecture layers
620
+
621
+ Use Glob and Grep to identify:
622
+
623
+ 1. **Languages**: Check for `*.py`, `*.ts`, `*.tsx`, `*.go`, `*.rs`, `*.java`, `*.kt`, `*.rb`, `*.cs`
624
+ 2. **Frameworks**: Search for imports (`fastapi`, `express`, `react`, `vue`, `angular`, `django`, `spring`, `gin`, `actix`, `rails`)
625
+ 3. **Directory structure**: Identify backend/frontend/core/test directories
626
+ 4. **Database**: Check for SQL files, ORM configs, migration directories
627
+ 5. **CI/CD**: Parse workflow files for lint/test/build commands
628
+
629
+ ### 1.3 Infer conventions
630
+
631
+ Read 3-5 representative source files from each detected layer to understand:
632
+ - Naming conventions (camelCase, snake_case, PascalCase)
633
+ - Import patterns
634
+ - Error handling patterns
635
+ - Testing patterns (framework, structure, mocking approach)
636
+ - API patterns (REST, GraphQL, tRPC)
637
+
638
+ ### 1.4 Present findings
639
+
640
+ Display the detected architecture to the user:
641
+
642
+ ```
643
+ ## Codebase Analysis
644
+
645
+ | Layer | Tech | Path |
646
+ |-------------|---------------------|---------------|
647
+ | Backend | FastAPI (Python) | backend/ |
648
+ | Frontend | React + TypeScript | frontend/ |
649
+ | Core | Python package | src/ |
650
+ | Tests | pytest | tests/ |
651
+ | Database | PostgreSQL | migrations/ |
652
+
653
+ ### CI Commands Detected
654
+ - Lint: `ruff check .`
655
+ - Format: `ruff format --check .`
656
+ - Test: `pytest tests/ -q`
657
+ - Frontend lint: `npm run lint`
658
+ - Frontend build: `npx tsc --noEmit`
659
+
660
+ ### Conventions Detected
661
+ - Python: snake_case, type hints, Pydantic models
662
+ - TypeScript: strict mode, functional components
663
+ - Testing: pytest fixtures with scope="function"
664
+
665
+ ### OSS Project Detection
666
+
667
+ Read `.specrails/setup-templates/.oss-detection.json` if it exists.
668
+
669
+ | Signal | Status |
670
+ |--------|--------|
671
+ | Public repository | [Yes / No / Unknown] |
672
+ | CI workflows (.github/workflows/) | [Yes / No] |
673
+ | CONTRIBUTING.md | [Yes / No] |
674
+ | **Result** | **OSS detected / Not detected / Could not check** |
675
+
676
+ If `is_oss: false` but at least one signal is `true`:
677
+ > "Some OSS signals were found but not all three. Is this an open-source project? (yes/no)"
678
+
679
+ If `.oss-detection.json` does not exist:
680
+ > "Is this an open-source project? (yes/no)"
681
+
682
+ When `IS_OSS=false` and no signals are present, skip OSS output entirely to avoid cluttering the display for non-OSS projects.
683
+
684
+ Store the final OSS determination as `IS_OSS` for use throughout the rest of setup.
685
+
686
+ [Confirm] [Modify] [Rescan]
687
+ ```
688
+
689
+ Wait for user confirmation. If they want to modify, ask what to change.
690
+
691
+ ---
692
+
693
+ ## Phase 2: User Personas & Product Discovery
694
+
695
+ ### 2.1 Ask about target users
696
+
697
+ Ask the user:
698
+
699
+ > If IS_OSS=true, prepend:
700
+ > "This is an OSS project. The **Maintainer** persona (Kai) is automatically included —
701
+ > you do not need to add 'open-source maintainers' to your list.
702
+ > Describe your other target user types below."
703
+
704
+ > **Who are the target users of your software?**
705
+ >
706
+ > Describe them in natural language. Examples:
707
+ > - "Developers who manage Kubernetes clusters"
708
+ > - "Small business owners tracking inventory and sales"
709
+ > - "Gamers who collect and trade digital items"
710
+ >
711
+ > I'll research the competitive landscape and create detailed personas
712
+ > with Value Proposition Canvas profiles for each user type.
713
+ >
714
+ > **How many distinct user types do you have?** (typically 2-3)
715
+
716
+ Wait for the user's response.
717
+
718
+ ### 2.2 Research competitive landscape
719
+
720
+ For each user type described, use WebSearch to research:
721
+
722
+ 1. **Existing tools** they use today (competitors)
723
+ 2. **Common pain points** reported in forums, Reddit, product reviews
724
+ 3. **Feature gaps** in current tools
725
+ 4. **Unmet needs** and workflow frustrations
726
+
727
+ Search queries to use (adapt to the domain):
728
+ - `"[domain] [user type] best tools 2025"`
729
+ - `"[domain] [user type] pain points frustrations"`
730
+ - `"[competitor name] missing features complaints"`
731
+ - `"[domain] management app feature comparison"`
732
+ - `site:reddit.com "[domain] [user type] what tool do you use"`
733
+
734
+ ### 2.3 Generate VPC personas
735
+
736
+ For each user type, generate a full Value Proposition Canvas persona file following the template at `.specrails/setup-templates/personas/persona.md`.
737
+
738
+ Each persona must include:
739
+ - **Profile**: Demographics, behaviors, tools used, spending patterns
740
+ - **Customer Jobs**: Functional, social, emotional (6-8 jobs)
741
+ - **Pains**: Graded by severity (Critical > High > Medium > Low) with 6-8 entries
742
+ - **Gains**: Graded by impact (High > Medium > Low) with 6-8 entries
743
+ - **Key Insight**: The #1 unmet need that this project can address
744
+ - **Sources**: Links to competitive analysis, forums, reviews used in research
745
+
746
+ ### 2.4 Present personas
747
+
748
+ Display each generated persona to the user:
749
+
750
+ ```
751
+ ## Generated Personas
752
+
753
+ ### Persona 1: "[Nickname]" — The [Role]
754
+ - Age: X-Y
755
+ - Key pain: [Critical pain]
756
+ - Key insight: [Main unmet need]
757
+
758
+ ### Persona 2: "[Nickname]" — The [Role]
759
+ - Age: X-Y
760
+ - Key pain: [Critical pain]
761
+ - Key insight: [Main unmet need]
762
+
763
+ [Accept] [Edit] [Regenerate]
764
+ ```
765
+
766
+ Wait for confirmation. If the user wants edits, apply them.
767
+
768
+ ---
769
+
770
+ ## Phase 3: Configuration
771
+
772
+ ### 3.1 Agents to install
773
+
774
+ Present the available agents and let the user choose:
775
+
776
+ ```
777
+ ## Agent Selection
778
+
779
+ Which agents do you want to install?
780
+
781
+ | Agent | Purpose | Model | Required |
782
+ |-------|---------|-------|----------|
783
+ | sr-architect | Design features, create implementation plans | Sonnet | Yes |
784
+ | sr-developer (full-stack) | Implement features across all layers | Sonnet | Yes |
785
+ | sr-reviewer | CI/CD quality gate, fix issues | Sonnet | Yes |
786
+ | sr-test-writer | Generate unit, integration, and edge-case tests after implementation | Sonnet | Yes |
787
+ | sr-security-reviewer | Scan for secrets, OWASP vulnerabilities, hardcoded credentials | Sonnet | Yes |
788
+ | sr-product-manager | Product discovery, ideation, VPC evaluation | Opus | Recommended |
789
+ | sr-product-analyst | Read-only backlog analysis | Haiku | Recommended |
790
+ | sr-backend-developer | Specialized backend implementation | Sonnet | If backend layer exists |
791
+ | sr-frontend-developer | Specialized frontend implementation | Sonnet | If frontend layer exists |
792
+
793
+ [All] [Required only] [Custom selection]
794
+ ```
795
+
796
+ ### 3.2 Backlog provider
797
+
798
+ Ask the user how they want to manage their product backlog. Default is local — no external tools or accounts required:
799
+
800
+ ```
801
+ ## Backlog Provider
802
+
803
+ Use local ticket management or connect an external provider?
804
+
805
+ 1. **Local tickets** (default, recommended) — lightweight JSON-based ticket management built into the project.
806
+ No external tools or accounts required. Tickets stored in `.specrails/local-tickets.json`, version-controlled and diffable.
807
+ 2. **External provider** — connect GitHub Issues, JIRA, or disable backlog commands
808
+ ```
809
+
810
+ If the user selects **1** or presses Enter without typing anything: set `BACKLOG_PROVIDER=local` and proceed directly to **If Local Tickets** below. Do NOT ask about GitHub CLI, JIRA credentials, or any external provider configuration.
811
+
812
+ If the user selects **2**: display the secondary menu:
813
+
814
+ ```
815
+ ## External Backlog Provider
816
+
817
+ Which external provider?
818
+
819
+ 1. **Local tickets** (recommended) — lightweight JSON-based ticket management built into the project.
820
+ No external tools required. Tickets stored in `.specrails/local-tickets.json`, version-controlled and diffable.
821
+ 2. **GitHub Issues** — uses `gh` CLI to read/create issues with labels and VPC scores
822
+ 3. **JIRA** — uses JIRA CLI or REST API to read/create tickets in a JIRA project
823
+ 4. **None** — skip backlog commands (you can still use /implement with text descriptions)
824
+ ```
825
+
826
+ Wait for the user's choice. Set `BACKLOG_PROVIDER` to `local`, `github`, `jira`, or `none`.
827
+
828
+ #### If Local Tickets
829
+
830
+ No external tools or credentials required. Initialize the storage file:
831
+
832
+ 1. Copy `templates/local-tickets-schema.json` to `.specrails/local-tickets.json`
833
+ 2. Set `last_updated` to the current ISO-8601 timestamp
834
+
835
+ Store configuration in `.specrails/backlog-config.json`:
836
+ ```json
837
+ {
838
+ "provider": "local",
839
+ "write_access": true,
840
+ "git_auto": true
841
+ }
842
+ ```
843
+
844
+ Local tickets are always read-write — there is no "read only" mode since the file is local.
845
+
846
+ **Ticket schema** — each entry in the `tickets` map has these fields:
847
+
848
+ ```json
849
+ {
850
+ "id": 1,
851
+ "title": "Feature title",
852
+ "description": "Markdown description",
853
+ "status": "todo",
854
+ "priority": "medium",
855
+ "labels": ["area:frontend", "effort:medium"],
856
+ "assignee": null,
857
+ "prerequisites": [],
858
+ "metadata": {
859
+ "vpc_scores": {},
860
+ "effort_level": "Medium",
861
+ "user_story": "",
862
+ "area": ""
863
+ },
864
+ "comments": [],
865
+ "created_at": "<ISO-8601>",
866
+ "updated_at": "<ISO-8601>",
867
+ "created_by": "user",
868
+ "source": "manual"
869
+ }
870
+ ```
871
+
872
+ **Status values:** `todo`, `in_progress`, `done`, `cancelled`
873
+ **Priority values:** `critical`, `high`, `medium`, `low`
874
+ **Labels:** Freeform strings following the `area:*` and `effort:*` convention
875
+ **Source values:** `manual`, `get-backlog-specs`, `propose-spec`
876
+
877
+ **Advisory file locking protocol** (CLI agents and hub server must both follow this):
878
+
879
+ The `revision` counter in the JSON root enables optimistic concurrency — increment it on **every** write. The lock file prevents concurrent corruption:
880
+
881
+ 1. **Acquire lock:** Check for `.specrails/local-tickets.json.lock`
882
+ - If the file exists and its `timestamp` is less than 30 seconds old: wait 500ms and retry (max 5 attempts before aborting with an error)
883
+ - If the file exists and its `timestamp` is 30+ seconds old (stale): delete it and proceed
884
+ - If no lock file exists: proceed immediately
885
+ 2. **Create lock file:** Write `{"agent": "<agent-name-or-process>", "timestamp": "<ISO-8601>"}` to `.specrails/local-tickets.json.lock`
886
+ 3. **Minimal lock window:** Read the JSON → modify in memory → write back → release
887
+ 4. **Release lock:** Delete `.specrails/local-tickets.json.lock`
888
+ 5. **Always increment `revision`** by 1 and update `last_updated` on every successful write
889
+
890
+ The hub server uses `proper-lockfile` (or equivalent) to honor the same protocol via the `.lock` file path.
891
+
892
+ #### If GitHub Issues
893
+
894
+ - Verify `gh auth status` works. If not, warn and offer to skip.
895
+ - Ask about **access mode**:
896
+
897
+ ```
898
+ ## GitHub Issues — Access Mode
899
+
900
+ How should we interact with GitHub Issues?
901
+
902
+ 1. **Read & Write** (default) — read backlog, create new issues from product discovery,
903
+ close resolved issues, add comments on partial progress
904
+ 2. **Read only** — read backlog for prioritization, but don't create or modify issues.
905
+ Product discovery will propose ideas as output but won't sync them to GitHub.
906
+ ```
907
+
908
+ Set `BACKLOG_WRITE=true/false`.
909
+
910
+ - If write mode, ask if they want to create labels:
911
+ - `product-driven-backlog` (purple) — product feature ideas
912
+ - `area:*` labels for each detected layer/area
913
+ - `enhancement`, `bug`, `tech-debt`
914
+
915
+ #### If JIRA
916
+
917
+ First, check if JIRA CLI is installed:
918
+
919
+ ```bash
920
+ command -v jira &> /dev/null
921
+ ```
922
+
923
+ If not installed, offer to install it:
924
+
925
+ > JIRA CLI is not installed. There are several options:
926
+ >
927
+ > 1. **go-jira** (recommended) — lightweight CLI
928
+ > - macOS: `brew install go-jira`
929
+ > - Linux/other: `go install github.com/go-jira/jira/cmd/jira@latest`
930
+ > 2. **Atlassian CLI** — official but heavier
931
+ > - `npm install -g @atlassian/cli`
932
+ > 3. **Skip CLI, use REST API** — no CLI needed, uses `curl` with API token
933
+ >
934
+ > Which option? (1/2/3)
935
+
936
+ If the user chooses option 1 or 2, run the install command. If option 3, proceed with REST API mode.
937
+
938
+ Then ask for JIRA configuration:
939
+
940
+ > To connect to JIRA, I need:
941
+ >
942
+ > 1. **JIRA base URL** (e.g., `https://your-company.atlassian.net`)
943
+ > 2. **Project key** (e.g., `PROJ`, `DECK`, `MYAPP`)
944
+ > 3. **Authentication method**:
945
+ > - **JIRA CLI** (`jira` command) — if already configured
946
+ > - **API token** — stored in `.env` as `JIRA_API_TOKEN` and `JIRA_USER_EMAIL`
947
+ >
948
+ > Optional:
949
+ > - **Custom issue type** for backlog items (default: "Story")
950
+ > - **Custom fields** for VPC scores (or use labels/description)
951
+
952
+ Then ask about **access mode**:
953
+
954
+ ```
955
+ ## JIRA — Access Mode
956
+
957
+ How should we interact with JIRA?
958
+
959
+ 1. **Read & Write** — read tickets for implementation context, create new tickets
960
+ from product discovery, add a comment to tickets when implementation is complete
961
+ 2. **Read only** — read tickets for implementation context, but never create or
962
+ modify tickets. Product discovery will propose ideas as output only. After
963
+ implementation, the pipeline will show what to update manually but won't
964
+ touch JIRA.
965
+ ```
966
+
967
+ Set `BACKLOG_WRITE=true/false`.
968
+
969
+ <!-- no separate template — this file IS the source (install.sh copies commands/setup.md directly) -->
970
+
971
+ #### Project Label
972
+
973
+ After the access mode selection, ask:
974
+
975
+ > **Project Label (optional but recommended)**
976
+ >
977
+ > JIRA teams often tag all tickets for a product with a project label
978
+ > (e.g., `PROJECT-specrails`, `PLATFORM`, `MOBILE`). This label is applied
979
+ > to every ticket the backlog pipeline creates — making it easy to filter all
980
+ > AI-generated backlog items across JIRA.
981
+ >
982
+ > Enter a project label, or press Enter to skip:
983
+
984
+ If the user enters a label: set `PROJECT_LABEL=<value>`.
985
+ If the user skips: set `PROJECT_LABEL=""`.
986
+
987
+ #### Epic Link Field
988
+
989
+ Ask:
990
+
991
+ > **Epic Link Field (optional — advanced)**
992
+ >
993
+ > JIRA Next-Gen (team-managed) projects link stories to epics using the `parent`
994
+ > field. JIRA Classic (company-managed) projects use `Epic Link` (customfield_10014).
995
+ >
996
+ > Which does your project use?
997
+ > 1. `parent` — Next-Gen / team-managed **(default)**
998
+ > 2. `customfield_10014` — Classic / company-managed
999
+
1000
+ Set `EPIC_LINK_FIELD` to `parent` or `customfield_10014`. Default: `parent`.
1001
+
1002
+ Store the full configuration in `.specrails/backlog-config.json`:
1003
+ ```json
1004
+ {
1005
+ "provider": "jira",
1006
+ "write_access": true,
1007
+ "jira_base_url": "https://your-company.atlassian.net",
1008
+ "jira_project_key": "PROJ",
1009
+ "issue_type": "Story",
1010
+ "auth_method": "api_token",
1011
+ "cli_installed": true,
1012
+ "project_label": "<PROJECT_LABEL or empty string>",
1013
+ "epic_link_field": "parent",
1014
+ "epic_mapping": {}
1015
+ }
1016
+ ```
1017
+
1018
+ #### If None
1019
+
1020
+ - Skip `/specrails:get-backlog-specs` and `/specrails:auto-propose-backlog-specs` commands.
1021
+ - The `/specrails:implement` command will still work with text descriptions.
1022
+
1023
+ ### 3.3 Git & shipping workflow
1024
+
1025
+ Ask how the user wants to handle git operations after implementation:
1026
+
1027
+ ```
1028
+ ## Git & Shipping
1029
+
1030
+ After implementation is complete, how should we handle shipping?
1031
+
1032
+ 1. **Automatic** (default) — create branch, commit changes, push, and open a PR
1033
+ (requires GitHub CLI for PRs, otherwise prints a compare URL)
1034
+ 2. **Manual** — stop after implementation and review. You handle branching,
1035
+ committing, and PR creation yourself. The pipeline will show a summary
1036
+ of all changes but won't touch git.
1037
+ ```
1038
+
1039
+ Set `GIT_AUTO=true/false`.
1040
+
1041
+ If automatic, also check if `gh` is authenticated (for PR creation). If not, warn that PRs will be skipped but commits and push will still work.
1042
+
1043
+ ### 3.4 Commands to install
1044
+
1045
+ ```
1046
+ ## Command Selection
1047
+
1048
+ | Command | Purpose | Requires |
1049
+ |---------|---------|----------|
1050
+ | /specrails:implement | Full pipeline: sr-architect → sr-developer → sr-reviewer → ship | sr-architect + sr-developer + sr-reviewer |
1051
+ | /specrails:batch-implement | Orchestrate multiple features in dependency-aware waves | sr-architect + sr-developer + sr-reviewer |
1052
+ | /specrails:propose-spec | Interactively propose and refine a feature spec, then create a GitHub issue | GitHub CLI |
1053
+ | /specrails:get-backlog-specs | View prioritized backlog with VPC scores | sr-product-analyst + Backlog provider |
1054
+ | /specrails:auto-propose-backlog-specs | Generate new feature ideas via product discovery | sr-product-manager + Backlog provider |
1055
+ | /specrails:compat-check | Snapshot API surface and detect breaking changes | None |
1056
+ | /specrails:refactor-recommender | Scan for refactoring opportunities ranked by impact/effort | None |
1057
+ | /specrails:why | Search past architectural decisions from agent memory | None |
1058
+
1059
+ [All] [Custom selection]
1060
+ ```
1061
+
1062
+ Note: If `BACKLOG_PROVIDER=none`, the backlog commands are not offered.
1063
+
1064
+ ### 3.5 Confirm configuration
1065
+
1066
+ Display the full configuration summary including access modes:
1067
+
1068
+ ```
1069
+ ## Configuration Summary
1070
+
1071
+ | Setting | Value |
1072
+ |---------|-------|
1073
+ | Backlog provider | GitHub Issues / JIRA / None |
1074
+ | Backlog access | Read & Write / Read only |
1075
+ | Project label (JIRA) | PROJECT-specrails / (none) |
1076
+ | Epic link field (JIRA) | parent / customfield_10014 |
1077
+ | Git workflow | Automatic / Manual |
1078
+ | Agents | [list] |
1079
+ | Commands | [list] |
1080
+ | Personas | [count] personas |
1081
+
1082
+ Note: The `Project label (JIRA)` and `Epic link field (JIRA)` rows are only shown when `BACKLOG_PROVIDER=jira`.
1083
+
1084
+ [Confirm] [Modify]
1085
+ ```
1086
+
1087
+ Wait for final confirmation.
1088
+
1089
+ ---
1090
+
1091
+ ## Phase 4: Generate Files
1092
+
1093
+ Read each template from `.specrails/setup-templates/` and generate the final files adapted to this project. Use the codebase analysis from Phase 1, personas from Phase 2, and configuration from Phase 3.
1094
+
1095
+ **Provider detection (required before any file generation):** Read `.specrails/setup-templates/.provider-detection.json` to determine `cli_provider` (`"claude"` or `"codex"`) and `specrails_dir` (`.claude` or `.codex`). All output paths in Phase 4 use `$SPECRAILS_DIR` as the base directory. If the file is missing, fall back to `cli_provider = "claude"` and `specrails_dir = ".claude"`.
1096
+
1097
+ ### 4.1 Generate agents
1098
+
1099
+ For each selected agent, read the template and generate the adapted version.
1100
+
1101
+ **Template → Output mapping:**
1102
+
1103
+ **If `cli_provider == "claude"` (default):**
1104
+ - `.specrails/setup-templates/agents/sr-architect.md` → `.claude/agents/sr-architect.md`
1105
+ - `.specrails/setup-templates/agents/sr-developer.md` → `.claude/agents/sr-developer.md`
1106
+ - `.specrails/setup-templates/agents/sr-reviewer.md` → `.claude/agents/sr-reviewer.md`
1107
+ - `.specrails/setup-templates/agents/sr-test-writer.md` → `.claude/agents/sr-test-writer.md`
1108
+ - `.specrails/setup-templates/agents/sr-security-reviewer.md` → `.claude/agents/sr-security-reviewer.md`
1109
+ - `.specrails/setup-templates/agents/sr-product-manager.md` → `.claude/agents/sr-product-manager.md`
1110
+ - `.specrails/setup-templates/agents/sr-product-analyst.md` → `.claude/agents/sr-product-analyst.md`
1111
+ - `.specrails/setup-templates/agents/sr-backend-developer.md` → `.claude/agents/sr-backend-developer.md` (if backend layer)
1112
+ - `.specrails/setup-templates/agents/sr-frontend-developer.md` → `.claude/agents/sr-frontend-developer.md` (if frontend layer)
1113
+
1114
+ **If `cli_provider == "codex"`:**
1115
+ - `.specrails/setup-templates/agents/sr-architect.md` → `.codex/agents/sr-architect.toml`
1116
+ - `.specrails/setup-templates/agents/sr-developer.md` → `.codex/agents/sr-developer.toml`
1117
+ - `.specrails/setup-templates/agents/sr-reviewer.md` → `.codex/agents/sr-reviewer.toml`
1118
+ - `.specrails/setup-templates/agents/sr-test-writer.md` → `.codex/agents/sr-test-writer.toml`
1119
+ - `.specrails/setup-templates/agents/sr-security-reviewer.md` → `.codex/agents/sr-security-reviewer.toml`
1120
+ - `.specrails/setup-templates/agents/sr-product-manager.md` → `.codex/agents/sr-product-manager.toml`
1121
+ - `.specrails/setup-templates/agents/sr-product-analyst.md` → `.codex/agents/sr-product-analyst.toml`
1122
+ - `.specrails/setup-templates/agents/sr-backend-developer.md` → `.codex/agents/sr-backend-developer.toml` (if backend layer)
1123
+ - `.specrails/setup-templates/agents/sr-frontend-developer.md` → `.codex/agents/sr-frontend-developer.toml` (if frontend layer)
1124
+
1125
+ When generating each agent:
1126
+ 1. Read the template
1127
+ 2. Replace all `{{PLACEHOLDER}}` values with project-specific content:
1128
+ - `{{PROJECT_NAME}}` → project name
1129
+ - `{{ARCHITECTURE_DIAGRAM}}` → detected architecture
1130
+ - `{{LAYER_TAGS}}` → detected layer tags (e.g., `[backend]`, `[frontend]`, `[api]`, `[mobile]`)
1131
+ - `{{CI_COMMANDS_BACKEND}}` → backend CI commands from Phase 1
1132
+ - `{{CI_COMMANDS_FRONTEND}}` → frontend CI commands from Phase 1
1133
+ - `{{LAYER_CONVENTIONS}}` → detected conventions per layer
1134
+ - `{{PERSONA_NAMES}}` → names from generated personas
1135
+ - `{{PERSONA_FILES}}` → paths to persona files
1136
+ - `{{DOMAIN_EXPERTISE}}` → domain knowledge from Phase 2 research
1137
+ - `{{COMPETITIVE_LANDSCAPE}}` → competitors discovered in Phase 2
1138
+ - `{{KEY_FILE_PATHS}}` → important file paths detected in Phase 1
1139
+ - `{{WARNINGS}}` → project-specific warnings (from existing CLAUDE.md or detected)
1140
+ - `{{MEMORY_PATH}}` → agent memory directory path (e.g., `$SPECRAILS_DIR/agent-memory/sr-<agent-name>/`)
1141
+ - `{{TECH_EXPERTISE}}` → detected languages, frameworks, and test frameworks from Phase 1
1142
+ - `{{LAYER_CLAUDE_MD_PATHS}}` → comma-separated paths to per-layer rules files (e.g., `$SPECRAILS_DIR/rules/backend.md`, `$SPECRAILS_DIR/rules/frontend.md`)
1143
+ - `{{SECURITY_EXEMPTIONS_PATH}}` → `$SPECRAILS_DIR/security-exemptions.yaml`
1144
+ 3. Write the final file in the format for the active provider:
1145
+
1146
+ **If `cli_provider == "claude"`:** Write as Markdown with YAML frontmatter — the template file as-is (frontmatter preserved).
1147
+
1148
+ **If `cli_provider == "codex"`:** Convert to TOML format:
1149
+ - Extract YAML frontmatter fields: `name`, `description`, `model`
1150
+ - Extract the body content (everything after the closing `---` of the frontmatter)
1151
+ - Map the `model` field: `sonnet` → `codex-mini-latest`, `opus` → `o3`, `haiku` → `codex-mini-latest`
1152
+ - Write a `.toml` file with this structure:
1153
+ ```toml
1154
+ name = "<name from frontmatter>"
1155
+ description = "<description from frontmatter, escaped for TOML>"
1156
+ model = "codex-mini-latest"
1157
+ prompt = """
1158
+ <body content after placeholder substitution>
1159
+ """
1160
+ ```
1161
+
1162
+ ### 4.2 Generate personas
1163
+
1164
+ If IS_OSS=true:
1165
+ 1. Copy `.specrails/setup-templates/personas/the-maintainer.md` to `$SPECRAILS_DIR/agents/personas/the-maintainer.md`
1166
+ 2. Log: "Maintainer persona included"
1167
+ 3. Set MAINTAINER_INCLUDED=true for use in template substitution
1168
+ 4. Set `{{MAINTAINER_PERSONA_LINE}}` = `- \`$SPECRAILS_DIR/agents/personas/the-maintainer.md\` — "Kai" the Maintainer (open-source maintainer)`
1169
+ 5. Increment `{{PERSONA_COUNT}}` by 1 to account for the Maintainer
1170
+
1171
+ If IS_OSS=false:
1172
+ - Set `{{MAINTAINER_PERSONA_LINE}}` = *(empty string)*
1173
+
1174
+ Then for each user-defined VPC persona from Phase 2.3:
1175
+
1176
+ Write each persona to `$SPECRAILS_DIR/agents/personas/`:
1177
+ - Use the VPC personas generated in Phase 2
1178
+ - File naming: kebab-case of persona nickname (e.g., `the-developer.md`, `the-admin.md`)
1179
+
1180
+ ### 4.3 Generate commands / skills
1181
+
1182
+ For each selected command, read the template and adapt.
1183
+
1184
+ **If `cli_provider == "claude"` (default):**
1185
+ - `.specrails/setup-templates/commands/specrails/implement.md` → `.claude/commands/specrails/implement.md`
1186
+ - `.specrails/setup-templates/commands/specrails/batch-implement.md` → `.claude/commands/specrails/batch-implement.md`
1187
+ - `.specrails/setup-templates/commands/specrails/propose-spec.md` → `.claude/commands/specrails/propose-spec.md`
1188
+ - `.specrails/setup-templates/commands/specrails/get-backlog-specs.md` → `.claude/commands/specrails/get-backlog-specs.md` (if `BACKLOG_PROVIDER != none`)
1189
+ - `.specrails/setup-templates/commands/specrails/auto-propose-backlog-specs.md` → `.claude/commands/specrails/auto-propose-backlog-specs.md` (if `BACKLOG_PROVIDER != none`)
1190
+ - `.specrails/setup-templates/commands/specrails/compat-check.md` → `.claude/commands/specrails/compat-check.md`
1191
+ - `.specrails/setup-templates/commands/specrails/refactor-recommender.md` → `.claude/commands/specrails/refactor-recommender.md`
1192
+ - `.specrails/setup-templates/commands/specrails/why.md` → `.claude/commands/specrails/why.md`
1193
+
1194
+ **If `cli_provider == "codex"`:**
1195
+ - `.specrails/setup-templates/skills/sr-implement/SKILL.md` → `.agents/skills/sr-implement/SKILL.md`
1196
+ - `.specrails/setup-templates/skills/sr-batch-implement/SKILL.md` → `.agents/skills/sr-batch-implement/SKILL.md`
1197
+ - `.specrails/setup-templates/commands/specrails/propose-spec.md` → `.agents/skills/sr-propose-spec/SKILL.md` (wrap with YAML frontmatter if no skill template exists)
1198
+ - `.specrails/setup-templates/commands/specrails/get-backlog-specs.md` → `.agents/skills/sr-get-backlog-specs/SKILL.md` (if `BACKLOG_PROVIDER != none`; wrap with frontmatter)
1199
+ - `.specrails/setup-templates/commands/specrails/auto-propose-backlog-specs.md` → `.agents/skills/sr-auto-propose-backlog-specs/SKILL.md` (if `BACKLOG_PROVIDER != none`; wrap with frontmatter)
1200
+ - `.specrails/setup-templates/skills/sr-compat-check/SKILL.md` → `.agents/skills/sr-compat-check/SKILL.md`
1201
+ - `.specrails/setup-templates/skills/sr-refactor-recommender/SKILL.md` → `.agents/skills/sr-refactor-recommender/SKILL.md`
1202
+ - `.specrails/setup-templates/skills/sr-why/SKILL.md` → `.agents/skills/sr-why/SKILL.md`
1203
+
1204
+ **Codex skill frontmatter wrapping:** When a dedicated skill template does not exist in `.specrails/setup-templates/skills/` for a command, generate the `SKILL.md` by prepending YAML frontmatter to the command content:
1205
+ ```yaml
1206
+ ---
1207
+ name: sr-<name>
1208
+ description: "<one-line description from the command's first heading>"
1209
+ license: MIT
1210
+ compatibility: "Requires git."
1211
+ metadata:
1212
+ author: specrails
1213
+ version: "1.0"
1214
+ ---
1215
+ ```
1216
+
1217
+ For both providers, create the output directory before writing (`mkdir -p` for `.claude/commands/specrails/` or `.agents/skills/sr-<name>/`).
1218
+
1219
+ Adapt:
1220
+ - CI commands to match detected stack
1221
+ - **Persona references** to match generated personas (see substitution rules below)
1222
+ - File paths to match project structure
1223
+ - Layer tags to match detected layers
1224
+ - **Backlog provider commands** based on `BACKLOG_PROVIDER`:
1225
+
1226
+ #### Backlog command persona placeholder substitution
1227
+
1228
+ When adapting `auto-propose-backlog-specs.md` and `get-backlog-specs.md`, substitute the persona placeholders based on the full persona set (user-generated personas + Maintainer if `IS_OSS=true`):
1229
+
1230
+ | Placeholder | Substitution rule |
1231
+ |-------------|------------------|
1232
+ | `{{PERSONA_FILE_READ_LIST}}` | One bullet per persona file: `- Read \`$SPECRAILS_DIR/agents/personas/{name}.md\`` |
1233
+ | `{{PERSONA_SCORE_HEADERS}}` | Column headers for each persona nickname: e.g., `Alex \| Sara \| Kai` |
1234
+ | `{{PERSONA_SCORE_SEPARATORS}}` | One `------` separator per persona column |
1235
+ | `{{PERSONA_FIT_FORMAT}}` | Inline score display: e.g., `Alex: X/5, Sara: X/5, Kai: X/5` |
1236
+ | `{{PERSONA_VPC_SECTIONS}}` | One VPC section block per persona (see format below) |
1237
+ | `{{MAX_SCORE}}` | Total max score = 5 × number of personas (e.g., `15` for 3 personas) |
1238
+ | `{{PERSONA_NAMES_WITH_ROLES}}` | Comma-separated: e.g., `Alex (Lead Dev), Sara (Product Founder), Kai (OSS Maintainer)` |
1239
+
1240
+ **`{{PERSONA_VPC_SECTIONS}}` format** — repeat for each persona in order:
1241
+ ```
1242
+ ### "{Nickname}" — The {Role} (X/5)
1243
+ - **Jobs addressed**: {list}
1244
+ - **Pains relieved**: {list with severity}
1245
+ - **Gains created**: {list with impact}
1246
+ ```
1247
+
1248
+ **Kai inclusion rule**: When `IS_OSS=true`, Kai (`sr-the-maintainer.md`) is always the last entry in persona lists and the rightmost column in scoring tables. Kai uses the evaluation criteria defined in `.claude/agents/personas/sr-the-maintainer.md` — features score high (4-5/5) for Kai when they reduce async review burden, enforce project-specific conventions, or automate release/dependency coordination; features score low (0-1/5) when they add configuration complexity or require paid tiers.
1249
+
1250
+ **When `IS_OSS=false`**: All Kai-related persona references are omitted. `{{MAX_SCORE}}` reduces by 5. Tables and inline scores contain only user-generated personas.
1251
+
1252
+ #### Local Tickets (`BACKLOG_PROVIDER=local`)
1253
+
1254
+ For the local provider, backlog placeholders resolve to **inline file-operation instructions** embedded in the generated command markdown — not shell commands. Agents execute these by reading/writing `.specrails/local-tickets.json` directly using their file tools.
1255
+
1256
+ All write operations must follow the **advisory file locking protocol** defined in Phase 3.2. Always increment `revision` and update `last_updated` on every write.
1257
+
1258
+ | Placeholder | Substituted value |
1259
+ |-------------|-------------------|
1260
+ | `{{BACKLOG_PROVIDER_NAME}}` | `Local Tickets` |
1261
+ | `{{BACKLOG_PREFLIGHT}}` | `[[ -f ".specrails/local-tickets.json" ]] && echo "Local tickets storage: OK" \|\| echo "WARNING: .specrails/local-tickets.json not found — run /specrails:enrich to initialize"` |
1262
+ | `{{BACKLOG_FETCH_CMD}}` | Read `.specrails/local-tickets.json`. Parse the `tickets` map and return all entries where `status` is `"todo"` or `"in_progress"`. |
1263
+ | `{{BACKLOG_FETCH_ALL_CMD}}` | Read `.specrails/local-tickets.json`. Parse the `tickets` map and return all entries regardless of status. |
1264
+ | `{{BACKLOG_FETCH_CLOSED_CMD}}` | Read `.specrails/local-tickets.json`. Parse the `tickets` map and return all entries where `status` is `"done"` or `"cancelled"`. |
1265
+ | `{{BACKLOG_VIEW_CMD}}` | Read `.specrails/local-tickets.json`. Parse JSON and return the full ticket object at `tickets["{id}"]`, or an error if not found. |
1266
+ | `{{BACKLOG_CREATE_CMD}}` | Write to `.specrails/local-tickets.json` using the advisory locking protocol: acquire lock → read file → set `id = next_id`, increment `next_id`, set all ticket fields, set `created_at` and `updated_at` to now, bump `revision`, update `last_updated` → write → release lock. |
1267
+ | `{{BACKLOG_UPDATE_CMD}}` | Write to `.specrails/local-tickets.json` using the advisory locking protocol: acquire lock → read file → update fields in `tickets["{id}"]`, set `updated_at` to now, bump `revision`, update `last_updated` → write → release lock. |
1268
+ | `{{BACKLOG_DELETE_CMD}}` | Write to `.specrails/local-tickets.json` using the advisory locking protocol: acquire lock → read file → delete `tickets["{id}"]`, bump `revision`, update `last_updated` → write → release lock. |
1269
+ | `{{BACKLOG_COMMENT_CMD}}` | Write to `.specrails/local-tickets.json` using the advisory locking protocol: acquire lock → read file → append `{"author": "<agent-name>", "body": "<comment>", "created_at": "<ISO-8601>"}` to `tickets["{id}"].comments` (create the array if absent), set `updated_at` to now, bump `revision`, update `last_updated` → write → release lock. |
1270
+ | `{{BACKLOG_PARTIAL_COMMENT_CMD}}` | Same as `{{BACKLOG_COMMENT_CMD}}` but append `{"author": "<agent-name>", "body": "<comment>", "type": "progress", "created_at": "<ISO-8601>"}`. |
1271
+ | `{{BACKLOG_INIT_LABELS_CMD}}` | No label initialization required. Local tickets use freeform label strings. Standard label conventions: `area:frontend`, `area:backend`, `area:api`, `effort:low`, `effort:medium`, `effort:high`. |
1272
+
1273
+ #### GitHub Issues (`BACKLOG_PROVIDER=github`)
1274
+ - Issue fetch: `gh issue list --label "product-driven-backlog" --state open --limit 100 --json number,title,labels,body`
1275
+ - Issue create: `gh issue create --title "..." --label "..." --body "..."`
1276
+ - Issue view: `gh issue view {number} --json number,title,labels,body`
1277
+ - Issue label names to match project areas
1278
+ - Pre-flight check: `gh auth status`
1279
+
1280
+ #### JIRA (`BACKLOG_PROVIDER=jira`)
1281
+ - Issue fetch: `jira issue list --project {{JIRA_PROJECT_KEY}} --type Story --label get-backlog-specs --status "To Do" --plain` or equivalent JIRA REST API call via curl:
1282
+ ```bash
1283
+ curl -s -u "$JIRA_USER_EMAIL:$JIRA_API_TOKEN" \
1284
+ "{{JIRA_BASE_URL}}/rest/api/3/search?jql=project={{JIRA_PROJECT_KEY}} AND labels=get-backlog-specs AND status='To Do'&fields=summary,description,labels,priority"
1285
+ ```
1286
+ - Issue create: `jira issue create --project {{JIRA_PROJECT_KEY}} --type Story --summary "..." --label get-backlog-specs --description "..."` or equivalent REST API call
1287
+ - Issue view: `jira issue view {key}` or REST API
1288
+ - VPC scores stored in the issue description body (same markdown format, parsed from description)
1289
+ - Pre-flight check: `jira me` or test API connectivity
1290
+ - Store JIRA config in `.specrails/backlog-config.json`:
1291
+ ```json
1292
+ {
1293
+ "provider": "jira",
1294
+ "jira_base_url": "https://your-company.atlassian.net",
1295
+ "jira_project_key": "PROJ",
1296
+ "issue_type": "Story",
1297
+ "auth_method": "api_token"
1298
+ }
1299
+ ```
1300
+
1301
+ The command templates use `{{BACKLOG_FETCH_CMD}}`, `{{BACKLOG_CREATE_CMD}}`, `{{BACKLOG_VIEW_CMD}}`, `{{BACKLOG_PREFLIGHT}}`, and related placeholders that get filled with the provider-specific commands (for `local`) or instructions (for `github`, `jira`). The `{{BACKLOG_PROVIDER_NAME}}` placeholder is substituted with a human-readable provider label in all three cases.
1302
+
1303
+ ### 4.4 Generate rules
1304
+
1305
+ For each detected layer, read the layer rule template and generate a layer-specific rules file:
1306
+ - `.specrails/setup-templates/rules/layer.md` → `$SPECRAILS_DIR/rules/{layer-name}.md`
1307
+
1308
+ Each rule file must:
1309
+ - Have the correct `paths:` frontmatter matching the layer's directory
1310
+ - Contain conventions specific to that layer (from Phase 1 analysis)
1311
+ - Reference actual file paths and patterns from the codebase
1312
+
1313
+ ### 4.5 Generate root instructions file
1314
+
1315
+ **If `cli_provider == "claude"`:** If no `CLAUDE.md` exists, generate one from the template. If one already exists, **merge** — add the agent workflow sections without removing existing content.
1316
+
1317
+ **If `cli_provider == "codex"`:** If no `AGENTS.md` exists, generate one from the template. If one already exists, **merge** — add the agent workflow sections without removing existing content.
1318
+
1319
+ ### 4.6 Generate settings
1320
+
1321
+ Read `.specrails/setup-templates/.provider-detection.json` (written by `install.sh`) to determine `cli_provider` (`"claude"` or `"codex"`).
1322
+
1323
+ **If `cli_provider == "claude"` (default):**
1324
+
1325
+ Create or merge `.claude/settings.json` with permissions for:
1326
+ - All detected CI commands
1327
+ - Git operations
1328
+ - OpenSpec CLI (if installed)
1329
+ - GitHub CLI (if available)
1330
+ - Language-specific tools (python, npm, cargo, go, etc.)
1331
+
1332
+ **If `cli_provider == "codex"`:**
1333
+
1334
+ 1. Read `.specrails/setup-templates/settings/codex-config.toml`. Write it to `.codex/config.toml` as-is (no substitutions needed — the TOML is static).
1335
+
1336
+ 2. Read `.specrails/setup-templates/settings/codex-rules.star`. Replace `{{CODEX_SHELL_RULES}}` with Starlark `prefix_rule(...)` lines for each detected tool allowance:
1337
+
1338
+ | Detected tool/command | Starlark rule |
1339
+ |----------------------|---------------|
1340
+ | OpenSpec CLI (`openspec`) | `prefix_rule(pattern=["openspec"], decision="allow")` |
1341
+ | Python (`python`, `pip`) | `prefix_rule(pattern=["python"], decision="allow")`<br>`prefix_rule(pattern=["pip"], decision="allow")` |
1342
+ | npm (`npm`) | `prefix_rule(pattern=["npm"], decision="allow")` |
1343
+ | Cargo (`cargo`) | `prefix_rule(pattern=["cargo"], decision="allow")` |
1344
+ | Go (`go`) | `prefix_rule(pattern=["go"], decision="allow")` |
1345
+ | Any detected CI command | `prefix_rule(pattern=["<cmd>"], decision="allow")` |
1346
+
1347
+ Write the rendered file to `.codex/rules/default.rules`.
1348
+
1349
+ ```bash
1350
+ mkdir -p .codex/rules
1351
+ ```
1352
+
1353
+ If `cli_provider` cannot be determined (file missing), fall back to `"claude"` behavior.
1354
+
1355
+ ### 4.7 Initialize agent memory
1356
+
1357
+ Create memory directories for each installed agent using the provider-aware base directory:
1358
+
1359
+ ```bash
1360
+ mkdir -p $SPECRAILS_DIR/agent-memory/sr-{agent-name}/
1361
+ ```
1362
+
1363
+ Each gets an empty `MEMORY.md` that will be populated during usage.
1364
+
1365
+ ---
1366
+
1367
+ ## Phase 5: Cleanup & Summary
1368
+
1369
+ ### 5.1 Remove all scaffolding artifacts
1370
+
1371
+ The setup process installed temporary files that are only needed during installation. Remove them all now that the final files have been generated.
1372
+
1373
+ ```bash
1374
+ # 1. Remove setup templates (used as structural references during generation)
1375
+ rm -rf .specrails/setup-templates/
1376
+
1377
+ # 2. Remove the /specrails:enrich command itself — it's a one-time installer, not a permanent command
1378
+ rm -f .claude/commands/enrich.md
1379
+
1380
+ # 3. Remove the specrails/ directory from the repo if it exists at the root
1381
+ # (it was only needed for install.sh and templates — everything is now in .claude/)
1382
+ # NOTE: Only remove if it's inside this repo. Ask the user if unsure.
1383
+ ```
1384
+
1385
+ **What gets removed:**
1386
+ | Artifact | Why |
1387
+ |----------|-----|
1388
+ | `.specrails/setup-templates/` | Temporary — templates already rendered into final files |
1389
+ | `.claude/commands/enrich.md` | One-time installer — running it again would overwrite customized agents |
1390
+
1391
+ **What to do with `specrails/`:**
1392
+
1393
+ The `specrails/` directory should NOT be committed to the target repo — it's an installer tool, not part of the project. Always add it to `.gitignore`:
1394
+
1395
+ ```bash
1396
+ # Add specrails/ to .gitignore if not already there
1397
+ if ! grep -q '^specrails/' .gitignore 2>/dev/null; then
1398
+ echo '' >> .gitignore
1399
+ echo '# specrails installer (one-time setup tool, not part of the project)' >> .gitignore
1400
+ echo 'specrails/' >> .gitignore
1401
+ fi
1402
+ ```
1403
+
1404
+ Then ask the user:
1405
+
1406
+ > `specrails/` has been added to `.gitignore`. Do you also want to delete it?
1407
+ >
1408
+ > 1. **Keep it** (default) — stays locally in case you want to re-run setup or install in other repos
1409
+ > 2. **Delete it** — everything is installed, you don't need it anymore
1410
+
1411
+ Apply the user's choice.
1412
+
1413
+ ### 5.2 Verify clean state
1414
+
1415
+ After cleanup, verify that only the intended files remain:
1416
+
1417
+ ```bash
1418
+ # These should exist (the actual system) — use $SPECRAILS_DIR from .provider-detection.json:
1419
+ # If cli_provider == "claude":
1420
+ ls .claude/agents/sr-*.md
1421
+ ls .claude/agents/personas/*.md
1422
+ ls .claude/commands/specrails/*.md
1423
+ ls .claude/rules/*.md
1424
+ ls .claude/agent-memory/
1425
+
1426
+ # If cli_provider == "codex":
1427
+ ls .codex/agents/sr-*.toml
1428
+ ls .codex/agents/personas/*.md
1429
+ ls .agents/skills/sr-*/SKILL.md
1430
+ ls .codex/rules/*.md
1431
+ ls .codex/agent-memory/
1432
+
1433
+ # These should NOT exist (scaffolding):
1434
+ # .specrails/setup-templates/ — GONE
1435
+ # If cli_provider == "claude": $SPECRAILS_DIR/commands/enrich.md — GONE
1436
+ # If cli_provider == "codex": .agents/skills/setup/ — GONE (installer scaffold, not a generated sr-skill)
1437
+ ```
1438
+
1439
+ If any scaffolding artifact remains, remove it.
1440
+
1441
+ ### 5.3 Summary
1442
+
1443
+ Display the complete installation summary:
1444
+
1445
+ ```
1446
+ ## Setup Complete
1447
+
1448
+ ### Agents Installed
1449
+ | Agent | File | Model |
1450
+ |-------|------|-------|
1451
+ [If cli_provider == "claude":]
1452
+ | sr-architect | .claude/agents/sr-architect.md | Sonnet |
1453
+ | sr-developer | .claude/agents/sr-developer.md | Sonnet |
1454
+ | sr-reviewer | .claude/agents/sr-reviewer.md | Sonnet |
1455
+ | sr-test-writer | .claude/agents/sr-test-writer.md | Sonnet |
1456
+ | sr-security-reviewer | .claude/agents/sr-security-reviewer.md | Sonnet |
1457
+ | sr-product-manager | .claude/agents/sr-product-manager.md | Opus |
1458
+ [If cli_provider == "codex":]
1459
+ | sr-architect | .codex/agents/sr-architect.toml | codex-mini-latest |
1460
+ | sr-developer | .codex/agents/sr-developer.toml | codex-mini-latest |
1461
+ | sr-reviewer | .codex/agents/sr-reviewer.toml | codex-mini-latest |
1462
+ | sr-test-writer | .codex/agents/sr-test-writer.toml | codex-mini-latest |
1463
+ | sr-security-reviewer | .codex/agents/sr-security-reviewer.toml | codex-mini-latest |
1464
+ | sr-product-manager | .codex/agents/sr-product-manager.toml | o3 |
1465
+
1466
+ ### Personas Created
1467
+ | Persona | File | Source |
1468
+ |---------|------|--------|
1469
+ [If IS_OSS=true:]
1470
+ | "Kai" — The Maintainer | $SPECRAILS_DIR/agents/personas/sr-the-maintainer.md | Auto-included (OSS) |
1471
+ [For each user-generated persona:]
1472
+ | "[Name]" — The [Role] | $SPECRAILS_DIR/agents/personas/[name].md | Generated |
1473
+
1474
+ ### Commands / Skills Installed
1475
+ [If cli_provider == "claude":]
1476
+ | Command | File |
1477
+ |---------|------|
1478
+ | /specrails:implement | .claude/commands/specrails/implement.md |
1479
+ | /specrails:batch-implement | .claude/commands/specrails/batch-implement.md |
1480
+ | /specrails:propose-spec | .claude/commands/specrails/propose-spec.md |
1481
+ | /specrails:get-backlog-specs | .claude/commands/specrails/get-backlog-specs.md |
1482
+ | /specrails:auto-propose-backlog-specs | .claude/commands/specrails/auto-propose-backlog-specs.md |
1483
+ | /specrails:compat-check | .claude/commands/specrails/compat-check.md |
1484
+ | /specrails:refactor-recommender | .claude/commands/specrails/refactor-recommender.md |
1485
+ | /specrails:why | .claude/commands/specrails/why.md |
1486
+ [If cli_provider == "codex":]
1487
+ | Skill | File |
1488
+ |-------|------|
1489
+ | $sr-implement | .agents/skills/sr-implement/SKILL.md |
1490
+ | $sr-batch-implement | .agents/skills/sr-batch-implement/SKILL.md |
1491
+ | $sr-propose-spec | .agents/skills/sr-propose-spec/SKILL.md |
1492
+ | $sr-get-backlog-specs | .agents/skills/sr-get-backlog-specs/SKILL.md |
1493
+ | $sr-auto-propose-backlog-specs | .agents/skills/sr-auto-propose-backlog-specs/SKILL.md |
1494
+ | $sr-compat-check | .agents/skills/sr-compat-check/SKILL.md |
1495
+ | $sr-refactor-recommender | .agents/skills/sr-refactor-recommender/SKILL.md |
1496
+ | $sr-why | .agents/skills/sr-why/SKILL.md |
1497
+
1498
+ Note: Only commands/skills selected during setup are shown. Backlog commands are excluded if no backlog provider was configured.
1499
+
1500
+ ### Rules Created
1501
+ | Layer | File |
1502
+ |-------|------|
1503
+ | Backend | $SPECRAILS_DIR/rules/backend.md |
1504
+ | Frontend | $SPECRAILS_DIR/rules/frontend.md |
1505
+
1506
+ ### Scaffolding Removed
1507
+ | Artifact | Status |
1508
+ |----------|--------|
1509
+ | .specrails/setup-templates/ | Deleted |
1510
+ [If cli_provider == "claude":] | .claude/commands/enrich.md | Deleted |
1511
+ [If cli_provider == "codex":] | .agents/skills/setup/ | Deleted |
1512
+ | specrails/ | [User's choice] |
1513
+
1514
+ ### Next Steps
1515
+ [If cli_provider == "claude":]
1516
+ 1. Review the generated files in .claude/
1517
+ 2. Run `/specrails:get-backlog-specs` to see your backlog (if GitHub Issues exist)
1518
+ 3. Run `/specrails:auto-propose-backlog-specs` to generate feature ideas
1519
+ 4. Run `/specrails:implement #issue-number` to implement a feature
1520
+ 5. Commit the .claude/ directory to version control
1521
+ [If cli_provider == "codex":]
1522
+ 1. Review the generated files in .codex/ and .agents/skills/
1523
+ 2. Run `$sr-get-backlog-specs` to see your backlog (if GitHub Issues exist)
1524
+ 3. Run `$sr-auto-propose-backlog-specs` to generate feature ideas
1525
+ 4. Run `$sr-implement #issue-number` to implement a feature
1526
+ 5. Commit the .codex/ and .agents/ directories to version control
1527
+
1528
+ ### Quick Start
1529
+ [If cli_provider == "claude":]
1530
+ - `/specrails:implement "describe a feature"` — implement something right now
1531
+ - `/specrails:get-backlog-specs` — see prioritized feature ideas
1532
+ - `/specrails:auto-propose-backlog-specs` — discover new features using VPC
1533
+ [If cli_provider == "codex":]
1534
+ - `$sr-implement "describe a feature"` — implement something right now
1535
+ - `$sr-get-backlog-specs` — see prioritized feature ideas
1536
+ - `$sr-auto-propose-backlog-specs` — discover new features using VPC
1537
+ ```
1538
+
1539
+ ## First Task Prompt (Full Wizard)
1540
+
1541
+ After displaying the setup complete summary above, detect the project type and output:
1542
+
1543
+ **New project** (no `package.json`, `Gemfile`, `pyproject.toml`, `go.mod`, or `pom.xml` in root):
1544
+ ```
1545
+ ✅ Setup complete.
1546
+
1547
+ Try your first spec:
1548
+ [If cli_provider == "claude":]
1549
+ > /specrails:get-backlog-specs
1550
+ [If cli_provider == "codex":]
1551
+ > $sr-get-backlog-specs
1552
+ ```
1553
+
1554
+ **Existing codebase** (one or more of the above files found in root):
1555
+ ```
1556
+ ✅ Setup complete.
1557
+
1558
+ Try your first spec:
1559
+ [If cli_provider == "claude":]
1560
+ > /specrails:refactor-recommender
1561
+ [If cli_provider == "codex":]
1562
+ > $sr-refactor-recommender
1563
+ ```
1564
+
1565
+ Then stop.