specfact-cli 0.4.2__py3-none-any.whl → 0.6.8__py3-none-any.whl

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.
Files changed (66) hide show
  1. specfact_cli/__init__.py +1 -1
  2. specfact_cli/agents/analyze_agent.py +2 -3
  3. specfact_cli/analyzers/__init__.py +2 -1
  4. specfact_cli/analyzers/ambiguity_scanner.py +601 -0
  5. specfact_cli/analyzers/code_analyzer.py +462 -30
  6. specfact_cli/analyzers/constitution_evidence_extractor.py +491 -0
  7. specfact_cli/analyzers/contract_extractor.py +419 -0
  8. specfact_cli/analyzers/control_flow_analyzer.py +281 -0
  9. specfact_cli/analyzers/requirement_extractor.py +337 -0
  10. specfact_cli/analyzers/test_pattern_extractor.py +330 -0
  11. specfact_cli/cli.py +151 -206
  12. specfact_cli/commands/constitution.py +281 -0
  13. specfact_cli/commands/enforce.py +42 -34
  14. specfact_cli/commands/import_cmd.py +481 -152
  15. specfact_cli/commands/init.py +224 -55
  16. specfact_cli/commands/plan.py +2133 -547
  17. specfact_cli/commands/repro.py +100 -78
  18. specfact_cli/commands/sync.py +701 -186
  19. specfact_cli/enrichers/constitution_enricher.py +765 -0
  20. specfact_cli/enrichers/plan_enricher.py +294 -0
  21. specfact_cli/importers/speckit_converter.py +364 -48
  22. specfact_cli/importers/speckit_scanner.py +65 -0
  23. specfact_cli/models/plan.py +42 -0
  24. specfact_cli/resources/mappings/node-async.yaml +49 -0
  25. specfact_cli/resources/mappings/python-async.yaml +47 -0
  26. specfact_cli/resources/mappings/speckit-default.yaml +82 -0
  27. specfact_cli/resources/prompts/specfact-enforce.md +185 -0
  28. specfact_cli/resources/prompts/specfact-import-from-code.md +626 -0
  29. specfact_cli/resources/prompts/specfact-plan-add-feature.md +188 -0
  30. specfact_cli/resources/prompts/specfact-plan-add-story.md +212 -0
  31. specfact_cli/resources/prompts/specfact-plan-compare.md +571 -0
  32. specfact_cli/resources/prompts/specfact-plan-init.md +531 -0
  33. specfact_cli/resources/prompts/specfact-plan-promote.md +352 -0
  34. specfact_cli/resources/prompts/specfact-plan-review.md +1276 -0
  35. specfact_cli/resources/prompts/specfact-plan-select.md +401 -0
  36. specfact_cli/resources/prompts/specfact-plan-update-feature.md +242 -0
  37. specfact_cli/resources/prompts/specfact-plan-update-idea.md +211 -0
  38. specfact_cli/resources/prompts/specfact-repro.md +268 -0
  39. specfact_cli/resources/prompts/specfact-sync.md +497 -0
  40. specfact_cli/resources/schemas/deviation.schema.json +61 -0
  41. specfact_cli/resources/schemas/plan.schema.json +204 -0
  42. specfact_cli/resources/schemas/protocol.schema.json +53 -0
  43. specfact_cli/resources/templates/github-action.yml.j2 +140 -0
  44. specfact_cli/resources/templates/plan.bundle.yaml.j2 +141 -0
  45. specfact_cli/resources/templates/pr-template.md.j2 +58 -0
  46. specfact_cli/resources/templates/protocol.yaml.j2 +24 -0
  47. specfact_cli/resources/templates/telemetry.yaml.example +35 -0
  48. specfact_cli/sync/__init__.py +10 -1
  49. specfact_cli/sync/watcher.py +268 -0
  50. specfact_cli/telemetry.py +440 -0
  51. specfact_cli/utils/acceptance_criteria.py +127 -0
  52. specfact_cli/utils/enrichment_parser.py +445 -0
  53. specfact_cli/utils/feature_keys.py +12 -3
  54. specfact_cli/utils/ide_setup.py +170 -0
  55. specfact_cli/utils/structure.py +179 -2
  56. specfact_cli/utils/yaml_utils.py +33 -0
  57. specfact_cli/validators/repro_checker.py +22 -1
  58. specfact_cli/validators/schema.py +15 -4
  59. specfact_cli-0.6.8.dist-info/METADATA +456 -0
  60. specfact_cli-0.6.8.dist-info/RECORD +99 -0
  61. {specfact_cli-0.4.2.dist-info → specfact_cli-0.6.8.dist-info}/entry_points.txt +1 -0
  62. specfact_cli-0.6.8.dist-info/licenses/LICENSE.md +202 -0
  63. specfact_cli-0.4.2.dist-info/METADATA +0 -370
  64. specfact_cli-0.4.2.dist-info/RECORD +0 -62
  65. specfact_cli-0.4.2.dist-info/licenses/LICENSE.md +0 -61
  66. {specfact_cli-0.4.2.dist-info → specfact_cli-0.6.8.dist-info}/WHEEL +0 -0
