specfact-cli 0.51.1__py3-none-any.whl → 0.53.2__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.
specfact_cli/__init__.py CHANGED
@@ -76,6 +76,6 @@ def _install_progressive_disclosure() -> None:
76
76
  # keeps missing-command and missing-parameter UX consistent outside the root CLI too.
77
77
  _install_progressive_disclosure()
78
78
 
79
- __version__ = "0.51.1"
79
+ __version__ = "0.53.2"
80
80
 
81
81
  __all__ = ["__version__"]
@@ -10,8 +10,10 @@ from specfact_cli.requirements.context import (
10
10
  inspect_requirement_context_coverage,
11
11
  load_requirements_from_bundle,
12
12
  normalize_requirement_records,
13
+ requires_native_openspec_validation,
13
14
  validate_requirement_context,
14
15
  )
16
+ from specfact_cli.requirements.importers import import_openspec_change, import_speckit_feature
15
17
 
16
18
 
17
19
  __all__ = [
@@ -21,8 +23,11 @@ __all__ = [
21
23
  "RequirementContextDiagnosticSeverity",
22
24
  "RequirementContextImportResult",
23
25
  "attach_requirements_to_bundle",
26
+ "import_openspec_change",
27
+ "import_speckit_feature",
24
28
  "inspect_requirement_context_coverage",
25
29
  "load_requirements_from_bundle",
26
30
  "normalize_requirement_records",
31
+ "requires_native_openspec_validation",
27
32
  "validate_requirement_context",
28
33
  ]
@@ -2,11 +2,13 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import hashlib
5
6
  from collections.abc import Mapping, Sequence
6
7
  from enum import StrEnum
7
8
  from pathlib import Path
8
9
  from typing import Any, Literal, Protocol, cast, get_args
9
10
 
11
+ import yaml
10
12
  from beartype import beartype
11
13
  from icontract import ensure, require
12
14
  from pydantic import BaseModel, ConfigDict, Field, ValidationError
@@ -15,10 +17,12 @@ from specfact_cli.models.project import ProjectBundle
15
17
  from specfact_cli.models.requirements import (
16
18
  RequirementEvidenceLinkType,
17
19
  RequirementInput,
20
+ RequirementSourceType,
18
21
  load_requirements_input_extension,
19
22
  requirements_input_extension_payload,
20
23
  )
21
24
  from specfact_cli.models.validation import ValidationReport
25
+ from specfact_cli.modules.init.src.first_run_selection import resolve_profile_config
22
26
 
23
27
 
24
28
  RequirementContextValidationProfile = Literal[
@@ -26,6 +30,7 @@ RequirementContextValidationProfile = Literal[
26
30
  "startup",
27
31
  "team",
28
32
  "enterprise",
33
+ "mid_size",
29
34
  "strict",
30
35
  "solo_developer",
31
36
  "api_first_team",
@@ -33,6 +38,19 @@ RequirementContextValidationProfile = Literal[
33
38
  ]
34
39
  KNOWN_REQUIREMENT_CONTEXT_PROFILES: frozenset[str] = frozenset(get_args(RequirementContextValidationProfile))
35
40
  STRICT_REQUIREMENT_CONTEXT_PROFILES: frozenset[str] = frozenset({"enterprise", "strict", "enterprise_full_stack"})
41
+ _PROFILE_RESOLUTION_ALIASES: dict[str, str] = {
42
+ "api_first_team": "mid_size",
43
+ "enterprise_full_stack": "enterprise",
44
+ "solo_developer": "solo",
45
+ "strict": "enterprise",
46
+ "team": "mid_size",
47
+ }
48
+ _REQUIRED_FIELD_ALIASES: dict[str, str] = {
49
+ "id": "requirement_id",
50
+ "title": "title",
51
+ "acceptance": "business_rules",
52
+ "trace_links": "evidence_links",
53
+ }
36
54
 
37
55
 
38
56
  class RequirementContextDiagnosticSeverity(StrEnum):
@@ -131,16 +149,101 @@ def _optional_text(value: str | None) -> str | None:
131
149
  return value
132
150
 
133
151
 
134
- def _profile_nonempty(profile: str) -> bool:
135
- return profile.strip() != ""
152
+ def _source_locator_supported(source_locator: str | None) -> bool:
153
+ return source_locator is None or type(source_locator) is str
136
154
 
137
155
 
138
- def _profile_supported(profile: str) -> bool:
139
- return profile in KNOWN_REQUIREMENT_CONTEXT_PROFILES
156
+ def _optional_profile_supported(profile: str | None) -> bool:
157
+ return profile is None or (profile.strip() != "" and profile in KNOWN_REQUIREMENT_CONTEXT_PROFILES)
140
158
 
141
159
 
142
- def _source_locator_supported(source_locator: str | None) -> bool:
143
- return source_locator is None or type(source_locator) is str
160
+ def _project_root_supported(project_root: Path | None) -> bool:
161
+ return project_root is None or isinstance(project_root, Path)
162
+
163
+
164
+ def _read_config_mapping(path: Path) -> dict[str, Any]:
165
+ try:
166
+ if not path.is_file():
167
+ return {}
168
+ raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
169
+ except (OSError, UnicodeDecodeError, yaml.YAMLError):
170
+ return {}
171
+ return raw if isinstance(raw, dict) else {}
172
+
173
+
174
+ def _without_profile_derived_values(layer: Mapping[str, Any]) -> dict[str, Any]:
175
+ return {key: value for key, value in layer.items() if key not in {"profile", "requirements_schema"}}
176
+
177
+
178
+ def _configured_profile(*layers: Mapping[str, object]) -> str:
179
+ for layer in layers:
180
+ profile = layer.get("profile")
181
+ if isinstance(profile, str) and profile in KNOWN_REQUIREMENT_CONTEXT_PROFILES:
182
+ return profile
183
+ return "startup"
184
+
185
+
186
+ def _requirements_schema_fields(values: Mapping[str, Any]) -> list[str]:
187
+ schema = values.get("requirements_schema")
188
+ if not isinstance(schema, Mapping):
189
+ return []
190
+ fields = cast(Mapping[str, object], schema).get("required_fields")
191
+ return [field for field in fields if isinstance(field, str)] if isinstance(fields, list) else []
192
+
193
+
194
+ def _resolve_requirement_profile(
195
+ profile: RequirementContextValidationProfile | None,
196
+ project_root: Path | None,
197
+ ) -> tuple[str, dict[str, Any]]:
198
+ root = project_root or Path.cwd()
199
+ org_baseline = _read_config_mapping(Path.home() / ".specfact" / "config.yaml")
200
+ repo_overlay = _read_config_mapping(root / ".specfact" / "config.yaml")
201
+ developer_local = _read_config_mapping(root / ".specfact" / "config.local.yaml")
202
+ configured = _configured_profile(developer_local, repo_overlay, org_baseline)
203
+ effective_profile = profile or configured
204
+ resolver_profile = _PROFILE_RESOLUTION_ALIASES.get(effective_profile, effective_profile)
205
+ if profile is not None:
206
+ org_baseline = _without_profile_derived_values(org_baseline)
207
+ repo_overlay = _without_profile_derived_values(repo_overlay)
208
+ developer_local = _without_profile_derived_values(developer_local)
209
+ resolved = resolve_profile_config(
210
+ resolver_profile,
211
+ org_baseline=org_baseline,
212
+ repo_overlay=repo_overlay,
213
+ developer_local=developer_local,
214
+ )
215
+ return effective_profile, resolved.values
216
+
217
+
218
+ @beartype
219
+ @require(_optional_profile_supported, "profile must be a supported requirements profile when provided")
220
+ @require(_project_root_supported, "project_root must be a Path when provided")
221
+ @ensure(lambda result: isinstance(result, bool), "result must be a boolean")
222
+ def requires_native_openspec_validation(
223
+ *,
224
+ profile: RequirementContextValidationProfile | None = None,
225
+ project_root: Path | None = None,
226
+ ) -> bool:
227
+ """Return whether layered policy requires native OpenSpec validation."""
228
+ effective_profile, resolved_config = _resolve_requirement_profile(profile, project_root)
229
+ validation_tier = _PROFILE_RESOLUTION_ALIASES.get(effective_profile, effective_profile)
230
+ validation_value = resolved_config.get("validation")
231
+ if not isinstance(validation_value, Mapping):
232
+ return validation_tier == "enterprise"
233
+ validation = cast(Mapping[str, object], validation_value)
234
+ openspec_value = validation.get("openspec")
235
+ if not isinstance(openspec_value, Mapping):
236
+ return validation_tier == "enterprise"
237
+ openspec = cast(Mapping[str, object], openspec_value)
238
+ configured = openspec.get("require_native_validation")
239
+ return configured if isinstance(configured, bool) else validation_tier == "enterprise"
240
+
241
+
242
+ def _is_imported_requirement(requirement: RequirementInput) -> bool:
243
+ return any(
244
+ source.source_type in {RequirementSourceType.OPENSPEC_CHANGE, RequirementSourceType.SPECKIT_SPEC}
245
+ for source in requirement.sources
246
+ )
144
247
 
145
248
 
146
249
  def _coverage_summary_consistent(result: RequirementContextCoverageSummary) -> bool:
@@ -274,6 +377,7 @@ def _missing_evidence_violations(
274
377
  ) -> list[dict[str, str]]:
275
378
  return [
276
379
  {
380
+ "code": "missing-evidence",
277
381
  "severity": severity,
278
382
  "message": "Requirement input has no downstream evidence links.",
279
383
  "location": f"requirements.inputs[{requirement_id}].evidence_links",
@@ -282,6 +386,142 @@ def _missing_evidence_violations(
282
386
  ]
283
387
 
284
388
 
389
+ def _scenario_unverified_violation(requirement: RequirementInput, *, severity: str) -> dict[str, str] | None:
390
+ if not requirement.business_rules or any(
391
+ link.link_type in {RequirementEvidenceLinkType.TEST, RequirementEvidenceLinkType.VALIDATION}
392
+ for link in requirement.evidence_links
393
+ ):
394
+ return None
395
+ rule_ids = ", ".join(rule.rule_id for rule in requirement.business_rules)
396
+ return {
397
+ "code": "scenario-unverified",
398
+ "severity": severity,
399
+ "message": f"Imported scenarios have no test or validation evidence links: {rule_ids}.",
400
+ "location": f"requirements.inputs[{requirement.requirement_id}].business_rules",
401
+ }
402
+
403
+
404
+ def _source_integrity_violations(
405
+ requirement: RequirementInput,
406
+ *,
407
+ severity: str,
408
+ project_root: Path,
409
+ ) -> list[dict[str, str]]:
410
+ violations: list[dict[str, str]] = []
411
+ for source in requirement.sources:
412
+ if source.source_type not in {RequirementSourceType.OPENSPEC_CHANGE, RequirementSourceType.SPECKIT_SPEC}:
413
+ continue
414
+ source_path = Path(source.locator)
415
+ if not source_path.is_absolute():
416
+ source_path = project_root / source_path
417
+ if not source_path.is_file():
418
+ violations.append(
419
+ {
420
+ "code": "source-missing",
421
+ "severity": severity,
422
+ "message": "Imported source artifact no longer exists.",
423
+ "location": source.locator,
424
+ }
425
+ )
426
+ continue
427
+ if source.revision and source.revision.startswith("sha256:"):
428
+ current_revision = f"sha256:{hashlib.sha256(source_path.read_bytes()).hexdigest()}"
429
+ if current_revision != source.revision:
430
+ violations.append(
431
+ {
432
+ "code": "stale-import",
433
+ "severity": severity,
434
+ "message": "Imported source artifact content changed after import.",
435
+ "location": source.locator,
436
+ }
437
+ )
438
+ return violations
439
+
440
+
441
+ def _ambiguous_mapping_violations(identities: Mapping[str, set[str]], *, severity: str) -> list[dict[str, str]]:
442
+ return [
443
+ {
444
+ "code": "ambiguous-mapping",
445
+ "severity": severity,
446
+ "message": "Multiple imported sources claim the same requirement identity.",
447
+ "location": f"requirements.inputs[{requirement_id}]",
448
+ }
449
+ for requirement_id, locators in identities.items()
450
+ if len(locators) > 1
451
+ ]
452
+
453
+
454
+ def _import_gate_violations(
455
+ requirements: Sequence[RequirementInput],
456
+ *,
457
+ severity: str,
458
+ project_root: Path,
459
+ ) -> list[dict[str, str]]:
460
+ violations: list[dict[str, str]] = []
461
+ identities: dict[str, set[str]] = {}
462
+ for requirement in requirements:
463
+ if not _is_imported_requirement(requirement):
464
+ continue
465
+ identities.setdefault(requirement.requirement_id, set()).update(
466
+ source.locator
467
+ for source in requirement.sources
468
+ if source.source_type
469
+ in {
470
+ RequirementSourceType.OPENSPEC_CHANGE,
471
+ RequirementSourceType.SPECKIT_SPEC,
472
+ }
473
+ )
474
+ scenario_violation = _scenario_unverified_violation(requirement, severity=severity)
475
+ if scenario_violation:
476
+ violations.append(scenario_violation)
477
+ violations.extend(
478
+ _source_integrity_violations(
479
+ requirement,
480
+ severity=severity,
481
+ project_root=project_root,
482
+ )
483
+ )
484
+ violations.extend(_ambiguous_mapping_violations(identities, severity=severity))
485
+ return violations
486
+
487
+
488
+ def _required_field_violations(
489
+ requirements: Sequence[RequirementInput],
490
+ required_fields: Sequence[str],
491
+ *,
492
+ severity: str,
493
+ ) -> list[dict[str, str]]:
494
+ imported_requirements = [requirement for requirement in requirements if _is_imported_requirement(requirement)]
495
+ if not imported_requirements:
496
+ return []
497
+
498
+ violations: list[dict[str, str]] = []
499
+ for field in required_fields:
500
+ attribute = _REQUIRED_FIELD_ALIASES.get(field)
501
+ if attribute is None:
502
+ violations.append(
503
+ {
504
+ "code": "unsupported-profile-field",
505
+ "severity": "info",
506
+ "message": "Profile field is not represented by the import-first requirements evidence schema.",
507
+ "location": f"requirements_schema.required_fields[{field}]",
508
+ }
509
+ )
510
+ continue
511
+ for requirement in imported_requirements:
512
+ value = getattr(requirement, attribute)
513
+ if not value:
514
+ violations.append(
515
+ {
516
+ "code": "required-field-missing",
517
+ "severity": severity,
518
+ "message": f"Required evidence field '{field}' is missing.",
519
+ "location": f"requirements.inputs[{requirement.requirement_id}].{attribute}",
520
+ }
521
+ )
522
+ return violations
523
+
524
+
285
525
  def _validation_status(failed: int, warnings: int) -> Literal["passed", "failed", "warnings"]:
286
526
  if failed:
287
527
  return "failed"
@@ -307,21 +547,40 @@ def _validation_summary(
307
547
 
308
548
  @beartype
309
549
  @require(lambda bundle: isinstance(bundle, ProjectBundle), "bundle must be a ProjectBundle")
310
- @require(_profile_nonempty, "profile must not be empty")
311
- @require(_profile_supported, "profile must be a supported requirements context validation profile")
550
+ @require(
551
+ _optional_profile_supported, "profile must be a supported requirements context validation profile when provided"
552
+ )
553
+ @require(_project_root_supported, "project_root must be a Path when provided")
312
554
  @ensure(lambda result: isinstance(result, ValidationReport))
313
555
  def validate_requirement_context(
314
556
  bundle: ProjectBundle,
315
557
  *,
316
- profile: RequirementContextValidationProfile = "startup",
558
+ profile: RequirementContextValidationProfile | None = None,
559
+ project_root: Path | None = None,
317
560
  ) -> ValidationReport:
318
561
  """Validate requirements context evidence usefulness for a ProjectBundle."""
319
562
  requirements = load_requirements_from_bundle(bundle)
320
563
  if not requirements:
321
564
  return _empty_requirements_report()
322
565
 
566
+ effective_profile, resolved_config = _resolve_requirement_profile(profile, project_root)
567
+ severity = _missing_evidence_severity(cast(RequirementContextValidationProfile, effective_profile))
323
568
  coverage = inspect_requirement_context_coverage(requirements)
324
- violations = _missing_evidence_violations(coverage, severity=_missing_evidence_severity(profile))
569
+ violations = _missing_evidence_violations(coverage, severity=severity)
570
+ violations.extend(
571
+ _import_gate_violations(
572
+ requirements,
573
+ severity=severity,
574
+ project_root=project_root or Path.cwd(),
575
+ )
576
+ )
577
+ violations.extend(
578
+ _required_field_violations(
579
+ requirements,
580
+ _requirements_schema_fields(resolved_config),
581
+ severity=severity,
582
+ )
583
+ )
325
584
  summary = _validation_summary(requirements, coverage, violations)
326
585
  return ValidationReport(
327
586
  status=_validation_status(summary["failed"], summary["warnings"]),
@@ -0,0 +1,532 @@
1
+ """Read-only normalizers for native OpenSpec and Spec Kit requirement evidence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ import subprocess
9
+ from pathlib import Path
10
+ from typing import cast
11
+
12
+ import yaml
13
+ from beartype import beartype
14
+ from icontract import ensure, require
15
+
16
+ from specfact_cli.adapters.openspec_parser import OpenSpecParser
17
+ from specfact_cli.importers.speckit_scanner import SpecKitScanner
18
+ from specfact_cli.models.requirements import (
19
+ BusinessRule,
20
+ RequirementInput,
21
+ RequirementSourceReference,
22
+ RequirementSourceType,
23
+ )
24
+ from specfact_cli.requirements.context import (
25
+ RequirementContextDiagnostic,
26
+ RequirementContextDiagnosticSeverity,
27
+ RequirementContextImportResult,
28
+ RequirementContextValidationProfile,
29
+ requires_native_openspec_validation,
30
+ )
31
+
32
+
33
+ _DEFAULT_OPENSPEC_SCHEMA = "spec-driven"
34
+ _OPENSPEC_REQUIREMENT_PATTERN = re.compile(r"^### Requirement:\s+.+$", re.MULTILINE)
35
+ _OPENSPEC_SCENARIO_PATTERN = re.compile(r"^#### Scenario:\s+.+$", re.MULTILINE)
36
+ _SPECKIT_TITLE_PATTERN = re.compile(r"^# Feature Specification:\s+.+$", re.MULTILINE)
37
+ _SPECKIT_REQUIREMENT_PATTERN = re.compile(r"^\s*-?\s*\*\*FR-\d+\*\*:\s*System MUST\s+(?P<text>.+?)\s*$", re.MULTILINE)
38
+ _SPECKIT_CUSTOMIZATION_ROOTS = (
39
+ Path(".specify/templates/overrides"),
40
+ Path(".specify/presets"),
41
+ Path(".specify/extensions"),
42
+ )
43
+ _OPENSPEC_VALIDATOR_TIMEOUT_SECONDS = 10
44
+ _SPECKIT_TEMPLATE_MARKERS = (
45
+ "# Feature Specification: [FEATURE NAME]",
46
+ "**Feature Branch**: `[###-feature-name]`",
47
+ '**Input**: User description: "$ARGUMENTS"',
48
+ "### User Story 1 - [Brief Title] (Priority: P1)",
49
+ "[Describe this user journey in plain language]",
50
+ "- **FR-001**: System MUST [specific capability,",
51
+ )
52
+ _SPECKIT_NEEDS_CLARIFICATION_MARKER = "[NEEDS CLARIFICATION:"
53
+ _SPECKIT_USER_STORY_PATTERN = re.compile(r"^### User Story\s+\d+\s+-\s+.+$", re.MULTILINE)
54
+ _SPECKIT_SECTION_PATTERN = re.compile(r"^#{1,3}\s+", re.MULTILINE)
55
+
56
+
57
+ def _slug(value: str) -> str:
58
+ return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", value.lower())).strip("-") or "requirement"
59
+
60
+
61
+ def _unique_requirement_id(base_id: str, seen_ids: set[str]) -> str:
62
+ candidate = base_id
63
+ ordinal = 2
64
+ while candidate in seen_ids:
65
+ candidate = f"{base_id}-{ordinal}"
66
+ ordinal += 1
67
+ seen_ids.add(candidate)
68
+ return candidate
69
+
70
+
71
+ def _source_revision(path: Path) -> str:
72
+ return f"sha256:{hashlib.sha256(path.read_bytes()).hexdigest()}"
73
+
74
+
75
+ def _scenario_rules(requirement_id: str, content: str) -> list[BusinessRule]:
76
+ rules: list[BusinessRule] = []
77
+ scenario_pattern = re.compile(
78
+ r"^#### Scenario:\s*(.+?)\n(.*?)(?=^#### Scenario:|^### Requirement:|\Z)",
79
+ re.MULTILINE | re.DOTALL,
80
+ )
81
+ for match in scenario_pattern.finditer(content):
82
+ name = match.group(1).strip()
83
+ body = match.group(2)
84
+ clauses: dict[str, str] = {}
85
+ for clause in ("given", "when", "then"):
86
+ clause_match = re.search(
87
+ rf"^- \*\*{clause.upper()}\*\*\s+([^\n]+(?:\n[ \t]+[^\n]+)*)",
88
+ body,
89
+ re.MULTILINE | re.IGNORECASE,
90
+ )
91
+ if clause_match:
92
+ clauses[clause] = " ".join(clause_match.group(1).split())
93
+ if len(clauses) == 3:
94
+ rules.append(
95
+ BusinessRule(
96
+ rule_id=f"{requirement_id}:{_slug(name)}",
97
+ name=name,
98
+ given=clauses["given"],
99
+ when=clauses["when"],
100
+ then=clauses["then"],
101
+ )
102
+ )
103
+ return rules
104
+
105
+
106
+ def _speckit_user_story_blocks(content: str) -> list[str]:
107
+ """Return the content of explicitly headed Spec Kit user stories."""
108
+ matches = list(_SPECKIT_USER_STORY_PATTERN.finditer(content))
109
+ blocks: list[str] = []
110
+ for match in matches:
111
+ following_section = _SPECKIT_SECTION_PATTERN.search(content, match.end())
112
+ end = following_section.start() if following_section else len(content)
113
+ blocks.append(content[match.start() : end])
114
+ return blocks
115
+
116
+
117
+ def _speckit_has_substantive_requirement(content: str) -> bool:
118
+ """Return whether a supported FR entry contains completed, non-template text."""
119
+ return any(
120
+ "[" not in match.group("text") and "]" not in match.group("text")
121
+ for match in _SPECKIT_REQUIREMENT_PATTERN.finditer(content)
122
+ )
123
+
124
+
125
+ def _speckit_rules(
126
+ requirement_id: str,
127
+ content: str,
128
+ *,
129
+ source_requirement_id: str | None = None,
130
+ ) -> list[BusinessRule]:
131
+ rules: list[BusinessRule] = []
132
+ pattern = re.compile(
133
+ r"\*\*Given\*\*\s+(.+?),\s*\*\*When\*\*\s+(.+?),\s*\*\*Then\*\*\s+(.+?)(?=\n|$)",
134
+ re.IGNORECASE,
135
+ )
136
+ story_blocks = _speckit_user_story_blocks(content)
137
+ if source_requirement_id is not None:
138
+ story_blocks = [
139
+ block
140
+ for block in story_blocks
141
+ if re.search(rf"\b{re.escape(source_requirement_id)}\b", block, re.IGNORECASE)
142
+ ]
143
+ story_content = "\n".join(story_blocks)
144
+ for index, match in enumerate(pattern.finditer(story_content), start=1):
145
+ rules.append(
146
+ BusinessRule(
147
+ rule_id=f"{requirement_id}:scenario-{index}",
148
+ name=f"Acceptance scenario {index}",
149
+ given=match.group(1).strip(),
150
+ when=match.group(2).strip(),
151
+ then=match.group(3).strip(),
152
+ )
153
+ )
154
+ return rules
155
+
156
+
157
+ def _missing_source_result(source: Path, source_type: RequirementSourceType) -> RequirementContextImportResult:
158
+ return RequirementContextImportResult(
159
+ diagnostics=[
160
+ RequirementContextDiagnostic(
161
+ severity=RequirementContextDiagnosticSeverity.ERROR,
162
+ code="source-missing",
163
+ message=f"Required {source_type.value} source does not exist.",
164
+ source_locator=str(source),
165
+ )
166
+ ]
167
+ )
168
+
169
+
170
+ def _unsupported_source_result(
171
+ source: Path,
172
+ source_type: RequirementSourceType,
173
+ message: str,
174
+ ) -> RequirementContextImportResult:
175
+ return RequirementContextImportResult(
176
+ diagnostics=[
177
+ RequirementContextDiagnostic(
178
+ severity=RequirementContextDiagnosticSeverity.ERROR,
179
+ code="unsupported-source-schema",
180
+ message=message,
181
+ source_locator=str(source),
182
+ )
183
+ ]
184
+ )
185
+
186
+
187
+ def _readiness_error_result(
188
+ source: Path,
189
+ source_type: RequirementSourceType,
190
+ code: str,
191
+ message: str,
192
+ ) -> RequirementContextImportResult:
193
+ return RequirementContextImportResult(
194
+ diagnostics=[
195
+ RequirementContextDiagnostic(
196
+ severity=RequirementContextDiagnosticSeverity.ERROR,
197
+ code=code,
198
+ message=message,
199
+ source_locator=str(source),
200
+ )
201
+ ]
202
+ )
203
+
204
+
205
+ def _load_schema_name(path: Path) -> str | None:
206
+ try:
207
+ if not path.is_file():
208
+ return None
209
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
210
+ except (OSError, UnicodeDecodeError, yaml.YAMLError):
211
+ return "<invalid>"
212
+ if not isinstance(data, dict):
213
+ return "<invalid>"
214
+ schema = cast(dict[str, object], data).get("schema")
215
+ return "<invalid>" if "schema" in data and not isinstance(schema, str) else cast(str | None, schema)
216
+
217
+
218
+ def _openspec_compatibility_error(change_dir: Path, spec_paths: list[Path]) -> RequirementContextImportResult | None:
219
+ config_paths = (change_dir.parent.parent / "config.yaml", change_dir / ".openspec.yaml")
220
+ for config_path in config_paths:
221
+ schema = _load_schema_name(config_path)
222
+ if schema is not None and schema != _DEFAULT_OPENSPEC_SCHEMA:
223
+ return _unsupported_source_result(
224
+ config_path,
225
+ RequirementSourceType.OPENSPEC_CHANGE,
226
+ "OpenSpec schema is not supported by the default evidence import profile.",
227
+ )
228
+ if not spec_paths:
229
+ return _unsupported_source_result(
230
+ change_dir,
231
+ RequirementSourceType.OPENSPEC_CHANGE,
232
+ "OpenSpec change has no default-profile spec.md artifact to import.",
233
+ )
234
+ for spec_path in spec_paths:
235
+ try:
236
+ content = spec_path.read_text(encoding="utf-8")
237
+ except (OSError, UnicodeDecodeError):
238
+ return _unsupported_source_result(
239
+ spec_path,
240
+ RequirementSourceType.OPENSPEC_CHANGE,
241
+ "OpenSpec artifact cannot be read as UTF-8 under the default evidence import profile.",
242
+ )
243
+ if not (_OPENSPEC_REQUIREMENT_PATTERN.search(content) and _OPENSPEC_SCENARIO_PATTERN.search(content)):
244
+ return _unsupported_source_result(
245
+ spec_path,
246
+ RequirementSourceType.OPENSPEC_CHANGE,
247
+ "OpenSpec artifact does not match the supported default requirement/scenario Markdown profile.",
248
+ )
249
+ return None
250
+
251
+
252
+ def _speckit_project_root(feature_dir: Path) -> Path | None:
253
+ for directory in (feature_dir.parent, *feature_dir.parents):
254
+ if (directory / ".specify").is_dir():
255
+ return directory
256
+ return None
257
+
258
+
259
+ def _speckit_compatibility_error(
260
+ feature_dir: Path, spec_path: Path, content: str
261
+ ) -> RequirementContextImportResult | None:
262
+ project_root = _speckit_project_root(feature_dir)
263
+ if project_root:
264
+ for customization_root in _SPECKIT_CUSTOMIZATION_ROOTS:
265
+ path = project_root / customization_root
266
+ if path.exists():
267
+ return _unsupported_source_result(
268
+ path,
269
+ RequirementSourceType.SPECKIT_SPEC,
270
+ "Spec Kit template customization is not supported by the default evidence import profile.",
271
+ )
272
+ if not (_SPECKIT_TITLE_PATTERN.search(content) and _SPECKIT_REQUIREMENT_PATTERN.search(content)):
273
+ return _unsupported_source_result(
274
+ spec_path,
275
+ RequirementSourceType.SPECKIT_SPEC,
276
+ "Spec Kit artifact does not match the supported default Markdown template profile.",
277
+ )
278
+ return None
279
+
280
+
281
+ def _speckit_readiness_error(spec_path: Path, content: str) -> RequirementContextImportResult | None:
282
+ if not _SPECKIT_TITLE_PATTERN.search(content):
283
+ return None
284
+ if any(marker in content for marker in _SPECKIT_TEMPLATE_MARKERS) or _SPECKIT_NEEDS_CLARIFICATION_MARKER in content:
285
+ return _readiness_error_result(
286
+ spec_path,
287
+ RequirementSourceType.SPECKIT_SPEC,
288
+ "incomplete-source-template",
289
+ "Spec Kit source still contains a supported official scaffold placeholder.",
290
+ )
291
+ if not _speckit_has_substantive_requirement(content):
292
+ return _readiness_error_result(
293
+ spec_path,
294
+ RequirementSourceType.SPECKIT_SPEC,
295
+ "source-incomplete",
296
+ "Spec Kit source has no substantive Functional Requirement.",
297
+ )
298
+ if not _speckit_rules("readiness", content):
299
+ return _readiness_error_result(
300
+ spec_path,
301
+ RequirementSourceType.SPECKIT_SPEC,
302
+ "source-incomplete",
303
+ "Spec Kit source has no recognized user-story acceptance scenario.",
304
+ )
305
+ return None
306
+
307
+
308
+ def _openspec_native_validation_error(
309
+ change_dir: Path,
310
+ *,
311
+ profile: RequirementContextValidationProfile | None,
312
+ project_root: Path | None,
313
+ ) -> RequirementContextImportResult | None:
314
+ if not requires_native_openspec_validation(profile=profile, project_root=project_root):
315
+ return None
316
+ try:
317
+ completed = subprocess.run(
318
+ ["openspec", "validate", change_dir.name, "--strict", "--json"],
319
+ cwd=change_dir.parents[2],
320
+ capture_output=True,
321
+ check=False,
322
+ text=True,
323
+ timeout=_OPENSPEC_VALIDATOR_TIMEOUT_SECONDS,
324
+ )
325
+ except FileNotFoundError:
326
+ return _readiness_error_result(
327
+ change_dir,
328
+ RequirementSourceType.OPENSPEC_CHANGE,
329
+ "upstream-validator-unavailable",
330
+ "Required native OpenSpec validator is unavailable.",
331
+ )
332
+ except (OSError, subprocess.TimeoutExpired):
333
+ return _readiness_error_result(
334
+ change_dir,
335
+ RequirementSourceType.OPENSPEC_CHANGE,
336
+ "source-invalid",
337
+ "Required native OpenSpec validation did not complete successfully.",
338
+ )
339
+ try:
340
+ payload = json.loads(completed.stdout)
341
+ except json.JSONDecodeError:
342
+ payload = None
343
+ if completed.returncode != 0 or not _native_openspec_result_valid(payload, change_dir.name):
344
+ return _readiness_error_result(
345
+ change_dir,
346
+ RequirementSourceType.OPENSPEC_CHANGE,
347
+ "source-invalid",
348
+ "Required native OpenSpec validation reported the source invalid.",
349
+ )
350
+ return None
351
+
352
+
353
+ def _native_openspec_result_valid(payload: object, change_name: str) -> bool:
354
+ if not isinstance(payload, dict):
355
+ return False
356
+ result = cast(dict[str, object], payload)
357
+ items = result.get("items")
358
+ if not isinstance(items, list):
359
+ return False
360
+ return any(
361
+ isinstance(item, dict)
362
+ and cast(dict[str, object], item).get("id") == change_name
363
+ and cast(dict[str, object], item).get("valid") is True
364
+ for item in items
365
+ )
366
+
367
+
368
+ def _import_result_has_requirements(result: RequirementContextImportResult) -> bool:
369
+ return all(isinstance(record, RequirementInput) for record in result.requirements)
370
+
371
+
372
+ @require(lambda change_dir: isinstance(change_dir, Path), "change_dir must be a Path")
373
+ @require(lambda profile: profile is None or isinstance(profile, str), "profile must be text when provided")
374
+ @require(
375
+ lambda project_root: project_root is None or isinstance(project_root, Path),
376
+ "project_root must be a Path when provided",
377
+ )
378
+ @ensure(_import_result_has_requirements)
379
+ @beartype
380
+ def import_openspec_change(
381
+ change_dir: Path,
382
+ *,
383
+ profile: RequirementContextValidationProfile | None = None,
384
+ project_root: Path | None = None,
385
+ ) -> RequirementContextImportResult:
386
+ """Normalize one native OpenSpec change directory without modifying it."""
387
+ if not change_dir.is_dir():
388
+ return _missing_source_result(change_dir, RequirementSourceType.OPENSPEC_CHANGE)
389
+
390
+ native_validation_error = _openspec_native_validation_error(
391
+ change_dir,
392
+ profile=profile,
393
+ project_root=project_root,
394
+ )
395
+ if native_validation_error:
396
+ return native_validation_error
397
+
398
+ spec_paths = sorted((change_dir / "specs").glob("*/spec.md"))
399
+ compatibility_error = _openspec_compatibility_error(change_dir, spec_paths)
400
+ if compatibility_error:
401
+ return compatibility_error
402
+
403
+ parser = OpenSpecParser()
404
+ requirements: list[RequirementInput] = []
405
+ diagnostics: list[RequirementContextDiagnostic] = []
406
+ seen_requirement_ids: set[str] = set()
407
+ for spec_path in spec_paths:
408
+ parsed = parser.parse_change_spec_delta(spec_path)
409
+ if parsed is None:
410
+ return RequirementContextImportResult(
411
+ diagnostics=[
412
+ RequirementContextDiagnostic(
413
+ severity=RequirementContextDiagnosticSeverity.ERROR,
414
+ code="source-missing",
415
+ message="OpenSpec delta specification could not be read.",
416
+ source_locator=str(spec_path),
417
+ )
418
+ ]
419
+ )
420
+ content = str(parsed.get("raw_content", ""))
421
+ capability = spec_path.parent.name
422
+ source = RequirementSourceReference(
423
+ source_type=RequirementSourceType.OPENSPEC_CHANGE,
424
+ locator=str(spec_path),
425
+ title=capability,
426
+ revision=_source_revision(spec_path),
427
+ )
428
+ for match in re.finditer(
429
+ r"^### Requirement:\s*(.+?)\n(.*?)(?=^### Requirement:|\Z)", content, re.MULTILINE | re.DOTALL
430
+ ):
431
+ title = match.group(1).strip()
432
+ requirement_id = _unique_requirement_id(
433
+ f"openspec:{change_dir.name}:{capability}:{_slug(title)}",
434
+ seen_requirement_ids,
435
+ )
436
+ body = match.group(2).strip()
437
+ summary = body.split("#### Scenario:", maxsplit=1)[0].strip() or None
438
+ requirements.append(
439
+ RequirementInput(
440
+ schema_version="1",
441
+ requirement_id=requirement_id,
442
+ title=title,
443
+ summary=summary,
444
+ sources=[source],
445
+ business_rules=_scenario_rules(requirement_id, body),
446
+ )
447
+ )
448
+ return RequirementContextImportResult(requirements=requirements, diagnostics=diagnostics)
449
+
450
+
451
+ @require(lambda feature_dir: isinstance(feature_dir, Path), "feature_dir must be a Path")
452
+ @ensure(_import_result_has_requirements)
453
+ @beartype
454
+ def import_speckit_feature(feature_dir: Path) -> RequirementContextImportResult:
455
+ """Normalize one native Spec Kit feature directory without modifying it."""
456
+ spec_path = feature_dir / "spec.md"
457
+ if not feature_dir.is_dir() or not spec_path.is_file():
458
+ return _missing_source_result(feature_dir, RequirementSourceType.SPECKIT_SPEC)
459
+
460
+ try:
461
+ content = spec_path.read_text(encoding="utf-8")
462
+ except (OSError, UnicodeDecodeError):
463
+ return _unsupported_source_result(
464
+ spec_path,
465
+ RequirementSourceType.SPECKIT_SPEC,
466
+ "Spec Kit artifact cannot be read as UTF-8 under the default evidence import profile.",
467
+ )
468
+ readiness_error = _speckit_readiness_error(spec_path, content)
469
+ if readiness_error:
470
+ return readiness_error
471
+ compatibility_error = _speckit_compatibility_error(feature_dir, spec_path, content)
472
+ if compatibility_error:
473
+ return compatibility_error
474
+
475
+ parsed = SpecKitScanner(feature_dir.parent).parse_spec_markdown(spec_path)
476
+ if parsed is None:
477
+ return _missing_source_result(spec_path, RequirementSourceType.SPECKIT_SPEC)
478
+
479
+ source = RequirementSourceReference(
480
+ source_type=RequirementSourceType.SPECKIT_SPEC,
481
+ locator=str(spec_path),
482
+ title=str(parsed.get("feature_title") or feature_dir.name),
483
+ revision=_source_revision(spec_path),
484
+ )
485
+ requirements: list[RequirementInput] = []
486
+ seen_requirement_ids: set[str] = set()
487
+ raw_requirements = cast(list[object], parsed.get("requirements", []))
488
+ diagnostics: list[RequirementContextDiagnostic] = []
489
+ for index, raw_requirement in enumerate(raw_requirements):
490
+ if not isinstance(raw_requirement, dict):
491
+ diagnostics.append(
492
+ RequirementContextDiagnostic(
493
+ severity=RequirementContextDiagnosticSeverity.WARNING,
494
+ code="source-malformed",
495
+ message="Spec Kit requirement entry is not a mapping.",
496
+ source_locator=str(spec_path),
497
+ record_index=index,
498
+ )
499
+ )
500
+ continue
501
+ requirement_values = cast(dict[str, object], raw_requirement)
502
+ summary = str(requirement_values.get("text", "")).strip()
503
+ if not summary:
504
+ diagnostics.append(
505
+ RequirementContextDiagnostic(
506
+ severity=RequirementContextDiagnosticSeverity.WARNING,
507
+ code="source-malformed",
508
+ message="Spec Kit requirement entry has no text.",
509
+ source_locator=str(spec_path),
510
+ record_index=index,
511
+ )
512
+ )
513
+ continue
514
+ requirement_id = _unique_requirement_id(
515
+ f"speckit:{feature_dir.name}:{_slug(summary)}",
516
+ seen_requirement_ids,
517
+ )
518
+ requirements.append(
519
+ RequirementInput(
520
+ schema_version="1",
521
+ requirement_id=requirement_id,
522
+ title=summary[:1].upper() + summary[1:],
523
+ summary=summary,
524
+ sources=[source],
525
+ business_rules=_speckit_rules(
526
+ requirement_id,
527
+ content,
528
+ source_requirement_id=f"FR-{index + 1:03d}",
529
+ ),
530
+ )
531
+ )
532
+ return RequirementContextImportResult(requirements=requirements, diagnostics=diagnostics)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: specfact-cli
3
- Version: 0.51.1
3
+ Version: 0.53.2
4
4
  Summary: AI-bloat defense CLI for Python teams. Run deterministic code review, cleanup forecasts, and spec/contract evidence for AI-assisted and brownfield delivery.
5
5
  Project-URL: Homepage, https://github.com/nold-ai/specfact-cli
6
6
  Project-URL: Repository, https://github.com/nold-ai/specfact-cli.git
@@ -355,6 +355,11 @@ For cleanup work, run a JSON review, inspect the cleanup forecast and AI-bloat i
355
355
 
356
356
  These findings are bloat-shape detection and cleanup guidance, not AI-authorship detection. Exact simplify flags and report fields live in the [AI bloat quickstart](https://modules.specfact.io/quickstart-ai-bloat/) and [Code Review run guide](https://modules.specfact.io/bundles/code-review/run/) on the modules docs site.
357
357
 
358
+ Official workflow package IDs are `nold-ai/specfact-project`,
359
+ `nold-ai/specfact-backlog`, `nold-ai/specfact-codebase`,
360
+ `nold-ai/specfact-code-review`, `nold-ai/specfact-spec`,
361
+ `nold-ai/specfact-govern`, and `nold-ai/specfact-requirements`.
362
+
358
363
  ## What SpecFact does
359
364
 
360
365
  - **Defends against AI bloat deterministically** — forecast cleanup impact and route remediation packets to your AI IDE
@@ -446,6 +451,7 @@ specfact module install nold-ai/specfact-backlog
446
451
  specfact module install nold-ai/specfact-codebase
447
452
  specfact module install nold-ai/specfact-code-review
448
453
  specfact module install nold-ai/specfact-govern
454
+ specfact module install nold-ai/specfact-spec
449
455
  specfact module install nold-ai/specfact-requirements
450
456
  ```
451
457
 
@@ -1,4 +1,4 @@
1
- specfact_cli/__init__.py,sha256=QY6gExVcTmqLTBeZ-OGEoowP37lUwykE7JiDchdxYl4,2764
1
+ specfact_cli/__init__.py,sha256=tMcHrgGfuvvAxAW-JAOfmarc0wcnvaH0Wb-5SmBnkys,2764
2
2
  specfact_cli/__main__.py,sha256=EpP5xlutNYI5AuMlMw8fGt1TywZUR1-CXHpzpWKyNuo,141
3
3
  specfact_cli/cli.py,sha256=GRsW3xTJh1pPJl7VpshvPT6YiHgJMMsKt7lE94ZcrAA,53151
4
4
  specfact_cli/evidence.py,sha256=51UTnikb2WY_wktg4D_-1jH9YR4WKXG-aZ6NkL_10lU,2924
@@ -157,8 +157,9 @@ specfact_cli/registry/module_packages.py,sha256=jpyxc5tPwitHDWXtJyqdy18W7EVvHNxd
157
157
  specfact_cli/registry/module_security.py,sha256=RfKJmkR9sdBXP7q1YBsK1Io-ys0vhHshhPR06uk5TjM,4517
158
158
  specfact_cli/registry/module_state.py,sha256=zBMPrjJOhTBZmSY7tur5gOABcRgXZWf_qpOL9iIRRLY,3463
159
159
  specfact_cli/registry/registry.py,sha256=FnQz9-jkiQ1f1e9YjfOZ_Rx7yRVj_mhKQuvoCgmSA78,6856
160
- specfact_cli/requirements/__init__.py,sha256=pjKgqaX2Wl6IwhBqg1PrZDkf4NeYqpLUHxBo7bgt1hQ,857
161
- specfact_cli/requirements/context.py,sha256=upTAzn04uZL-3E4niWlEJiMpZ-h2GQsHbr-CI02gGfw,13379
160
+ specfact_cli/requirements/__init__.py,sha256=f8zWVNT6s59dS2rd5p7fI3AyGEOJbV1syQLzhGrxJ0A,1096
161
+ specfact_cli/requirements/context.py,sha256=mCblpFsJURJrWJ7JNyh4uML2St7RXxeZQc-lio5mgRM,23626
162
+ specfact_cli/requirements/importers.py,sha256=HaP8qDLIBy32m6ipg0IqaVC8p6SSV2HBHyfb2dVeqlw,20483
162
163
  specfact_cli/resources/semgrep/async.yml,sha256=pz4xuPx7_CAEAwN-iq1zyc8srcid3GYtl7exsr1_5k8,8232
163
164
  specfact_cli/resources/semgrep/code-quality.yml,sha256=Nx-E2XuShwioUJhG-JvjEgOMPU9FuNr7H-VCCjKia30,7749
164
165
  specfact_cli/resources/semgrep/feature-detection.yml,sha256=6nZ6sqVtAmGWZxgZYJwu_YNv59xIYgRJsM-5ZtFxXUw,21538
@@ -292,8 +293,8 @@ specfact_cli/resources/templates/policies/kanban.yaml,sha256=9jt7YYfZ8e8aB5skY2D
292
293
  specfact_cli/resources/templates/policies/mixed.yaml,sha256=-fkrT-TLKLTBzjKeKr8bEJHFC-nh1TlyLOEFfgRdSi8,243
293
294
  specfact_cli/resources/templates/policies/safe.yaml,sha256=uiwe5_ABvaU4nmq6rsLUn8zRotkBITItPUsdPZPTHTw,157
294
295
  specfact_cli/resources/templates/policies/scrum.yaml,sha256=6FHYOntkjCxHAn-ga14IQzA1PvYUJgxfLsEQYtWJILM,188
295
- specfact_cli-0.51.1.dist-info/METADATA,sha256=2PyBc1ZRTgPSR8_AYLTWEeI-T_hDqqpLitxBUxkYxDg,25659
296
- specfact_cli-0.51.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
297
- specfact_cli-0.51.1.dist-info/entry_points.txt,sha256=pwDD5Ttu6AF3p3T05M4G0aR2BELFyUu3214kjMRGEow,96
298
- specfact_cli-0.51.1.dist-info/licenses/LICENSE,sha256=nWX_6oozyEFlF3mDaSWyBD9HLpyLRmCYYqdcgoVOrOk,11361
299
- specfact_cli-0.51.1.dist-info/RECORD,,
296
+ specfact_cli-0.53.2.dist-info/METADATA,sha256=1jo25R5wwphnjMaqK3ZBU78mjYFW_tcz9OmJwcgYDTM,25946
297
+ specfact_cli-0.53.2.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
298
+ specfact_cli-0.53.2.dist-info/entry_points.txt,sha256=pwDD5Ttu6AF3p3T05M4G0aR2BELFyUu3214kjMRGEow,96
299
+ specfact_cli-0.53.2.dist-info/licenses/LICENSE,sha256=nWX_6oozyEFlF3mDaSWyBD9HLpyLRmCYYqdcgoVOrOk,11361
300
+ specfact_cli-0.53.2.dist-info/RECORD,,