quality-graph-github 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/PKG-INFO +2 -2
  2. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/pyproject.toml +2 -2
  3. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/approvals.py +10 -37
  4. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/artifacts.py +17 -36
  5. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/commands.py +33 -68
  6. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/comments.py +2 -9
  7. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/compiler.py +49 -31
  8. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/declarations.py +5 -6
  9. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/github.py +7 -16
  10. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/labels.py +2 -8
  11. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/provider.py +2 -1
  12. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/publication.py +41 -76
  13. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/required_checks.py +28 -55
  14. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/runtime.py +6 -42
  15. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/.gitignore +0 -0
  16. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/README.md +0 -0
  17. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/__init__.py +0 -0
  18. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/annotations.py +0 -0
  19. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/controls.py +0 -0
  20. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/dashboard.py +0 -0
  21. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/presentation.py +0 -0
  22. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/py.typed +0 -0
  23. {quality_graph_github-0.2.0 → quality_graph_github-0.2.1}/src/qg_github/reporting.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quality-graph-github
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: GitHub provider and Action runtime for Quality Graph
5
5
  Project-URL: Homepage, https://quality-graph.xyz/
6
6
  Project-URL: Documentation, https://quality-graph.xyz/
@@ -9,7 +9,7 @@ Requires-Python: >=3.12
9
9
  Requires-Dist: httpx>=0.28.1
10
10
  Requires-Dist: jinja2>=3.1.6
11
11
  Requires-Dist: pyyaml>=6.0.2
12
- Requires-Dist: quality-graph-core==0.2.0
12
+ Requires-Dist: quality-graph-core==0.2.1
13
13
  Description-Content-Type: text/markdown
14
14
 
15
15
  # Quality Graph GitHub Provider
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "quality-graph-github"
7
- version = "0.2.0"
7
+ version = "0.2.1"
8
8
  description = "GitHub provider and Action runtime for Quality Graph"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -13,7 +13,7 @@ dependencies = [
13
13
  "httpx>=0.28.1",
14
14
  "jinja2>=3.1.6",
15
15
  "pyyaml>=6.0.2",
16
- "quality-graph-core==0.2.0",
16
+ "quality-graph-core==0.2.1",
17
17
  ]
18
18
 
19
19
  [project.urls]
@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, cast
10
10
 
11
11
  from qg_github.comments import DEFAULT_BOT_LOGIN
12
12
  from qg_github.github import GitHubPort, paged
13
+ from quality_graph_core.json_values import JSON
13
14
  from quality_graph_core.policy import ApprovalTarget
14
15
 
15
16
  if TYPE_CHECKING:
@@ -55,23 +56,23 @@ class ApprovalRecord:
55
56
  @classmethod
56
57
  def from_json(cls, value: str) -> ApprovalRecord:
57
58
  """Parse a record from untrusted marker JSON."""
58
- data = _object(cast("JsonValue", json.loads(value)), "approval record")
59
+ data = JSON.object(cast("JsonValue", json.loads(value)), "approval record")
59
60
  if data.get("version") != 0:
60
61
  message = "unsupported approval record version"
61
62
  raise ValueError(message)
62
- operation = _string(data.get("operation"), "approval operation")
63
+ operation = JSON.string(data.get("operation"), "approval operation")
63
64
  if operation not in {"add", "remove"}:
64
65
  message = f"unknown approval operation: {operation}"
65
66
  raise ValueError(message)
66
67
  targets = tuple(
67
- ApprovalTarget.from_key(_string(item, "approval target"))
68
- for item in _array(data.get("targets"), "approval targets")
68
+ ApprovalTarget.from_key(JSON.string(item, "approval target"))
69
+ for item in JSON.array(data.get("targets"), "approval targets")
69
70
  )
70
71
  return cls(
71
72
  operation == "add",
72
73
  targets,
73
- _string(data.get("actor"), "approval actor"),
74
- _integer(data.get("sourceCommentId"), "approval source comment id"),
74
+ JSON.string(data.get("actor"), "approval actor"),
75
+ JSON.integer(data.get("sourceCommentId"), "approval source comment id"),
75
76
  )
76
77
 
77
78
 
