Repository navigation
Expand file tree
/
Copy pathcheck-feature-context.py
More file actions
921 lines (832 loc) · 35 KB
/
Copy pathcheck-feature-context.py
File metadata and controls
921 lines (832 loc) · 35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import re
import sys
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from checker_support import (
CheckFailure,
configure_utf8_stdio,
discover_memory_root_authority,
optional_section,
read_text,
require_supported_python,
table,
)
from feature_authority_support import (
BUG_ADAPTER,
CUSTOM_ADAPTER,
FEATURE_ADAPTER,
HUMAN_ADAPTER,
REQUIREMENT_ADAPTER,
AuthorityResolution,
is_external_locator,
resolve_feature_authority,
)
from requirement_product_support import (
CONCEPT_ID_PATTERN,
EffectiveProductSource,
MODEL_ID_PATTERN,
ProductDefinitionError,
normalized,
resolve_effective_product_definition,
)
CURRENT = 0
BLOCKED = 1
CHANGED = 0
NOT_APPLICABLE = 0
COMPATIBLE_REQUIREMENT_STATUS = {
"accepted",
"in-progress",
"partially-implemented",
"implemented",
}
SHA256 = re.compile(r"[0-9a-f]{64}")
REQUIRED_SNAPSHOT_FIELDS = (
"Requirement Set",
"Requirement Lifecycle",
"Resolved Product Source",
"Product Definition Profile",
"Product Review",
"Product Source SHA-256",
"Applicable Decisions",
"Decision Source SHA-256",
"Product Slice References",
"Verified At",
"Freshness",
)
REQUIRED_SNAPSHOT_SECTIONS = (
"Product Outcome",
"Actors And Core Journey",
"Applicable Product Rules And Invariants",
"Applicable States, Exceptions, And Recovery",
"Feature Boundary And Acceptance Context",
)
COMMON_AUTHORITY_SNAPSHOT_FIELDS = (
"Authority Type",
"Authority Adapter",
"Primary Authority Reference",
"Supporting Authority References",
"Authority Applicability",
"Authority Facts",
"Authority Source SHA-256",
"Verified At",
"Freshness",
)
@dataclass(frozen=True)
class ContextResult:
status: str
reasons: tuple[str, ...]
@property
def exit_code(self) -> int:
return {
"current": CURRENT,
"changed": CHANGED,
"not_applicable": NOT_APPLICABLE,
"blocked": BLOCKED,
}[self.status]
class AuthorityFailure(ValueError):
"""Physical or uniqueness contradiction that prevents safe source resolution."""
def field(text: str, name: str) -> str | None:
match = re.search(
rf"(?mi)^\s*(?:-\s*)?{re.escape(name)}\s*:\s*(.*?)\s*$",
text,
)
return match.group(1).strip() if match else None
def project_path(project_root: Path, value: str) -> Path:
cleaned = normalized(value).replace("\\", "/")
candidate = Path(cleaned)
if candidate.is_absolute():
raise AuthorityFailure(f"path must be project-root-relative: {value}")
resolved = (project_root / candidate).resolve()
try:
resolved.relative_to(project_root.resolve())
except ValueError as error:
raise AuthorityFailure(f"path escapes project root: {value}") from error
return resolved
def compatible_text_digests(path: Path) -> frozenset[str]:
raw = path.read_bytes()
canonical = raw.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
crlf = canonical.replace(b"\n", b"\r\n")
return frozenset(
hashlib.sha256(content).hexdigest()
for content in (raw, canonical, crlf)
)
def heading_anchors(content: str) -> set[str]:
values = re.findall(r"^#{2,3}\s+(.+?)\s*$", content, re.MULTILINE)
anchors = set()
for value in values:
cleaned = re.sub(r"[^a-z0-9 -]", "", value.lower())
anchors.add(re.sub(r"[ -]+", "-", cleaned).strip("-"))
return anchors
def memory_root_for(project_root: Path, feature_spec: Path) -> Path:
try:
authority = discover_memory_root_authority(project_root)
except CheckFailure as error:
raise AuthorityFailure(error.detail) from error
if authority is None:
raise AuthorityFailure("project must contain exactly one accepted memory root")
try:
feature_relative = feature_spec.resolve().relative_to(authority.resolved)
except ValueError as error:
raise AuthorityFailure(
"Feature spec is outside the accepted memory root"
) from error
if len(feature_relative.parts) < 3 or feature_relative.parts[0] != "features":
raise AuthorityFailure(
"Feature spec must be inside the memory root features directory"
)
return authority.logical
def require_within(path: Path, boundary: Path, label: str) -> None:
try:
path.resolve().relative_to(boundary.resolve())
except ValueError as error:
raise AuthorityFailure(f"{label} escapes accepted boundary") from error
def relative_project_path(project_root: Path, path: Path) -> str:
resolved = path.resolve()
try:
authority = discover_memory_root_authority(project_root)
except CheckFailure:
authority = None
if authority is not None:
try:
within_memory = resolved.relative_to(authority.resolved)
except ValueError:
pass
else:
return (
authority.logical.relative_to(project_root) / within_memory
).as_posix()
try:
return path.relative_to(project_root).as_posix()
except ValueError:
return resolved.relative_to(project_root.resolve()).as_posix()
def effective_source_path(readme_path: Path, readme_text: str) -> Path:
new_pointer = optional_section(readme_text, "Effective Product Definition")
legacy_pointer = optional_section(readme_text, "Effective Concept Foundation")
if new_pointer is not None and legacy_pointer is not None:
raise AuthorityFailure("multiple effective product source pointers")
if new_pointer is not None:
source_value = field(new_pointer, "Source")
elif legacy_pointer is not None:
source_value = field(legacy_pointer, "Effective Source")
else:
raise AuthorityFailure("missing effective product source pointer")
if not normalized(source_value):
raise AuthorityFailure("effective product source pointer is missing")
cleaned = normalized(source_value).replace("\\", "/")
candidate = Path(cleaned)
if candidate.is_absolute():
raise AuthorityFailure(
"effective product source must be Requirement-relative"
)
source_path = (readme_path.parent / candidate).resolve()
require_within(source_path, readme_path.parent, "effective product source")
return source_path
def best_effort_source_facts(
readme_path: Path,
source_path: Path,
) -> tuple[EffectiveProductSource, str | None]:
"""Read objective source facts even when strict product semantics need review."""
try:
return resolve_effective_product_definition(readme_path, source_path), None
except (CheckFailure, ProductDefinitionError) as error:
content = read_text(source_path)
readme_text = read_text(readme_path)
legacy = optional_section(readme_text, "Effective Concept Foundation") is not None
profile = None if legacy else normalized(field(content, "Product Definition Profile"))
review = normalized(
field(
content,
"Concept Foundation Status" if legacy else "Product Review",
)
)
return (
EffectiveProductSource(
path=source_path.resolve(),
content=content,
kind="concept-foundation" if legacy else "product-definition",
profile=profile or None,
review=review,
legacy=legacy,
concept_ids=frozenset(CONCEPT_ID_PATTERN.findall(content)),
model_ids=frozenset(MODEL_ID_PATTERN.findall(content)),
),
str(error),
)
def validate_references(
value: str,
known_ids: set[str],
known_anchors: set[str],
*,
label: str,
) -> None:
ids = set(CONCEPT_ID_PATTERN.findall(value))
ids.update(MODEL_ID_PATTERN.findall(value))
anchors = set(re.findall(r"product\.md#([a-z0-9-]+)", value))
unknown_ids = sorted(ids - known_ids)
unknown_anchors = sorted(anchors - known_anchors)
if unknown_ids:
raise ValueError(f"{label} contains unknown source IDs: {', '.join(unknown_ids)}")
if unknown_anchors:
raise ValueError(
f"{label} contains unknown source anchors: {', '.join(unknown_anchors)}"
)
def decision_paths(
project_root: Path,
memory_root: Path,
raw_value: str,
) -> list[tuple[str, Path]]:
if normalized(raw_value).lower() == "none":
return []
values = [normalized(item) for item in raw_value.split(",")]
if any(not value for value in values):
raise ValueError("Applicable Decisions contains an empty path")
if len(values) != len(set(values)):
raise ValueError("Applicable Decisions contains duplicate paths")
result: list[tuple[str, Path]] = []
decisions_root = memory_root / "decisions"
for value in values:
path = project_path(project_root, value)
require_within(path, decisions_root, "Applicable Decision")
if path.suffix.lower() != ".md":
raise AuthorityFailure(f"Applicable Decision is not Markdown: {value}")
result.append((relative_project_path(project_root, path), path))
return result
def recorded_decision_digests(raw_value: str) -> dict[str, str]:
if normalized(raw_value).lower() == "none":
return {}
result: dict[str, str] = {}
for item in raw_value.split(";"):
if "=" not in item:
raise ValueError("Decision Source SHA-256 contains a malformed entry")
raw_path, raw_digest = item.split("=", 1)
path_value = normalized(raw_path).replace("\\", "/")
digest_value = normalized(raw_digest)
if not path_value or not SHA256.fullmatch(digest_value):
raise ValueError("Decision Source SHA-256 contains malformed evidence")
if path_value in result:
raise ValueError("Decision Source SHA-256 contains duplicate paths")
result[path_value] = digest_value
return result
def valid_verified_at(value: str) -> bool:
candidate = normalized(value)
if candidate.endswith("Z"):
candidate = f"{candidate[:-1]}+00:00"
try:
parsed = datetime.fromisoformat(candidate)
except ValueError:
return False
return parsed.tzinfo is not None
def normalized_reference(value: str | None) -> str:
return normalized(value).replace("\\", "/")
def supporting_reference_set(value: str | None) -> set[str]:
cleaned = normalized(value)
if not cleaned or cleaned.casefold() == "none":
return set()
return {
normalized_reference(item)
for item in cleaned.split(";")
if normalized(item)
}
def same_local_authority_reference(
project_root: Path,
left: str | None,
right: str | None,
) -> bool:
left_value = normalized_reference(left)
right_value = normalized_reference(right)
if left_value == right_value:
return True
if not left_value or not right_value:
return False
if is_external_locator(left_value, REQUIREMENT_ADAPTER) or is_external_locator(
right_value,
REQUIREMENT_ADAPTER,
):
return False
try:
return project_path(project_root, left_value) == project_path(
project_root,
right_value,
)
except AuthorityFailure:
return False
def adapter_label_matches(recorded: str, authority: AuthorityResolution) -> bool:
slug = re.sub(r"[^a-z0-9]+", "-", recorded.casefold()).strip("-")
aliases = {
REQUIREMENT_ADAPTER: {
REQUIREMENT_ADAPTER,
"feature-authority-requirement-product-definition",
},
FEATURE_ADAPTER: {FEATURE_ADAPTER, "feature-authority"},
BUG_ADAPTER: {BUG_ADAPTER, "bug-authority"},
HUMAN_ADAPTER: {HUMAN_ADAPTER, "human-authority"},
}
if authority.adapter == CUSTOM_ADAPTER:
return bool(slug)
return slug in aliases[authority.adapter]
def authority_fact(authority: AuthorityResolution, prefix: str) -> str:
for fact in authority.facts:
if fact.startswith(prefix):
return fact[len(prefix) :]
return ""
def common_authority_snapshot_reasons(
project_root: Path,
snapshot: str | None,
authority: AuthorityResolution,
) -> list[str]:
if authority.compatibility_shape != "explicit-feature-authority":
return []
if snapshot is None:
return ["Feature Context Snapshot is missing for explicit Feature Authority"]
values = {
name: normalized(field(snapshot, name)) or None
for name in COMMON_AUTHORITY_SNAPSHOT_FIELDS
}
reasons = [
f"Snapshot field is missing: {name}"
for name, value in values.items()
if value is None
]
recorded_type = values["Authority Type"]
if recorded_type and recorded_type != authority.authority_type:
reasons.append("Snapshot Authority Type differs from Feature Authority")
recorded_adapter = values["Authority Adapter"]
if recorded_adapter and not adapter_label_matches(recorded_adapter, authority):
reasons.append("Snapshot Authority Adapter differs from resolved adapter")
recorded_primary = values["Primary Authority Reference"]
if recorded_primary and normalized_reference(recorded_primary) != normalized_reference(
authority.primary_reference
):
reasons.append("Snapshot Primary Authority Reference changed")
recorded_supporting = values["Supporting Authority References"]
if recorded_supporting and supporting_reference_set(recorded_supporting) != {
normalized_reference(item) for item in authority.supporting_references
}:
reasons.append("Snapshot Supporting Authority References changed")
recorded_applicability = values["Authority Applicability"]
if recorded_applicability and recorded_applicability != authority.applicability:
reasons.append("Snapshot Authority Applicability changed")
recorded_facts = values["Authority Facts"]
if recorded_facts and normalized(recorded_facts) != "; ".join(authority.facts):
reasons.append("Snapshot Authority Facts differ from resolved authority facts")
raw_digest = values["Authority Source SHA-256"]
primary_external = is_external_locator(
authority.primary_reference,
authority.adapter,
)
if raw_digest:
if primary_external:
if raw_digest.casefold() != "none":
reasons.append(
"external Authority Source SHA-256 must be none and remain advisory"
)
elif raw_digest.casefold() == "none":
reasons.append("local Authority Source SHA-256 is missing")
elif "=" not in raw_digest:
reasons.append("Authority Source SHA-256 contains malformed evidence")
else:
raw_path, raw_value = raw_digest.split("=", 1)
recorded_path = normalized_reference(raw_path)
digest_value = normalized(raw_value)
if recorded_path != normalized_reference(authority.primary_reference):
reasons.append("Authority Source SHA-256 path differs from primary authority")
elif not SHA256.fullmatch(digest_value):
reasons.append("Authority Source SHA-256 is malformed")
else:
try:
source_path = project_path(project_root, authority.primary_reference)
if digest_value not in compatible_text_digests(source_path):
reasons.append("Authority Source SHA-256 changed")
except (AuthorityFailure, OSError) as error:
reasons.append(
f"Authority Source SHA-256 cached path is invalid: {error}"
)
verified_at = values["Verified At"]
if verified_at and not valid_verified_at(verified_at):
reasons.append("Verified At must be an ISO-8601 timestamp with a timezone")
freshness = values["Freshness"]
if freshness == "blocked":
reasons.append("Snapshot Freshness records blocked authority facts")
elif freshness in {"refresh-required", "changed"}:
reasons.append("Snapshot Freshness records changed authority facts")
elif freshness not in {None, "current"}:
reasons.append("Snapshot Freshness value is unsupported")
if authority.adapter == BUG_ADAPTER:
bug_fields = {
"Bug ID": authority_fact(authority, "Bug ID "),
"Expected Behavior Evidence Locator": authority_fact(
authority,
"Expected Behavior evidence ",
),
"Feature Location": authority_fact(authority, "Feature Location "),
}
for name, expected in bug_fields.items():
recorded = normalized(field(snapshot, name))
if not recorded:
reasons.append(f"Bug Snapshot field is missing: {name}")
elif expected and recorded != expected:
reasons.append(f"Bug Snapshot field changed: {name}")
route = normalized(field(snapshot, "Resolution Path / Fix Feature Locator"))
expected_path = authority_fact(authority, "Resolution Path ")
expected_feature = authority_fact(authority, "Fix Feature ")
if not route:
reasons.append(
"Bug Snapshot field is missing: Resolution Path / Fix Feature Locator"
)
elif expected_path not in route or expected_feature not in route:
reasons.append("Bug Snapshot Resolution Path / Fix Feature Locator changed")
if authority.adapter in {HUMAN_ADAPTER, CUSTOM_ADAPTER}:
evidence_locator = normalized_reference(field(snapshot, "Evidence Locator"))
if not evidence_locator:
reasons.append("advisory Snapshot Evidence Locator is missing")
elif evidence_locator != normalized_reference(authority.primary_reference):
reasons.append("advisory Snapshot Evidence Locator changed")
if normalized(field(snapshot, "Agent Review Required")).casefold() != "yes":
reasons.append("advisory Snapshot must record Agent Review Required: yes")
return reasons
def classify(
project_root: Path,
feature_spec: Path,
) -> ContextResult:
blocked_reasons: list[str] = []
changed_reasons: list[str] = []
try:
require_within(feature_spec, project_root, "Feature spec")
if not feature_spec.is_file():
raise ValueError(f"missing Feature spec: {feature_spec}")
memory_root = memory_root_for(project_root, feature_spec)
spec_text = read_text(feature_spec)
except (OSError, UnicodeError, ValueError) as error:
return ContextResult("blocked", (str(error),))
authority = resolve_feature_authority(project_root, feature_spec, spec_text)
if authority.status == "blocked":
return ContextResult("blocked", authority.reasons)
snapshot = optional_section(spec_text, "Feature Context Snapshot")
changed_reasons.extend(
common_authority_snapshot_reasons(project_root, snapshot, authority)
)
if authority.adapter != REQUIREMENT_ADAPTER:
if authority.status == "changed":
changed_reasons.extend(authority.reasons)
if changed_reasons:
return ContextResult("changed", tuple(sorted(set(changed_reasons))))
return ContextResult("current", authority.reasons)
if authority.status == "changed":
changed_reasons.extend(authority.reasons)
source_section = optional_section(spec_text, "Product Requirement Source")
if source_section is None:
return ContextResult(
"blocked",
("Feature spec is missing Product Requirement Source",),
)
if snapshot is None:
changed_reasons.append("Feature Context Snapshot is missing")
snapshot_fields: dict[str, str | None] = {}
else:
snapshot_fields = {
name: normalized(field(snapshot, name)) or None
for name in REQUIRED_SNAPSHOT_FIELDS
}
for name, value in snapshot_fields.items():
if value is None:
changed_reasons.append(f"Snapshot field is missing: {name}")
for heading in REQUIRED_SNAPSHOT_SECTIONS:
content = optional_section(snapshot, heading, level=3)
if content is None or not content.strip():
changed_reasons.append(f"Snapshot section is incomplete: {heading}")
source_requirement = normalized(field(source_section, "Requirement Set"))
if (
authority.compatibility_shape == "explicit-feature-authority"
and source_requirement
and not same_local_authority_reference(
project_root,
authority.primary_reference,
source_requirement,
)
):
blocked_reasons.append(
"Feature Authority primary reference conflicts with "
"Product Requirement Source Requirement Set"
)
snapshot_requirement = snapshot_fields.get("Requirement Set")
if snapshot_requirement and source_requirement:
if snapshot_requirement.replace("\\", "/") != source_requirement.replace("\\", "/"):
changed_reasons.append("Feature contains ambiguous Requirement Set pointers")
requirement_value = source_requirement
if not source_requirement:
blocked_reasons.append("Requirement Set pointer is missing")
readme_path: Path | None = None
source = None
readme_text = ""
actual_lifecycle = ""
if requirement_value:
try:
readme_path = project_path(project_root, requirement_value)
require_within(readme_path, memory_root / "requirements", "Requirement Set")
if readme_path.name != "README.md":
raise AuthorityFailure("Requirement Set must point to README.md")
if not readme_path.is_file():
raise AuthorityFailure(
f"Requirement README is missing: {requirement_value}"
)
readme_text = read_text(readme_path)
actual_lifecycle = normalized(field(readme_text, "Status"))
if actual_lifecycle not in COMPATIBLE_REQUIREMENT_STATUS:
changed_reasons.append(
"Requirement lifecycle is incompatible: "
f"{actual_lifecycle or 'missing'}"
)
resolved_source = effective_source_path(readme_path, readme_text)
require_within(
resolved_source,
readme_path.parent,
"resolved Product Definition",
)
require_within(
resolved_source,
memory_root,
"resolved Product Definition",
)
if not resolved_source.is_file():
raise AuthorityFailure(
f"resolved Product Definition is missing: {resolved_source}"
)
source, source_issue = best_effort_source_facts(
readme_path,
resolved_source,
)
if source_issue:
changed_reasons.append(
f"Product authority needs Agent review: {source_issue}"
)
except (
AuthorityFailure,
OSError,
UnicodeError,
) as error:
blocked_reasons.append(str(error))
if source is not None and readme_path is not None:
resolved_value = snapshot_fields.get("Resolved Product Source")
recorded_profile = snapshot_fields.get("Product Definition Profile")
recorded_review = snapshot_fields.get("Product Review")
source_product_value = normalized(
field(source_section, "Effective Product Definition")
)
if source_product_value:
try:
source_product_candidate = Path(
source_product_value.replace("\\", "/")
)
if (
source_product_value == source_product_candidate.name
and source_product_candidate.name == source.path.name
):
source_product_path = source.path
else:
source_product_path = project_path(
project_root,
source_product_value,
)
require_within(
source_product_path,
readme_path.parent,
"Product Requirement Source Product Definition",
)
if resolved_value:
snapshot_product_path = project_path(
project_root,
resolved_value,
)
if source_product_path != snapshot_product_path:
changed_reasons.append(
"Feature contains ambiguous "
"Effective Product Definition pointers"
)
if source_product_path != source.path:
changed_reasons.append(
"Product Requirement Source Product Definition changed"
)
except AuthorityFailure as error:
changed_reasons.append(
"Product Requirement Source Effective Product Definition "
f"is invalid cached evidence: {error}"
)
else:
changed_reasons.append(
"Product Requirement Source Effective Product Definition is missing"
)
expected_profile = source.profile or ("legacy" if source.legacy else "unknown")
source_profile = normalized(
field(source_section, "Product Definition Profile")
)
if source_profile:
if recorded_profile and source_profile != recorded_profile:
changed_reasons.append(
"Feature contains ambiguous Product Definition Profile values"
)
if source_profile != expected_profile:
changed_reasons.append(
"Product Requirement Source Product Definition Profile changed"
)
else:
changed_reasons.append(
"Product Requirement Source Product Definition Profile is missing"
)
source_review_evidence = normalized(
field(source_section, "Product Review Evidence")
)
expected_review = source.review
if not source_review_evidence:
changed_reasons.append(
"Product Requirement Source Product Review Evidence is missing"
)
elif recorded_review and not re.search(
rf"(?i)(?<![a-z]){re.escape(recorded_review)}(?![a-z])",
source_review_evidence,
):
changed_reasons.append(
"Product Requirement Source Product Review Evidence "
f"does not confirm {recorded_review}"
)
recorded_lifecycle = snapshot_fields.get("Requirement Lifecycle")
if recorded_lifecycle and recorded_lifecycle != actual_lifecycle:
changed_reasons.append("Requirement Lifecycle changed")
resolved_relative = relative_project_path(project_root, source.path)
if resolved_value:
try:
recorded_source = project_path(project_root, resolved_value)
require_within(
recorded_source,
readme_path.parent,
"recorded Product Source",
)
require_within(
recorded_source,
memory_root,
"recorded Product Source",
)
if recorded_source.resolve() != source.path.resolve():
changed_reasons.append("Resolved Product Source changed")
except AuthorityFailure as error:
changed_reasons.append(
f"recorded Product Source is invalid cached evidence: {error}"
)
elif snapshot is not None:
changed_reasons.append("Resolved Product Source is missing")
if recorded_profile and recorded_profile != expected_profile:
changed_reasons.append("Product Definition Profile changed")
if recorded_review and recorded_review != source.review:
changed_reasons.append("Product Review evidence changed")
product_digest = snapshot_fields.get("Product Source SHA-256")
if product_digest:
if not SHA256.fullmatch(product_digest):
changed_reasons.append("Product Source SHA-256 is malformed")
elif product_digest not in compatible_text_digests(source.path):
changed_reasons.append("Product Source SHA-256 changed")
verified_at = snapshot_fields.get("Verified At")
if verified_at and not valid_verified_at(verified_at):
changed_reasons.append(
"Verified At must be an ISO-8601 timestamp with a timezone"
)
known_ids = set(source.concept_ids) | set(source.model_ids)
known_anchors = heading_anchors(source.content)
try:
for row in table(spec_text, "Product Slice"):
validate_references(
row.get("Source Section / Model ID", ""),
known_ids,
known_anchors,
label="Product Slice",
)
snapshot_references = snapshot_fields.get("Product Slice References")
if snapshot_references:
validate_references(
snapshot_references,
known_ids,
known_anchors,
label="Product Slice References",
)
if not (
CONCEPT_ID_PATTERN.search(snapshot_references)
or MODEL_ID_PATTERN.search(snapshot_references)
or re.search(r"product\.md#[a-z0-9-]+", snapshot_references)
):
changed_reasons.append(
"Product Slice References contains no resolvable reference"
)
except (CheckFailure, ValueError) as error:
changed_reasons.append(str(error))
source_decisions = (
normalized(field(source_section, "Applicable Decisions")) or "none"
)
raw_decisions = snapshot_fields.get("Applicable Decisions") or source_decisions
try:
source_decision_paths = decision_paths(
project_root,
memory_root,
source_decisions,
)
snapshot_decision_paths = decision_paths(
project_root,
memory_root,
raw_decisions,
)
if snapshot_fields.get("Applicable Decisions") is not None and {
display_path for display_path, _ in snapshot_decision_paths
} != {
display_path for display_path, _ in source_decision_paths
}:
changed_reasons.append(
"Feature contains ambiguous Applicable Decisions pointers"
)
decisions = source_decision_paths
for display_path, decision_path in decisions:
if not decision_path.is_file():
raise AuthorityFailure(
f"Applicable Decision is missing: {display_path}"
)
decision_text = read_text(decision_path)
status = normalized(field(decision_text, "Status"))
compatibility = normalized(
field(decision_text, "Upstream Compatibility")
)
if status != "accepted":
changed_reasons.append(
f"Applicable Decision is not accepted: {display_path}"
)
if compatibility != "current":
changed_reasons.append(
"Applicable Decision Upstream Compatibility is not current: "
f"{display_path}"
)
raw_evidence = snapshot_fields.get("Decision Source SHA-256")
if raw_evidence:
evidence = recorded_decision_digests(raw_evidence)
decision_names = {display for display, _ in decisions}
if set(evidence) != decision_names:
changed_reasons.append(
"Decision Source SHA-256 paths differ from Applicable Decisions"
)
for display_path, decision_path in decisions:
if display_path in evidence and evidence[display_path] not in compatible_text_digests(decision_path):
changed_reasons.append(
f"Decision Source SHA-256 changed: {display_path}"
)
elif snapshot is not None:
changed_reasons.append("Decision Source SHA-256 is missing")
except AuthorityFailure as error:
blocked_reasons.append(str(error))
except (OSError, UnicodeError) as error:
blocked_reasons.append(str(error))
except ValueError as error:
changed_reasons.append(str(error))
if resolved_value and resolved_value.replace("\\", "/") != resolved_relative:
changed_reasons.append("recorded Product Source path is stale")
recorded_freshness = snapshot_fields.get("Freshness")
if recorded_freshness == "blocked":
changed_reasons.append("Snapshot Freshness records legacy blocked")
elif recorded_freshness in {"refresh-required", "changed"}:
changed_reasons.append("Snapshot Freshness records changed facts")
elif recorded_freshness not in {None, "current"}:
changed_reasons.append("Snapshot Freshness value is unsupported")
if blocked_reasons:
return ContextResult("blocked", tuple(sorted(set(blocked_reasons))))
if changed_reasons:
return ContextResult(
"changed",
tuple(sorted(set(changed_reasons))),
)
return ContextResult("current", ("authority and digests match",))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Check Feature Context Snapshot authority and freshness."
)
parser.add_argument("--project-root", required=True, type=Path)
parser.add_argument("feature_spec", type=Path)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
configure_utf8_stdio()
require_supported_python()
args = parse_args(argv)
project_root = args.project_root.resolve()
feature_spec = (
args.feature_spec.resolve()
if args.feature_spec.is_absolute()
else (project_root / args.feature_spec).resolve()
)
result = classify(project_root, feature_spec)
prefix = {
"current": "CURRENT",
"changed": "CHANGED",
"not_applicable": "NOT_APPLICABLE",
"blocked": "BLOCKED",
}[result.status]
print(f"{prefix}: {'; '.join(result.reasons)}")
return result.exit_code
if __name__ == "__main__":
raise SystemExit(main())