perucompras-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.
Files changed (50) hide show
  1. perucompras_cli-0.1.0.dist-info/METADATA +429 -0
  2. perucompras_cli-0.1.0.dist-info/RECORD +50 -0
  3. perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
  4. perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
  6. piloto_ai_cli/__init__.py +51 -0
  7. piloto_ai_cli/__main__.py +5 -0
  8. piloto_ai_cli/api.py +394 -0
  9. piloto_ai_cli/attribute_text.py +106 -0
  10. piloto_ai_cli/attributes_service.py +250 -0
  11. piloto_ai_cli/auto_tag.py +65 -0
  12. piloto_ai_cli/backoff.py +25 -0
  13. piloto_ai_cli/cards.py +871 -0
  14. piloto_ai_cli/cli.py +602 -0
  15. piloto_ai_cli/connectors.py +106 -0
  16. piloto_ai_cli/database.py +491 -0
  17. piloto_ai_cli/enrichment.py +557 -0
  18. piloto_ai_cli/errors.py +92 -0
  19. piloto_ai_cli/excel.py +186 -0
  20. piloto_ai_cli/extraction.py +1316 -0
  21. piloto_ai_cli/health.py +398 -0
  22. piloto_ai_cli/health_workflow.py +1060 -0
  23. piloto_ai_cli/http_client.py +610 -0
  24. piloto_ai_cli/llm_client.py +259 -0
  25. piloto_ai_cli/llm_extraction.py +444 -0
  26. piloto_ai_cli/llm_output.py +90 -0
  27. piloto_ai_cli/pane.py +303 -0
  28. piloto_ai_cli/parsers.py +477 -0
  29. piloto_ai_cli/payload_store.py +227 -0
  30. piloto_ai_cli/pdf_parser.py +12 -0
  31. piloto_ai_cli/py.typed +0 -0
  32. piloto_ai_cli/query_compiler.py +1112 -0
  33. piloto_ai_cli/query_result.py +175 -0
  34. piloto_ai_cli/query_service.py +199 -0
  35. piloto_ai_cli/reextract.py +129 -0
  36. piloto_ai_cli/review.py +217 -0
  37. piloto_ai_cli/rules.py +67 -0
  38. piloto_ai_cli/run_log.py +230 -0
  39. piloto_ai_cli/schema/__init__.py +25 -0
  40. piloto_ai_cli/schema/contract-v1.schema.json +261 -0
  41. piloto_ai_cli/schema/contract.py +257 -0
  42. piloto_ai_cli/schema/migration_filters.py +59 -0
  43. piloto_ai_cli/schema/models.py +747 -0
  44. piloto_ai_cli/schema/snowflake_autogen.py +134 -0
  45. piloto_ai_cli/search_form.py +82 -0
  46. piloto_ai_cli/settings.py +174 -0
  47. piloto_ai_cli/snowflake_url.py +90 -0
  48. piloto_ai_cli/stamp_service.py +53 -0
  49. piloto_ai_cli/sync.py +1157 -0
  50. piloto_ai_cli/unit_converter.py +81 -0