@@ -0,0 +1,626 @@
1
+ ---
2
+ description: Import plan bundle from existing codebase (one-way import from repository).
3
+ ---
4
+ # SpecFact Import From Code Command (brownfield integration on existing projects)
5
+
6
+ ## User Input
7
+
8
+ ```text
9
+ $ARGUMENTS
10
+ ```
11
+
12
+ You **MUST** consider the user input before proceeding (if not empty).
13
+
14
+ ## Interactive Flow
15
+
16
+ **Step 1**: Check if `--name` is provided in user input or arguments.
17
+
18
+ - **If provided**: Use the provided name (it will be automatically sanitized)
19
+ - **If missing**: **Ask the user interactively** for a meaningful plan name:
20
+ - Prompt: "What name would you like to use for this plan? (e.g., 'API Client v2', 'User Authentication', 'Payment Processing')"
21
+ - Wait for user response
22
+ - The name will be automatically sanitized (lowercased, spaces/special chars removed) for filesystem persistence
23
+ - Example: User provides "API Client v2" → saved as `api-client-v2.2025-11-04T23-19-31.bundle.yaml`
24
+
25
+ **Step 2**: Proceed with import using the plan name (either provided or obtained from user).
26
+
27
+ ## ⚠️ CRITICAL: CLI Usage Enforcement
28
+
29
+ **YOU MUST ALWAYS USE THE SPECFACT CLI**. Never create artifacts directly.
30
+
31
+ ### Rules
32
+
33
+ 1. **ALWAYS execute CLI first**: Run `specfact import from-code` before any analysis - execute the CLI command before any other operations
34
+ 2. **NEVER write code**: Do not implement import logic - the CLI handles this
35
+ 3. **NEVER create YAML/JSON directly**: All artifacts must be CLI-generated
36
+ 4. **NEVER bypass CLI validation**: CLI ensures schema compliance and metadata - use it, don't bypass its validation
37
+ 5. **Use CLI output as grounding**: Parse CLI output, don't regenerate or recreate it - use the CLI output as the source of truth
38
+ 6. **NEVER manipulate internal code**: Do NOT use Python code to directly modify PlanBundle objects, Feature objects, or any internal data structures. The CLI is THE interface - use it exclusively.
39
+ 7. **No internal knowledge required**: You should NOT need to know about internal implementation details (PlanBundle model, Feature class, EnrichmentParser, etc.). All operations must be performed via CLI commands.
40
+ 8. **NEVER read artifacts directly**: Do NOT read plan bundle files directly to extract information unless for enrichment analysis (Phase 2). Use CLI commands to get plan information. After enrichment, always apply via CLI using `--enrichment` flag.
41
+
42
+ ### What Happens If You Don't Follow This
43
+
44
+ - ❌ Artifacts may not match CLI schema versions
45
+ - ❌ Missing metadata and telemetry
46
+ - ❌ Format inconsistencies
47
+ - ❌ Validation failures
48
+ - ❌ Works only in Copilot mode, fails in CI/CD
49
+ - ❌ Breaks when CLI internals change
50
+ - ❌ Requires knowledge of internal code structure
51
+
52
+ ### Available CLI Commands for Plan Updates
53
+
54
+ **For updating features** (after enrichment):
55
+
56
+ - `specfact plan update-feature --key <key> --title <title> --outcomes <outcomes> --acceptance <acceptance> --constraints <constraints> --confidence <confidence> --draft <true/false> --plan <path>`
57
+ - Updates existing feature metadata (title, outcomes, acceptance criteria, constraints, confidence, draft status)
58
+ - Works in CI/CD, Copilot, and interactive modes
59
+ - Example: `specfact plan update-feature --key FEATURE-001 --title "New Title" --outcomes "Outcome 1, Outcome 2"`
60
+
61
+ **For adding features**:
62
+
63
+ - `specfact plan add-feature --key <key> --title <title> --outcomes <outcomes> --acceptance <acceptance> --plan <path>`
64
+
65
+ **For adding stories**:
66
+
67
+ - `specfact plan add-story --feature <feature-key> --key <story-key> --title <title> --acceptance <acceptance> --story-points <points> --value-points <points> --plan <path>`
68
+
69
+ **❌ FORBIDDEN**: Direct Python code manipulation like:
70
+
71
+ ```python
72
+ # ❌ NEVER DO THIS:
73
+ from specfact_cli.models.plan import PlanBundle, Feature
74
+ from specfact_cli.generators.plan_generator import PlanGenerator
75
+ plan_bundle.features[0].title = "New Title" # Direct manipulation
76
+ generator.generate(plan_bundle, plan_path) # Bypassing CLI
77
+ ```
78
+
79
+ **✅ CORRECT**: Use CLI commands:
80
+
81
+ ```bash
82
+ # ✅ ALWAYS DO THIS:
83
+ specfact plan update-feature --key FEATURE-001 --title "New Title" --plan <path>
84
+ ```
85
+
86
+ ## ⏸️ Wait States: User Input Required
87
+
88
+ **When user input is required, you MUST wait for the user's response.**
89
+
90
+ ### Wait State Rules
91
+
92
+ 1. **Never assume**: If input is missing, ask and wait
93
+ 2. **Never continue**: Do not proceed until user responds
94
+ 3. **Be explicit**: Clearly state what information you need
95
+ 4. **Provide options**: Give examples or default suggestions
96
+
97
+ ### Example Wait States
98
+
99
+ #### Missing Required Argument
100
+
101
+ ```text
102
+ ❌ WRONG: "Assuming --name is 'auto-derived' and continuing..."
103
+ ✅ CORRECT:
104
+ "What name would you like to use for this plan?
105
+ (e.g., 'API Client v2', 'User Authentication')
106
+ [WAIT FOR USER RESPONSE - DO NOT CONTINUE]"
107
+ ```
108
+
109
+ ## Goal
110
+
111
+ Import an existing codebase (brownfield) into a plan bundle that represents the current system using **CLI-first with LLM enrichment**. This command uses the specfact CLI for structured analysis and optionally enriches results with semantic understanding.
112
+
113
+ **Note**: This is a **one-way import** operation - it imports from repository code into SpecFact format. It does NOT analyze Spec-Kit artifacts for consistency (that's a different task).
114
+
115
+ ## Operating Constraints
116
+
117
+ **STRICTLY READ-ONLY**: Do **not** modify the codebase. All plan bundles must be generated by the specfact CLI.
118
+
119
+ **Command**: `specfact import from-code`
120
+
121
+ **Mode Auto-Detection**: The CLI automatically detects operational mode (CI/CD or CoPilot) based on environment. No need to specify `--mode` flag. Mode is detected from:
122
+
123
+ - Environment variables (`SPECFACT_MODE`)
124
+ - CoPilot API availability
125
+ - IDE integration (VS Code/Cursor with CoPilot)
126
+ - Defaults to CI/CD mode if none detected
127
+
128
+ ## 🔄 Dual-Stack Workflow (Copilot Mode)
129
+
130
+ When in copilot mode, follow this three-phase workflow:
131
+
132
+ ### Phase 1: CLI Grounding (REQUIRED)
133
+
134
+ **ALWAYS execute CLI first** to get structured, validated output:
135
+
136
+ ```bash
137
+ # Full repository analysis
138
+ specfact import from-code --repo <path> --name <name> --confidence <score>
139
+
140
+ # Partial repository analysis (analyze only specific subdirectory)
141
+ specfact import from-code --repo <path> --name <name> --entry-point <subdirectory> --confidence <score>
142
+ ```
143
+
144
+ **Note**: Mode is auto-detected by the CLI (CI/CD in non-interactive environments, CoPilot when in IDE/Copilot session). No need to specify `--mode` flag.
145
+
146
+ **Capture from CLI output**:
147
+
148
+ - CLI-generated plan bundle (`.specfact/plans/<name>-<timestamp>.bundle.yaml`)
149
+ - Analysis report (`.specfact/reports/brownfield/analysis-<timestamp>.md`)
150
+ - Metadata (timestamps, confidence scores, file paths)
151
+ - Telemetry (execution time, file counts, validation results)
152
+
153
+ ### Phase 2: LLM Enrichment (REQUIRED in Copilot Mode, OPTIONAL in CI/CD)
154
+
155
+ **⚠️ CRITICAL**: In Copilot mode, enrichment is **REQUIRED**, not optional. This is the core value of the dual-stack approach.
156
+
157
+ **Purpose**: Add semantic understanding to CLI output
158
+
159
+ **What to do**:
160
+
161
+ - Read CLI-generated plan bundle and analysis report
162
+ - Research codebase for additional context (code comments, docs, dependencies)
163
+ - Identify missing features/stories that AST analysis may have missed
164
+ - Suggest confidence score adjustments based on code quality
165
+ - Extract business context (priorities, constraints, unknowns)
166
+
167
+ **What NOT to do**:
168
+
169
+ - ❌ Create YAML/JSON artifacts directly
170
+ - ❌ Modify CLI artifacts directly
171
+ - ❌ Bypass CLI validation
172
+ - ❌ Skip enrichment in Copilot mode (this defeats the purpose of dual-stack workflow)
173
+
174
+ **Output**: Generate enrichment report (Markdown) with insights
175
+
176
+ **Enrichment Report Location**:
177
+
178
+ - Extract the plan bundle path from CLI output (e.g., `.specfact/plans/specfact-import-test.2025-11-17T12-21-48.bundle.yaml`)
179
+ - Derive enrichment report path by:
180
+ - Taking the plan bundle filename (e.g., `specfact-import-test.2025-11-17T12-21-48.bundle.yaml`)
181
+ - Replacing `.bundle.yaml` with `.enrichment.md` (e.g., `specfact-import-test.2025-11-17T12-21-48.enrichment.md`)
182
+ - Placing it in `.specfact/reports/enrichment/` directory
183
+ - Full path example: `.specfact/reports/enrichment/specfact-import-test.2025-11-17T12-21-48.enrichment.md`
184
+ - **Ensure the directory exists**: Create `.specfact/reports/enrichment/` if it doesn't exist
185
+
186
+ ### Phase 3: CLI Artifact Creation (REQUIRED)
187
+
188
+ **⚠️ CRITICAL**: If enrichment was generated in Phase 2 (which should always happen in Copilot mode), you MUST apply it via CLI using the `--enrichment` flag. Do not skip this step.
189
+
190
+ **Apply enrichments via CLI using the `--enrichment` flag**:
191
+
192
+ ```bash
193
+ # Apply enrichment report to refine the auto-detected plan bundle
194
+ specfact import from-code --repo <path> --name <name> --enrichment <enrichment-report-path>
195
+ ```
196
+
197
+ **The `--enrichment` flag**:
198
+
199
+ - Accepts a path to a Markdown enrichment report
200
+ - Applies missing features discovered by LLM
201
+ - Adjusts confidence scores for existing features
202
+ - Adds business context (priorities, constraints, unknowns)
203
+ - Validates and writes the enriched plan bundle via CLI
204
+
205
+ **Enrichment report format** (Markdown):
206
+
207
+ ```markdown
208
+ ## Missing Features
209
+
210
+ 1. **IDE Integration Feature** (Key: FEATURE-IDEINTEGRATION)
211
+ - Confidence: 0.85
212
+ - Outcomes: Enables slash command support for VS Code/Cursor
213
+ - Reason: AST missed because it's spread across multiple modules
214
+ - **Stories** (REQUIRED - at least one story per feature):
215
+ 1. **As a developer, I can use slash commands in IDE**
216
+ - Title: IDE Slash Command Support
217
+ - Acceptance:
218
+ - Slash commands are available in IDE command palette
219
+ - Commands execute specfact CLI correctly
220
+ - Tasks:
221
+ - Implement command registration
222
+ - Add command handlers
223
+ - Story Points: 5
224
+ - Value Points: 8
225
+
226
+ ## Confidence Adjustments
227
+
228
+ - FEATURE-ANALYZEAGENT → 0.95 (strong semantic understanding capabilities)
229
+ - FEATURE-SPECKITSYNC → 0.9 (well-implemented bidirectional sync)
230
+
231
+ ## Business Context
232
+
233
+ - Priority: "Core CLI tool for contract-driven development"
234
+ - Constraint: "Must support both CI/CD and Copilot modes"
235
+ ```
236
+
237
+ **Result**: Final artifacts are CLI-generated (ensures format consistency, metadata, telemetry)
238
+
239
+ ## Execution Steps
240
+
241
+ ### 1. Parse Arguments
242
+
243
+ Extract arguments from user input:
244
+
245
+ - `--repo PATH` - Repository path (default: current directory)
246
+ - `--name NAME` - Custom plan name (will be sanitized for filesystem, optional, default: "auto-derived")
247
+ - `--confidence FLOAT` - Minimum confidence score (0.0-1.0, default: 0.5)
248
+ - `--out PATH` - Output plan bundle path (optional, default: `.specfact/plans/<name>-<timestamp>.bundle.yaml`)
249
+ - `--report PATH` - Analysis report path (optional, default: `.specfact/reports/brownfield/analysis-<timestamp>.md`)
250
+ - `--shadow-only` - Observe mode without enforcing (optional)
251
+ - `--key-format {classname|sequential}` - Feature key format (default: `classname`)
252
+ - `--entry-point PATH` - Subdirectory path for partial analysis (relative to repo root). Analyzes only files within this directory and subdirectories. Useful for:
253
+ - Multi-project repositories (monorepos): Analyze one project at a time
254
+ - Large codebases: Focus on specific modules or subsystems
255
+ - Incremental modernization: Modernize one part of the codebase at a time
256
+ - Example: `--entry-point projects/api-service` analyzes only `projects/api-service/` and its subdirectories
257
+
258
+ **Important**: If `--name` is not provided, **ask the user interactively** for a meaningful plan name and **WAIT for their response**. The name will be automatically sanitized (lowercased, spaces/special chars removed) for filesystem persistence.
259
+
260
+ **WAIT STATE**: If `--name` is missing, you MUST:
261
+
262
+ 1. Ask: "What name would you like to use for this plan? (e.g., 'API Client v2', 'User Authentication', 'Payment Processing')"
263
+ 2. **STOP and WAIT** for user response
264
+ 3. **DO NOT continue** until user provides a name
265
+
266
+ For single quotes in args like "I'm Groot", use escape syntax: e.g `'I'\''m Groot'` (or double-quote if possible: `"I'm Groot"`).
267
+
268
+ ### 2. Execute CLI Grounding (REQUIRED)
269
+
270
+ **ALWAYS execute the specfact CLI first** to get structured, validated output:
271
+
272
+ ```bash
273
+ # Full repository analysis
274
+ specfact import from-code --repo <repo_path> --name <plan_name> --confidence <confidence>
275
+
276
+ # Partial repository analysis (analyze only specific subdirectory)
277
+ specfact import from-code --repo <repo_path> --name <plan_name> --entry-point <subdirectory> --confidence <confidence>
278
+ ```
279
+
280
+ **Note**: Mode is auto-detected by the CLI. No need to specify `--mode` flag.
281
+
282
+ **Capture CLI output**:
283
+
284
+ - Plan bundle path: `.specfact/plans/<name>-<timestamp>.bundle.yaml`
285
+ - Analysis report path: `.specfact/reports/brownfield/analysis-<timestamp>.md`
286
+ - Metadata: feature counts, story counts, average confidence, execution time
287
+ - **Deduplication summary**: "✓ Removed N duplicate features from plan bundle" (if duplicates were found during import)
288
+ - Any error messages or warnings
289
+
290
+ **Understanding Deduplication**:
291
+
292
+ The CLI automatically deduplicates features during import using normalized key matching. However, when importing from code, you should also review for **semantic/logical duplicates**:
293
+
294
+ 1. **Review feature titles and descriptions**: Look for features that represent the same functionality with different names
295
+ - Example: "Git Operations Manager" vs "Git Operations Handler" (both handle git operations)
296
+ - Example: "Telemetry Settings" vs "Telemetry Configuration" (both configure telemetry)
297
+ 2. **Check code coverage**: If multiple features reference the same code files/modules, they might be the same feature
298
+ 3. **Analyze class relationships**: Features derived from related classes (e.g., parent/child classes) might be duplicates
299
+ 4. **Suggest consolidation**: When semantic duplicates are found:
300
+ - Use `specfact plan update-feature` to merge information into one feature
301
+ - Use `specfact plan add-feature` to create a consolidated feature if needed
302
+ - Document which features were consolidated and why
303
+
304
+ **If CLI execution fails**:
305
+
306
+ - Report the error to the user
307
+ - Do not attempt to create artifacts manually
308
+ - Suggest fixes based on error message
309
+
310
+ ### 3. LLM Enrichment (REQUIRED in Copilot Mode, OPTIONAL in CI/CD)
311
+
312
+ **⚠️ CRITICAL**: In Copilot mode, enrichment is **REQUIRED**. Do not skip this step. This is the core value of the dual-stack workflow.
313
+
314
+ **Only if in copilot mode and CLI execution succeeded** (which should be the case when using slash commands):
315
+
316
+ 1. **Read CLI-generated artifacts**:
317
+ - Load the CLI-generated plan bundle
318
+ - Read the CLI-generated analysis report
319
+
320
+ 2. **Research codebase for semantic understanding**:
321
+ - Analyze code structure, dependencies, business logic
322
+ - Read code comments, documentation, README files
323
+ - Identify patterns that AST analysis may have missed
324
+
325
+ 3. **Generate enrichment report** (Markdown):
326
+ - Missing features discovered (not in CLI output)
327
+ - **CRITICAL**: Each missing feature MUST include at least one story
328
+ - Stories are required for features to pass promotion validation (draft → review → approved)
329
+ - CLI automatically generates stories from code methods during import
330
+ - LLM enrichment must also include stories when adding features
331
+ - Confidence score adjustments suggested
332
+ - Business context extracted (priorities, constraints, unknowns)
333
+ - Semantic insights and recommendations
334
+
335
+ 4. **Save enrichment report** to the proper location:
336
+ - Extract the plan bundle path from CLI output (e.g., `.specfact/plans/specfact-cli.2025-11-17T09-26-47.bundle.yaml`)
337
+ - Derive enrichment report path by:
338
+ - Taking the plan bundle filename (e.g., `specfact-cli.2025-11-17T09-26-47.bundle.yaml`)
339
+ - Replacing `.bundle.yaml` with `.enrichment.md` (e.g., `specfact-cli.2025-11-17T09-26-47.enrichment.md`)
340
+ - Placing it in `.specfact/reports/enrichment/` directory
341
+ - Full path example: `.specfact/reports/enrichment/specfact-cli.2025-11-17T09-26-47.enrichment.md`
342
+ - **Ensure the directory exists**: Create `.specfact/reports/enrichment/` if it doesn't exist
343
+
344
+ **What NOT to do**:
345
+
346
+ - ❌ Create YAML/JSON artifacts directly
347
+ - ❌ Modify CLI-generated plan bundle directly
348
+ - ❌ Bypass CLI validation
349
+
350
+ ### 4. CLI Artifact Creation (REQUIRED)
351
+
352
+ **Final artifacts MUST be CLI-generated**:
353
+
354
+ **If enrichment was generated**:
355
+
356
+ 1. **Save enrichment report** to the enrichment reports directory with a name that matches the plan bundle:
357
+ - Location: `.specfact/reports/enrichment/`
358
+ - Naming: Use the same name and timestamp as the plan bundle, replacing `.bundle.yaml` with `.enrichment.md`
359
+ - Example: If plan bundle is `specfact-cli.2025-11-17T09-26-47.bundle.yaml`, save enrichment as `specfact-cli.2025-11-17T09-26-47.enrichment.md`
360
+ - Full path: `.specfact/reports/enrichment/specfact-cli.2025-11-17T09-26-47.enrichment.md`
361
+
362
+ 2. **Execute CLI with `--enrichment` flag**:
363
+
364
+ ```bash
365
+ specfact import from-code --repo <repo_path> --name <plan_name> --enrichment <enrichment-report-path>
366
+ ```
367
+
368
+ 3. **The CLI will**:
369
+ - Load the original plan bundle (if it exists, derived from enrichment report path)
370
+ - Parse the enrichment report
371
+ - Apply missing features to the plan bundle
372
+ - Adjust confidence scores
373
+ - Add business context
374
+ - Validate and write the enriched plan bundle as a **new file** with clear naming:
375
+ - Format: `<name>.<original-timestamp>.enriched.<enrichment-timestamp>.bundle.yaml`
376
+ - Example: `specfact-cli.2025-11-17T09-26-47.enriched.2025-11-17T11-15-29.bundle.yaml`
377
+ - The original plan bundle remains unchanged
378
+ - The enriched plan is stored as a separate file for comparison and versioning
379
+
380
+ **If no enrichment**:
381
+
382
+ - Use CLI-generated artifacts as-is from Phase 2
383
+
384
+ **Result**: All artifacts are CLI-generated (ensures format consistency, metadata, telemetry)
385
+
386
+ **Enriched Plan Naming Convention**:
387
+
388
+ - When enrichment is applied, the CLI creates a new enriched plan bundle with a clear label
389
+ - Original plan: `<name>.<timestamp>.bundle.yaml` (e.g., `specfact-cli.2025-11-17T09-26-47.bundle.yaml`)
390
+ - Enriched plan: `<name>.<original-timestamp>.enriched.<enrichment-timestamp>.bundle.yaml` (e.g., `specfact-cli.2025-11-17T09-26-47.enriched.2025-11-17T11-15-29.bundle.yaml`)
391
+ - Both plans are stored in `.specfact/plans/` for comparison and versioning
392
+ - The original plan remains unchanged, allowing you to compare before/after enrichment
393
+
394
+ ### 5. Generate Import Report (Optional)
395
+
396
+ If `--report` is provided, generate a Markdown import report:
397
+
398
+ - Repository path and timestamp
399
+ - Confidence threshold used
400
+ - Feature/story counts and average confidence
401
+ - Detailed feature descriptions
402
+ - Recommendations and insights
403
+
404
+ ### 6. Present Results
405
+
406
+ **Present the CLI-generated plan bundle** to the user:
407
+
408
+ - **Plan bundle location**: Show where the CLI wrote the YAML file
409
+ - **Original plan** (if enrichment was applied): Show the original plan bundle path
410
+ - **Enriched plan** (if enrichment was applied): Show the enriched plan bundle path with clear naming
411
+ - **Feature summary**: List features from CLI output with confidence scores
412
+ - **Story summary**: List stories from CLI output per feature
413
+ - **CLI metadata**: Execution time, file counts, validation results
414
+ - **Enrichment insights** (if enrichment was generated): Additional findings, missing features, confidence adjustments
415
+
416
+ **Example Output**:
417
+
418
+ ```markdown
419
+ ✓ Import complete!
420
+
421
+ Original plan: specfact-cli.2025-11-17T09-26-47.bundle.yaml
422
+ Enriched plan: specfact-cli.2025-11-17T09-26-47.enriched.2025-11-17T11-15-29.bundle.yaml
423
+
424
+ CLI Analysis Results:
425
+ - Features identified: 19
426
+ - Stories extracted: 45
427
+ - Average confidence: 0.72
428
+ - Execution time: 12.3s
429
+
430
+ Features (from CLI):
431
+ - User Authentication (Confidence: 0.85)
432
+ - Payment Processing (Confidence: 0.78)
433
+ - ...
434
+
435
+ LLM Enrichment Insights (optional):
436
+ - Missing feature discovered: "User Onboarding Flow" (Confidence: 0.85)
437
+ - Confidence adjustment: "User Authentication" → 0.90 (strong test coverage)
438
+ - Business context: "Critical for user onboarding" (from code comments)
439
+ ```
440
+
441
+ ## Output Format
442
+
443
+ ### Plan Bundle Structure (Complete Example)
444
+
445
+ ```yaml
446
+ version: "1.0"
447
+ product:
448
+ themes:
449
+ - "Security"
450
+ - "User Management"
451
+ releases: []
452
+ features:
453
+ - key: "FEATURE-001"
454
+ title: "User Authentication"
455
+ outcomes:
456
+ - "Secure login"
457
+ - "Session management"
458
+ acceptance:
459
+ - "Users can log in"
460
+ - "Sessions persist"
461
+ constraints: []
462
+ confidence: 0.85
463
+ draft: false
464
+ stories:
465
+ - key: "STORY-001"
466
+ title: "Login API"
467
+ acceptance:
468
+ - "API returns JWT token"
469
+ tags: []
470
+ confidence: 0.90
471
+ draft: false
472
+ metadata:
473
+ stage: "draft"
474
+ ```
475
+
476
+ ### Import Report Structure
477
+
478
+ ```markdown
479
+ # Brownfield Import Report
480
+
481
+ **Repository**: `/path/to/repo`
482
+ **Timestamp**: `2025-11-02T12:00:00Z`
483
+ **Confidence Threshold**: `0.5`
484
+
485
+ ## Summary
486
+
487
+ - **Features Identified**: 5
488
+ - **Stories Identified**: 12
489
+ - **Average Confidence**: 0.72
490
+
491
+ ## Features
492
+
493
+ ### FEATURE-001: User Authentication (Confidence: 0.85)
494
+ ...
495
+ ```
496
+
497
+ ## Guidelines
498
+
499
+ ### CLI-First with LLM Enrichment
500
+
501
+ **Primary workflow**:
502
+
503
+ 1. **Execute CLI first**: Always run `specfact import from-code` to get structured output
504
+ 2. **Use CLI output as grounding**: Parse CLI-generated artifacts, don't regenerate them
505
+ 3. **Enrich with semantic understanding** (optional): Add insights, missing features, context
506
+ 4. **Final artifacts are CLI-generated**: Ensure format consistency and metadata
507
+
508
+ **LLM enrichment** (REQUIRED in copilot mode, optional in CI/CD):
509
+
510
+ - **In Copilot Mode**: Enrichment is REQUIRED - this is the core value of dual-stack workflow
511
+ - Read CLI-generated plan bundle and analysis report
512
+ - Research codebase for additional context
513
+ - Identify missing features/stories
514
+ - Suggest confidence adjustments
515
+ - **Review for semantic duplicates**: After automated deduplication, identify features that represent the same functionality with different names or cover the same code modules
516
+ - Extract business context
517
+ - **Always generate and save enrichment report** when in Copilot mode
518
+
519
+ **What NOT to do**:
520
+
521
+ - ❌ Create YAML/JSON artifacts directly
522
+ - ❌ Modify CLI artifacts directly
523
+ - ❌ Bypass CLI validation
524
+
525
+ ### Feature Identification
526
+
527
+ - Group related functionality into logical features (from business logic, not just structure)
528
+ - Use code organization (modules, packages) as guidance
529
+ - Prefer broader features over granular ones
530
+ - Assign meaningful titles based on code purpose and business intent
531
+
532
+ ### Feature Key Naming
533
+
534
+ - **Format**: `FEATURE-{CLASSNAME}` (e.g., `FEATURE-CONTRACTFIRSTTESTMANAGER` for class `ContractFirstTestManager`)
535
+ - **Note**: This format differs from manually created plans which may use `000_FEATURE_NAME` or `FEATURE-001` formats
536
+ - When comparing with existing plans, normalize keys by removing prefixes and underscores
537
+
538
+ ### Feature Scope
539
+
540
+ - **Auto-derived plans** only include **implemented features** from the codebase (classes that exist in source code)
541
+ - **Main plans** may include **planned features** that don't exist as classes yet
542
+ - **Expected discrepancy**: If main plan has 66 features and auto-derived has 32, this means:
543
+ - 32 features are implemented (found in codebase)
544
+ - 34 features are planned but not yet implemented
545
+
546
+ ### Confidence Scoring
547
+
548
+ - **High (0.8-1.0)**: Clear evidence from code structure, tests, and commit history
549
+ - **Medium (0.5-0.8)**: Moderate evidence from code structure or tests
550
+ - **Low (0.0-0.5)**: Weak evidence, inferred from patterns
551
+ - **Threshold**: Only include features/stories above threshold
552
+
553
+ ### Classes That Don't Generate Features
554
+
555
+ Classes are skipped if:
556
+
557
+ - Private classes (starting with `_`) or test classes (starting with `Test`)
558
+ - Confidence score < 0.5 (no docstring, no stories, or poor documentation)
559
+ - No methods can be grouped into stories (methods don't match CRUD/validation/processing patterns)
560
+
561
+ ### Error Handling
562
+
563
+ - **Missing repository**: Report error and exit
564
+ - **Invalid confidence**: Report error and use default (0.5)
565
+ - **Permission errors**: Report error and exit gracefully
566
+ - **Malformed code**: Continue with best-effort analysis
567
+ - **File write errors**: Report error and suggest manual creation
568
+
569
+ ### YAML Generation Guidelines
570
+
571
+ **When generating YAML**:
572
+
573
+ - Use proper YAML formatting (2-space indentation, no flow style)
574
+ - Preserve string quotes where needed (use `"` for strings with special characters)
575
+ - Use proper list indentation (2 spaces for lists, 4 spaces for nested items)
576
+ - Ensure all required fields are present (version, features, product)
577
+ - Use ISO 8601 timestamp format for filenames: `YYYY-MM-DDTHH-MM-SS`
578
+
579
+ **Plan Bundle Structure**:
580
+
581
+ - Must include `version: "1.0"`
582
+ - Must include `product` with at least `themes: []` and `releases: []`
583
+ - Must include `features: []` (can be empty if no features found)
584
+ - Optional: `idea`, `business`, `metadata`
585
+ - Each feature must have `key`, `title`, `confidence`, `draft`
586
+ - Each story must have `key`, `title`, `confidence`, `draft`
587
+
588
+ ## Expected Behavior
589
+
590
+ **This command imports features from existing code, not planned features.**
591
+
592
+ When comparing imported plans with main plans:
593
+
594
+ - **Imported plans** contain only **implemented features** (classes that exist in the codebase)
595
+ - **Main plans** may contain **planned features** (features that don't exist as classes yet)
596
+ - **Key naming difference**: Imported plans use `FEATURE-CLASSNAME`, main plans may use `000_FEATURE_NAME` or `FEATURE-001`
597
+
598
+ To compare plans, normalize feature keys by removing prefixes and underscores, then match by normalized key.
599
+
600
+ **Important**: This is a **one-way import** - it imports from code into SpecFact format. It does NOT perform consistency checking on Spec-Kit artifacts. For Spec-Kit artifact consistency checking, use Spec-Kit's `/speckit.analyze` command instead.
601
+
602
+ ## Constitution Bootstrap (Optional)
603
+
604
+ After a brownfield import, the CLI may suggest generating a bootstrap constitution for Spec-Kit integration:
605
+
606
+ **If constitution is missing or minimal**:
607
+
608
+ - The CLI will suggest: "Generate bootstrap constitution from repository analysis?"
609
+ - **Recommended**: Accept the suggestion to auto-generate a constitution from your repository
610
+ - **Command**: `specfact constitution bootstrap --repo .`
611
+ - **What it does**: Analyzes your repository (README.md, pyproject.toml, .cursor/rules/, docs/rules/) and generates a bootstrap constitution
612
+ - **Next steps**: Review the generated constitution, then run `specfact sync spec-kit` to sync with Spec-Kit artifacts
613
+
614
+ **If you decline the suggestion**:
615
+
616
+ - You can run `specfact constitution bootstrap --repo .` manually later
617
+ - Or use `/speckit.constitution` command in your AI assistant for manual creation
618
+
619
+ **Validation**:
620
+
621
+ - After generating or updating the constitution, run `specfact constitution validate` to check completeness
622
+ - The constitution must be populated (not just template placeholders) before syncing with Spec-Kit
623
+
624
+ ## Context
625
+
626
+ {ARGS}