@@ -105,7 +106,7 @@ def approval_ledger(
105
106
  approvals: set[ApprovalTarget] = set()
106
107
  comments = sorted(
107
108
  paged(port, f"/issues/{number}/comments"),
108
- key=lambda item: _integer(item.get("id"), "approval comment id"),
109
+ key=lambda item: JSON.integer(item.get("id"), "approval comment id"),
109
110
  )
110
111
  for comment in comments:
111
112
  author = comment.get("user")
@@ -137,36 +138,8 @@ def append_approval_record(
137
138
  f"Quality Graph recorded that @{record.actor} {action} {targets}.\n\n"
138
139
  f"{record_marker(record)}"
139
140
  )
140
- response = _object(
141
+ response = JSON.object(
141
142
  port.request("POST", f"/issues/{number}/comments", {"body": body}),
142
143
  "approval comment",
143
144
  )
144
- return _integer(response.get("id"), "approval comment id")
145
-
146
-
147
- def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
148
- if not isinstance(value, dict):
149
- message = f"{context} must be an object"
150
- raise TypeError(message)
151
- return value
152
-
153
-
154
- def _array(value: JsonValue, context: str) -> list[JsonValue]:
155
- if not isinstance(value, list):
156
- message = f"{context} must be an array"
157
- raise TypeError(message)
158
- return value
159
-
160
-
161
- def _string(value: JsonValue, context: str) -> str:
162
- if not isinstance(value, str):
163
- message = f"{context} must be a string"
164
- raise TypeError(message)
165
- return value
166
-
167
-
168
- def _integer(value: JsonValue, context: str) -> int:
169
- if not isinstance(value, int) or isinstance(value, bool):
170
- message = f"{context} must be an integer"
171
- raise TypeError(message)
172
- return value
145
+ return JSON.integer(response.get("id"), "approval comment id")
@@ -12,6 +12,7 @@ from pathlib import PurePosixPath
12
12
  from typing import TYPE_CHECKING
13
13
 
14
14
  from qg_github.github import GITHUB_PAGE_SIZE, GitHubPort
15
+ from quality_graph_core.json_values import JsonValidator
15
16
  from quality_graph_core.result import JsonValue, Provenance, Result, ResultStatus
16
17
 
17
18
  if TYPE_CHECKING:
@@ -30,6 +31,9 @@ class ArtifactError(ValueError):
30
31
  """Represent an invalid or incompatible result artifact."""
31
32
 
32
33
 
34
+ JSON = JsonValidator(ArtifactError)
35
+
36
+
33
37
  class DeclarationMismatchError(ArtifactError):
34
38
  """Identify a different declaration after workflow identity has been verified."""
35
39
 
@@ -101,10 +105,10 @@ def _artifact_descriptors(port: GitHubPort, run_id: int) -> tuple[ArtifactDescri
101
105
  page = 1
102
106
  while True:
103
107
  path = f"/actions/runs/{run_id}/artifacts?per_page={GITHUB_PAGE_SIZE}&page={page}"
104
- response = _object(port.request("GET", path), "workflow artifacts")
105
- artifacts = _array(response.get("artifacts"), "workflow artifacts")
108
+ response = JSON.object(port.request("GET", path), "workflow artifacts")
109
+ artifacts = JSON.array(response.get("artifacts"), "workflow artifacts")
106
110
  for value in artifacts:
107
- descriptor = _artifact_descriptor(_object(value, "workflow artifact"))
111
+ descriptor = _artifact_descriptor(JSON.object(value, "workflow artifact"))
108
112
  if descriptor is not None:
109
113
  descriptors.append(descriptor)
110
114
  if len(artifacts) < GITHUB_PAGE_SIZE:
@@ -113,19 +117,19 @@ def _artifact_descriptors(port: GitHubPort, run_id: int) -> tuple[ArtifactDescri
113
117
 
114
118
 
115
119
  def _artifact_descriptor(data: dict[str, JsonValue]) -> ArtifactDescriptor | None:
116
- name = _string(data.get("name"), "artifact name")
120
+ name = JSON.string(data.get("name"), "artifact name")
117
121
  match = ARTIFACT_NAME_RE.fullmatch(name)
118
122
  if match is None:
119
123
  return None
120
124
  if data.get("expired") is True:
121
125
  message = f"result artifact has expired: {name}"
122
126
  raise ArtifactError(message)
123
- artifact_id = _integer(data.get("id"), "artifact id")
124
- size = _integer(data.get("size_in_bytes"), "artifact size")
127
+ artifact_id = JSON.integer(data.get("id"), "artifact id")
128
+ size = JSON.integer(data.get("size_in_bytes"), "artifact size")
125
129
  if not 0 <= size <= MAX_ARTIFACT_ARCHIVE_BYTES:
126
130
  message = f"artifact exceeds the archive size limit: {name}"
127
131
  raise ArtifactError(message)
128
- digest = _string(data.get("digest"), "artifact digest")
132
+ digest = JSON.string(data.get("digest"), "artifact digest")
129
133
  if not digest.startswith("sha256:") or len(digest) != len("sha256:") + 64:
130
134
  message = f"artifact has an invalid digest: {name}"
131
135
  raise ArtifactError(message)
@@ -218,36 +222,13 @@ def _validate_result(
218
222
  message = f"artifact provenance does not match workflow metadata: {descriptor.id}"
219
223
  raise ArtifactError(message)
220
224
  if provenance.graph_digest != expectation.graph_digest:
221
- message = f"artifact provenance does not match workflow metadata: {descriptor.id}"
225
+ message = (
226
+ f"artifact {descriptor.id} provenance: graphDigest mismatch: "
227
+ f"expected {expectation.graph_digest}, "
228
+ f"execution reported {provenance.graph_digest}; "
229
+ "see https://quality-graph.xyz/security/#graph-evolution"
230
+ )
222
231
  raise DeclarationMismatchError(message)
223
232
  if observed[5:] != expected[5:]:
224
233
  message = f"artifact provenance does not match workflow metadata: {descriptor.id}"
225
234
  raise ArtifactError(message)
226
-
227
-
228
- def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
229
- if not isinstance(value, dict):
230
- message = f"{context} must be an object"
231
- raise ArtifactError(message)
232
- return value
233
-
234
-
235
- def _array(value: JsonValue, context: str) -> list[JsonValue]:
236
- if not isinstance(value, list):
237
- message = f"{context} must be an array"
238
- raise ArtifactError(message)
239
- return value
240
-
241
-
242
- def _string(value: JsonValue, context: str) -> str:
243
- if not isinstance(value, str):
244
- message = f"{context} must be a string"
245
- raise ArtifactError(message)
246
- return value
247
-
248
-
249
- def _integer(value: JsonValue, context: str) -> int:
250
- if not isinstance(value, int) or isinstance(value, bool):
251
- message = f"{context} must be an integer"
252
- raise ArtifactError(message)
253
- return value
@@ -16,6 +16,7 @@ from qg_github.declarations import read_pr_results
16
16
  from qg_github.github import GITHUB_PAGE_SIZE, GitHubPort
17
17
  from qg_github.presentation import pr_presentation_graph
18
18
  from quality_graph_core.graph import Graph
19
+ from quality_graph_core.json_values import JSON
19
20
  from quality_graph_core.policy import ApprovalTarget, effective_graph
20
21
  from quality_graph_core.result import ControlKind, JsonValue
21
22
 
@@ -103,16 +104,16 @@ def command_request(
103
104
  bot_logins: tuple[str, ...] = (DEFAULT_BOT_LOGIN,),
104
105
  ) -> CommandRequest | None:
105
106
  """Extract a direct command or one canonical checkbox transition."""
106
- event = _object(event_value, "issue comment event")
107
- comment = _object(event.get("comment"), "issue comment")
108
- comment_id = _integer(comment.get("id"), "comment id")
109
- body = _string(comment.get("body"), "comment body").strip()
110
- issue = _object(event.get("issue"), "issue")
111
- number = _optional_integer(issue.get("number"), "issue number")
107
+ event = JSON.object(event_value, "issue comment event")
108
+ comment = JSON.object(event.get("comment"), "issue comment")
109
+ comment_id = JSON.integer(comment.get("id"), "comment id")
110
+ body = JSON.string(comment.get("body"), "comment body").strip()
111
+ issue = JSON.object(event.get("issue"), "issue")
112
+ number = JSON.optional_integer(issue.get("number"), "issue number")
112
113
  pull_request = number if issue.get("pull_request") is not None else None
113
114
  author = comment.get("user")
114
115
  author_login = (
115
- _optional_string(author.get("login"), "comment author")
116
+ JSON.optional_string(author.get("login"), "comment author")
116
117
  if isinstance(author, dict)
117
118
  else None
118
119
  )
@@ -120,9 +121,9 @@ def command_request(
120
121
  return CommandRequest(comment_id, body, author_login, pull_request)
121
122
  if event.get("action") != "edited" or author_login not in bot_logins:
122
123
  return None
123
- changes = _object(event.get("changes"), "comment changes")
124
- body_change = _object(changes.get("body"), "comment body change")
125
- previous = _string(body_change.get("from"), "previous comment body")
124
+ changes = JSON.object(event.get("changes"), "comment changes")
125
+ body_change = JSON.object(changes.get("body"), "comment body change")
126
+ previous = JSON.string(body_change.get("from"), "previous comment body")
126
127
  before = control_states(previous)
127
128
  after = control_states(body)
128
129
  changed = [marker for marker in before.keys() & after.keys() if before[marker] != after[marker]]
@@ -132,8 +133,8 @@ def command_request(
132
133
  if commands is None:
133
134
  return None
134
135
  apply, reverse = commands
135
- sender = _object(event.get("sender"), "event sender")
136
- actor = _optional_string(sender.get("login"), "event sender login")
136
+ sender = JSON.object(event.get("sender"), "event sender")
137
+ actor = JSON.optional_string(sender.get("login"), "event sender login")
137
138
  selected = apply if after[changed[0]] else reverse
138
139
  return CommandRequest(comment_id, selected, actor, pull_request, previous)
139
140
 
@@ -185,9 +186,9 @@ def dispatch_pr_command(port: GitHubPort, event_value: JsonValue) -> CommandOutc
185
186
  request = command_request(event_value)
186
187
  if request is None or request.pull_request is None:
187
188
  return CommandOutcome(handled=False)
188
- pull = _object(port.request("GET", f"/pulls/{request.pull_request}"), "pull request")
189
- base = _object(pull.get("base"), "pull request base")
190
- base_sha = _string(base.get("sha"), "pull request base SHA")
189
+ pull = JSON.object(port.request("GET", f"/pulls/{request.pull_request}"), "pull request")
190
+ base = JSON.object(pull.get("base"), "pull request base")
191
+ base_sha = JSON.string(base.get("sha"), "pull request base SHA")
191
192
  graph = Graph.from_yaml(_repository_file(port, "qg.yaml", base_sha))
192
193
  if pr_presentation_graph(graph) is None:
193
194
  return CommandOutcome(handled=False)
@@ -196,11 +197,11 @@ def dispatch_pr_command(port: GitHubPort, event_value: JsonValue) -> CommandOutc
196
197
 
197
198
  # pragma: no mutate start
198
199
  def _command_context(port: GitHubPort, number: int) -> CommandContext:
199
- pull = _object(port.request("GET", f"/pulls/{number}"), "pull request")
200
- head = _object(pull.get("head"), "pull request head")
201
- base = _object(pull.get("base"), "pull request base")
202
- head_sha = _string(head.get("sha"), "pull request head SHA")
203
- base_sha = _string(base.get("sha"), "pull request base SHA")
200
+ pull = JSON.object(port.request("GET", f"/pulls/{number}"), "pull request")
201
+ head = JSON.object(pull.get("head"), "pull request head")
202
+ base = JSON.object(pull.get("base"), "pull request base")
203
+ head_sha = JSON.string(head.get("sha"), "pull request head SHA")
204
+ base_sha = JSON.string(base.get("sha"), "pull request base SHA")
204
205
  graph = Graph.from_yaml(_repository_file(port, "qg.yaml", base_sha))
205
206
  compiled = compile_graph(graph)
206
207
  projected = pr_presentation_graph(graph)
@@ -209,8 +210,8 @@ def _command_context(port: GitHubPort, number: int) -> CommandContext:
209
210
  raise ValueError(message)
210
211
  graph = projected
211
212
  run = _latest_run(port, number)
212
- run_id = _integer(run.get("id"), "workflow run id")
213
- attempt = _integer(run.get("run_attempt", 1), "workflow run attempt")
213
+ run_id = JSON.integer(run.get("id"), "workflow run id")
214
+ attempt = JSON.integer(run.get("run_attempt", 1), "workflow run attempt")
214
215
  expectation = ArtifactExpectation(
215
216
  port.repository,
216
217
  number,
@@ -235,15 +236,15 @@ def _latest_run(port: GitHubPort, number: int) -> dict[str, JsonValue]:
235
236
  "/actions/workflows/quality-graph.yml/runs?event=pull_request"
236
237
  f"&per_page={GITHUB_PAGE_SIZE}&page={page}"
237
238
  )
238
- response = _object(port.request("GET", path), "workflow runs")
239
- values = _array(response.get("workflow_runs", []), "workflow runs")
239
+ response = JSON.object(port.request("GET", path), "workflow runs")
240
+ values = JSON.array(response.get("workflow_runs", []), "workflow runs")
240
241
  runs.extend(
241
242
  run
242
243
  for value in values
243
- for run in (_object(value, "workflow run"),)
244
+ for run in (JSON.object(value, "workflow run"),)
244
245
  if any(
245
- _object(pull, "workflow pull request").get("number") == number
246
- for pull in _array(run.get("pull_requests", []), "workflow pull requests")
246
+ JSON.object(pull, "workflow pull request").get("number") == number
247
+ for pull in JSON.array(run.get("pull_requests", []), "workflow pull requests")
247
248
  )
248
249
  )
249
250
  if len(values) < GITHUB_PAGE_SIZE:
@@ -252,7 +253,7 @@ def _latest_run(port: GitHubPort, number: int) -> dict[str, JsonValue]:
252
253
  if not runs:
253
254
  message = f"no Quality Graph workflow run found for PR #{number}"
254
255
  raise ValueError(message)
255
- return max(runs, key=lambda run: _integer(run.get("id"), "workflow run id"))
256
+ return max(runs, key=lambda run: JSON.integer(run.get("id"), "workflow run id"))
256
257
 
257
258
 
258
259
  # pragma: no mutate end
@@ -262,8 +263,8 @@ def _authorized(port: GitHubPort, actor: str, roles: tuple[str, ...]) -> bool:
262
263
  response = port.request("GET", f"/collaborators/{login}/permission")
263
264
  except RuntimeError:
264
265
  return False
265
- data = _object(response, "collaborator permission")
266
- permission = _optional_string(data.get("permission"), "collaborator permission")
266
+ data = JSON.object(response, "collaborator permission")
267
+ permission = JSON.optional_string(data.get("permission"), "collaborator permission")
267
268
  return permission in roles
268
269
 
269
270
 
@@ -292,11 +293,11 @@ def _command_targets(
292
293
  def _repository_file(port: GitHubPort, path: str, ref: str) -> str:
293
294
  encoded_path = urllib.parse.quote(path, safe="")
294
295
  encoded_ref = urllib.parse.quote(ref, safe="")
295
- response = _object(
296
+ response = JSON.object(
296
297
  port.request("GET", f"/contents/{encoded_path}?ref={encoded_ref}"),
297
298
  "repository file",
298
299
  )
299
- content = _string(response.get("content"), "repository file content")
300
+ content = JSON.string(response.get("content"), "repository file content")
300
301
  return base64.b64decode(content.replace("\n", ""), validate=True).decode()
301
302
 
302
303
 
@@ -322,40 +323,4 @@ def _help_body() -> str:
322
323
  - `/qg remove-ignore-file <path>`"""
323
324
 
324
325
 
325
- def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
326
- if not isinstance(value, dict):
327
- message = f"{context} must be an object"
328
- raise TypeError(message)
329
- return value
330
-
331
-
332
- def _array(value: JsonValue, context: str) -> list[JsonValue]:
333
- if not isinstance(value, list):
334
- message = f"{context} must be an array"
335
- raise TypeError(message)
336
- return value
337
-
338
-
339
- def _string(value: JsonValue, context: str) -> str:
340
- if not isinstance(value, str):
341
- message = f"{context} must be a string"
342
- raise TypeError(message)
343
- return value
344
-
345
-
346
- def _optional_string(value: JsonValue, context: str) -> str | None:
347
- return None if value is None else _string(value, context)
348
-
349
-
350
- def _integer(value: JsonValue, context: str) -> int:
351
- if not isinstance(value, int) or isinstance(value, bool):
352
- message = f"{context} must be an integer"
353
- raise TypeError(message)
354
- return value
355
-
356
-
357
- def _optional_integer(value: JsonValue, context: str) -> int | None:
358
- return None if value is None else _integer(value, context)
359
-
360
-
361
326
  # pragma: no mutate end
@@ -6,11 +6,11 @@ from dataclasses import dataclass
6
6
  from typing import TYPE_CHECKING
7
7
 
8
8
  from qg_github.github import GitHubPort, paged
9
+ from quality_graph_core.json_values import JSON
9
10
 
10
11
  if TYPE_CHECKING:
11
12
  from collections.abc import Iterable
12
13
 
13
- from quality_graph_core.result import JsonValue
14
14
 
15
15
  GITHUB_COMMENT_BODY_LIMIT = 65_536
16
16
  DEFAULT_BOT_LOGIN = "github-actions[bot]"
@@ -87,7 +87,7 @@ def upsert_managed_comment(
87
87
  return existing
88
88
  else:
89
89
  response = port.request("PATCH", f"/issues/comments/{existing.id}", {"body": rendered})
90
- data = _object(response, "managed comment")
90
+ data = JSON.object(response, "managed comment")
91
91
  comment_id = data.get("id")
92
92
  response_body = data.get("body")
93
93
  if not isinstance(comment_id, int) or isinstance(comment_id, bool):
@@ -97,10 +97,3 @@ def upsert_managed_comment(
97
97
  message = "managed comment response has no body"
98
98
  raise TypeError(message)
99
99
  return ManagedComment(comment_id, response_body)
100
-
101
-
102
- def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
103
- if not isinstance(value, dict):
104
- message = f"{context} must be an object"
105
- raise TypeError(message)
106
- return value
@@ -21,7 +21,13 @@ from quality_graph_core.graph import (
21
21
  Profile,
22
22
  Step,
23
23
  )
24
- from quality_graph_core.provider import GeneratedFile, GeneratedProject
24
+ from quality_graph_core.projection import project_event
25
+ from quality_graph_core.provider import (
26
+ GeneratedFile,
27
+ GeneratedProject,
28
+ ProfileDefaults,
29
+ ProviderCapabilities,
30
+ )
25
31
 
26
32
  if TYPE_CHECKING:
27
33
  from collections.abc import Mapping
@@ -60,6 +66,21 @@ INVALID_BRANCH_CHARACTER_RE = re.compile(r"[\x00-\x20\x7f ~^:?*\[\\]")
60
66
  MAX_BRANCH_NAME_LENGTH = 255
61
67
  SUPPORTED_EVENTS = ("pull-request", "push")
62
68
 
69
+ CAPABILITIES = ProviderCapabilities(
70
+ events=frozenset((*SUPPORTED_EVENTS, "workflow-dispatch")),
71
+ presentations={
72
+ "none": frozenset((*SUPPORTED_EVENTS, "workflow-dispatch")),
73
+ "github-pr": frozenset({"pull-request"}),
74
+ "release": frozenset({"push", "workflow-dispatch"}),
75
+ },
76
+ execution_modes=frozenset({"design-only", "github-actions"}),
77
+ profile_defaults=ProfileDefaults("ubuntu-latest", {"contents": "read"}),
78
+ )
79
+
80
+
81
+ def _execution_mode(flow: Flow) -> str:
82
+ return flow.execution if flow.is_release else "github-actions"
83
+
63
84
 
64
85
  @dataclass(frozen=True)
65
86
  class EventProjection:
@@ -97,6 +118,7 @@ def _validate_github_graph(graph: Graph) -> _GitHubConfiguration:
97
118
  if graph.provider.name != "github":
98
119
  message = f"GitHub provider cannot compile provider '{graph.provider.name}'"
99
120
  raise ValueError(message)
121
+ CAPABILITIES.validate(graph)
100
122
  unknown = graph.provider.values.keys() - {"default-branch", "runtime", "merge"}
101
123
  if unknown:
102
124
  message = f"GitHub provider contains unknown configuration: {', '.join(sorted(unknown))}"
@@ -140,11 +162,15 @@ def _validate_execution_contracts(graph: Graph) -> None:
140
162
  for step in profile.setup:
141
163
  _validate_step(step)
142
164
  for node in graph.nodes:
143
- _validate_node_contract(node, graph.expanded_profiles()[node.profile], allow_write=False)
165
+ _validate_node_contract(
166
+ node,
167
+ graph.expanded_profiles(CAPABILITIES.profile_defaults)[node.profile],
168
+ allow_write=False,
169
+ )
144
170
  for operation in graph.operations:
145
171
  _validate_node_contract(
146
172
  operation.place(FlowNode(operation.id, operation.id), DependencyPolicy.GRAPH),
147
- graph.expanded_profiles()[operation.profile],
173
+ graph.expanded_profiles(CAPABILITIES.profile_defaults)[operation.profile],
148
174
  allow_write=True,
149
175
  )
150
176
  titles = [node.title for node in graph.nodes]
@@ -178,7 +204,7 @@ def _event_projections(graph: Graph) -> tuple[EventProjection, ...]:
178
204
  return tuple(
179
205
  EventProjection(
180
206
  "push" if flow.trigger == "push" else "pull-request",
181
- graph.for_flow(flow.id).nodes,
207
+ project_event(graph, flow.trigger, flow_id=flow.id).nodes,
182
208
  flow.dependencies,
183
209
  )
184
210
  for flow in graph.flows
@@ -194,23 +220,11 @@ def _event_projections(graph: Graph) -> tuple[EventProjection, ...]:
194
220
  raise ValueError(message)
195
221
  projections: list[EventProjection] = []
196
222
  for event in SUPPORTED_EVENTS:
197
- nodes = tuple(node for node in graph.nodes if not node.events or event in node.events)
223
+ nodes = project_event(graph, event).nodes
198
224
  if not nodes:
199
225
  message = f"GitHub {event} event projection must contain at least one node"
200
226
  raise ValueError(message)
201
227
  dependency_policy = graph.execution.get(event, DependencyPolicy.GRAPH)
202
- if dependency_policy is DependencyPolicy.GRAPH:
203
- selected = {node.id for node in nodes}
204
- for node in nodes:
205
- missing = set(node.needs) - selected
206
- if missing:
207
- message = (
208
- f"GitHub {event} event projection excludes dependencies of {node.id}: "
209
- f"{', '.join(sorted(missing))}"
210
- )
211
- raise ValueError(message)
212
- else:
213
- nodes = tuple(replace(node, needs=()) for node in nodes)
214
228
  projections.append(EventProjection(event, nodes, dependency_policy))
215
229
  return tuple(projections)
216
230
 
@@ -229,7 +243,7 @@ def project_graph(graph: Graph, event: str) -> Graph:
229
243
  if graph.flows:
230
244
  for flow in graph.flows:
231
245
  if flow.trigger == event and not flow.is_release:
232
- return graph.for_flow(flow.id)
246
+ return project_event(graph, event, flow_id=flow.id)
233
247
  message = f"no flow declares the {event} trigger"
234
248
  raise ValueError(message)
235
249
  return replace(graph, nodes=event_projection(graph, event).nodes)
@@ -242,7 +256,9 @@ def _validate_explicit_flows(graph: Graph) -> None:
242
256
  message = f"GitHub supports one {trigger} flow per declaration"
243
257
  raise ValueError(message)
244
258
  releases = [
245
- flow for flow in graph.flows if flow.is_release and flow.execution_mode == "github-actions"
259
+ flow
260
+ for flow in graph.flows
261
+ if flow.is_release and _execution_mode(flow) == "github-actions"
246
262
  ]
247
263
  if len(releases) > 1:
248
264
  message = "GitHub supports one executable release flow per declaration"
@@ -256,7 +272,9 @@ def _validate_explicit_flows(graph: Graph) -> None:
256
272
  _validate_release_contract(graph, flow)
257
273
  for node in graph.for_flow(flow.id).nodes:
258
274
  _validate_node_contract(
259
- node, graph.expanded_profiles()[node.profile], allow_write=flow.is_release
275
+ node,
276
+ graph.expanded_profiles(CAPABILITIES.profile_defaults)[node.profile],
277
+ allow_write=flow.is_release,
260
278
  )
261
279
  if flow.presentation == "github-pr":
262
280
  titles = [node.title for node in graph.for_flow(flow.id).nodes]
@@ -287,14 +305,14 @@ def _validate_release_contract(graph: Graph, flow: Flow) -> None:
287
305
  ):
288
306
  message = "release tag patterns must be literal nonnegative filters without whitespace"
289
307
  raise ValueError(message)
290
- if not flow.is_release or flow.execution_mode != "github-actions":
308
+ if not flow.is_release or _execution_mode(flow) != "github-actions":
291
309
  return
292
310
  if any(node.checkpoint for node in flow.nodes):
293
311
  message = (
294
312
  "executable release checkpoints require a resumable provider; use design-only mode"
295
313
  )
296
314
  raise ValueError(message)
297
- profiles = graph.expanded_profiles()
315
+ profiles = graph.expanded_profiles(CAPABILITIES.profile_defaults)
298
316
  for node in graph.for_flow(flow.id).nodes:
299
317
  profile = profiles[node.profile]
300
318
  for step in (*profile.setup, *(node.steps or (node.step,))):
@@ -339,7 +357,7 @@ def _upload_artifact_action(runtime: Mapping[str, JsonValue]) -> str:
339
357
 
340
358
 
341
359
  def _validate_permissions(profile: Profile, *, allow_write: bool = False) -> None:
342
- for permission, access in profile.permissions.items():
360
+ for permission, access in (profile.permissions or {}).items():
343
361
  if permission not in PERMISSION_NAMES:
344
362
  message = f"unknown GitHub permission: {permission}"
345
363
  raise ValueError(message)
@@ -401,7 +419,7 @@ def compile_graph(graph: Graph) -> GeneratedProject:
401
419
 
402
420
  def _compile_flows(graph: Graph, configuration: _GitHubConfiguration) -> GeneratedProject:
403
421
  manifest = _manifest_value(graph, configuration)
404
- profiles = graph.expanded_profiles()
422
+ profiles = graph.expanded_profiles(CAPABILITIES.profile_defaults)
405
423
  manifest.pop("nodes")
406
424
  manifest["manifestVersion"] = 1
407
425
  manifest["operations"] = {
@@ -424,7 +442,7 @@ def _compile_flows(graph: Graph, configuration: _GitHubConfiguration) -> Generat
424
442
  manifest.update({"graphDigest": digest, "_generated": GENERATED_NOTICE})
425
443
  files: list[GeneratedFile] = []
426
444
  for flow in graph.flows:
427
- if flow.execution_mode == "design-only":
445
+ if _execution_mode(flow) == "design-only":
428
446
  continue
429
447
  projection = EventProjection(flow.trigger, graph.for_flow(flow.id).nodes, flow.dependencies)
430
448
  flow_configuration = configuration
@@ -489,7 +507,7 @@ def _flow_value(flow: Flow) -> dict[str, JsonValue]:
489
507
  "dependencies": flow.dependencies.value,
490
508
  "presentation": flow.presentation,
491
509
  "concurrency": flow.concurrency,
492
- "execution": flow.execution_mode,
510
+ "execution": _execution_mode(flow),
493
511
  "nodes": [
494
512
  {
495
513
  "id": node.id,
@@ -509,7 +527,7 @@ def _manifest_value(
509
527
  graph: Graph,
510
528
  configuration: _GitHubConfiguration,
511
529
  ) -> dict[str, JsonValue]:
512
- profiles = graph.expanded_profiles()
530
+ profiles = graph.expanded_profiles(CAPABILITIES.profile_defaults)
513
531
  value: dict[str, JsonValue] = {
514
532
  "manifestVersion": 0,
515
533
  "graphVersion": graph.version,
@@ -549,7 +567,7 @@ def _profile_value(profile: Profile) -> dict[str, JsonValue]:
549
567
  "runner": profile.runner,
550
568
  "setup": [_step_value(step) for step in profile.setup],
551
569
  "env": dict(profile.environment),
552
- "permissions": dict(profile.permissions),
570
+ "permissions": dict(profile.permissions or {}),
553
571
  "services": dict(profile.services),
554
572
  }
555
573
  _put_optional(value, "timeoutMinutes", profile.timeout_minutes)
@@ -616,7 +634,7 @@ def _labels_value(graph: Graph) -> dict[str, JsonValue]:
616
634
 
617
635
  def pr_contract(graph: Graph) -> dict[str, JsonValue]:
618
636
  """Describe effective PR checks and governance independently of pin revisions."""
619
- profiles = graph.expanded_profiles()
637
+ profiles = graph.expanded_profiles(CAPABILITIES.profile_defaults)
620
638
  configuration = dict(graph.provider.values)
621
639
  runtime = cast("dict[str, JsonValue]", configuration.pop("runtime"))
622
640
  return {
@@ -648,7 +666,7 @@ def _execution_workflow(
648
666
  *,
649
667
  flow: Flow | None = None,
650
668
  ) -> dict[str, JsonValue]:
651
- profiles = graph.expanded_profiles()
669
+ profiles = graph.expanded_profiles(CAPABILITIES.profile_defaults)
652
670
  jobs: dict[str, JsonValue] = {
653
671
  node.id: _execution_job(
654
672
  node,
@@ -728,7 +746,7 @@ def _execution_job(
728
746
  value: dict[str, JsonValue] = {
729
747
  "name": node.title,
730
748
  "runs-on": runner,
731
- "permissions": dict(profile.permissions),
749
+ "permissions": dict(profile.permissions or {}),
732
750
  "steps": [
733
751
  *(_workflow_step(step) for step in profile.setup),
734
752
  *([_workflow_step(step) for step in node.steps] if node.steps else [command]),
@@ -35,14 +35,13 @@ def read_pr_results(
35
35
  projected = pr_presentation_graph(head)
36
36
  except (GitHubError, ValueError, TypeError) as error:
37
37
  raise mismatch from error
38
- if (
39
- projected is None
40
- or compiled.graph_digest == expectation.graph_digest
41
- or not _preserves_required_checks(graph, projected)
42
- ):
38
+ if projected is None or compiled.graph_digest == expectation.graph_digest:
39
+ raise
40
+ if not _preserves_required_checks(graph, projected):
43
41
  message = (
44
42
  "PR declaration changes existing required checks or governance; "
45
- "the trusted base declaration must be updated before these results can be accepted"
43
+ "update the trusted base declaration before accepting these results. "
44
+ f"Artifact diagnostic: {mismatch}"
46
45
  )
47
46
  raise DeclarationMismatchError(message) from mismatch
48
47
  current = replace(
@@ -10,6 +10,8 @@ from typing import TYPE_CHECKING, Protocol, cast
10
10
 
11
11
  import httpx
12
12
 
13
+ from quality_graph_core.json_values import JsonValidator
14
+
13
15
  if TYPE_CHECKING:
14
16
  from collections.abc import Mapping
15
17
 
@@ -19,6 +21,9 @@ REQUEST_TIMEOUT_SECONDS = 30.0
19
21
  GITHUB_PAGE_SIZE = 100
20
22
 
21
23
 
24
+ JSON = JsonValidator(verb="return")
25
+
26
+
22
27
  class GitHubPort(Protocol):
23
28
  """Describe the single request interface required by GitHub modules."""
24
29
 
@@ -162,22 +167,8 @@ def paged(port: GitHubPort, path: str) -> tuple[dict[str, JsonValue], ...]:
162
167
  while True:
163
168
  separator = "&" if "?" in path else "?"
164
169
  page_path = f"{path}{separator}per_page={GITHUB_PAGE_SIZE}&page={page}"
165
- items = _array(port.request("GET", page_path), page_path)
166
- result.extend(_object(item, page_path) for item in items)
170
+ items = JSON.array(port.request("GET", page_path), page_path)
171
+ result.extend(JSON.object(item, page_path) for item in items)
167
172
  if len(items) < GITHUB_PAGE_SIZE:
168
173
  return tuple(result)
169
174
  page += 1
170
-
171
-
172
- def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
173
- if not isinstance(value, dict):
174
- message = f"{context} must return an object"
175
- raise TypeError(message)
176
- return value
177
-
178
-
179
- def _array(value: JsonValue, context: str) -> list[JsonValue]:
180
- if not isinstance(value, list):
181
- message = f"{context} must return an array"
182
- raise TypeError(message)
183
- return value
@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, cast
10
10
 
11
11
  from qg_github.github import GitHubPort, paged
12
12
  from quality_graph_core.graph import Graph, LabelSpec
13
+ from quality_graph_core.json_values import JSON
13
14
  from quality_graph_core.result import JsonValue, Result, ResultStatus
14
15
 
15
16
  if TYPE_CHECKING:
@@ -67,7 +68,7 @@ def reconcile_labels(
67
68
  if not graph.labels.enabled:
68
69
  return
69
70
  current = {
70
- _string(item.get("name"), "pull request label")
71
+ JSON.string(item.get("name"), "pull request label")
71
72
  for item in paged(port, f"/issues/{number}/labels")
72
73
  }
73
74
  desired = _desired_labels(graph, results)
@@ -124,10 +125,3 @@ def _ensure_label(port: GitHubPort, specification: LabelSpec) -> None:
124
125
  "description": specification.description,
125
126
  },
126
127
  )
127
-
128
-
129
- def _string(value: JsonValue, context: str) -> str:
130
- if not isinstance(value, str):
131
- message = f"{context} must be a string"
132
- raise TypeError(message)
133
- return value
@@ -1,6 +1,6 @@
1
1
  """Expose GitHub workflow generation through the core provider seam."""
2
2
 
3
- from qg_github.compiler import compile_graph
3
+ from qg_github.compiler import CAPABILITIES, compile_graph
4
4
  from quality_graph_core.graph import Graph
5
5
  from quality_graph_core.provider import GeneratedProject
6
6
 
@@ -9,6 +9,7 @@ class GitHubProvider:
9
9
  """Generate the complete GitHub representation of a Quality Graph."""
10
10
 
11
11
  name = "github"
12
+ capabilities = CAPABILITIES
12
13
 
13
14
  def generate(self, graph: Graph) -> GeneratedProject:
14
15
  """Compile a graph into GitHub workflows and trusted metadata."""
@@ -29,6 +29,7 @@ from qg_github.github import GITHUB_PAGE_SIZE, GitHubPort
29
29
  from qg_github.labels import parse_label_state, reconcile_labels
30
30
  from qg_github.presentation import pr_presentation_graph
31
31
  from quality_graph_core.graph import Graph
32
+ from quality_graph_core.json_values import JSON
32
33
  from quality_graph_core.policy import effective_graph
33
34
  from quality_graph_core.result import JsonValue, Provenance, ResultStatus
34
35
 
@@ -56,25 +57,25 @@ class WorkflowRunEvent:
56
57
  @classmethod
57
58
  def from_value(cls, value: JsonValue) -> WorkflowRunEvent:
58
59
  """Narrow an untrusted GitHub event payload."""
59
- event = _object(value, "workflow event")
60
- run = _object(event.get("workflow_run"), "workflow run")
61
- pulls = _array(run.get("pull_requests", []), "workflow pull requests")
60
+ event = JSON.object(value, "workflow event")
61
+ run = JSON.object(event.get("workflow_run"), "workflow run")
62
+ pulls = JSON.array(run.get("pull_requests", []), "workflow pull requests")
62
63
  pull_number: int | None = None
63
64
  pull_head: str | None = None
64
65
  if pulls:
65
- pull = _object(pulls[0], "workflow pull request")
66
- pull_number = _optional_integer(pull.get("number"), "pull request number")
66
+ pull = JSON.object(pulls[0], "workflow pull request")
67
+ pull_number = JSON.optional_integer(pull.get("number"), "pull request number")
67
68
  head = pull.get("head")
68
69
  if isinstance(head, dict):
69
- pull_head = _optional_string(head.get("sha"), "pull request head SHA")
70
+ pull_head = JSON.optional_string(head.get("sha"), "pull request head SHA")
70
71
  return cls(
71
- _string(event.get("action"), "workflow action"),
72
- _string(run.get("event"), "workflow trigger event"),
73
- _integer(run.get("id"), "workflow run id"),
74
- _integer(run.get("run_attempt", 1), "workflow run attempt"),
75
- _string(run.get("head_sha"), "workflow head SHA"),
72
+ JSON.string(event.get("action"), "workflow action"),
73
+ JSON.string(run.get("event"), "workflow trigger event"),
74
+ JSON.integer(run.get("id"), "workflow run id"),
75
+ JSON.integer(run.get("run_attempt", 1), "workflow run attempt"),
76
+ JSON.string(run.get("head_sha"), "workflow head SHA"),
76
77
  pull_head,
77
- _string(run.get("html_url"), "workflow run URL"),
78
+ JSON.string(run.get("html_url"), "workflow run URL"),
78
79
  pull_number,
79
80
  )
80
81
 
@@ -236,22 +237,22 @@ def publish_workflow_jobs(
236
237
 
237
238
 
238
239
  def _workflow_run_completed(port: GitHubPort, run_id: int) -> bool:
239
- run = _object(port.request("GET", f"/actions/runs/{run_id}"), "workflow run")
240
- return _string(run.get("status"), "workflow run status") == "completed"
240
+ run = JSON.object(port.request("GET", f"/actions/runs/{run_id}"), "workflow run")
241
+ return JSON.string(run.get("status"), "workflow run status") == "completed"
241
242
 
242
243
 
243
244
  def _workflow_jobs(port: GitHubPort, run_id: int) -> tuple[JsonValue, ...]:
244
245
  jobs: list[JsonValue] = []
245
246
  page = 1
246
247
  while True:
247
- response = _object(
248
+ response = JSON.object(
248
249
  port.request(
249
250
  "GET",
250
251
  f"/actions/runs/{run_id}/jobs?filter=all&per_page={GITHUB_PAGE_SIZE}&page={page}",
251
252
  ),
252
253
  "workflow jobs",
253
254
  )
254
- values = _array(response.get("jobs", []), "workflow jobs")
255
+ values = JSON.array(response.get("jobs", []), "workflow jobs")
255
256
  jobs.extend(values)
256
257
  if len(values) < GITHUB_PAGE_SIZE:
257
258
  return tuple(jobs)
@@ -266,7 +267,7 @@ def _optional_workflow_jobs(port: GitHubPort, run_id: int) -> tuple[JsonValue, .
266
267
 
267
268
 
268
269
  def _workflow_job_status(job: Mapping[str, JsonValue]) -> ResultStatus:
269
- status = _string(job.get("status"), "workflow job status")
270
+ status = JSON.string(job.get("status"), "workflow job status")
270
271
  if status == "queued":
271
272
  return ResultStatus.WAITING
272
273
  if status in {"in_progress", "pending", "requested", "waiting"}:
@@ -274,7 +275,7 @@ def _workflow_job_status(job: Mapping[str, JsonValue]) -> ResultStatus:
274
275
  if status != "completed":
275
276
  message = f"unsupported workflow job status: {status}"
276
277
  raise ValueError(message)
277
- conclusion = _optional_string(job.get("conclusion"), "workflow job conclusion")
278
+ conclusion = JSON.optional_string(job.get("conclusion"), "workflow job conclusion")
278
279
  if conclusion == "success":
279
280
  return ResultStatus.PASSED
280
281
  if conclusion == "skipped":
@@ -348,22 +349,22 @@ def _completed_dashboard(
348
349
 
349
350
 
350
351
  def _pull_request(port: GitHubPort, number: int) -> PullRequestState:
351
- pull = _object(port.request("GET", f"/pulls/{number}"), "pull request")
352
- head = _object(pull.get("head"), "pull request head")
353
- base = _object(pull.get("base"), "pull request base")
352
+ pull = JSON.object(port.request("GET", f"/pulls/{number}"), "pull request")
353
+ head = JSON.object(pull.get("head"), "pull request head")
354
+ base = JSON.object(pull.get("base"), "pull request base")
354
355
  return PullRequestState(
355
356
  number,
356
- _string(head.get("sha"), "pull request head SHA"),
357
- _string(base.get("sha"), "pull request base SHA"),
357
+ JSON.string(head.get("sha"), "pull request head SHA"),
358
+ JSON.string(base.get("sha"), "pull request base SHA"),
358
359
  )
359
360
 
360
361
 
361
362
  def _resolve_pull_request(port: GitHubPort, head_sha: str) -> int | None:
362
- pulls = _array(port.request("GET", f"/commits/{head_sha}/pulls"), "commit pull requests")
363
+ pulls = JSON.array(port.request("GET", f"/commits/{head_sha}/pulls"), "commit pull requests")
363
364
  numbers: list[int] = []
364
365
  for value in pulls:
365
- pull = _object(value, "commit pull request")
366
- number = _optional_integer(pull.get("number"), "pull request number")
366
+ pull = JSON.object(value, "commit pull request")
367
+ number = JSON.optional_integer(pull.get("number"), "pull request number")
367
368
  if number is not None:
368
369
  numbers.append(number)
369
370
  return max(numbers) if numbers else None
@@ -374,14 +375,14 @@ def _is_latest_run(port: GitHubPort, event: WorkflowRunEvent, number: int) -> bo
374
375
  "/actions/workflows/quality-graph.yml/runs?event=pull_request"
375
376
  f"&per_page={GITHUB_PAGE_SIZE}&page=1"
376
377
  )
377
- response = _object(port.request("GET", path), "workflow runs")
378
- runs = _array(response.get("workflow_runs", []), "workflow runs")
378
+ response = JSON.object(port.request("GET", path), "workflow runs")
379
+ runs = JSON.array(response.get("workflow_runs", []), "workflow runs")
379
380
  matching_runs = [
380
- (run_id, _integer(run.get("run_attempt", 1), "workflow run attempt"))
381
+ (run_id, JSON.integer(run.get("run_attempt", 1), "workflow run attempt"))
381
382
  for value in runs
382
- for run in (_object(value, "workflow run"),)
383
+ for run in (JSON.object(value, "workflow run"),)
383
384
  if _run_has_pull(run, number)
384
- for run_id in (_optional_integer(run.get("id"), "workflow run id"),)
385
+ for run_id in (JSON.optional_integer(run.get("id"), "workflow run id"),)
385
386
  if run_id is not None
386
387
  ]
387
388
  return not matching_runs or (event.id, event.attempt) >= max(matching_runs)
@@ -389,19 +390,19 @@ def _is_latest_run(port: GitHubPort, event: WorkflowRunEvent, number: int) -> bo
389
390
 
390
391
  def _run_has_pull(run: Mapping[str, JsonValue], number: int) -> bool:
391
392
  return any(
392
- _object(value, "workflow pull request").get("number") == number
393
- for value in _array(run.get("pull_requests", []), "workflow pull requests")
393
+ JSON.object(value, "workflow pull request").get("number") == number
394
+ for value in JSON.array(run.get("pull_requests", []), "workflow pull requests")
394
395
  )
395
396
 
396
397
 
397
398
  def _repository_file(port: GitHubPort, path: str, ref: str) -> str:
398
399
  encoded_path = urllib.parse.quote(path, safe="")
399
400
  encoded_ref = urllib.parse.quote(ref, safe="")
400
- response = _object(
401
+ response = JSON.object(
401
402
  port.request("GET", f"/contents/{encoded_path}?ref={encoded_ref}"),
402
403
  "repository file",
403
404
  )
404
- content = _string(response.get("content"), "repository file content")
405
+ content = JSON.string(response.get("content"), "repository file content")
405
406
  try:
406
407
  return base64.b64decode(content.replace("\n", ""), validate=True).decode()
407
408
  except (ValueError, UnicodeDecodeError) as error:
@@ -426,7 +427,7 @@ def _publish_check(port: GitHubPort, model: DashboardModel) -> None:
426
427
  if completed:
427
428
  payload["conclusion"] = "success" if model.status is ResultStatus.PASSED else "failure"
428
429
  name = urllib.parse.quote("Quality Graph", safe="")
429
- response = _object(
430
+ response = JSON.object(
430
431
  port.request(
431
432
  "GET",
432
433
  f"/commits/{model.head_sha}/check-runs"
@@ -436,9 +437,9 @@ def _publish_check(port: GitHubPort, model: DashboardModel) -> None:
436
437
  )
437
438
  check_id = next(
438
439
  (
439
- _optional_integer(check.get("id"), "check run id")
440
- for value in _array(response.get("check_runs", []), "check runs")
441
- for check in (_object(value, "check run"),)
440
+ JSON.optional_integer(check.get("id"), "check run id")
441
+ for value in JSON.array(response.get("check_runs", []), "check runs")
442
+ for check in (JSON.object(value, "check run"),)
442
443
  if check.get("external_id") == external_id
443
444
  ),
444
445
  None,
@@ -453,43 +454,7 @@ def _publish_check(port: GitHubPort, model: DashboardModel) -> None:
453
454
  def read_event_json(value: str) -> dict[str, JsonValue]:
454
455
  """Decode and narrow one GitHub event JSON document."""
455
456
  event = cast("JsonValue", json.loads(value))
456
- return _object(event, "GitHub event")
457
-
458
-
459
- def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
460
- if not isinstance(value, dict):
461
- message = f"{context} must be an object"
462
- raise TypeError(message)
463
- return value
464
-
465
-
466
- def _array(value: JsonValue, context: str) -> list[JsonValue]:
467
- if not isinstance(value, list):
468
- message = f"{context} must be an array"
469
- raise TypeError(message)
470
- return value
471
-
472
-
473
- def _string(value: JsonValue, context: str) -> str:
474
- if not isinstance(value, str):
475
- message = f"{context} must be a string"
476
- raise TypeError(message)
477
- return value
478
-
479
-
480
- def _optional_string(value: JsonValue, context: str) -> str | None:
481
- return None if value is None else _string(value, context)
482
-
483
-
484
- def _integer(value: JsonValue, context: str) -> int:
485
- if not isinstance(value, int) or isinstance(value, bool):
486
- message = f"{context} must be an integer"
487
- raise TypeError(message)
488
- return value
489
-
490
-
491
- def _optional_integer(value: JsonValue, context: str) -> int | None:
492
- return None if value is None else _integer(value, context)
457
+ return JSON.object(event, "GitHub event")
493
458
 
494
459
 
495
460
  def _workflow_node_jobs(
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, cast
9
9
 
10
10
  from qg_github.compiler import _validate_github_graph
11
11
  from qg_github.github import GitHubError
12
+ from quality_graph_core.json_values import JSON
12
13
 
13
14
  if TYPE_CHECKING:
14
15
  from qg_github.github import GitHubPort
@@ -49,23 +50,23 @@ def plan_required_checks(port: GitHubPort, graph: Graph) -> RequiredChecksPlan:
49
50
  configuration = _validate_github_graph(graph)
50
51
  branch = configuration.default_branch
51
52
  encoded = urllib.parse.quote(branch, safe="")
52
- rules = _array(_request(port, "GET", f"/rules/branches/{encoded}"), "branch rules")
53
+ rules = JSON.array(_request(port, "GET", f"/rules/branches/{encoded}"), "branch rules")
53
54
  sources = {
54
55
  (
55
- _string(rule.get("ruleset_source_type"), "ruleset source type"),
56
- _integer(rule.get("ruleset_id"), "ruleset id"),
56
+ JSON.string(rule.get("ruleset_source_type"), "ruleset source type"),
57
+ JSON.integer(rule.get("ruleset_id"), "ruleset id"),
57
58
  )
58
59
  for value in rules
59
- for rule in (_object(value, "branch rule"),)
60
+ for rule in (JSON.object(value, "branch rule"),)
60
61
  }
61
62
  required_sources = {
62
63
  source
63
64
  for value in rules
64
- for rule in (_object(value, "branch rule"),)
65
+ for rule in (JSON.object(value, "branch rule"),)
65
66
  for source in (
66
67
  (
67
- _string(rule.get("ruleset_source_type"), "ruleset source type"),
68
- _integer(rule.get("ruleset_id"), "ruleset id"),
68
+ JSON.string(rule.get("ruleset_source_type"), "ruleset source type"),
69
+ JSON.integer(rule.get("ruleset_id"), "ruleset id"),
69
70
  ),
70
71
  )
71
72
  if rule.get("type") == "required_status_checks"
@@ -124,13 +125,13 @@ def _ruleset_plan(
124
125
  required: bool,
125
126
  ) -> RequiredChecksPlan:
126
127
  path = f"/rulesets/{ruleset_id}"
127
- ruleset = _object(_request(port, "GET", path), "repository ruleset")
128
- rules = _array(ruleset.get("rules"), "repository ruleset rules")
128
+ ruleset = JSON.object(_request(port, "GET", path), "repository ruleset")
129
+ rules = JSON.array(ruleset.get("rules"), "repository ruleset rules")
129
130
  index = next(
130
131
  (
131
132
  position
132
133
  for position, value in enumerate(rules)
133
- if _object(value, "ruleset rule").get("type") == "required_status_checks"
134
+ if JSON.object(value, "ruleset rule").get("type") == "required_status_checks"
134
135
  ),
135
136
  None,
136
137
  )
@@ -152,16 +153,16 @@ def _ruleset_plan(
152
153
  "repository ruleset", branch, None, None, None, (), (QUALITY_GRAPH_CONTEXT,)
153
154
  )
154
155
  return _ruleset_update(ruleset, desired_rules, path, plan)
155
- current_rule = _object(rules[index], "required status checks rule")
156
- parameters = _object(current_rule.get("parameters"), "required status checks parameters")
157
- checks = _array(parameters.get("required_status_checks"), "required status checks")
156
+ current_rule = JSON.object(rules[index], "required status checks rule")
157
+ parameters = JSON.object(current_rule.get("parameters"), "required status checks parameters")
158
+ checks = JSON.array(parameters.get("required_status_checks"), "required status checks")
158
159
  before = tuple(
159
- _string(_object(value, "required status check").get("context"), "status context")
160
+ JSON.string(JSON.object(value, "required status check").get("context"), "status context")
160
161
  for value in checks
161
162
  )
162
163
  desired_checks = _desired_check_objects(checks, required=required)
163
164
  after = tuple(
164
- _string(_object(value, "required status check").get("context"), "status context")
165
+ JSON.string(JSON.object(value, "required status check").get("context"), "status context")
165
166
  for value in desired_checks
166
167
  )
167
168
  if checks == desired_checks:
@@ -213,18 +214,18 @@ def _classic_plan(
213
214
  before: tuple[str, ...] = ()
214
215
  strict = False
215
216
  checks: list[JsonValue] | None = None
216
- full_protection = _object(protection, "branch protection")
217
+ full_protection = JSON.object(protection, "branch protection")
217
218
  else:
218
- value = _object(status, "required status check protection")
219
+ value = JSON.object(status, "required status check protection")
219
220
  strict = bool(value.get("strict", False))
220
221
  raw_checks = value.get("checks")
221
- checks = None if raw_checks is None else _array(raw_checks, "status checks")
222
+ checks = None if raw_checks is None else JSON.array(raw_checks, "status checks")
222
223
  if checks is None:
223
- contexts = _array(value.get("contexts", []), "status contexts")
224
- before = tuple(_string(item, "status context") for item in contexts)
224
+ contexts = JSON.array(value.get("contexts", []), "status contexts")
225
+ before = tuple(JSON.string(item, "status context") for item in contexts)
225
226
  else:
226
227
  before = tuple(
227
- _string(_object(item, "status check").get("context"), "status context")
228
+ JSON.string(JSON.object(item, "status check").get("context"), "status context")
228
229
  for item in checks
229
230
  )
230
231
  desired = _desired_contexts(before, required=required)
@@ -283,7 +284,7 @@ def _branch_protection_payload(
283
284
  def _pull_request_reviews(value: JsonValue) -> JsonValue:
284
285
  if value is None:
285
286
  return None
286
- reviews = _object(value, "pull request review protection")
287
+ reviews = JSON.object(value, "pull request review protection")
287
288
  payload: dict[str, JsonValue] = {
288
289
  key: reviews[key]
289
290
  for key in (
@@ -303,7 +304,7 @@ def _pull_request_reviews(value: JsonValue) -> JsonValue:
303
304
  def _restrictions(value: JsonValue) -> JsonValue:
304
305
  if value is None:
305
306
  return None
306
- restrictions = _object(value, "branch restrictions")
307
+ restrictions = JSON.object(value, "branch restrictions")
307
308
  return {
308
309
  "users": _actor_names(restrictions.get("users", []), "login"),
309
310
  "teams": _actor_names(restrictions.get("teams", []), "slug"),
@@ -313,8 +314,8 @@ def _restrictions(value: JsonValue) -> JsonValue:
313
314
 
314
315
  def _actor_names(value: JsonValue, field: str) -> list[JsonValue]:
315
316
  return [
316
- _string(_object(actor, "branch restriction actor").get(field), field)
317
- for actor in _array(value, "branch restriction actors")
317
+ JSON.string(JSON.object(actor, "branch restriction actor").get(field), field)
318
+ for actor in JSON.array(value, "branch restriction actors")
318
319
  ]
319
320
 
320
321
 
@@ -323,7 +324,7 @@ def _enabled_or_none(value: JsonValue) -> JsonValue:
323
324
 
324
325
 
325
326
  def _enabled(value: JsonValue, context: str) -> bool:
326
- enabled = _object(value, context).get("enabled")
327
+ enabled = JSON.object(value, context).get("enabled")
327
328
  if not isinstance(enabled, bool):
328
329
  message = f"{context} enabled must be a boolean"
329
330
  raise TypeError(message)
@@ -334,7 +335,7 @@ def _desired_check_objects(checks: list[JsonValue], *, required: bool) -> list[J
334
335
  managed = [
335
336
  item
336
337
  for item in checks
337
- if _object(item, "status check").get("context") == QUALITY_GRAPH_CONTEXT
338
+ if JSON.object(item, "status check").get("context") == QUALITY_GRAPH_CONTEXT
338
339
  ]
339
340
  if required and managed:
340
341
  return list(checks)
@@ -359,31 +360,3 @@ def _request(port: GitHubPort, method: str, path: str, payload: JsonValue = None
359
360
  message = "GitHub token requires repository Administration write permission"
360
361
  raise PermissionError(message) from error
361
362
  raise
362
-
363
-
364
- def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
365
- if not isinstance(value, dict):
366
- message = f"{context} must be an object"
367
- raise TypeError(message)
368
- return value
369
-
370
-
371
- def _array(value: JsonValue, context: str) -> list[JsonValue]:
372
- if not isinstance(value, list):
373
- message = f"{context} must be an array"
374
- raise TypeError(message)
375
- return value
376
-
377
-
378
- def _string(value: JsonValue, context: str) -> str:
379
- if not isinstance(value, str):
380
- message = f"{context} must be a string"
381
- raise TypeError(message)
382
- return value
383
-
384
-
385
- def _integer(value: JsonValue, context: str) -> int:
386
- if not isinstance(value, int) or isinstance(value, bool):
387
- message = f"{context} must be an integer"
388
- raise TypeError(message)
389
- return value
@@ -18,16 +18,8 @@ from qg_github.publication import (
18
18
  watch_workflow_run,
19
19
  )
20
20
  from qg_github.reporting import append_job_summary
21
- from quality_graph_core.adapters import (
22
- AdapterContext,
23
- AdapterError,
24
- adapt_exit,
25
- adapt_junit,
26
- adapt_native,
27
- adapt_sarif,
28
- adapter_failure,
29
- read_report,
30
- )
21
+ from quality_graph_core.adapters import AdapterContext
22
+ from quality_graph_core.collection import collect_report
31
23
  from quality_graph_core.graph import AdapterKind, ApprovalPolicy
32
24
  from quality_graph_core.policy import policy_controls
33
25
  from quality_graph_core.result import FailureKind, JsonValue, Provenance, Result, ResultStatus
@@ -95,31 +87,10 @@ class CollectionRequest:
95
87
 
96
88
  def collect(request: CollectionRequest) -> Result:
97
89
  """Collect one command outcome through its selected adapter."""
98
- try:
99
- if request.adapter is AdapterKind.EXIT_CODE:
100
- output = ""
101
- if request.report_path is not None:
102
- try:
103
- output = read_report(request.workspace, request.report_path).decode()
104
- except UnicodeDecodeError as error:
105
- message = "Exit-code command output must be UTF-8"
106
- raise AdapterError(message) from error
107
- return _with_policy_controls(
108
- request,
109
- adapt_exit(request.context, output),
110
- )
111
- report = _structured_report(request)
112
- if request.adapter is AdapterKind.NATIVE:
113
- return _with_policy_controls(request, adapt_native(request.context, report))
114
- if request.adapter is AdapterKind.SARIF:
115
- result = adapt_sarif(request.context, report)
116
- else:
117
- result = adapt_junit(request.context, report)
118
- return _with_policy_controls(request, result)
119
- except (AdapterError, OSError) as error:
120
- return _with_policy_controls(
121
- request, adapter_failure(request.context, AdapterError(str(error)))
122
- )
90
+ result = collect_report(
91
+ request.context, request.adapter, request.workspace, request.report_path
92
+ )
93
+ return _with_policy_controls(request, result)
123
94
 
124
95
 
125
96
  def _with_policy_controls(request: CollectionRequest, result: Result) -> Result:
@@ -129,13 +100,6 @@ def _with_policy_controls(request: CollectionRequest, result: Result) -> Result:
129
100
  return replace(result, controls=controls)
130
101
 
131
102
 
132
- def _structured_report(request: CollectionRequest) -> bytes:
133
- if request.report_path is None:
134
- message = f"{request.adapter.value} adapter requires a report path"
135
- raise AdapterError(message)
136
- return read_report(request.workspace, request.report_path)
137
-
138
-
139
103
  def publish_collection(request: CollectionRequest, result: Result) -> int:
140
104
  """Write result, summary, annotations, and Action outputs."""
141
105
  request.result_path.parent.mkdir(parents=True, exist_ok=True)