specfact-cli 0.50.2__py3-none-any.whl → 0.52.3__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 +1 -1
- specfact_cli/evidence.py +74 -0
- specfact_cli/requirements/__init__.py +3 -0
- specfact_cli/requirements/context.py +239 -10
- specfact_cli/requirements/importers.py +339 -0
- specfact_cli/traceability.py +284 -0
- {specfact_cli-0.50.2.dist-info → specfact_cli-0.52.3.dist-info}/METADATA +7 -1
- {specfact_cli-0.50.2.dist-info → specfact_cli-0.52.3.dist-info}/RECORD +11 -8
- {specfact_cli-0.50.2.dist-info → specfact_cli-0.52.3.dist-info}/WHEEL +0 -0
- {specfact_cli-0.50.2.dist-info → specfact_cli-0.52.3.dist-info}/entry_points.txt +0 -0
- {specfact_cli-0.50.2.dist-info → specfact_cli-0.52.3.dist-info}/licenses/LICENSE +0 -0
specfact_cli/__init__.py
CHANGED
specfact_cli/evidence.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Core machine-readable evidence envelope contracts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from types import MappingProxyType
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from beartype import beartype
|
|
10
|
+
from icontract import ensure
|
|
11
|
+
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, computed_field, field_serializer, field_validator
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@beartype
|
|
15
|
+
class EvidenceResultSummary(BaseModel):
|
|
16
|
+
"""Pass, failure, and advisory totals for one evidence category."""
|
|
17
|
+
|
|
18
|
+
model_config = ConfigDict(frozen=True, populate_by_name=True, serialize_by_alias=True)
|
|
19
|
+
|
|
20
|
+
pass_count: int = Field(
|
|
21
|
+
default=0, ge=0, validation_alias=AliasChoices("pass", "pass_count"), serialization_alias="pass"
|
|
22
|
+
)
|
|
23
|
+
fail_count: int = Field(
|
|
24
|
+
default=0, ge=0, validation_alias=AliasChoices("fail", "fail_count"), serialization_alias="fail"
|
|
25
|
+
)
|
|
26
|
+
advisory_count: int = Field(
|
|
27
|
+
default=0,
|
|
28
|
+
ge=0,
|
|
29
|
+
validation_alias=AliasChoices("advisory", "advisory_count"),
|
|
30
|
+
serialization_alias="advisory",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@beartype
|
|
35
|
+
class EvidenceEnvelope(BaseModel):
|
|
36
|
+
"""Core-only envelope; runtime emitters belong to the modules repository."""
|
|
37
|
+
|
|
38
|
+
model_config = ConfigDict(frozen=True)
|
|
39
|
+
|
|
40
|
+
schema_version: Literal["1.0"] = "1.0"
|
|
41
|
+
profile: str = Field(..., min_length=1)
|
|
42
|
+
validation_results: Mapping[str, EvidenceResultSummary] = Field(default_factory=dict)
|
|
43
|
+
|
|
44
|
+
@field_validator("validation_results", mode="after")
|
|
45
|
+
@classmethod
|
|
46
|
+
def _freeze_validation_results(
|
|
47
|
+
cls, results: Mapping[str, EvidenceResultSummary]
|
|
48
|
+
) -> Mapping[str, EvidenceResultSummary]:
|
|
49
|
+
"""Copy result summaries into a read-only mapping for stable verdicts."""
|
|
50
|
+
return MappingProxyType({name: summary.model_copy(deep=True) for name, summary in results.items()})
|
|
51
|
+
|
|
52
|
+
@field_serializer("validation_results")
|
|
53
|
+
def _serialize_validation_results(self, results: Mapping[str, EvidenceResultSummary]) -> dict[str, dict[str, int]]:
|
|
54
|
+
"""Emit immutable results using the standardized JSON summary keys."""
|
|
55
|
+
return {name: summary.model_dump(by_alias=True) for name, summary in results.items()}
|
|
56
|
+
|
|
57
|
+
@computed_field
|
|
58
|
+
@property
|
|
59
|
+
@ensure(lambda result: result in {"PASS", "PASS_WITH_ADVISORY", "FAIL"})
|
|
60
|
+
def overall_verdict(self) -> Literal["PASS", "PASS_WITH_ADVISORY", "FAIL"]:
|
|
61
|
+
"""Derive the immutable CI verdict from validation result summaries."""
|
|
62
|
+
summaries = self.validation_results.values()
|
|
63
|
+
if any(summary.fail_count for summary in summaries):
|
|
64
|
+
return "FAIL"
|
|
65
|
+
if any(summary.advisory_count for summary in summaries):
|
|
66
|
+
return "PASS_WITH_ADVISORY"
|
|
67
|
+
return "PASS"
|
|
68
|
+
|
|
69
|
+
@computed_field
|
|
70
|
+
@property
|
|
71
|
+
@ensure(lambda result: result in {0, 1})
|
|
72
|
+
def ci_exit_code(self) -> int:
|
|
73
|
+
"""Return the CI exit code derived from the immutable verdict."""
|
|
74
|
+
return 1 if self.overall_verdict == "FAIL" else 0
|
|
@@ -12,6 +12,7 @@ from specfact_cli.requirements.context import (
|
|
|
12
12
|
normalize_requirement_records,
|
|
13
13
|
validate_requirement_context,
|
|
14
14
|
)
|
|
15
|
+
from specfact_cli.requirements.importers import import_openspec_change, import_speckit_feature
|
|
15
16
|
|
|
16
17
|
|
|
17
18
|
__all__ = [
|
|
@@ -21,6 +22,8 @@ __all__ = [
|
|
|
21
22
|
"RequirementContextDiagnosticSeverity",
|
|
22
23
|
"RequirementContextImportResult",
|
|
23
24
|
"attach_requirements_to_bundle",
|
|
25
|
+
"import_openspec_change",
|
|
26
|
+
"import_speckit_feature",
|
|
24
27
|
"inspect_requirement_context_coverage",
|
|
25
28
|
"load_requirements_from_bundle",
|
|
26
29
|
"normalize_requirement_records",
|
|
@@ -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,77 @@ def _optional_text(value: str | None) -> str | None:
|
|
|
131
149
|
return value
|
|
132
150
|
|
|
133
151
|
|
|
134
|
-
def
|
|
135
|
-
return
|
|
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
|
|
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
|
|
143
|
-
return
|
|
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
|
+
def _is_imported_requirement(requirement: RequirementInput) -> bool:
|
|
219
|
+
return any(
|
|
220
|
+
source.source_type in {RequirementSourceType.OPENSPEC_CHANGE, RequirementSourceType.SPECKIT_SPEC}
|
|
221
|
+
for source in requirement.sources
|
|
222
|
+
)
|
|
144
223
|
|
|
145
224
|
|
|
146
225
|
def _coverage_summary_consistent(result: RequirementContextCoverageSummary) -> bool:
|
|
@@ -274,6 +353,7 @@ def _missing_evidence_violations(
|
|
|
274
353
|
) -> list[dict[str, str]]:
|
|
275
354
|
return [
|
|
276
355
|
{
|
|
356
|
+
"code": "missing-evidence",
|
|
277
357
|
"severity": severity,
|
|
278
358
|
"message": "Requirement input has no downstream evidence links.",
|
|
279
359
|
"location": f"requirements.inputs[{requirement_id}].evidence_links",
|
|
@@ -282,6 +362,136 @@ def _missing_evidence_violations(
|
|
|
282
362
|
]
|
|
283
363
|
|
|
284
364
|
|
|
365
|
+
def _scenario_unverified_violation(requirement: RequirementInput, *, severity: str) -> dict[str, str] | None:
|
|
366
|
+
if not requirement.business_rules or any(
|
|
367
|
+
link.link_type in {RequirementEvidenceLinkType.TEST, RequirementEvidenceLinkType.VALIDATION}
|
|
368
|
+
for link in requirement.evidence_links
|
|
369
|
+
):
|
|
370
|
+
return None
|
|
371
|
+
rule_ids = ", ".join(rule.rule_id for rule in requirement.business_rules)
|
|
372
|
+
return {
|
|
373
|
+
"code": "scenario-unverified",
|
|
374
|
+
"severity": severity,
|
|
375
|
+
"message": f"Imported scenarios have no test or validation evidence links: {rule_ids}.",
|
|
376
|
+
"location": f"requirements.inputs[{requirement.requirement_id}].business_rules",
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _source_integrity_violations(
|
|
381
|
+
requirement: RequirementInput,
|
|
382
|
+
*,
|
|
383
|
+
severity: str,
|
|
384
|
+
project_root: Path,
|
|
385
|
+
) -> list[dict[str, str]]:
|
|
386
|
+
violations: list[dict[str, str]] = []
|
|
387
|
+
for source in requirement.sources:
|
|
388
|
+
if source.source_type not in {RequirementSourceType.OPENSPEC_CHANGE, RequirementSourceType.SPECKIT_SPEC}:
|
|
389
|
+
continue
|
|
390
|
+
source_path = Path(source.locator)
|
|
391
|
+
if not source_path.is_absolute():
|
|
392
|
+
source_path = project_root / source_path
|
|
393
|
+
if not source_path.is_file():
|
|
394
|
+
violations.append(
|
|
395
|
+
{
|
|
396
|
+
"code": "source-missing",
|
|
397
|
+
"severity": severity,
|
|
398
|
+
"message": "Imported source artifact no longer exists.",
|
|
399
|
+
"location": source.locator,
|
|
400
|
+
}
|
|
401
|
+
)
|
|
402
|
+
continue
|
|
403
|
+
if source.revision and source.revision.startswith("sha256:"):
|
|
404
|
+
current_revision = f"sha256:{hashlib.sha256(source_path.read_bytes()).hexdigest()}"
|
|
405
|
+
if current_revision != source.revision:
|
|
406
|
+
violations.append(
|
|
407
|
+
{
|
|
408
|
+
"code": "stale-import",
|
|
409
|
+
"severity": severity,
|
|
410
|
+
"message": "Imported source artifact content changed after import.",
|
|
411
|
+
"location": source.locator,
|
|
412
|
+
}
|
|
413
|
+
)
|
|
414
|
+
return violations
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _ambiguous_mapping_violations(identities: Mapping[str, set[str]], *, severity: str) -> list[dict[str, str]]:
|
|
418
|
+
return [
|
|
419
|
+
{
|
|
420
|
+
"code": "ambiguous-mapping",
|
|
421
|
+
"severity": severity,
|
|
422
|
+
"message": "Multiple imported sources claim the same requirement identity.",
|
|
423
|
+
"location": f"requirements.inputs[{requirement_id}]",
|
|
424
|
+
}
|
|
425
|
+
for requirement_id, locators in identities.items()
|
|
426
|
+
if len(locators) > 1
|
|
427
|
+
]
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _import_gate_violations(
|
|
431
|
+
requirements: Sequence[RequirementInput],
|
|
432
|
+
*,
|
|
433
|
+
severity: str,
|
|
434
|
+
project_root: Path,
|
|
435
|
+
) -> list[dict[str, str]]:
|
|
436
|
+
violations: list[dict[str, str]] = []
|
|
437
|
+
identities: dict[str, set[str]] = {}
|
|
438
|
+
for requirement in requirements:
|
|
439
|
+
if not _is_imported_requirement(requirement):
|
|
440
|
+
continue
|
|
441
|
+
identities.setdefault(requirement.requirement_id, set()).update(
|
|
442
|
+
source.locator for source in requirement.sources
|
|
443
|
+
)
|
|
444
|
+
scenario_violation = _scenario_unverified_violation(requirement, severity=severity)
|
|
445
|
+
if scenario_violation:
|
|
446
|
+
violations.append(scenario_violation)
|
|
447
|
+
violations.extend(
|
|
448
|
+
_source_integrity_violations(
|
|
449
|
+
requirement,
|
|
450
|
+
severity=severity,
|
|
451
|
+
project_root=project_root,
|
|
452
|
+
)
|
|
453
|
+
)
|
|
454
|
+
violations.extend(_ambiguous_mapping_violations(identities, severity=severity))
|
|
455
|
+
return violations
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _required_field_violations(
|
|
459
|
+
requirements: Sequence[RequirementInput],
|
|
460
|
+
required_fields: Sequence[str],
|
|
461
|
+
*,
|
|
462
|
+
severity: str,
|
|
463
|
+
) -> list[dict[str, str]]:
|
|
464
|
+
imported_requirements = [requirement for requirement in requirements if _is_imported_requirement(requirement)]
|
|
465
|
+
if not imported_requirements:
|
|
466
|
+
return []
|
|
467
|
+
|
|
468
|
+
violations: list[dict[str, str]] = []
|
|
469
|
+
for field in required_fields:
|
|
470
|
+
attribute = _REQUIRED_FIELD_ALIASES.get(field)
|
|
471
|
+
if attribute is None:
|
|
472
|
+
violations.append(
|
|
473
|
+
{
|
|
474
|
+
"code": "unsupported-profile-field",
|
|
475
|
+
"severity": "info",
|
|
476
|
+
"message": "Profile field is not represented by the import-first requirements evidence schema.",
|
|
477
|
+
"location": f"requirements_schema.required_fields[{field}]",
|
|
478
|
+
}
|
|
479
|
+
)
|
|
480
|
+
continue
|
|
481
|
+
for requirement in imported_requirements:
|
|
482
|
+
value = getattr(requirement, attribute)
|
|
483
|
+
if not value:
|
|
484
|
+
violations.append(
|
|
485
|
+
{
|
|
486
|
+
"code": "required-field-missing",
|
|
487
|
+
"severity": severity,
|
|
488
|
+
"message": f"Required evidence field '{field}' is missing.",
|
|
489
|
+
"location": f"requirements.inputs[{requirement.requirement_id}].{attribute}",
|
|
490
|
+
}
|
|
491
|
+
)
|
|
492
|
+
return violations
|
|
493
|
+
|
|
494
|
+
|
|
285
495
|
def _validation_status(failed: int, warnings: int) -> Literal["passed", "failed", "warnings"]:
|
|
286
496
|
if failed:
|
|
287
497
|
return "failed"
|
|
@@ -307,21 +517,40 @@ def _validation_summary(
|
|
|
307
517
|
|
|
308
518
|
@beartype
|
|
309
519
|
@require(lambda bundle: isinstance(bundle, ProjectBundle), "bundle must be a ProjectBundle")
|
|
310
|
-
@require(
|
|
311
|
-
|
|
520
|
+
@require(
|
|
521
|
+
_optional_profile_supported, "profile must be a supported requirements context validation profile when provided"
|
|
522
|
+
)
|
|
523
|
+
@require(_project_root_supported, "project_root must be a Path when provided")
|
|
312
524
|
@ensure(lambda result: isinstance(result, ValidationReport))
|
|
313
525
|
def validate_requirement_context(
|
|
314
526
|
bundle: ProjectBundle,
|
|
315
527
|
*,
|
|
316
|
-
profile: RequirementContextValidationProfile =
|
|
528
|
+
profile: RequirementContextValidationProfile | None = None,
|
|
529
|
+
project_root: Path | None = None,
|
|
317
530
|
) -> ValidationReport:
|
|
318
531
|
"""Validate requirements context evidence usefulness for a ProjectBundle."""
|
|
319
532
|
requirements = load_requirements_from_bundle(bundle)
|
|
320
533
|
if not requirements:
|
|
321
534
|
return _empty_requirements_report()
|
|
322
535
|
|
|
536
|
+
effective_profile, resolved_config = _resolve_requirement_profile(profile, project_root)
|
|
537
|
+
severity = _missing_evidence_severity(cast(RequirementContextValidationProfile, effective_profile))
|
|
323
538
|
coverage = inspect_requirement_context_coverage(requirements)
|
|
324
|
-
violations = _missing_evidence_violations(coverage, severity=
|
|
539
|
+
violations = _missing_evidence_violations(coverage, severity=severity)
|
|
540
|
+
violations.extend(
|
|
541
|
+
_import_gate_violations(
|
|
542
|
+
requirements,
|
|
543
|
+
severity=severity,
|
|
544
|
+
project_root=project_root or Path.cwd(),
|
|
545
|
+
)
|
|
546
|
+
)
|
|
547
|
+
violations.extend(
|
|
548
|
+
_required_field_violations(
|
|
549
|
+
requirements,
|
|
550
|
+
_requirements_schema_fields(resolved_config),
|
|
551
|
+
severity=severity,
|
|
552
|
+
)
|
|
553
|
+
)
|
|
325
554
|
summary = _validation_summary(requirements, coverage, violations)
|
|
326
555
|
return ValidationReport(
|
|
327
556
|
status=_validation_status(summary["failed"], summary["warnings"]),
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
"""Read-only normalizers for native OpenSpec and Spec Kit requirement evidence."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import cast
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
from beartype import beartype
|
|
12
|
+
from icontract import ensure, require
|
|
13
|
+
|
|
14
|
+
from specfact_cli.adapters.openspec_parser import OpenSpecParser
|
|
15
|
+
from specfact_cli.importers.speckit_scanner import SpecKitScanner
|
|
16
|
+
from specfact_cli.models.requirements import (
|
|
17
|
+
BusinessRule,
|
|
18
|
+
RequirementInput,
|
|
19
|
+
RequirementSourceReference,
|
|
20
|
+
RequirementSourceType,
|
|
21
|
+
)
|
|
22
|
+
from specfact_cli.requirements.context import (
|
|
23
|
+
RequirementContextDiagnostic,
|
|
24
|
+
RequirementContextDiagnosticSeverity,
|
|
25
|
+
RequirementContextImportResult,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
_DEFAULT_OPENSPEC_SCHEMA = "spec-driven"
|
|
30
|
+
_OPENSPEC_REQUIREMENT_PATTERN = re.compile(r"^### Requirement:\s+.+$", re.MULTILINE)
|
|
31
|
+
_OPENSPEC_SCENARIO_PATTERN = re.compile(r"^#### Scenario:\s+.+$", re.MULTILINE)
|
|
32
|
+
_SPECKIT_TITLE_PATTERN = re.compile(r"^# Feature Specification:\s+.+$", re.MULTILINE)
|
|
33
|
+
_SPECKIT_REQUIREMENT_PATTERN = re.compile(r"^\s*-?\s*\*\*FR-\d+\*\*:\s*System MUST\s+.+$", re.MULTILINE)
|
|
34
|
+
_SPECKIT_CUSTOMIZATION_ROOTS = (
|
|
35
|
+
Path(".specify/templates/overrides"),
|
|
36
|
+
Path(".specify/presets"),
|
|
37
|
+
Path(".specify/extensions"),
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _slug(value: str) -> str:
|
|
42
|
+
return re.sub(r"-+", "-", re.sub(r"[^a-z0-9]+", "-", value.lower())).strip("-") or "requirement"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _unique_requirement_id(base_id: str, seen_ids: set[str]) -> str:
|
|
46
|
+
candidate = base_id
|
|
47
|
+
ordinal = 2
|
|
48
|
+
while candidate in seen_ids:
|
|
49
|
+
candidate = f"{base_id}-{ordinal}"
|
|
50
|
+
ordinal += 1
|
|
51
|
+
seen_ids.add(candidate)
|
|
52
|
+
return candidate
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _source_revision(path: Path) -> str:
|
|
56
|
+
return f"sha256:{hashlib.sha256(path.read_bytes()).hexdigest()}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _scenario_rules(requirement_id: str, content: str) -> list[BusinessRule]:
|
|
60
|
+
rules: list[BusinessRule] = []
|
|
61
|
+
scenario_pattern = re.compile(
|
|
62
|
+
r"^#### Scenario:\s*(.+?)\n(.*?)(?=^#### Scenario:|^### Requirement:|\Z)",
|
|
63
|
+
re.MULTILINE | re.DOTALL,
|
|
64
|
+
)
|
|
65
|
+
for match in scenario_pattern.finditer(content):
|
|
66
|
+
name = match.group(1).strip()
|
|
67
|
+
body = match.group(2)
|
|
68
|
+
clauses: dict[str, str] = {}
|
|
69
|
+
for clause in ("given", "when", "then"):
|
|
70
|
+
clause_match = re.search(
|
|
71
|
+
rf"^- \*\*{clause.upper()}\*\*\s+([^\n]+(?:\n[ \t]+[^\n]+)*)",
|
|
72
|
+
body,
|
|
73
|
+
re.MULTILINE | re.IGNORECASE,
|
|
74
|
+
)
|
|
75
|
+
if clause_match:
|
|
76
|
+
clauses[clause] = " ".join(clause_match.group(1).split())
|
|
77
|
+
if len(clauses) == 3:
|
|
78
|
+
rules.append(
|
|
79
|
+
BusinessRule(
|
|
80
|
+
rule_id=f"{requirement_id}:{_slug(name)}",
|
|
81
|
+
name=name,
|
|
82
|
+
given=clauses["given"],
|
|
83
|
+
when=clauses["when"],
|
|
84
|
+
then=clauses["then"],
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
return rules
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _speckit_rules(requirement_id: str, content: str) -> list[BusinessRule]:
|
|
91
|
+
rules: list[BusinessRule] = []
|
|
92
|
+
pattern = re.compile(
|
|
93
|
+
r"\*\*Given\*\*\s+(.+?),\s*\*\*When\*\*\s+(.+?),\s*\*\*Then\*\*\s+(.+?)(?=\n|$)",
|
|
94
|
+
re.IGNORECASE,
|
|
95
|
+
)
|
|
96
|
+
for index, match in enumerate(pattern.finditer(content), start=1):
|
|
97
|
+
rules.append(
|
|
98
|
+
BusinessRule(
|
|
99
|
+
rule_id=f"{requirement_id}:scenario-{index}",
|
|
100
|
+
name=f"Acceptance scenario {index}",
|
|
101
|
+
given=match.group(1).strip(),
|
|
102
|
+
when=match.group(2).strip(),
|
|
103
|
+
then=match.group(3).strip(),
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
return rules
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _missing_source_result(source: Path, source_type: RequirementSourceType) -> RequirementContextImportResult:
|
|
110
|
+
return RequirementContextImportResult(
|
|
111
|
+
diagnostics=[
|
|
112
|
+
RequirementContextDiagnostic(
|
|
113
|
+
severity=RequirementContextDiagnosticSeverity.ERROR,
|
|
114
|
+
code="source-missing",
|
|
115
|
+
message=f"Required {source_type.value} source does not exist.",
|
|
116
|
+
source_locator=str(source),
|
|
117
|
+
)
|
|
118
|
+
]
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _unsupported_source_result(
|
|
123
|
+
source: Path,
|
|
124
|
+
source_type: RequirementSourceType,
|
|
125
|
+
message: str,
|
|
126
|
+
) -> RequirementContextImportResult:
|
|
127
|
+
return RequirementContextImportResult(
|
|
128
|
+
diagnostics=[
|
|
129
|
+
RequirementContextDiagnostic(
|
|
130
|
+
severity=RequirementContextDiagnosticSeverity.ERROR,
|
|
131
|
+
code="unsupported-source-schema",
|
|
132
|
+
message=message,
|
|
133
|
+
source_locator=str(source),
|
|
134
|
+
)
|
|
135
|
+
]
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _load_schema_name(path: Path) -> str | None:
|
|
140
|
+
try:
|
|
141
|
+
if not path.is_file():
|
|
142
|
+
return None
|
|
143
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
144
|
+
except (OSError, UnicodeDecodeError, yaml.YAMLError):
|
|
145
|
+
return "<invalid>"
|
|
146
|
+
if not isinstance(data, dict):
|
|
147
|
+
return "<invalid>"
|
|
148
|
+
schema = cast(dict[str, object], data).get("schema")
|
|
149
|
+
return "<invalid>" if "schema" in data and not isinstance(schema, str) else cast(str | None, schema)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _openspec_compatibility_error(change_dir: Path, spec_paths: list[Path]) -> RequirementContextImportResult | None:
|
|
153
|
+
config_paths = (change_dir.parent.parent / "config.yaml", change_dir / ".openspec.yaml")
|
|
154
|
+
for config_path in config_paths:
|
|
155
|
+
schema = _load_schema_name(config_path)
|
|
156
|
+
if schema is not None and schema != _DEFAULT_OPENSPEC_SCHEMA:
|
|
157
|
+
return _unsupported_source_result(
|
|
158
|
+
config_path,
|
|
159
|
+
RequirementSourceType.OPENSPEC_CHANGE,
|
|
160
|
+
"OpenSpec schema is not supported by the default evidence import profile.",
|
|
161
|
+
)
|
|
162
|
+
if not spec_paths:
|
|
163
|
+
return _unsupported_source_result(
|
|
164
|
+
change_dir,
|
|
165
|
+
RequirementSourceType.OPENSPEC_CHANGE,
|
|
166
|
+
"OpenSpec change has no default-profile spec.md artifact to import.",
|
|
167
|
+
)
|
|
168
|
+
for spec_path in spec_paths:
|
|
169
|
+
content = spec_path.read_text(encoding="utf-8")
|
|
170
|
+
if not (_OPENSPEC_REQUIREMENT_PATTERN.search(content) and _OPENSPEC_SCENARIO_PATTERN.search(content)):
|
|
171
|
+
return _unsupported_source_result(
|
|
172
|
+
spec_path,
|
|
173
|
+
RequirementSourceType.OPENSPEC_CHANGE,
|
|
174
|
+
"OpenSpec artifact does not match the supported default requirement/scenario Markdown profile.",
|
|
175
|
+
)
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _speckit_project_root(feature_dir: Path) -> Path | None:
|
|
180
|
+
for directory in (feature_dir.parent, *feature_dir.parents):
|
|
181
|
+
if (directory / ".specify").is_dir():
|
|
182
|
+
return directory
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _speckit_compatibility_error(
|
|
187
|
+
feature_dir: Path, spec_path: Path, content: str
|
|
188
|
+
) -> RequirementContextImportResult | None:
|
|
189
|
+
project_root = _speckit_project_root(feature_dir)
|
|
190
|
+
if project_root:
|
|
191
|
+
for customization_root in _SPECKIT_CUSTOMIZATION_ROOTS:
|
|
192
|
+
path = project_root / customization_root
|
|
193
|
+
if path.exists():
|
|
194
|
+
return _unsupported_source_result(
|
|
195
|
+
path,
|
|
196
|
+
RequirementSourceType.SPECKIT_SPEC,
|
|
197
|
+
"Spec Kit template customization is not supported by the default evidence import profile.",
|
|
198
|
+
)
|
|
199
|
+
if not (_SPECKIT_TITLE_PATTERN.search(content) and _SPECKIT_REQUIREMENT_PATTERN.search(content)):
|
|
200
|
+
return _unsupported_source_result(
|
|
201
|
+
spec_path,
|
|
202
|
+
RequirementSourceType.SPECKIT_SPEC,
|
|
203
|
+
"Spec Kit artifact does not match the supported default Markdown template profile.",
|
|
204
|
+
)
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _import_result_has_requirements(result: RequirementContextImportResult) -> bool:
|
|
209
|
+
return all(isinstance(record, RequirementInput) for record in result.requirements)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@require(lambda change_dir: isinstance(change_dir, Path), "change_dir must be a Path")
|
|
213
|
+
@ensure(_import_result_has_requirements)
|
|
214
|
+
@beartype
|
|
215
|
+
def import_openspec_change(change_dir: Path) -> RequirementContextImportResult:
|
|
216
|
+
"""Normalize one native OpenSpec change directory without modifying it."""
|
|
217
|
+
if not change_dir.is_dir():
|
|
218
|
+
return _missing_source_result(change_dir, RequirementSourceType.OPENSPEC_CHANGE)
|
|
219
|
+
|
|
220
|
+
spec_paths = sorted((change_dir / "specs").glob("*/spec.md"))
|
|
221
|
+
compatibility_error = _openspec_compatibility_error(change_dir, spec_paths)
|
|
222
|
+
if compatibility_error:
|
|
223
|
+
return compatibility_error
|
|
224
|
+
|
|
225
|
+
parser = OpenSpecParser()
|
|
226
|
+
requirements: list[RequirementInput] = []
|
|
227
|
+
diagnostics: list[RequirementContextDiagnostic] = []
|
|
228
|
+
seen_requirement_ids: set[str] = set()
|
|
229
|
+
for spec_path in spec_paths:
|
|
230
|
+
parsed = parser.parse_change_spec_delta(spec_path)
|
|
231
|
+
if parsed is None:
|
|
232
|
+
diagnostics.append(
|
|
233
|
+
RequirementContextDiagnostic(
|
|
234
|
+
severity=RequirementContextDiagnosticSeverity.ERROR,
|
|
235
|
+
code="source-missing",
|
|
236
|
+
message="OpenSpec delta specification could not be read.",
|
|
237
|
+
source_locator=str(spec_path),
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
continue
|
|
241
|
+
content = str(parsed.get("raw_content", ""))
|
|
242
|
+
capability = spec_path.parent.name
|
|
243
|
+
source = RequirementSourceReference(
|
|
244
|
+
source_type=RequirementSourceType.OPENSPEC_CHANGE,
|
|
245
|
+
locator=str(spec_path),
|
|
246
|
+
title=capability,
|
|
247
|
+
revision=_source_revision(spec_path),
|
|
248
|
+
)
|
|
249
|
+
for match in re.finditer(
|
|
250
|
+
r"^### Requirement:\s*(.+?)\n(.*?)(?=^### Requirement:|\Z)", content, re.MULTILINE | re.DOTALL
|
|
251
|
+
):
|
|
252
|
+
title = match.group(1).strip()
|
|
253
|
+
requirement_id = _unique_requirement_id(
|
|
254
|
+
f"openspec:{change_dir.name}:{capability}:{_slug(title)}",
|
|
255
|
+
seen_requirement_ids,
|
|
256
|
+
)
|
|
257
|
+
body = match.group(2).strip()
|
|
258
|
+
summary = body.split("#### Scenario:", maxsplit=1)[0].strip() or None
|
|
259
|
+
requirements.append(
|
|
260
|
+
RequirementInput(
|
|
261
|
+
schema_version="1",
|
|
262
|
+
requirement_id=requirement_id,
|
|
263
|
+
title=title,
|
|
264
|
+
summary=summary,
|
|
265
|
+
sources=[source],
|
|
266
|
+
business_rules=_scenario_rules(requirement_id, body),
|
|
267
|
+
)
|
|
268
|
+
)
|
|
269
|
+
return RequirementContextImportResult(requirements=requirements, diagnostics=diagnostics)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@require(lambda feature_dir: isinstance(feature_dir, Path), "feature_dir must be a Path")
|
|
273
|
+
@ensure(_import_result_has_requirements)
|
|
274
|
+
@beartype
|
|
275
|
+
def import_speckit_feature(feature_dir: Path) -> RequirementContextImportResult:
|
|
276
|
+
"""Normalize one native Spec Kit feature directory without modifying it."""
|
|
277
|
+
spec_path = feature_dir / "spec.md"
|
|
278
|
+
if not feature_dir.is_dir() or not spec_path.is_file():
|
|
279
|
+
return _missing_source_result(feature_dir, RequirementSourceType.SPECKIT_SPEC)
|
|
280
|
+
|
|
281
|
+
content = spec_path.read_text(encoding="utf-8")
|
|
282
|
+
compatibility_error = _speckit_compatibility_error(feature_dir, spec_path, content)
|
|
283
|
+
if compatibility_error:
|
|
284
|
+
return compatibility_error
|
|
285
|
+
|
|
286
|
+
parsed = SpecKitScanner(feature_dir.parent).parse_spec_markdown(spec_path)
|
|
287
|
+
if parsed is None:
|
|
288
|
+
return _missing_source_result(spec_path, RequirementSourceType.SPECKIT_SPEC)
|
|
289
|
+
|
|
290
|
+
source = RequirementSourceReference(
|
|
291
|
+
source_type=RequirementSourceType.SPECKIT_SPEC,
|
|
292
|
+
locator=str(spec_path),
|
|
293
|
+
title=str(parsed.get("feature_title") or feature_dir.name),
|
|
294
|
+
revision=_source_revision(spec_path),
|
|
295
|
+
)
|
|
296
|
+
requirements: list[RequirementInput] = []
|
|
297
|
+
seen_requirement_ids: set[str] = set()
|
|
298
|
+
raw_requirements = cast(list[object], parsed.get("requirements", []))
|
|
299
|
+
diagnostics: list[RequirementContextDiagnostic] = []
|
|
300
|
+
for index, raw_requirement in enumerate(raw_requirements):
|
|
301
|
+
if not isinstance(raw_requirement, dict):
|
|
302
|
+
diagnostics.append(
|
|
303
|
+
RequirementContextDiagnostic(
|
|
304
|
+
severity=RequirementContextDiagnosticSeverity.WARNING,
|
|
305
|
+
code="source-missing",
|
|
306
|
+
message="Spec Kit requirement entry is not a mapping.",
|
|
307
|
+
source_locator=str(spec_path),
|
|
308
|
+
record_index=index,
|
|
309
|
+
)
|
|
310
|
+
)
|
|
311
|
+
continue
|
|
312
|
+
requirement_values = cast(dict[str, object], raw_requirement)
|
|
313
|
+
summary = str(requirement_values.get("text", "")).strip()
|
|
314
|
+
if not summary:
|
|
315
|
+
diagnostics.append(
|
|
316
|
+
RequirementContextDiagnostic(
|
|
317
|
+
severity=RequirementContextDiagnosticSeverity.WARNING,
|
|
318
|
+
code="source-missing",
|
|
319
|
+
message="Spec Kit requirement entry has no text.",
|
|
320
|
+
source_locator=str(spec_path),
|
|
321
|
+
record_index=index,
|
|
322
|
+
)
|
|
323
|
+
)
|
|
324
|
+
continue
|
|
325
|
+
requirement_id = _unique_requirement_id(
|
|
326
|
+
f"speckit:{feature_dir.name}:{_slug(summary)}",
|
|
327
|
+
seen_requirement_ids,
|
|
328
|
+
)
|
|
329
|
+
requirements.append(
|
|
330
|
+
RequirementInput(
|
|
331
|
+
schema_version="1",
|
|
332
|
+
requirement_id=requirement_id,
|
|
333
|
+
title=summary[:1].upper() + summary[1:],
|
|
334
|
+
summary=summary,
|
|
335
|
+
sources=[source],
|
|
336
|
+
business_rules=_speckit_rules(requirement_id, content),
|
|
337
|
+
)
|
|
338
|
+
)
|
|
339
|
+
return RequirementContextImportResult(requirements=requirements, diagnostics=diagnostics)
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Generic core artifact evidence index contracts and requirements adapter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections import Counter
|
|
7
|
+
from collections.abc import Sequence, Set
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from beartype import beartype
|
|
12
|
+
from icontract import ensure, require
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
from specfact_cli.models.project import ProjectBundle
|
|
16
|
+
from specfact_cli.models.requirements import RequirementInput
|
|
17
|
+
from specfact_cli.requirements.context import (
|
|
18
|
+
KNOWN_REQUIREMENT_CONTEXT_PROFILES,
|
|
19
|
+
STRICT_REQUIREMENT_CONTEXT_PROFILES,
|
|
20
|
+
RequirementContextValidationProfile,
|
|
21
|
+
load_requirements_from_bundle,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ArtifactKind(StrEnum):
|
|
26
|
+
"""Normalized kinds that adapters may contribute to the evidence index."""
|
|
27
|
+
|
|
28
|
+
REQUIREMENT = "requirement"
|
|
29
|
+
ARCHITECTURE = "architecture"
|
|
30
|
+
SPECIFICATION = "specification"
|
|
31
|
+
CODE = "code"
|
|
32
|
+
TEST = "test"
|
|
33
|
+
CONTRACT = "contract"
|
|
34
|
+
OPENSPEC = "openspec"
|
|
35
|
+
SPECKIT = "speckit"
|
|
36
|
+
BACKLOG = "backlog"
|
|
37
|
+
ADR = "adr"
|
|
38
|
+
POLICY = "policy"
|
|
39
|
+
REVIEW = "review"
|
|
40
|
+
VALIDATION = "validation"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@beartype
|
|
44
|
+
class ArtifactLink(BaseModel):
|
|
45
|
+
"""Directed relationship between stable artifact identities."""
|
|
46
|
+
|
|
47
|
+
target: str = Field(..., min_length=1)
|
|
48
|
+
relation: str = Field(default="references", min_length=1)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@beartype
|
|
52
|
+
class ArtifactRecord(BaseModel):
|
|
53
|
+
"""Adapter-neutral evidence artifact with stable identity and fingerprint."""
|
|
54
|
+
|
|
55
|
+
identity: str = Field(..., min_length=1)
|
|
56
|
+
kind: ArtifactKind
|
|
57
|
+
locator: str = Field(..., min_length=1)
|
|
58
|
+
fingerprint: str = Field(..., min_length=1)
|
|
59
|
+
links: list[ArtifactLink] = Field(default_factory=list)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@beartype
|
|
63
|
+
class ArtifactEvidenceIndex(BaseModel):
|
|
64
|
+
"""Deterministic core index; callers own persistence and rendering."""
|
|
65
|
+
|
|
66
|
+
schema_version: Literal["1"] = "1"
|
|
67
|
+
artifacts: list[ArtifactRecord] = Field(default_factory=list)
|
|
68
|
+
|
|
69
|
+
@ensure(lambda result: isinstance(result, str), "result must be JSON text")
|
|
70
|
+
def to_json(self) -> str:
|
|
71
|
+
"""Return canonical JSON suitable for a modules-owned persistence layer."""
|
|
72
|
+
return json.dumps(self.model_dump(mode="json"), sort_keys=True, separators=(",", ":"))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@beartype
|
|
76
|
+
class TraceabilityFinding(BaseModel):
|
|
77
|
+
"""Bounded index finding."""
|
|
78
|
+
|
|
79
|
+
code: str = Field(..., min_length=1)
|
|
80
|
+
identity: str = Field(..., min_length=1)
|
|
81
|
+
severity: Literal["warning", "error"]
|
|
82
|
+
location: str = Field(..., min_length=1)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
@ensure(lambda result: isinstance(result, str), "result must be text")
|
|
86
|
+
def requirement_id(self) -> str:
|
|
87
|
+
"""Compatibility identifier for requirements-first callers."""
|
|
88
|
+
return self.identity.removeprefix("requirement:")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@beartype
|
|
92
|
+
class ArtifactIndexBuildResult(BaseModel):
|
|
93
|
+
"""Index plus deterministic classifications and incremental rebuild facts."""
|
|
94
|
+
|
|
95
|
+
index: ArtifactEvidenceIndex
|
|
96
|
+
orphans: list[TraceabilityFinding] = Field(default_factory=list)
|
|
97
|
+
drift: list[TraceabilityFinding] = Field(default_factory=list)
|
|
98
|
+
ambiguities: list[TraceabilityFinding] = Field(default_factory=list)
|
|
99
|
+
contradictions: list[TraceabilityFinding] = Field(default_factory=list)
|
|
100
|
+
changed_identities: list[str] = Field(default_factory=list)
|
|
101
|
+
removed_identities: list[str] = Field(default_factory=list)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
TraceabilityResult = ArtifactIndexBuildResult
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _severity(profile: str) -> Literal["warning", "error"]:
|
|
108
|
+
return "error" if profile in STRICT_REQUIREMENT_CONTEXT_PROFILES else "warning"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _finding(code: str, identity: str, severity: Literal["warning", "error"]) -> TraceabilityFinding:
|
|
112
|
+
return TraceabilityFinding(code=code, identity=identity, severity=severity, location=f"artifacts[{identity}]")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _canonical_records(records: Sequence[ArtifactRecord]) -> tuple[list[ArtifactRecord], list[str]]:
|
|
116
|
+
grouped: dict[str, list[ArtifactRecord]] = {}
|
|
117
|
+
for record in records:
|
|
118
|
+
grouped.setdefault(record.identity, []).append(
|
|
119
|
+
record.model_copy(update={"links": sorted(record.links, key=lambda link: (link.target, link.relation))})
|
|
120
|
+
)
|
|
121
|
+
duplicates = sorted(identity for identity, values in grouped.items() if len(values) > 1)
|
|
122
|
+
canonical = [sorted(values, key=_record_signature)[0] for _, values in sorted(grouped.items())]
|
|
123
|
+
return canonical, duplicates
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _record_signature(record: ArtifactRecord) -> str:
|
|
127
|
+
return json.dumps(record.model_dump(mode="json"), sort_keys=True, separators=(",", ":"))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _incoming_links(records: Sequence[ArtifactRecord], identities: set[str]) -> Counter[str]:
|
|
131
|
+
return Counter(
|
|
132
|
+
link.target
|
|
133
|
+
for record in records
|
|
134
|
+
for link in record.links
|
|
135
|
+
if link.target in identities and link.target != record.identity
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _orphan_findings(
|
|
140
|
+
records: Sequence[ArtifactRecord], incoming: Counter[str], severity: Literal["warning", "error"]
|
|
141
|
+
) -> list[TraceabilityFinding]:
|
|
142
|
+
return [
|
|
143
|
+
_finding("unlinked_artifact", record.identity, severity)
|
|
144
|
+
for record in records
|
|
145
|
+
if not record.links and not incoming[record.identity]
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _classify_record_links(
|
|
150
|
+
record: ArtifactRecord, identities: set[str], severity: Literal["warning", "error"]
|
|
151
|
+
) -> list[TraceabilityFinding]:
|
|
152
|
+
findings: list[TraceabilityFinding] = []
|
|
153
|
+
for link in record.links:
|
|
154
|
+
if link.target == record.identity:
|
|
155
|
+
findings.append(_finding("self_referential_link", record.identity, severity))
|
|
156
|
+
elif link.target not in identities:
|
|
157
|
+
findings.append(_finding("dangling_link", record.identity, severity))
|
|
158
|
+
return findings
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _link_findings(
|
|
162
|
+
records: Sequence[ArtifactRecord], identities: set[str], severity: Literal["warning", "error"]
|
|
163
|
+
) -> tuple[list[TraceabilityFinding], list[TraceabilityFinding]]:
|
|
164
|
+
findings = [finding for record in records for finding in _classify_record_links(record, identities, severity)]
|
|
165
|
+
return (
|
|
166
|
+
[finding for finding in findings if finding.code == "dangling_link"],
|
|
167
|
+
[finding for finding in findings if finding.code == "self_referential_link"],
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _rebuild_delta(
|
|
172
|
+
records: Sequence[ArtifactRecord], previous_index: ArtifactEvidenceIndex | None
|
|
173
|
+
) -> tuple[list[str], list[str]]:
|
|
174
|
+
prior = {record.identity: record for record in (previous_index.artifacts if previous_index else [])}
|
|
175
|
+
current = {record.identity: record for record in records}
|
|
176
|
+
changed = sorted(
|
|
177
|
+
identity
|
|
178
|
+
for identity, record in current.items()
|
|
179
|
+
if identity not in prior or _record_signature(record) != _record_signature(prior[identity])
|
|
180
|
+
)
|
|
181
|
+
return changed, sorted(set(prior) - set(current))
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@require(
|
|
185
|
+
lambda records: all(isinstance(record, ArtifactRecord) for record in records),
|
|
186
|
+
"records must contain ArtifactRecord values",
|
|
187
|
+
)
|
|
188
|
+
@ensure(lambda result: isinstance(result, ArtifactIndexBuildResult), "result must be an ArtifactIndexBuildResult")
|
|
189
|
+
@beartype
|
|
190
|
+
def build_artifact_index(
|
|
191
|
+
records: Sequence[ArtifactRecord],
|
|
192
|
+
*,
|
|
193
|
+
previous_index: ArtifactEvidenceIndex | None = None,
|
|
194
|
+
profile: RequirementContextValidationProfile = "startup",
|
|
195
|
+
) -> ArtifactIndexBuildResult:
|
|
196
|
+
"""Build a generic deterministic index without collecting or persisting artifacts."""
|
|
197
|
+
severity = _severity(profile)
|
|
198
|
+
canonical, duplicates = _canonical_records(records)
|
|
199
|
+
identities = {record.identity for record in canonical}
|
|
200
|
+
incoming = _incoming_links(canonical, identities)
|
|
201
|
+
drift, contradictions = _link_findings(canonical, identities, severity)
|
|
202
|
+
changed, removed = _rebuild_delta(canonical, previous_index)
|
|
203
|
+
return ArtifactIndexBuildResult(
|
|
204
|
+
index=ArtifactEvidenceIndex(artifacts=canonical),
|
|
205
|
+
orphans=_orphan_findings(canonical, incoming, severity),
|
|
206
|
+
drift=drift,
|
|
207
|
+
ambiguities=[_finding("duplicate_identity", identity, severity) for identity in duplicates],
|
|
208
|
+
contradictions=contradictions,
|
|
209
|
+
changed_identities=changed,
|
|
210
|
+
removed_identities=removed,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@require(
|
|
215
|
+
lambda requirements: all(isinstance(requirement, RequirementInput) for requirement in requirements),
|
|
216
|
+
"requirements must contain RequirementInput values",
|
|
217
|
+
)
|
|
218
|
+
@beartype
|
|
219
|
+
def requirements_to_artifact_records(requirements: Sequence[RequirementInput]) -> list[ArtifactRecord]:
|
|
220
|
+
"""Map normalized requirements into generic core artifacts without parsing sources."""
|
|
221
|
+
return [
|
|
222
|
+
ArtifactRecord(
|
|
223
|
+
identity=f"requirement:{requirement.requirement_id}",
|
|
224
|
+
kind=ArtifactKind.REQUIREMENT,
|
|
225
|
+
locator=requirement.requirement_id,
|
|
226
|
+
fingerprint=json.dumps(requirement.model_dump(mode="json"), sort_keys=True, separators=(",", ":")),
|
|
227
|
+
links=[
|
|
228
|
+
ArtifactLink(target=f"{link.link_type}:{link.target}", relation=link.relation)
|
|
229
|
+
for link in requirement.evidence_links
|
|
230
|
+
],
|
|
231
|
+
)
|
|
232
|
+
for requirement in requirements
|
|
233
|
+
]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _known_target_records(requirements: Sequence[RequirementInput], known_targets: Set[str]) -> list[ArtifactRecord]:
|
|
237
|
+
kinds_by_target: dict[str, set[ArtifactKind]] = {}
|
|
238
|
+
link_kind_map = {
|
|
239
|
+
"architecture": ArtifactKind.ARCHITECTURE,
|
|
240
|
+
"spec": ArtifactKind.SPECIFICATION,
|
|
241
|
+
"code": ArtifactKind.CODE,
|
|
242
|
+
"test": ArtifactKind.TEST,
|
|
243
|
+
"validation": ArtifactKind.VALIDATION,
|
|
244
|
+
"requirement": ArtifactKind.REQUIREMENT,
|
|
245
|
+
}
|
|
246
|
+
for requirement in requirements:
|
|
247
|
+
for link in requirement.evidence_links:
|
|
248
|
+
if link.target in known_targets:
|
|
249
|
+
kinds_by_target.setdefault(link.target, set()).add(link_kind_map[str(link.link_type)])
|
|
250
|
+
return [
|
|
251
|
+
ArtifactRecord(
|
|
252
|
+
identity=f"{kind_prefix}:{target}",
|
|
253
|
+
kind=kind,
|
|
254
|
+
locator=target,
|
|
255
|
+
fingerprint=target,
|
|
256
|
+
)
|
|
257
|
+
for target in sorted(known_targets)
|
|
258
|
+
for kind in sorted(kinds_by_target.get(target, {ArtifactKind.CODE}), key=lambda item: item.value)
|
|
259
|
+
for kind_prefix in [next(prefix for prefix, value in link_kind_map.items() if value is kind)]
|
|
260
|
+
]
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
@require(lambda bundle: isinstance(bundle, ProjectBundle), "bundle must be a ProjectBundle")
|
|
264
|
+
@require(lambda profile: isinstance(profile, str) and bool(profile.strip()), "profile must not be empty")
|
|
265
|
+
@require(
|
|
266
|
+
lambda profile: profile in KNOWN_REQUIREMENT_CONTEXT_PROFILES, "profile must be a supported validation profile"
|
|
267
|
+
)
|
|
268
|
+
@ensure(lambda result: isinstance(result, TraceabilityResult), "result must be a TraceabilityResult")
|
|
269
|
+
@beartype
|
|
270
|
+
def analyze_requirement_traceability(
|
|
271
|
+
bundle: ProjectBundle,
|
|
272
|
+
*,
|
|
273
|
+
profile: RequirementContextValidationProfile,
|
|
274
|
+
known_targets: Set[str] | None = None,
|
|
275
|
+
) -> TraceabilityResult:
|
|
276
|
+
"""Analyze requirements; link drift requires a caller-provided target universe."""
|
|
277
|
+
requirements = load_requirements_from_bundle(bundle)
|
|
278
|
+
records = requirements_to_artifact_records(requirements)
|
|
279
|
+
if known_targets is not None:
|
|
280
|
+
records.extend(_known_target_records(requirements, known_targets))
|
|
281
|
+
result = build_artifact_index(records, profile=profile)
|
|
282
|
+
if known_targets is None:
|
|
283
|
+
return result.model_copy(update={"drift": []})
|
|
284
|
+
return result
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: specfact-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.52.3
|
|
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,8 +1,10 @@
|
|
|
1
|
-
specfact_cli/__init__.py,sha256=
|
|
1
|
+
specfact_cli/__init__.py,sha256=nl4udXmBs_BjzLQcrAYNaBDunkzbWt2LHHpP3ArNy90,2764
|
|
2
2
|
specfact_cli/__main__.py,sha256=EpP5xlutNYI5AuMlMw8fGt1TywZUR1-CXHpzpWKyNuo,141
|
|
3
3
|
specfact_cli/cli.py,sha256=GRsW3xTJh1pPJl7VpshvPT6YiHgJMMsKt7lE94ZcrAA,53151
|
|
4
|
+
specfact_cli/evidence.py,sha256=51UTnikb2WY_wktg4D_-1jH9YR4WKXG-aZ6NkL_10lU,2924
|
|
4
5
|
specfact_cli/runtime.py,sha256=4tEcOsz2bE6-KuZF5nuHvHuwinO7l8fNAGzrra9pNrc,13474
|
|
5
6
|
specfact_cli/telemetry.py,sha256=LS34mq8jIJPcXFCm9SgLRjDUe7Ks41fPWvZmD6PXcVM,31079
|
|
7
|
+
specfact_cli/traceability.py,sha256=o3ZoxoNe5A2sFs-L-EYu0ULj0Yrrr_zYEwlmHydqlRw,11109
|
|
6
8
|
specfact_cli/adapters/__init__.py,sha256=phzCwBSYzkXSLA6nIZan_EyInGNJ4SedmdRuAp3hyho,932
|
|
7
9
|
specfact_cli/adapters/ado.py,sha256=gLsiEjnwfXWTpWVcL2GgitJOLny7d6KtzXnqdQYK-Ds,163388
|
|
8
10
|
specfact_cli/adapters/backlog_base.py,sha256=CLsFDKhxxQeU00Tqj2glKiRn-eBPmAQ4S5J9BV_9geA,26167
|
|
@@ -155,8 +157,9 @@ specfact_cli/registry/module_packages.py,sha256=jpyxc5tPwitHDWXtJyqdy18W7EVvHNxd
|
|
|
155
157
|
specfact_cli/registry/module_security.py,sha256=RfKJmkR9sdBXP7q1YBsK1Io-ys0vhHshhPR06uk5TjM,4517
|
|
156
158
|
specfact_cli/registry/module_state.py,sha256=zBMPrjJOhTBZmSY7tur5gOABcRgXZWf_qpOL9iIRRLY,3463
|
|
157
159
|
specfact_cli/registry/registry.py,sha256=FnQz9-jkiQ1f1e9YjfOZ_Rx7yRVj_mhKQuvoCgmSA78,6856
|
|
158
|
-
specfact_cli/requirements/__init__.py,sha256=
|
|
159
|
-
specfact_cli/requirements/context.py,sha256=
|
|
160
|
+
specfact_cli/requirements/__init__.py,sha256=zTqn6HrNS95Dl8FpsJe6qeQT8LM6zamRbyLQKqoMIo4,1012
|
|
161
|
+
specfact_cli/requirements/context.py,sha256=O5R2btyCC9xn3Ypqrev1EF-P5qeMChcSG-lFPga3cns,22180
|
|
162
|
+
specfact_cli/requirements/importers.py,sha256=_WziYtDQ0fRma25pzjaPPYgUhsfe8wfFpj5hu5x_eSo,13344
|
|
160
163
|
specfact_cli/resources/semgrep/async.yml,sha256=pz4xuPx7_CAEAwN-iq1zyc8srcid3GYtl7exsr1_5k8,8232
|
|
161
164
|
specfact_cli/resources/semgrep/code-quality.yml,sha256=Nx-E2XuShwioUJhG-JvjEgOMPU9FuNr7H-VCCjKia30,7749
|
|
162
165
|
specfact_cli/resources/semgrep/feature-detection.yml,sha256=6nZ6sqVtAmGWZxgZYJwu_YNv59xIYgRJsM-5ZtFxXUw,21538
|
|
@@ -290,8 +293,8 @@ specfact_cli/resources/templates/policies/kanban.yaml,sha256=9jt7YYfZ8e8aB5skY2D
|
|
|
290
293
|
specfact_cli/resources/templates/policies/mixed.yaml,sha256=-fkrT-TLKLTBzjKeKr8bEJHFC-nh1TlyLOEFfgRdSi8,243
|
|
291
294
|
specfact_cli/resources/templates/policies/safe.yaml,sha256=uiwe5_ABvaU4nmq6rsLUn8zRotkBITItPUsdPZPTHTw,157
|
|
292
295
|
specfact_cli/resources/templates/policies/scrum.yaml,sha256=6FHYOntkjCxHAn-ga14IQzA1PvYUJgxfLsEQYtWJILM,188
|
|
293
|
-
specfact_cli-0.
|
|
294
|
-
specfact_cli-0.
|
|
295
|
-
specfact_cli-0.
|
|
296
|
-
specfact_cli-0.
|
|
297
|
-
specfact_cli-0.
|
|
296
|
+
specfact_cli-0.52.3.dist-info/METADATA,sha256=o1esXWZ7mkpw9ntEZ38ZfqOYo-atji3EQJ3Si9HSHis,25946
|
|
297
|
+
specfact_cli-0.52.3.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
298
|
+
specfact_cli-0.52.3.dist-info/entry_points.txt,sha256=pwDD5Ttu6AF3p3T05M4G0aR2BELFyUu3214kjMRGEow,96
|
|
299
|
+
specfact_cli-0.52.3.dist-info/licenses/LICENSE,sha256=nWX_6oozyEFlF3mDaSWyBD9HLpyLRmCYYqdcgoVOrOk,11361
|
|
300
|
+
specfact_cli-0.52.3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|