@@ -0,0 +1,1060 @@
1
+ """Turn a ``pc --json health`` report into the scheduled health workflow's issues.
2
+
3
+ ``.github/workflows/health.yml`` runs ``pc --json health`` against the live site
4
+ and the pilot database. It runs this stdlib-only module with
5
+ ``python -I src/piloto_ai_cli/health_workflow.py`` before the live checks:
6
+
7
+ ``recent-runs``
8
+ Reads this workflow's runs and prints the ids of the runs whose jobs must
9
+ be read to know whether live checks ran in the last 3 hours.
10
+ ``check-spacing``
11
+ Reads those runs and their jobs and fails, saying when the next run is
12
+ allowed, if another run of the workflow, or an earlier attempt of this
13
+ run, started its live checks less than 3 hours ago.
14
+
15
+ and after them:
16
+
17
+ ``report``
18
+ Reads the command's report (or, with ``--install-failed true``, reports
19
+ that the CLI could not be installed), redacts secrets from it, writes
20
+ ``report.json`` and prints ``failed=true|false`` for the workflow. It
21
+ imports only the standard library, so the workflow runs it with
22
+ ``python -I`` even when the project's environment could not be installed.
23
+ ``plan``
24
+ Reads that report and the repository's open issues and decides, for each
25
+ failed check, whether to open a new issue or to record the failure on the
26
+ open issue that already tracks it. It writes ``plan.tsv`` (one action per
27
+ line) and the issue and comment bodies.
28
+
29
+ Each failed check is tracked by its own issue, keyed by the check's name. The
30
+ key is carried in a hidden marker in the issue body, and only open issues the
31
+ workflow itself opened are considered, so a closed issue is never reopened: a
32
+ check that fails again after its issue was closed gets a new issue. The GitHub
33
+ calls themselves stay in the workflow; this module only reads and writes files.
34
+ """
35
+
36
+ import argparse
37
+ import json
38
+ import os
39
+ import re
40
+ import sys
41
+ from collections.abc import Callable, Iterable, Sequence
42
+ from dataclasses import dataclass, replace
43
+ from datetime import UTC, datetime, timedelta
44
+ from pathlib import Path
45
+ from typing import Any, Literal
46
+ from urllib.parse import quote, unquote, unquote_plus, urlsplit
47
+
48
+ # The hidden marker that carries an issue's key (the failed check's name).
49
+ MARKER_PREFIX = "<!-- pc-health-workflow check="
50
+ MARKER_SUFFIX = " -->"
51
+ _MARKER_RE = re.compile(r"<!-- pc-health-workflow check=(\S+) -->")
52
+ # The hidden marker of the report (run id and attempt of the health job) that an
53
+ # issue body or comment records, so a re-run of the issues job never records the
54
+ # same report twice.
55
+ REPORT_MARKER_PREFIX = "<!-- pc-health-workflow report="
56
+ _REPORT_ID_RE = re.compile(r"[0-9]+\.[0-9]+")
57
+ _REPORT_MARKER_RE = re.compile(r"<!-- pc-health-workflow report=([0-9]+\.[0-9]+) -->")
58
+ # The author of the issues the workflow opens with its own token. An issue anyone
59
+ # else wrote is never reused, even if it quotes a marker.
60
+ WORKFLOW_LOGIN = "github-actions[bot]"
61
+ ISSUE_TITLE_PREFIX = "pc health check failed: "
62
+ FORCED_TITLE_SUFFIX = " (forced test)"
63
+ FORCED_CHECK = "workflow.forced_failure"
64
+ RUN_CHECK = "workflow.pc_health"
65
+ INSTALL_CHECK = "workflow.install"
66
+ REPORT_ARTIFACT = "health-report"
67
+ PLAN_FILE = "plan.tsv"
68
+ # GitHub rejects issue and comment bodies over 65,536 characters and titles over 256.
69
+ MAX_BODY_LENGTH = 60_000
70
+ MAX_TITLE_LENGTH = 256
71
+ MAX_REASON_LENGTH = 1_000
72
+ # Live checks must not run more often than every 3 hours (polite client).
73
+ LIVE_SPACING = timedelta(hours=3)
74
+ # The workflow step that makes the live requests.
75
+ LIVE_STEP = "Run pc health"
76
+ # How far back the workflow lists its runs. A run can be re-run up to 30 days
77
+ # after it was created and keeps its creation time, and a job waits at most a
78
+ # day for a runner; older runs cannot have started live checks recently.
79
+ RUN_LOOKBACK = timedelta(days=31)
80
+ # GitHub returns at most 1,000 runs for a list filtered by creation time.
81
+ MAX_LISTED_RUNS = 1_000
82
+ _NOT_STARTED_JOB = frozenset({"queued", "waiting", "requested", "pending"})
83
+
84
+ # Environment variables whose values must never reach the report or an issue.
85
+ SECRET_VARIABLES = ("PILOTO_DATABASE_URL",)
86
+ _SECRET_QUERY_KEYS = {"password", "passcode", "token", "private_key", "private_key_file_pwd"}
87
+ _MIN_SECRET_LENGTH = 4
88
+ # Inserted after "@" in rendered text so a reason never mentions a GitHub user.
89
+ _ZERO_WIDTH_SPACE = "​"
90
+
91
+ Check = dict[str, str | None]
92
+
93
+
94
+ def load_checks(report_text: str, exit_code: int) -> list[Check]:
95
+ """Read the checks from a ``pc --json health`` report.
96
+
97
+ A report that is missing or malformed means ``pc health`` itself failed
98
+ (configuration, a crash), which is reported as one failed check. A non-zero
99
+ exit code with no failed check is reported the same way, so the run never
100
+ looks healthy when the command did not succeed.
101
+ """
102
+ checks = _parse_checks(report_text)
103
+ if checks is None:
104
+ return [
105
+ _failed(
106
+ RUN_CHECK,
107
+ f"pc health exited with code {exit_code} without a valid JSON report; "
108
+ "see the workflow run log",
109
+ )
110
+ ]
111
+ if exit_code != 0 and not any(check["status"] == "failed" for check in checks):
112
+ checks.append(
113
+ _failed(RUN_CHECK, f"pc health exited with code {exit_code} but reported no failure")
114
+ )
115
+ return checks
116
+
117
+
118
+ def _parse_checks(report_text: str) -> list[Check] | None:
119
+ try:
120
+ report = json.loads(report_text)
121
+ except ValueError:
122
+ return None
123
+ if not isinstance(report, dict) or not isinstance(report.get("checks"), list):
124
+ return None
125
+ checks: list[Check] = []
126
+ for item in report["checks"]:
127
+ if not isinstance(item, dict):
128
+ return None
129
+ name, status, reason = item.get("check"), item.get("status"), item.get("reason")
130
+ blocked_by = item.get("blocked_by")
131
+ if not isinstance(name, str) or status not in ("ok", "failed"):
132
+ return None
133
+ if reason is not None and not isinstance(reason, str):
134
+ return None
135
+ if blocked_by is not None and not isinstance(blocked_by, str):
136
+ return None
137
+ checks.append({"check": name, "status": status, "reason": reason, "blocked_by": blocked_by})
138
+ if not checks:
139
+ return None
140
+ return checks
141
+
142
+
143
+ def _failed(check: str, reason: str) -> Check:
144
+ return {"check": check, "status": "failed", "reason": reason, "blocked_by": None}
145
+
146
+
147
+ def install_failure() -> Check:
148
+ """The failed check reported when the CLI could not be installed."""
149
+ return _failed(
150
+ INSTALL_CHECK,
151
+ "the CLI and its dependencies could not be installed (setup-uv or uv sync --locked "
152
+ "failed), so pc health did not run; see the workflow run log",
153
+ )
154
+
155
+
156
+ def force_failure(checks: Sequence[Check]) -> list[Check]:
157
+ """Add the failed check a manual dispatch with ``force_failure`` asks for."""
158
+ return [
159
+ *checks,
160
+ _failed(
161
+ FORCED_CHECK,
162
+ "forced by a manual dispatch with force_failure to test the workflow; "
163
+ "nothing on the site or in the database needs fixing for this check",
164
+ ),
165
+ ]
166
+
167
+
168
+ def has_failure(checks: Iterable[Check]) -> bool:
169
+ """Return whether any check failed."""
170
+ return any(check["status"] == "failed" for check in checks)
171
+
172
+
173
+ def secret_fragments(values: Iterable[str]) -> list[str]:
174
+ """Return the strings to redact for each secret, including URL credentials."""
175
+ fragments: set[str] = set()
176
+ for value in values:
177
+ value = value.strip()
178
+ if not value:
179
+ continue
180
+ fragments.add(value)
181
+ try:
182
+ parts = urlsplit(value)
183
+ password = parts.password
184
+ except ValueError:
185
+ continue
186
+ if password:
187
+ fragments.update({password, unquote(password)})
188
+ for pair in parts.query.split("&"):
189
+ key, separator, item = pair.partition("=")
190
+ if separator and item and unquote_plus(key).lower() in _SECRET_QUERY_KEYS:
191
+ fragments.update({item, unquote_plus(item)})
192
+ # Redact longer fragments first so a shorter one never splits a longer match.
193
+ return sorted(
194
+ (fragment for fragment in fragments if len(fragment) >= _MIN_SECRET_LENGTH),
195
+ key=len,
196
+ reverse=True,
197
+ )
198
+
199
+
200
+ def redact(text: str, fragments: Iterable[str]) -> str:
201
+ """Replace every secret fragment in ``text`` with ``***``."""
202
+ for fragment in fragments:
203
+ text = text.replace(fragment, "***")
204
+ return text
205
+
206
+
207
+ def redact_checks(checks: Iterable[Check], fragments: Sequence[str]) -> list[Check]:
208
+ """Return copies of ``checks`` with every secret fragment redacted from each value.
209
+
210
+ Redaction must run on the raw values, before anything cuts, collapses or
211
+ escapes them (the Markdown table, ``json.dumps``): a secret that was
212
+ truncated or escaped no longer matches its fragment.
213
+ """
214
+ return [
215
+ {key: None if value is None else redact(value, fragments) for key, value in check.items()}
216
+ for check in checks
217
+ ]
218
+
219
+
220
+ # Issue keys and markers.
221
+
222
+
223
+ def issue_marker(key: str) -> str:
224
+ """Return the hidden marker that ties an issue to its key.
225
+
226
+ The key is percent-encoded, ``-`` included, so it holds no whitespace and
227
+ can never end the HTML comment early.
228
+ """
229
+ return f"{MARKER_PREFIX}{quote(key, safe=':,>').replace('-', '%2D')}{MARKER_SUFFIX}"
230
+
231
+
232
+ def parse_issue_key(body: str) -> str | None:
233
+ """Return the key of the first marker in an issue body, if any."""
234
+ match = _MARKER_RE.search(body)
235
+ return unquote(match.group(1)) if match else None
236
+
237
+
238
+ def report_marker(report_id: str) -> str:
239
+ """Return the hidden marker that records one report on an issue.
240
+
241
+ ``report_id`` is ``<run id>.<run attempt>`` of the health job that produced
242
+ the report; anything else raises ``ValueError``.
243
+ """
244
+ if not _REPORT_ID_RE.fullmatch(report_id):
245
+ raise ValueError(f"report id {report_id!r} is not <run id>.<run attempt>")
246
+ return f"{REPORT_MARKER_PREFIX}{report_id}{MARKER_SUFFIX}"
247
+
248
+
249
+ def parse_report_ids(text: str) -> frozenset[str]:
250
+ """Return the ids of every report marker in an issue body or comment."""
251
+ return frozenset(_REPORT_MARKER_RE.findall(text))
252
+
253
+
254
+ def _json_values(text: str) -> list[Any]:
255
+ """Read ``gh api --paginate`` output: one JSON value per page, concatenated."""
256
+ decoder = json.JSONDecoder()
257
+ values: list[Any] = []
258
+ position = 0
259
+ while True:
260
+ while position < len(text) and text[position].isspace():
261
+ position += 1
262
+ if position == len(text):
263
+ return values
264
+ value, position = decoder.raw_decode(text, position)
265
+ values.append(value)
266
+
267
+
268
+ @dataclass(frozen=True)
269
+ class OpenIssue:
270
+ """An open issue the workflow opened, and the check it tracks."""
271
+
272
+ number: int
273
+ key: str
274
+ assigned: bool
275
+ # The reports already recorded on the issue, by the workflow itself: in the
276
+ # issue body or in a comment it wrote.
277
+ reports: frozenset[str] = frozenset()
278
+
279
+
280
+ def load_open_issues(text: str) -> list[OpenIssue]:
281
+ """Read the workflow's own open issues from ``gh api --paginate`` output.
282
+
283
+ The output is one JSON array per page, concatenated. Pull requests, closed
284
+ issues, issues without a marker and issues anyone but the workflow opened
285
+ are left out. Malformed output raises ``ValueError``: deciding without the
286
+ open issues would open duplicates.
287
+ """
288
+ return _load_issues(text, open_only=True)
289
+
290
+
291
+ def load_workflow_issues(text: str) -> list[OpenIssue]:
292
+ """Read every issue the workflow opened, open or closed, like ``load_open_issues``.
293
+
294
+ Used to find the reports already recorded anywhere, so a closed issue that
295
+ records this report still prevents recording it again.
296
+ """
297
+ return _load_issues(text, open_only=False)
298
+
299
+
300
+ def _load_issues(text: str, *, open_only: bool) -> list[OpenIssue]:
301
+ issues: list[OpenIssue] = []
302
+ for item in _paged_values(text):
303
+ if not isinstance(item, dict):
304
+ raise ValueError("the issue list holds a value that is not an issue")
305
+ if item.get("pull_request") is not None:
306
+ continue
307
+ if open_only and item.get("state", "open") != "open":
308
+ continue
309
+ user = item.get("user")
310
+ if not isinstance(user, dict) or user.get("login") != WORKFLOW_LOGIN:
311
+ continue
312
+ body, number = item.get("body"), item.get("number")
313
+ key = parse_issue_key(body) if isinstance(body, str) else None
314
+ if key is None:
315
+ continue
316
+ if not isinstance(number, int):
317
+ raise ValueError("an issue in the issue list has no number")
318
+ assignees = item.get("assignees")
319
+ open_ = item.get("state", "open") == "open"
320
+ issues.append(
321
+ OpenIssue(number, key, open_ and bool(assignees), parse_report_ids(body or ""))
322
+ )
323
+ return sorted(issues, key=lambda issue: issue.number)
324
+
325
+
326
+ def _paged_values(text: str) -> list[Any]:
327
+ items: list[Any] = []
328
+ for value in _json_values(text):
329
+ if isinstance(value, list):
330
+ items.extend(value)
331
+ else:
332
+ items.append(value)
333
+ return items
334
+
335
+
336
+ def load_comment_reports(text: str) -> frozenset[str]:
337
+ """Return the reports recorded in an issue's comments the workflow wrote.
338
+
339
+ ``text`` is ``gh api --paginate`` output of the issue's comments. Comments
340
+ anyone else wrote are ignored, even if they quote a marker. Malformed output
341
+ raises ``ValueError``: planning without it could record a report twice.
342
+ """
343
+ reports: set[str] = set()
344
+ for item in _paged_values(text):
345
+ if not isinstance(item, dict):
346
+ raise ValueError("the comment list holds a value that is not a comment")
347
+ user, body = item.get("user"), item.get("body")
348
+ if isinstance(user, dict) and user.get("login") == WORKFLOW_LOGIN and isinstance(body, str):
349
+ reports |= parse_report_ids(body)
350
+ return frozenset(reports)
351
+
352
+
353
+ def with_comment_reports(issues: Iterable[OpenIssue], comments_dir: Path) -> list[OpenIssue]:
354
+ """Add the reports recorded in each issue's comments, read from ``<number>.json``.
355
+
356
+ A missing or unreadable file raises ``OSError`` or ``ValueError``.
357
+ """
358
+ return [
359
+ replace(
360
+ issue,
361
+ reports=issue.reports
362
+ | load_comment_reports((comments_dir / f"{issue.number}.json").read_text("utf-8")),
363
+ )
364
+ for issue in issues
365
+ ]
366
+
367
+
368
+ def issue_failures(checks: Iterable[Check]) -> list[Check]:
369
+ """Return the failed checks that each need an issue, one per check name.
370
+
371
+ A check that did not run because another check failed is a symptom of
372
+ that failure: it gets no issue only when the report names that check in
373
+ ``blocked_by`` and that check failed in the same report. Causality is
374
+ never inferred from the reason text, so every other failed check,
375
+ including one that did not run because a precondition failed, gets its
376
+ own issue. A chain of blocked checks always ends at one that is not
377
+ suppressed, so the failure that caused it is reported.
378
+ """
379
+ failed: dict[str, Check] = {}
380
+ for check in checks:
381
+ name = check["check"]
382
+ if check["status"] == "failed" and name is not None:
383
+ failed.setdefault(name, check)
384
+ return [
385
+ check
386
+ for check in failed.values()
387
+ if not (check.get("blocked_by") is not None and check.get("blocked_by") in failed)
388
+ ]
389
+
390
+
391
+ # Rendering.
392
+
393
+
394
+ def _text(value: str | None) -> str:
395
+ """Collapse, cut and neutralize a value for Markdown outside a code block."""
396
+ text = " ".join((value or "").split())
397
+ if len(text) > MAX_REASON_LENGTH:
398
+ text = text[: MAX_REASON_LENGTH - 1] + "…"
399
+ return text.replace("@", "@" + _ZERO_WIDTH_SPACE)
400
+
401
+
402
+ def _cell(value: str | None) -> str:
403
+ return _text(value).replace("\\", "\\\\").replace("|", "\\|") or "—"
404
+
405
+
406
+ def _when(now: datetime) -> str:
407
+ return f"{now.astimezone(UTC):%Y-%m-%d %H:%M} UTC"
408
+
409
+
410
+ def issue_title(key: str) -> str:
411
+ """Return the title of the issue for a failed check."""
412
+ suffix = FORCED_TITLE_SUFFIX if key == FORCED_CHECK else ""
413
+ name = " ".join(key.split())
414
+ room = MAX_TITLE_LENGTH - len(ISSUE_TITLE_PREFIX) - len(suffix)
415
+ if len(name) > room:
416
+ name = name[: room - 1] + "…"
417
+ return f"{ISSUE_TITLE_PREFIX}{name}{suffix}"
418
+
419
+
420
+ _GUIDANCE = [
421
+ "",
422
+ "## What to do",
423
+ "",
424
+ "- Endpoint checks are named `<connector>.<parser>` and live in "
425
+ "`src/piloto_ai_cli/health.py`. A failure there means the endpoint stopped working "
426
+ "or the site changed so the parser no longer extracts data (an HTTP 200 error page "
427
+ "counts as a failure). Fix the connector or parser against the current site and add "
428
+ "a replay test with the new response. The responses the checks received are stored "
429
+ "in the payload stage; `request_log` rows of this run point to them.",
430
+ "- `orphan:` checks name a foreign key with rows whose parent is missing; find what "
431
+ "wrote them instead of deleting the rows.",
432
+ "- `database.run_log`, `storage.request_log` and `workflow.pc_health` are failures of "
433
+ "the database, the payload store or the command itself, not of the site.",
434
+ "- If the site was only down for a while (a 502 or a timeout), say so and close this "
435
+ "issue: there is nothing to change. If the check fails again after this issue is "
436
+ "closed, the workflow opens a new issue.",
437
+ "- Keep every request going through `write_request()`. Do not rank, score, compare or "
438
+ "convert prices.",
439
+ ]
440
+
441
+
442
+ def render_issue(
443
+ check: Check,
444
+ checks: Sequence[Check],
445
+ *,
446
+ run_url: str,
447
+ report_id: str,
448
+ now: datetime,
449
+ secrets: Iterable[str] = (),
450
+ ) -> tuple[str, str]:
451
+ """Return the title and Markdown body of the issue for one failed check."""
452
+ fragments = secret_fragments(secrets)
453
+ check = redact_checks([check], fragments)[0]
454
+ checks = redact_checks(checks, fragments)
455
+ key = check["check"] or ""
456
+ failed = sum(1 for item in checks if item["status"] == "failed")
457
+ lines = [
458
+ issue_marker(key),
459
+ report_marker(report_id),
460
+ f"The `{_text(key)}` check failed in [this workflow run]({run_url}) on {_when(now)}.",
461
+ "",
462
+ ]
463
+ if key == FORCED_CHECK:
464
+ lines += [
465
+ "> [!NOTE]",
466
+ "> This issue tests the workflow: a manual dispatch with `force_failure` added "
467
+ "this check, so nothing needs fixing. Close this issue once the workflow is "
468
+ "verified. Any real failed check in the same run has an issue of its own.",
469
+ "",
470
+ ]
471
+ lines += [
472
+ "| Check | Reason |",
473
+ "|---|---|",
474
+ f"| `{_cell(key)}` | {_cell(check['reason'])} |",
475
+ "",
476
+ ]
477
+
478
+ def summary(where: str) -> str:
479
+ return (
480
+ f"{failed} of {len(checks)} check(s) failed in this run. Each failed check has "
481
+ "its own issue; a check that could not run because another one failed is listed "
482
+ f"in {where}, not opened as an issue."
483
+ )
484
+
485
+ report = json.dumps({"checks": list(checks)}, ensure_ascii=False, indent=2)
486
+ details = [
487
+ "",
488
+ "## Report",
489
+ "",
490
+ "<details><summary>All checks (<code>pc --json health</code>)</summary>",
491
+ "",
492
+ "```json",
493
+ report,
494
+ "```",
495
+ "",
496
+ "</details>",
497
+ ]
498
+ body = "\n".join([*lines, summary("the report below"), *details, *_GUIDANCE]) + "\n"
499
+ if len(body) > MAX_BODY_LENGTH:
500
+ omitted = [
501
+ "",
502
+ "## Report",
503
+ "",
504
+ f"The full report is too long for an issue; it is in the run's "
505
+ f"`{REPORT_ARTIFACT}` artifact.",
506
+ ]
507
+ artifact = summary(f"the run's `{REPORT_ARTIFACT}` artifact")
508
+ body = "\n".join([*lines, artifact, *omitted, *_GUIDANCE]) + "\n"
509
+ return issue_title(key), redact(body, fragments)
510
+
511
+
512
+ def render_recurrence(
513
+ check: Check,
514
+ *,
515
+ run_url: str,
516
+ report_id: str,
517
+ now: datetime,
518
+ secrets: Iterable[str] = (),
519
+ ) -> str:
520
+ """Return the comment that records a failure on the open issue that tracks it."""
521
+ fragments = secret_fragments(secrets)
522
+ check = redact_checks([check], fragments)[0]
523
+ body = (
524
+ f"{report_marker(report_id)}\n"
525
+ f"The `{_text(check['check'])}` check failed again in [this workflow run]({run_url}) "
526
+ f"on {_when(now)}: {_text(check['reason']) or 'no reason given'}\n\n"
527
+ f"The run's `{REPORT_ARTIFACT}` artifact holds its full report.\n"
528
+ )
529
+ return redact(body, fragments)
530
+
531
+
532
+ # Planning.
533
+
534
+
535
+ @dataclass(frozen=True)
536
+ class IssueAction:
537
+ """What the workflow does on GitHub for one failed check."""
538
+
539
+ action: Literal["open", "recur", "assign"]
540
+ key: str
541
+ body: str
542
+ # Set for "recur" and "assign": the open issue that already tracks the check.
543
+ number: int | None = None
544
+ # Set for "open".
545
+ title: str | None = None
546
+ # Whether to assign Copilot: always on a new issue, on an open one only
547
+ # when nobody holds it.
548
+ assign: bool = True
549
+
550
+
551
+ def plan_issues(
552
+ checks: Sequence[Check],
553
+ open_issues: Iterable[OpenIssue],
554
+ *,
555
+ run_url: str,
556
+ report_id: str,
557
+ now: datetime,
558
+ recorded_keys: Iterable[str] = (),
559
+ secrets: Iterable[str] = (),
560
+ ) -> list[IssueAction]:
561
+ """Decide, for each failed check, whether to open an issue or record a recurrence.
562
+
563
+ A failed check whose key has an open issue the workflow opened is already
564
+ with its owner: the failure is recorded on that issue (the oldest, should
565
+ there be several), and Copilot is assigned only if nobody is. Any other
566
+ failed check gets a new issue assigned to Copilot.
567
+
568
+ Planning is idempotent per report: when any issue the workflow opened, open
569
+ or closed, already records this report for the check (``recorded_keys``, or
570
+ the open issue's own reports), as on a re-run of the issues job, nothing is
571
+ opened or commented. Only the Copilot assignment is planned again, when the
572
+ open issue that records the report has nobody assigned.
573
+ """
574
+ report_marker(report_id)
575
+ recorded = set(recorded_keys)
576
+ secrets = list(secrets)
577
+ tracked: dict[str, OpenIssue] = {}
578
+ for open_issue in sorted(open_issues, key=lambda item: item.number):
579
+ tracked.setdefault(open_issue.key, open_issue)
580
+ actions: list[IssueAction] = []
581
+ for check in issue_failures(checks):
582
+ key = check["check"] or ""
583
+ issue = tracked.get(key)
584
+ if key in recorded or (issue is not None and report_id in issue.reports):
585
+ if issue is not None and report_id in issue.reports and not issue.assigned:
586
+ actions.append(IssueAction("assign", key, "", number=issue.number))
587
+ continue
588
+ if issue is None:
589
+ title, body = render_issue(
590
+ check, checks, run_url=run_url, report_id=report_id, now=now, secrets=secrets
591
+ )
592
+ actions.append(IssueAction("open", key, body, title=title))
593
+ else:
594
+ body = render_recurrence(
595
+ check, run_url=run_url, report_id=report_id, now=now, secrets=secrets
596
+ )
597
+ actions.append(
598
+ IssueAction("recur", key, body, number=issue.number, assign=not issue.assigned)
599
+ )
600
+ return actions
601
+
602
+
603
+ def write_plan(actions: Sequence[IssueAction], output_dir: Path) -> Path:
604
+ """Write the bodies and ``plan.tsv`` for the workflow to carry out.
605
+
606
+ Each line of ``plan.tsv`` is ``action, issue number (or -), assign
607
+ (true/false), title file (or -), body file, check name``, tab-separated.
608
+ """
609
+ output_dir.mkdir(parents=True, exist_ok=True)
610
+ lines: list[str] = []
611
+ for index, action in enumerate(actions, start=1):
612
+ body_path = output_dir / f"{index:03d}-body.md"
613
+ body_path.write_text(action.body, encoding="utf-8")
614
+ title_file = "-"
615
+ if action.title is not None:
616
+ title_path = output_dir / f"{index:03d}-title.txt"
617
+ title_path.write_text(action.title + "\n", encoding="utf-8")
618
+ title_file = str(title_path)
619
+ number = "-" if action.number is None else str(action.number)
620
+ fields = [
621
+ action.action,
622
+ number,
623
+ "true" if action.assign else "false",
624
+ title_file,
625
+ str(body_path),
626
+ # Only for the workflow's log lines; the last field may hold spaces.
627
+ " ".join(action.key.split()),
628
+ ]
629
+ lines.append("\t".join(fields))
630
+ plan = output_dir / PLAN_FILE
631
+ plan.write_text("".join(line + "\n" for line in lines), encoding="utf-8")
632
+ return plan
633
+
634
+
635
+ # Spacing of the live checks.
636
+
637
+
638
+ def _paged_items(text: str, field: str, *, limit: int | None = None) -> list[dict[str, Any]]:
639
+ """Return the ``field`` items of every page of a paginated GitHub list.
640
+
641
+ A list whose ``total_count`` is over ``limit`` was cut short by GitHub.
642
+ """
643
+ items: list[dict[str, Any]] = []
644
+ for page in _json_values(text):
645
+ if not isinstance(page, dict) or not isinstance(page.get(field), list):
646
+ raise ValueError(f"a page of the list has no {field} list")
647
+ total = page.get("total_count")
648
+ if not isinstance(total, int) or isinstance(total, bool):
649
+ raise ValueError("a page of the list has no total_count")
650
+ if limit is not None and total > limit:
651
+ raise ValueError(f"the list holds {total} items and GitHub returns only part of it")
652
+ for item in page[field]:
653
+ if not isinstance(item, dict):
654
+ raise ValueError(f"the {field} list holds a value that is not an object")
655
+ items.append(item)
656
+ return items
657
+
658
+
659
+ def _int(item: dict[str, Any], field: str) -> int:
660
+ value = item.get(field)
661
+ if not isinstance(value, int) or isinstance(value, bool):
662
+ raise ValueError(f"{field} is not a number")
663
+ return value
664
+
665
+
666
+ def _str(item: dict[str, Any], field: str) -> str:
667
+ value = item.get(field)
668
+ if not isinstance(value, str):
669
+ raise ValueError(f"{field} is not text")
670
+ return value
671
+
672
+
673
+ def _time(value: object, field: str) -> datetime:
674
+ if not isinstance(value, str):
675
+ raise ValueError(f"{field} is not a time")
676
+ try:
677
+ moment = datetime.fromisoformat(value)
678
+ except ValueError:
679
+ raise ValueError(f"{field} is not a time: {value!r}") from None
680
+ if moment.tzinfo is None:
681
+ raise ValueError(f"{field} has no time zone: {value!r}")
682
+ return moment.astimezone(UTC)
683
+
684
+
685
+ @dataclass(frozen=True)
686
+ class WorkflowRun:
687
+ """A run of the health workflow, as the runs list gives it."""
688
+
689
+ id: int
690
+ status: str
691
+ updated_at: datetime
692
+ url: str
693
+
694
+
695
+ def load_workflow_runs(text: str) -> list[WorkflowRun]:
696
+ """Read ``gh api --paginate`` output of the workflow's runs list.
697
+
698
+ Malformed output, or a list GitHub cut short, raises ``ValueError``: the
699
+ live checks never run when the earlier runs cannot be read.
700
+ """
701
+ runs: list[WorkflowRun] = []
702
+ for item in _paged_items(text, "workflow_runs", limit=MAX_LISTED_RUNS):
703
+ runs.append(
704
+ WorkflowRun(
705
+ id=_int(item, "id"),
706
+ status=_str(item, "status"),
707
+ updated_at=_time(item.get("updated_at"), "updated_at"),
708
+ url=_str(item, "html_url"),
709
+ )
710
+ )
711
+ return runs
712
+
713
+
714
+ def runs_to_inspect(
715
+ runs: Sequence[WorkflowRun], *, current_run_id: int, now: datetime
716
+ ) -> list[WorkflowRun]:
717
+ """Return the runs whose jobs may hold live checks started in the last 3 hours.
718
+
719
+ A completed run last updated more than 3 hours ago started every step
720
+ before then. Every other run is inspected, including the current one (an
721
+ earlier attempt of it may have run the live checks). The list must hold the
722
+ current run, or it is not this workflow's list.
723
+ """
724
+ if not any(run.id == current_run_id for run in runs):
725
+ raise ValueError(f"the runs list does not hold this run ({current_run_id})")
726
+ since = now - LIVE_SPACING
727
+ selected = {
728
+ run.id: run
729
+ for run in runs
730
+ if run.id == current_run_id or run.status != "completed" or run.updated_at >= since
731
+ }
732
+ return [selected[run_id] for run_id in sorted(selected)]
733
+
734
+
735
+ @dataclass(frozen=True)
736
+ class LiveStart:
737
+ """When an attempt of a run started (or may start) its live checks."""
738
+
739
+ run_id: int
740
+ attempt: int
741
+ started_at: datetime
742
+ url: str
743
+
744
+
745
+ def _live_start(job: dict[str, Any], now: datetime) -> datetime | None:
746
+ """Return when the job's live step started, or ``None`` if it never ran.
747
+
748
+ It is conservative: a live step that ran, was cancelled while running, or
749
+ may still start counts; only a skipped step or a job that never started
750
+ does not.
751
+ """
752
+ status = _str(job, "status")
753
+ if job.get("conclusion") == "skipped":
754
+ return None
755
+ steps = job.get("steps") or []
756
+ if not isinstance(steps, list) or not all(isinstance(step, dict) for step in steps):
757
+ raise ValueError("the steps of a job are not a list of steps")
758
+ live = [step for step in steps if step.get("name") == LIVE_STEP]
759
+ if len(live) > 1:
760
+ raise ValueError(f"a job has more than one {LIVE_STEP!r} step")
761
+ if live:
762
+ step = live[0]
763
+ step_status = _str(step, "status")
764
+ step_conclusion = step.get("conclusion")
765
+ if step_conclusion == "skipped":
766
+ return None
767
+ started = step.get("started_at")
768
+ if started is not None:
769
+ return _time(started, "started_at")
770
+ if step_status == "completed" and step_conclusion == "cancelled":
771
+ return None
772
+ if step_status not in _NOT_STARTED_JOB:
773
+ raise ValueError(f"the {LIVE_STEP!r} step is {step_status} without a start time")
774
+ if status == "completed" or status in _NOT_STARTED_JOB:
775
+ # GitHub lists every step a job ran: a finished job without a started
776
+ # live step never ran it, and a job that has not started has run nothing.
777
+ return None
778
+ if status == "in_progress":
779
+ # The live step has not started yet but may start at any moment.
780
+ return now
781
+ raise ValueError(f"a job has the unknown status {status!r}")
782
+
783
+
784
+ def load_live_starts(
785
+ text: str,
786
+ run: WorkflowRun,
787
+ *,
788
+ current_run_id: int,
789
+ current_attempt: int,
790
+ now: datetime,
791
+ ) -> list[LiveStart]:
792
+ """Read ``gh api --paginate`` output of a run's jobs (``filter=all``).
793
+
794
+ Returns when each attempt of the run started its live checks. The current
795
+ attempt of the current run is left out; its earlier attempts count.
796
+ Malformed output raises ``ValueError``.
797
+ """
798
+ starts: list[LiveStart] = []
799
+ for job in _paged_items(text, "jobs"):
800
+ if _int(job, "run_id") != run.id:
801
+ raise ValueError(f"a job of run {run.id} belongs to another run")
802
+ attempt = _int(job, "run_attempt")
803
+ if run.id == current_run_id and attempt == current_attempt:
804
+ continue
805
+ started_at = _live_start(job, now)
806
+ if started_at is not None:
807
+ starts.append(LiveStart(run.id, attempt, started_at, run.url))
808
+ return starts
809
+
810
+
811
+ def blocking_start(starts: Iterable[LiveStart], now: datetime) -> LiveStart | None:
812
+ """Return the latest live start less than 3 hours before ``now``, if any."""
813
+ recent = [start for start in starts if now - start.started_at < LIVE_SPACING]
814
+ return max(recent, key=lambda start: start.started_at, default=None)
815
+
816
+
817
+ def _utc(moment: datetime) -> str:
818
+ return moment.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S UTC")
819
+
820
+
821
+ def spacing_error(start: LiveStart) -> str:
822
+ """Explain why the live checks may not run yet and when they may."""
823
+ return (
824
+ "Live checks must not run more often than every 3 hours: run "
825
+ f"{start.run_id} (attempt {start.attempt}) started them at "
826
+ f"{_utc(start.started_at)} ({start.url}). The next run is allowed from "
827
+ f"{_utc(start.started_at + LIVE_SPACING)}. No live request was made."
828
+ )
829
+
830
+
831
+ # Command line.
832
+
833
+
834
+ def _parse_arguments(argv: Sequence[str]) -> argparse.Namespace:
835
+ parser = argparse.ArgumentParser(prog="python -m piloto_ai_cli.health_workflow")
836
+ commands = parser.add_subparsers(dest="command", required=True)
837
+
838
+ report = commands.add_parser("report", help="redact the report and say whether it failed")
839
+ report.add_argument("--report", type=Path, required=True, help="pc --json health output")
840
+ report.add_argument("--exit-code", type=int, required=True, help="pc health exit code")
841
+ report.add_argument("--forced", choices=("true", "false"), default="false")
842
+ report.add_argument(
843
+ "--install-failed",
844
+ choices=("true", "false"),
845
+ default="false",
846
+ help="the CLI could not be installed, so pc health did not run",
847
+ )
848
+ report.add_argument("--output-dir", type=Path, required=True, help="directory for report.json")
849
+
850
+ recent = commands.add_parser(
851
+ "recent-runs", help="print the ids of the runs whose jobs check-spacing reads"
852
+ )
853
+ check = commands.add_parser(
854
+ "check-spacing", help="fail if live checks started less than 3 hours ago"
855
+ )
856
+ for command in (recent, check):
857
+ command.add_argument(
858
+ "--runs",
859
+ type=Path,
860
+ required=True,
861
+ help="gh api --paginate output of this workflow's runs",
862
+ )
863
+ command.add_argument("--run-id", type=int, required=True, help="this run's id")
864
+ check.add_argument("--run-attempt", type=int, required=True, help="this run's attempt")
865
+ check.add_argument(
866
+ "--jobs-dir",
867
+ type=Path,
868
+ required=True,
869
+ help="directory of <run id>.json files, gh api --paginate output of each run's jobs",
870
+ )
871
+
872
+ plan = commands.add_parser("plan", help="plan the issues for the failed checks")
873
+ plan.add_argument("--report", type=Path, required=True, help="report.json from report")
874
+ plan.add_argument(
875
+ "--open-issues",
876
+ type=Path,
877
+ required=True,
878
+ help="gh api --paginate output of the repository's open issues",
879
+ )
880
+ plan.add_argument("--run-url", required=True, help="URL of the workflow run")
881
+ plan.add_argument(
882
+ "--report-id",
883
+ required=True,
884
+ help="<run id>.<run attempt> of the health job that produced the report",
885
+ )
886
+ plan.add_argument(
887
+ "--comments-dir",
888
+ type=Path,
889
+ required=True,
890
+ help="directory of <issue number>.json files, gh api --paginate output of the "
891
+ "comments of each issue tracked-issues printed",
892
+ )
893
+
894
+ plan.add_argument(
895
+ "--recent-issues",
896
+ type=Path,
897
+ required=True,
898
+ help="gh api --paginate output of the repository's issues in any state updated "
899
+ "since the report time",
900
+ )
901
+ plan.add_argument(
902
+ "--report-time",
903
+ required=True,
904
+ help="when the health job produced the report, ISO 8601 UTC (2026-11-20T10:23:00Z)",
905
+ )
906
+
907
+ tracked = commands.add_parser(
908
+ "tracked-issues",
909
+ help="print the numbers of the issues the workflow opened, in any state, whose "
910
+ "comments plan reads",
911
+ )
912
+ tracked.add_argument(
913
+ "--issues",
914
+ type=Path,
915
+ required=True,
916
+ help="gh api --paginate output of the repository's issues updated since the report time",
917
+ )
918
+ plan.add_argument(
919
+ "--output-dir", type=Path, required=True, help="directory for plan.tsv and the bodies"
920
+ )
921
+ return parser.parse_args(argv)
922
+
923
+
924
+ def _secrets() -> list[str]:
925
+ return [os.environ.get(name, "") for name in SECRET_VARIABLES]
926
+
927
+
928
+ def _report(arguments: argparse.Namespace) -> None:
929
+ try:
930
+ # A report cut mid-write (pc health stopped by its timeout) may end in a
931
+ # partial UTF-8 sequence: read it anyway, so it is reported as malformed.
932
+ report_text = arguments.report.read_text(encoding="utf-8", errors="replace")
933
+ except OSError:
934
+ report_text = ""
935
+ if arguments.install_failed == "true":
936
+ checks = [install_failure()]
937
+ else:
938
+ checks = load_checks(report_text, arguments.exit_code)
939
+ if arguments.forced == "true":
940
+ checks = force_failure(checks)
941
+ fragments = secret_fragments(_secrets())
942
+ output_dir: Path = arguments.output_dir
943
+ output_dir.mkdir(parents=True, exist_ok=True)
944
+ report = json.dumps({"checks": redact_checks(checks, fragments)}, ensure_ascii=False, indent=2)
945
+ (output_dir / "report.json").write_text(redact(report, fragments) + "\n", encoding="utf-8")
946
+ print(f"failed={'true' if has_failure(checks) else 'false'}")
947
+
948
+
949
+ def _plan(arguments: argparse.Namespace) -> None:
950
+ checks = _parse_checks(arguments.report.read_text(encoding="utf-8"))
951
+ if checks is None:
952
+ raise SystemExit(f"{arguments.report} is not a valid health report")
953
+ report_time = _report_time(arguments.report_time)
954
+ # Every issue the workflow opened and that changed since the report, open or
955
+ # closed, with the reports its body and the workflow's comments record.
956
+ recent = with_comment_reports(
957
+ load_workflow_issues(arguments.recent_issues.read_text(encoding="utf-8")),
958
+ arguments.comments_dir,
959
+ )
960
+ reports = {issue.number: issue.reports for issue in recent}
961
+ open_issues = [
962
+ replace(issue, reports=issue.reports | reports.get(issue.number, frozenset()))
963
+ for issue in load_open_issues(arguments.open_issues.read_text(encoding="utf-8"))
964
+ ]
965
+ actions = plan_issues(
966
+ checks,
967
+ open_issues,
968
+ run_url=arguments.run_url,
969
+ report_id=arguments.report_id,
970
+ now=report_time,
971
+ recorded_keys={issue.key for issue in recent if arguments.report_id in issue.reports},
972
+ secrets=_secrets(),
973
+ )
974
+ write_plan(actions, arguments.output_dir)
975
+ for action in actions:
976
+ target = "a new issue" if action.number is None else f"issue #{action.number}"
977
+ print(f"{action.key}: {action.action} ({target})")
978
+
979
+
980
+ def _report_time(value: str) -> datetime:
981
+ """Parse the report time (ISO 8601, UTC); anything else stops the plan."""
982
+ try:
983
+ moment = datetime.fromisoformat(value)
984
+ except ValueError:
985
+ raise SystemExit(f"report time {value!r} is not an ISO 8601 time") from None
986
+ if moment.utcoffset() != timedelta(0):
987
+ raise SystemExit(f"report time {value!r} is not in UTC")
988
+ return moment
989
+
990
+
991
+ def _tracked_issues(arguments: argparse.Namespace) -> None:
992
+ for issue in load_workflow_issues(arguments.issues.read_text(encoding="utf-8")):
993
+ print(issue.number)
994
+
995
+
996
+ def _runs_to_inspect(arguments: argparse.Namespace, now: datetime) -> list[WorkflowRun]:
997
+ runs = load_workflow_runs(arguments.runs.read_text(encoding="utf-8"))
998
+ return runs_to_inspect(runs, current_run_id=arguments.run_id, now=now)
999
+
1000
+
1001
+ def _recent_runs(arguments: argparse.Namespace) -> None:
1002
+ for run in _runs_to_inspect(arguments, datetime.now(UTC)):
1003
+ print(run.id)
1004
+
1005
+
1006
+ def _check_spacing(arguments: argparse.Namespace) -> None:
1007
+ # Called after recent-runs: time only moves on, so it inspects the same
1008
+ # runs or fewer, and each has its jobs file.
1009
+ now = datetime.now(UTC)
1010
+ starts: list[LiveStart] = []
1011
+ for run in _runs_to_inspect(arguments, now):
1012
+ jobs = (arguments.jobs_dir / f"{run.id}.json").read_text(encoding="utf-8")
1013
+ starts.extend(
1014
+ load_live_starts(
1015
+ jobs,
1016
+ run,
1017
+ current_run_id=arguments.run_id,
1018
+ current_attempt=arguments.run_attempt,
1019
+ now=now,
1020
+ )
1021
+ )
1022
+ start = blocking_start(starts, now)
1023
+ if start is not None:
1024
+ print(f"::error::{spacing_error(start)}", file=sys.stderr)
1025
+ raise SystemExit(1)
1026
+ print("No run of this workflow started live checks in the last 3 hours.")
1027
+
1028
+
1029
+ def _spacing_command(
1030
+ command: Callable[[argparse.Namespace], None], arguments: argparse.Namespace
1031
+ ) -> None:
1032
+ # Fail closed: when the earlier runs cannot be read, the live checks do not run.
1033
+ try:
1034
+ command(arguments)
1035
+ except (OSError, ValueError) as error:
1036
+ print(
1037
+ "::error::Could not verify that no live checks ran in the last 3 hours, "
1038
+ f"so none were run: {error}",
1039
+ file=sys.stderr,
1040
+ )
1041
+ raise SystemExit(1) from None
1042
+
1043
+
1044
+ def main(argv: Sequence[str] | None = None) -> None:
1045
+ """Run one step of the health workflow."""
1046
+ arguments = _parse_arguments(sys.argv[1:] if argv is None else argv)
1047
+ if arguments.command == "recent-runs":
1048
+ _spacing_command(_recent_runs, arguments)
1049
+ elif arguments.command == "check-spacing":
1050
+ _spacing_command(_check_spacing, arguments)
1051
+ elif arguments.command == "report":
1052
+ _report(arguments)
1053
+ elif arguments.command == "tracked-issues":
1054
+ _tracked_issues(arguments)
1055
+ else:
1056
+ _plan(arguments)
1057
+
1058
+
1059
+ if __name__ == "__main__":
1060
+ main()