open-quality-cli 0.1.0__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.
cli/core.py ADDED
@@ -0,0 +1,553 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from functools import lru_cache
6
+ from pathlib import Path
7
+ from typing import Any
8
+ from urllib.parse import urlparse
9
+
10
+ import yaml
11
+ from jsonschema import Draft202012Validator
12
+ from referencing import Registry
13
+ from referencing import Resource as SchemaResource
14
+
15
+ from .model import Bundle, Check, Report, Resource, StageResult
16
+
17
+ KINDS = {
18
+ "Project": "project",
19
+ "Workflow": "workflows",
20
+ "QualityRequirement": "requirements",
21
+ "Stage": "stages",
22
+ "QualityMeasure": "metrics",
23
+ "QualityMeasureElement": "quality_measure_elements",
24
+ "Artifact": "artifacts",
25
+ "Role": "roles",
26
+ "ApprovalPolicy": "approval_policies",
27
+ }
28
+ QUALITY_CHARACTERISTICS = {
29
+ "functional-suitability", "performance-efficiency", "compatibility",
30
+ "interaction-capability", "reliability", "security", "maintainability",
31
+ "flexibility", "safety", "beneficialness", "freedom-from-risk", "acceptability",
32
+ }
33
+ QUALITY_SUBCHARACTERISTICS = {
34
+ "functional-completeness", "functional-correctness", "functional-appropriateness",
35
+ "time-behaviour", "resource-utilization", "capacity", "co-existence",
36
+ "interoperability", "appropriateness-recognizability", "learnability", "operability",
37
+ "user-error-protection", "user-engagement", "inclusivity", "user-assistance",
38
+ "self-descriptiveness", "faultlessness", "availability", "fault-tolerance",
39
+ "recoverability", "confidentiality", "integrity", "non-repudiation", "accountability",
40
+ "authenticity", "resistance", "modularity", "reusability", "analysability",
41
+ "modifiability", "testability", "adaptability", "scalability", "installability",
42
+ "replaceability", "operational-constraint", "risk-identification", "fail-safe",
43
+ "hazard-warning", "safe-integration", "usability", "accessibility", "suitability",
44
+ "freedom-from-economic-risk", "freedom-from-environmental-and-societal-risk",
45
+ "freedom-from-health-risk", "freedom-from-human-life-risk", "experience",
46
+ "trustworthiness", "compliance",
47
+ }
48
+ TARGET_OPERATORS = {
49
+ "equals", "notEquals", "greaterThan", "greaterThanOrEqual",
50
+ "lessThan", "lessThanOrEqual", "exists", "approved",
51
+ }
52
+ ALLOWED: dict[str, set[str]] = {
53
+ "Project": {
54
+ "description",
55
+ "workflow",
56
+ "quality",
57
+ "metrics",
58
+ "documentation",
59
+ "roles",
60
+ "approvalPolicies",
61
+ },
62
+ "QualityRequirement": {
63
+ "statement",
64
+ "priority",
65
+ "qualityMeasures",
66
+ "documentation",
67
+ },
68
+ "Workflow": {"stages"},
69
+ "Stage": {
70
+ "environment",
71
+ "reviewScope",
72
+ "description",
73
+ "dependsOn",
74
+ "owner",
75
+ "owners",
76
+ "documentation",
77
+ "approvalPolicy",
78
+ },
79
+ "QualityMeasure": {
80
+ "measurementFunction",
81
+ "unit",
82
+ "description",
83
+ "sourceHint",
84
+ },
85
+ "QualityMeasureElement": {"unit", "measurementMethod", "description"},
86
+ "Artifact": {
87
+ "category",
88
+ "externalLink",
89
+ "required",
90
+ "retention",
91
+ "contentType",
92
+ },
93
+ "Role": {"description", "responsibilities"},
94
+ "ApprovalPolicy": {"strategy", "approvers", "minimum"},
95
+ }
96
+ SCHEMA_FILES = {
97
+ "Project": "project.schema.json",
98
+ "Workflow": "workflow.schema.json",
99
+ "QualityRequirement": "requirement.schema.json",
100
+ "Stage": "stage.schema.json",
101
+ "QualityMeasure": "metric.schema.json",
102
+ "QualityMeasureElement": "quality-measure-element.schema.json",
103
+ "Artifact": "artifact.schema.json",
104
+ "Role": "role.schema.json",
105
+ "ApprovalPolicy": "approval-policy.schema.json",
106
+ }
107
+
108
+
109
+ @lru_cache
110
+ def _contract_validator(kind: str) -> Draft202012Validator:
111
+ schema_directory = Path(__file__).parents[1] / "schema" / "v0.1"
112
+ registry = Registry()
113
+ for path in schema_directory.glob("*.json"):
114
+ schema = json.loads(path.read_text())
115
+ registry = registry.with_resource(schema["$id"], SchemaResource.from_contents(schema))
116
+ root = json.loads((schema_directory / SCHEMA_FILES[kind]).read_text())
117
+ return Draft202012Validator(root, registry=registry)
118
+
119
+
120
+ def _validate_schema(payload: dict[str, Any], kind: str) -> None:
121
+ errors = sorted(
122
+ _contract_validator(kind).iter_errors(payload),
123
+ key=lambda error: list(error.absolute_path),
124
+ )
125
+ if not errors:
126
+ return
127
+ error = errors[0]
128
+ location = ".".join(str(part) for part in error.absolute_path) or "resource"
129
+ if error.validator == "additionalProperties":
130
+ raise ValueError(f"{location} contains unknown field")
131
+ raise ValueError(f"{location}: {error.message}")
132
+
133
+
134
+ def _strict_mapping(value: Any, allowed: set[str], context: str) -> dict[str, Any]:
135
+ if not isinstance(value, dict):
136
+ raise ValueError(f"{context} must be a mapping")
137
+ unknown = set(value) - allowed
138
+ if unknown:
139
+ raise ValueError(f"{context} contains unknown field {sorted(unknown)[0]!r}")
140
+ return value
141
+
142
+
143
+ def parse(data: str | bytes) -> Resource:
144
+ payload = yaml.safe_load(data)
145
+ if not isinstance(payload, dict):
146
+ raise ValueError("resource must be a mapping")
147
+ allowed_top_level = {"specVersion", "kind", "metadata", "spec"}
148
+ if payload.get("kind") == "Project":
149
+ allowed_top_level.add("providers")
150
+ top = _strict_mapping(
151
+ payload, allowed_top_level, "resource"
152
+ )
153
+ version, kind = top.get("specVersion"), top.get("kind")
154
+ if version != "0.1":
155
+ raise ValueError(f"unsupported specVersion {version!r}")
156
+ if kind not in KINDS:
157
+ raise ValueError(f"unsupported kind {kind!r}")
158
+ _validate_schema(payload, kind)
159
+ metadata = _strict_mapping(
160
+ top.get("metadata"), {"id", "name", "description", "labels"}, "metadata"
161
+ )
162
+ spec = _strict_mapping(top.get("spec"), ALLOWED[kind], "spec")
163
+ providers = top.get("providers") or {}
164
+ if kind == "Project":
165
+ providers = _strict_mapping(providers, set(providers), "providers")
166
+ for provider_role, provider in providers.items():
167
+ if not isinstance(provider_role, str) or not provider_role:
168
+ raise ValueError("provider role must be a non-empty string")
169
+ _strict_mapping(
170
+ provider,
171
+ {"provider", "description", "config"},
172
+ f"provider {provider_role!r}",
173
+ )
174
+ if not provider.get("provider"):
175
+ raise ValueError(f"provider {provider_role!r} requires provider")
176
+ return Resource(version, kind, metadata, spec, providers)
177
+
178
+
179
+ def parse_state(data: str | bytes) -> dict[str, Any]:
180
+ value = _strict_mapping(
181
+ yaml.safe_load(data) or {},
182
+ {"metrics", "stages", "approvals", "documentation"},
183
+ "state",
184
+ )
185
+ return {
186
+ "metrics": value.get("metrics") or {},
187
+ "stages": value.get("stages") or {},
188
+ "approvals": value.get("approvals") or {},
189
+ "documentation": value.get("documentation") or {},
190
+ }
191
+
192
+
193
+ def load_contract(root: str | Path) -> Bundle:
194
+ bundle = Bundle()
195
+ for path in sorted(Path(root).rglob("*")):
196
+ if not path.is_file() or path.suffix not in {".yaml", ".yml"}:
197
+ continue
198
+ try:
199
+ resource = parse(path.read_text())
200
+ except Exception as error:
201
+ raise ValueError(f"{path}: {error}") from error
202
+ if not resource.id:
203
+ raise ValueError(f"{path}: metadata.id is required")
204
+ if resource.id in bundle.files:
205
+ raise ValueError(
206
+ f"{path}: duplicate id {resource.id!r} (already declared in {bundle.files[resource.id]})"
207
+ )
208
+ if resource.kind == "Project":
209
+ if bundle.project:
210
+ raise ValueError(f"{path}: contract contains more than one Project")
211
+ bundle.project = resource
212
+ else:
213
+ getattr(bundle, KINDS[resource.kind])[resource.id] = resource
214
+ bundle.files[resource.id] = str(path)
215
+ return bundle
216
+
217
+
218
+ def load_state(path: str | Path) -> dict[str, Any]:
219
+ try:
220
+ return parse_state(Path(path).read_text())
221
+ except Exception as error:
222
+ raise ValueError(f"{path}: {error}") from error
223
+
224
+
225
+ def quality_requirements(project: Resource) -> list[str]:
226
+ """Return requirement IDs in the project's quality hierarchy order."""
227
+ requirements: list[str] = []
228
+ for characteristic in project.spec.get("quality", []):
229
+ if not isinstance(characteristic, dict):
230
+ continue
231
+ requirements.extend(characteristic.get("requirements", []))
232
+ for subcharacteristic in characteristic.get("subcharacteristics", []):
233
+ if isinstance(subcharacteristic, dict):
234
+ requirements.extend(subcharacteristic.get("requirements", []))
235
+ return requirements
236
+
237
+
238
+ def validate(bundle: Bundle) -> list[str]:
239
+ errors: list[str] = []
240
+ add = errors.append
241
+ if not bundle.project:
242
+ return ["exactly one Project is required"]
243
+ project = bundle.project
244
+ if not project.name:
245
+ add("Project metadata.name is required")
246
+ for resource_id in bundle.files:
247
+ if not re.fullmatch(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*", resource_id):
248
+ add(f"id {resource_id!r} must be lowercase kebab-case")
249
+
250
+ def refs(ids: list[str], kind: str, source: dict[str, Resource]) -> None:
251
+ for item in ids or []:
252
+ if item not in source:
253
+ add(f"reference {item!r} does not resolve to {kind}")
254
+
255
+ def artifact_refs(ids: list[str], category: str) -> None:
256
+ for item in ids or []:
257
+ artifact = bundle.artifacts.get(item)
258
+ if not artifact:
259
+ add(f"reference {item!r} does not resolve to Artifact")
260
+ elif artifact.spec.get("category") != category:
261
+ add(f"reference {item!r} must be {category}, not Artifact")
262
+
263
+ spec = project.spec
264
+ workflow_id = spec.get("workflow", "")
265
+ if not workflow_id:
266
+ add("Project.spec.workflow is required")
267
+ elif workflow_id not in bundle.workflows:
268
+ add(f"Project workflow {workflow_id!r} does not resolve to Workflow")
269
+ quality = spec.get("quality")
270
+ if not isinstance(quality, list) or not quality:
271
+ add("Project.spec.quality must be a non-empty list")
272
+ quality = []
273
+ declared_requirements: set[str] = set()
274
+ def declare_requirements(requirements: Any, context: str) -> None:
275
+ if not isinstance(requirements, list) or not requirements:
276
+ add(f"{context} requires requirements")
277
+ return
278
+ for requirement_id in requirements:
279
+ requirement = bundle.requirements.get(requirement_id)
280
+ if not requirement:
281
+ add(f"Project quality requirement {requirement_id!r} does not resolve to QualityRequirement")
282
+ continue
283
+ if requirement_id in declared_requirements:
284
+ add(f"Project quality requirement {requirement_id!r} is declared more than once")
285
+ declared_requirements.add(requirement_id)
286
+
287
+ for characteristic in quality:
288
+ if not isinstance(characteristic, dict) or set(characteristic) - {"characteristic", "subcharacteristics", "requirements"}:
289
+ add("Project quality entry contains an unknown field")
290
+ continue
291
+ characteristic_id = characteristic.get("characteristic")
292
+ if characteristic_id not in QUALITY_CHARACTERISTICS:
293
+ add(f"Project quality characteristic {characteristic_id!r} is not supported")
294
+ subcharacteristics = characteristic.get("subcharacteristics")
295
+ requirements = characteristic.get("requirements")
296
+ if subcharacteristics is not None and requirements is not None:
297
+ add(f"Project quality characteristic {characteristic_id!r} may declare subcharacteristics or requirements, not both")
298
+ continue
299
+ if requirements is not None:
300
+ declare_requirements(requirements, f"Project quality characteristic {characteristic_id!r}")
301
+ continue
302
+ if not isinstance(subcharacteristics, list) or not subcharacteristics:
303
+ add(f"Project quality characteristic {characteristic_id!r} requires subcharacteristics or requirements")
304
+ continue
305
+ for subcharacteristic in subcharacteristics:
306
+ if not isinstance(subcharacteristic, dict) or set(subcharacteristic) - {"subcharacteristic", "requirements"}:
307
+ add("Project quality subcharacteristic entry must contain only subcharacteristic and requirements")
308
+ continue
309
+ subcharacteristic_id = subcharacteristic.get("subcharacteristic")
310
+ if subcharacteristic_id not in QUALITY_SUBCHARACTERISTICS:
311
+ add(f"Project quality subcharacteristic {subcharacteristic_id!r} is not supported")
312
+ declare_requirements(
313
+ subcharacteristic.get("requirements"),
314
+ f"Project quality subcharacteristic {subcharacteristic_id!r}",
315
+ )
316
+ for requirement_id in bundle.requirements:
317
+ if requirement_id not in declared_requirements:
318
+ add(f"QualityRequirement {requirement_id!r} is not declared in Project.spec.quality")
319
+ for key, kind, source in [
320
+ ("metrics", "QualityMeasure", bundle.metrics),
321
+ ("roles", "Role", bundle.roles),
322
+ ("approvalPolicies", "ApprovalPolicy", bundle.approval_policies),
323
+ ]:
324
+ refs(spec.get(key, []), kind, source)
325
+ artifact_refs(spec.get("documentation", []), "documentation")
326
+ for resource_id, workflow in bundle.workflows.items():
327
+ if not workflow.spec.get("stages"):
328
+ add(f"Workflow {resource_id!r} has no stages")
329
+ refs(workflow.spec.get("stages", []), "Stage", bundle.stages)
330
+ for resource_id, stage in bundle.stages.items():
331
+ s = stage.spec
332
+ if s.get("reviewScope") == "code" and not s.get("approvalPolicy"):
333
+ add(f"Stage {resource_id!r} with reviewScope code requires approvalPolicy")
334
+ refs(s.get("dependsOn", []), "Stage", bundle.stages)
335
+ artifact_refs(s.get("documentation", []), "documentation")
336
+ if s.get("owner"):
337
+ refs([s["owner"]], "Role", bundle.roles)
338
+ refs(s.get("owners", []), "Role", bundle.roles)
339
+ if s.get("approvalPolicy"):
340
+ refs([s["approvalPolicy"]], "ApprovalPolicy", bundle.approval_policies)
341
+ for resource_id, requirement in bundle.requirements.items():
342
+ s = requirement.spec
343
+ if not s.get("statement"):
344
+ add(f"Requirement {resource_id!r} statement is required")
345
+ if not requirement.name:
346
+ add(f"Requirement {resource_id!r} metadata.name is required")
347
+ if s.get("priority") not in {"low", "medium", "high", "critical"}:
348
+ add(
349
+ f"Requirement {resource_id!r} has invalid priority {s.get('priority', '')!r}"
350
+ )
351
+ quality_measures = s.get("qualityMeasures")
352
+ if not isinstance(quality_measures, list) or not quality_measures:
353
+ add(f"Requirement {resource_id!r} requires qualityMeasures")
354
+ else:
355
+ for quality_measure in quality_measures:
356
+ if not isinstance(quality_measure, dict) or set(quality_measure) - {"qualityMeasure", "target"}:
357
+ add(f"Requirement {resource_id!r} quality measure entry has unknown field")
358
+ continue
359
+ measure_id = quality_measure.get("qualityMeasure")
360
+ refs([measure_id], "QualityMeasure", bundle.metrics)
361
+ target = quality_measure.get("target")
362
+ if not isinstance(target, dict) or not {"operator", "value"} <= set(target):
363
+ add(f"Requirement {resource_id!r} quality measure {measure_id!r} requires target.operator and target.value")
364
+ elif target["operator"] not in TARGET_OPERATORS:
365
+ add(
366
+ f"Requirement {resource_id!r} quality measure {measure_id!r} "
367
+ f"uses invalid target operator {target['operator']!r}"
368
+ )
369
+ artifact_refs(s.get("documentation", []), "documentation")
370
+ for resource_id, policy in bundle.approval_policies.items():
371
+ s = policy.spec
372
+ if not s.get("approvers"):
373
+ add(f"ApprovalPolicy {resource_id!r} requires approvers")
374
+ refs(s.get("approvers", []), "Role", bundle.roles)
375
+ if s.get("strategy") not in {"all", "any", "minimum"}:
376
+ add(
377
+ f"ApprovalPolicy {resource_id!r} has invalid strategy {s.get('strategy', '')!r}"
378
+ )
379
+ if s.get("strategy") == "minimum" and not (
380
+ 1 <= s.get("minimum", 0) <= len(s.get("approvers", []))
381
+ ):
382
+ add(f"ApprovalPolicy {resource_id!r} has unsatisfiable minimum")
383
+ if s.get("strategy") != "minimum" and "minimum" in s:
384
+ add(f"ApprovalPolicy {resource_id!r} minimum is only valid for minimum strategy")
385
+ for resource_id, artifact in bundle.artifacts.items():
386
+ if artifact.spec.get("category") != "documentation":
387
+ add(
388
+ f"Artifact {resource_id!r} has invalid category {artifact.spec.get('category', '')!r}"
389
+ )
390
+ external_link = artifact.spec.get("externalLink", "")
391
+ if not isinstance(external_link, str):
392
+ add(f"Artifact {resource_id!r} externalLink must be an absolute URL")
393
+ else:
394
+ parsed_link = urlparse(external_link)
395
+ if not (parsed_link.scheme and parsed_link.netloc):
396
+ add(
397
+ f"Artifact {resource_id!r} externalLink must be an absolute URL"
398
+ )
399
+ if cycle := _find_cycle(bundle.stages):
400
+ add(f"stage dependency cycle: {cycle}")
401
+ return errors
402
+
403
+
404
+ def _find_cycle(stages: dict[str, Resource]) -> list[str]:
405
+ state: dict[str, int] = {}
406
+ stack: list[str] = []
407
+
408
+ def visit(resource_id: str) -> list[str]:
409
+ if state.get(resource_id) == 1:
410
+ return [*stack, resource_id]
411
+ if state.get(resource_id) == 2:
412
+ return []
413
+ state[resource_id] = 1
414
+ stack.append(resource_id)
415
+ for dependency in stages.get(resource_id, Resource("", "", {}, {})).spec.get(
416
+ "dependsOn", []
417
+ ):
418
+ if cycle := visit(dependency):
419
+ return cycle
420
+ stack.pop()
421
+ state[resource_id] = 2
422
+ return []
423
+
424
+ for resource_id in stages:
425
+ if cycle := visit(resource_id):
426
+ return cycle
427
+ return []
428
+
429
+
430
+ def _compare(
431
+ values: dict[str, Any], metric: str, operator: str, expected: Any
432
+ ) -> tuple[bool, str]:
433
+ actual = values.get(metric)
434
+ exists = metric in values
435
+ if operator == "exists":
436
+ return (True, "") if exists else (False, f"metric {metric} is missing")
437
+ if not exists:
438
+ return False, f"metric {metric} is missing"
439
+ if operator == "approved":
440
+ ok = actual is True or str(actual).lower() == "approved"
441
+ return (ok, "" if ok else f"metric {metric} is not approved")
442
+ try:
443
+ actual_number, expected_number = float(actual), float(expected)
444
+ predicates = {
445
+ "equals": actual_number == expected_number,
446
+ "notEquals": actual_number != expected_number,
447
+ "greaterThan": actual_number > expected_number,
448
+ "greaterThanOrEqual": actual_number >= expected_number,
449
+ "lessThan": actual_number < expected_number,
450
+ "lessThanOrEqual": actual_number <= expected_number,
451
+ }
452
+ ok = predicates.get(operator, False)
453
+ except (TypeError, ValueError):
454
+ equal = actual == expected or str(actual) == str(expected)
455
+ ok = (
456
+ equal
457
+ if operator == "equals"
458
+ else not equal if operator == "notEquals" else False
459
+ )
460
+ return (
461
+ (True, "")
462
+ if ok
463
+ else (False, f"{metric}={actual} does not satisfy {operator} {expected}")
464
+ )
465
+
466
+
467
+ def evaluate(bundle: Bundle, state: dict[str, Any]) -> Report:
468
+ assert bundle.project
469
+ report = Report(project=bundle.project.name)
470
+ workflow = bundle.workflows.get(bundle.project.spec.get("workflow"))
471
+ if not workflow:
472
+ report.ready = False
473
+ return report
474
+ report.workflow = workflow.name
475
+ active_stages: list[str] = []
476
+ pending_stages: list[str] = []
477
+ for resource_id in quality_requirements(bundle.project):
478
+ requirement = bundle.requirements[resource_id]
479
+ check = Check(resource_id, requirement.name, True)
480
+ for quality_measure in requirement.spec.get("qualityMeasures", []):
481
+ target = quality_measure.get("target", {})
482
+ passed, reason = _compare(
483
+ state["metrics"],
484
+ quality_measure.get("qualityMeasure"),
485
+ target.get("operator"),
486
+ target.get("value"),
487
+ )
488
+ if not passed:
489
+ check.passed = False
490
+ check.reason = reason
491
+ for field, label in (("documentation", "documentation"),):
492
+ for evidence_id in requirement.spec.get(field, []):
493
+ if state[field].get(evidence_id):
494
+ continue
495
+ check.passed = False
496
+ check.reason = "; ".join(
497
+ filter(None, [check.reason, f"missing {label} {evidence_id}"])
498
+ )
499
+ report.requirements.append(check)
500
+ report.ready &= check.passed
501
+ for stage_id in workflow.spec.get("stages", []):
502
+ stage = bundle.stages[stage_id]
503
+ status = state["stages"].get(stage_id, "pending") or "pending"
504
+ result = StageResult(stage_id, stage.name, status)
505
+ if status in {"running", "blocked"}:
506
+ active_stages.append(stage.name)
507
+ elif status == "pending":
508
+ pending_stages.append(stage.name)
509
+ for field, checks, label in (
510
+ ("documentation", result.documentation, "documentation"),
511
+ ):
512
+ for evidence_id in stage.spec.get(field, []):
513
+ ok = bool(state[field].get(evidence_id))
514
+ checks.append(
515
+ Check(
516
+ evidence_id,
517
+ bundle.artifacts[evidence_id].name,
518
+ ok,
519
+ reason="" if ok else f"missing {label}",
520
+ )
521
+ )
522
+ report.ready &= ok
523
+ policy_id = stage.spec.get("approvalPolicy")
524
+ if policy_id:
525
+ policy = bundle.approval_policies[policy_id]
526
+ approved = set(state["approvals"].get(policy_id, []))
527
+ approvers = policy.spec.get("approvers", [])
528
+ count = len(approved & set(approvers))
529
+ strategy = policy.spec.get("strategy")
530
+ ok = (
531
+ count == len(approvers)
532
+ if strategy == "all"
533
+ else (
534
+ count >= 1
535
+ if strategy == "any"
536
+ else count >= policy.spec.get("minimum", 0)
537
+ )
538
+ )
539
+ missing = ", ".join(sorted(set(approvers) - approved))
540
+ result.approval = Check(
541
+ policy_id,
542
+ policy.name,
543
+ ok,
544
+ reason="" if ok else f"missing approval from {missing}",
545
+ )
546
+ report.ready &= ok
547
+ if status != "completed":
548
+ report.ready = False
549
+ report.stages.append(result)
550
+ report.current_stage = ", ".join(active_stages) or next(
551
+ iter(pending_stages), "Complete"
552
+ )
553
+ return report
cli/model.py ADDED
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+
7
+ @dataclass
8
+ class Resource:
9
+ spec_version: str
10
+ kind: str
11
+ metadata: dict[str, Any]
12
+ spec: dict[str, Any]
13
+ providers: dict[str, dict[str, Any]] = field(default_factory=dict)
14
+
15
+ @property
16
+ def id(self) -> str:
17
+ return self.metadata.get("id", "")
18
+
19
+ @property
20
+ def name(self) -> str:
21
+ return self.metadata.get("name", "")
22
+
23
+
24
+ @dataclass
25
+ class Bundle:
26
+ project: Resource | None = None
27
+ workflows: dict[str, Resource] = field(default_factory=dict)
28
+ requirements: dict[str, Resource] = field(default_factory=dict)
29
+ stages: dict[str, Resource] = field(default_factory=dict)
30
+ metrics: dict[str, Resource] = field(default_factory=dict)
31
+ quality_measure_elements: dict[str, Resource] = field(default_factory=dict)
32
+ artifacts: dict[str, Resource] = field(default_factory=dict)
33
+ roles: dict[str, Resource] = field(default_factory=dict)
34
+ approval_policies: dict[str, Resource] = field(default_factory=dict)
35
+ files: dict[str, str] = field(default_factory=dict)
36
+
37
+
38
+ @dataclass
39
+ class Check:
40
+ id: str
41
+ name: str
42
+ passed: bool
43
+ warning: bool = False
44
+ reason: str = ""
45
+
46
+
47
+ @dataclass
48
+ class StageResult:
49
+ id: str
50
+ name: str
51
+ status: str
52
+ approval: Check | None = None
53
+ documentation: list[Check] = field(default_factory=list)
54
+
55
+
56
+ @dataclass
57
+ class Report:
58
+ project: str = ""
59
+ workflow: str = ""
60
+ current_stage: str = ""
61
+ requirements: list[Check] = field(default_factory=list)
62
+ stages: list[StageResult] = field(default_factory=list)
63
+ ready: bool = True
cli/provider.py ADDED
@@ -0,0 +1,40 @@
1
+ """Backward-compatible provider facade.
2
+
3
+ Provider implementations live in :mod:`cli.providers`. New code should import
4
+ the concrete adapter from ``cli.providers.openproject`` or program against the
5
+ contracts in ``cli.providers.interfaces``.
6
+ """
7
+
8
+ from .providers.openproject import (
9
+ ExternalResource,
10
+ OpenProjectClient,
11
+ OpenProjectProvider,
12
+ Operation,
13
+ ProjectMember,
14
+ ProviderState,
15
+ TargetConfig,
16
+ apply,
17
+ load_config,
18
+ load_members,
19
+ load_state,
20
+ new_state,
21
+ plan,
22
+ save_state,
23
+ )
24
+
25
+ __all__ = [
26
+ "ExternalResource",
27
+ "OpenProjectClient",
28
+ "OpenProjectProvider",
29
+ "Operation",
30
+ "ProjectMember",
31
+ "ProviderState",
32
+ "TargetConfig",
33
+ "apply",
34
+ "load_config",
35
+ "load_members",
36
+ "load_state",
37
+ "new_state",
38
+ "plan",
39
+ "save_state",
40
+ ]
@@ -0,0 +1,5 @@
1
+ """External provider adapters and their stable contracts."""
2
+
3
+ from .interfaces import ProviderAdapter, TargetLoader
4
+
5
+ __all__ = ["ProviderAdapter", "TargetLoader"]