-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcrane_scheduler.py
More file actions
976 lines (859 loc) · 36.8 KB
/
Copy pathcrane_scheduler.py
File metadata and controls
976 lines (859 loc) · 36.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
#!/usr/bin/env python3
"""Crane scheduler.
Decides which Crane migration (if any) is due for an iteration. Reads
migration definitions from ``.crane/migrations/`` (directory- and bare-
markdown-based) and from open GitHub issues labelled ``crane-migration``,
combines them with persisted per-migration scheduling state from the
``memory/crane`` repo-memory branch, and writes the selection to
``/tmp/gh-aw/crane.json`` for the agent step to consume.
Side effects:
* May bootstrap ``.crane/migrations/example.md`` on first run.
* May materialise issue-based migration bodies under
``/tmp/gh-aw/issue-migrations/``.
* Always writes ``/tmp/gh-aw/crane.json``.
Exit codes:
0 - a migration was selected, or there are unconfigured migrations to
report on (the agent step should run).
1 - nothing to do this run (no due migrations, no unconfigured
migrations); the workflow should skip the agent step.
Environment variables:
GITHUB_TOKEN - token used to query the issues API.
GITHUB_REPOSITORY - ``owner/repo`` slug.
CRANE_MIGRATION - optional migration name to force (bypasses
scheduling, but unconfigured migrations are still
rejected).
This file is the standalone counterpart of the scheduler used by
``workflows/crane.md``. Extracting it keeps the compiled ``run:`` step
small and makes the logic unit-testable.
"""
from __future__ import annotations
import glob
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
MIGRATIONS_DIR = ".crane/migrations"
TEMPLATE_FILE = os.path.join(MIGRATIONS_DIR, "example.md")
# Repo-memory files are cloned to /tmp/gh-aw/repo-memory/{id}/ where {id}
# is derived from the branch-name configured in the tools section
# (memory/crane -> crane).
REPO_MEMORY_DIR = "/tmp/gh-aw/repo-memory/crane"
ISSUE_MIGRATIONS_DIR = "/tmp/gh-aw/issue-migrations"
OUTPUT_DIR = "/tmp/gh-aw"
OUTPUT_FILE = os.path.join(OUTPUT_DIR, "crane.json")
# Default repo-memory ``max-file-size`` for state files. Mirrors the value
# configured under ``tools.repo-memory.max-file-size`` in
# ``workflows/crane.md``. Surfaced so the agent prompt can reason about the
# rolling-compaction budget without re-parsing workflow frontmatter.
STATE_FILE_MAX_BYTES = 40960
# ---------------------------------------------------------------------------
# Pure helpers (unit-tested directly)
# ---------------------------------------------------------------------------
def parse_machine_state(content):
"""Parse the [*] Machine State table from a state file. Returns a dict."""
state = {}
m = re.search(
r"##\s+(?:\[\*\]|\*)\s+Machine State.*?\n(.*?)(?=\n## |\Z)",
content,
re.DOTALL,
)
if not m:
return state
section = m.group(0)
for row in re.finditer(r"\|\s*(.+?)\s*\|\s*(.+?)\s*\|", section):
raw_key = row.group(1).strip()
raw_val = row.group(2).strip()
if raw_key.lower() == "field" or re.fullmatch(r":?-+:?", raw_key):
continue
key = raw_key.lower().replace(" ", "_")
val = None if raw_val in ("--", "-", "") else raw_val
state[key] = val
# Coerce types
for int_field in ("iteration_count", "consecutive_errors"):
if int_field in state:
try:
state[int_field] = int(state[int_field])
except (ValueError, TypeError):
state[int_field] = 0
if "paused" in state:
state["paused"] = str(state.get("paused", "")).lower() == "true"
if "completed" in state:
state["completed"] = str(state.get("completed", "")).lower() == "true"
# recent_statuses: stored as comma-separated words (e.g. "accepted, rejected, error")
rs_raw = state.get("recent_statuses") or ""
if rs_raw:
state["recent_statuses"] = [s.strip().lower() for s in rs_raw.split(",") if s.strip()]
else:
state["recent_statuses"] = []
return state
def parse_schedule(s):
"""Schedule string to a ``timedelta``; returns ``None`` for invalid input."""
s = s.strip().lower()
m = re.match(r"every\s+(\d+)\s*h", s)
if m:
return timedelta(hours=int(m.group(1)))
m = re.match(r"every\s+(\d+)\s*m", s)
if m:
return timedelta(minutes=int(m.group(1)))
if s == "daily":
return timedelta(hours=24)
if s == "weekly":
return timedelta(days=7)
return None
def get_migration_name(pf):
"""Extract migration name from a migration file path.
Directory-based: ``.crane/migrations/<name>/migration.md`` -> ``<name>``
Bare markdown: ``.crane/migrations/<name>.md`` -> ``<name>``
Issue-based: ``/tmp/gh-aw/issue-migrations/<name>.md`` -> ``<name>``
"""
if pf.endswith("/migration.md"):
return os.path.basename(os.path.dirname(pf))
return os.path.splitext(os.path.basename(pf))[0]
def slugify_issue_title(title, number=None):
"""Slugify a GitHub issue title into a migration name."""
slug = re.sub(r"[^a-z0-9]+", "-", (title or "").lower()).strip("-")
slug = re.sub(r"-+", "-", slug) # collapse consecutive hyphens
if not slug:
slug = "issue-{}".format(number) if number is not None else "issue"
return slug
def parse_link_header(header):
"""Parse the GitHub API ``Link`` header and return the ``rel="next"`` URL."""
if not header:
return None
for part in header.split(","):
section = part.strip()
m = re.match(r'^<([^>]+)>;\s*rel="next"$', section)
if m:
return m.group(1)
return None
def parse_migration_frontmatter(content):
"""Parse YAML frontmatter for ``schedule``, ``target-metric``, ``metric_direction``, and ``strategy``.
Returns a dict with these keys (any may be ``None``):
schedule_delta - timedelta or None
target_metric - float or None
target_metric_invalid - raw string (if value was invalid)
metric_direction - "higher" or "lower" (default "higher")
metric_direction_invalid - raw string (if value was invalid)
strategy - "in-place", "greenfield", or "auto" (default "auto")
strategy_invalid - raw string (if value was invalid)
"""
# Strip leading HTML comments before checking (issue-based migrations may have them).
content_stripped = re.sub(r"^(\s*<!--.*?-->\s*\n)*", "", content, flags=re.DOTALL)
result = {
"schedule_delta": None,
"target_metric": None,
"target_metric_invalid": None,
"metric_direction": "higher",
"metric_direction_invalid": None,
"strategy": "auto",
"strategy_invalid": None,
}
fm_match = re.match(r"^---\s*\n(.*?)\n---\s*\n", content_stripped, re.DOTALL)
if not fm_match:
return result
for line in fm_match.group(1).split("\n"):
stripped = line.strip()
if stripped.startswith("schedule:"):
schedule_str = line.split(":", 1)[1].strip()
result["schedule_delta"] = parse_schedule(schedule_str)
if stripped.startswith("target-metric:"):
raw = line.split(":", 1)[1].strip()
try:
result["target_metric"] = float(raw)
except (ValueError, TypeError):
result["target_metric_invalid"] = raw
if stripped.startswith("metric_direction:") or stripped.startswith("metric-direction:"):
raw = line.split(":", 1)[1].strip().strip('"').strip("'").lower()
if raw in ("higher", "lower"):
result["metric_direction"] = raw
else:
result["metric_direction_invalid"] = raw
if stripped.startswith("strategy:"):
raw = line.split(":", 1)[1].strip().strip('"').strip("'").lower()
if raw in ("in-place", "greenfield", "auto"):
result["strategy"] = raw
else:
result["strategy_invalid"] = raw
return result
def is_unconfigured(content):
"""Return True if a migration file still contains the unconfigured sentinel
or any TODO/REPLACE placeholder."""
if "<!-- CRANE:UNCONFIGURED -->" in content:
return True
if re.search(r"\bTODO\b|\bREPLACE", content):
return True
return False
def is_completed_state(state):
"""Return True when repo-memory says the migration is completed."""
return str(state.get("completed", "")).lower() == "true" or state.get("completed") is True
def check_skip_conditions(state, issue_active=False):
"""Return ``(should_skip, reason)`` based on the migration state."""
if is_completed_state(state) and not issue_active:
return True, "completed: target metric reached"
if state.get("paused"):
return True, "paused: {}".format(state.get("pause_reason", "unknown"))
recent = state.get("recent_statuses", [])[-5:]
if len(recent) >= 5 and all(s == "rejected" for s in recent):
return True, "plateau: 5 consecutive rejections"
return False, None
def evaluate_completed_label_recovery(
name,
state,
issue_active,
issue_completed_label,
repo,
github_token,
find_pr=None,
check_gate=None,
):
"""Return stale-completion recovery state for issue-based migrations.
Completed-label issues are only trustworthy when Crane can positively
confirm the current PR-head gate. A missing PR, pending checks, failing
checks, or unavailable gate evidence means the completed state is stale and
the migration should be selected again.
"""
if find_pr is None:
find_pr = find_existing_pr_for_branch
if check_gate is None:
check_gate = get_pr_head_check_gate
has_stale_completed_state = issue_active and is_completed_state(state)
recovered_completed_issue = False
recovery_event = None
if issue_completed_label and is_completed_state(state) and not issue_active:
existing_pr_for_recovery = find_pr(repo, name, github_token)
if existing_pr_for_recovery:
gate_passed, gate_reason = check_gate(
repo, existing_pr_for_recovery, github_token
)
if gate_passed is True:
recovery_event = (
"confirmed",
existing_pr_for_recovery,
gate_reason,
)
else:
has_stale_completed_state = True
recovered_completed_issue = True
recovery_event = (
"stale_gate",
existing_pr_for_recovery,
gate_reason or "gate-unavailable",
)
else:
has_stale_completed_state = True
recovered_completed_issue = True
recovery_event = ("stale_no_pr", None, "no-open-migration-pr")
return has_stale_completed_state, recovered_completed_issue, recovery_event
# ---------------------------------------------------------------------------
# I/O helpers
# ---------------------------------------------------------------------------
def read_migration_state(migration_name, repo_memory_dir=REPO_MEMORY_DIR):
"""Read scheduling state from the repo-memory state file (or ``{}``)."""
state_file = os.path.join(repo_memory_dir, "{}.md".format(migration_name))
if not os.path.isfile(state_file):
print(" {}: no state file found (first run)".format(migration_name))
return {}
with open(state_file, encoding="utf-8") as f:
content = f.read()
return parse_machine_state(content)
def get_state_file_size(migration_name, repo_memory_dir=REPO_MEMORY_DIR):
"""Return the size of the migration's state file in bytes (0 if missing)."""
state_file = os.path.join(repo_memory_dir, "{}.md".format(migration_name))
try:
st = os.stat(state_file)
except OSError:
return 0
return st.st_size
def _bootstrap_template_if_missing():
"""Create ``.crane/migrations/example.md`` if the directory is missing."""
if os.path.isdir(MIGRATIONS_DIR):
return
os.makedirs(MIGRATIONS_DIR, exist_ok=True)
bt = chr(96) # backtick -- keep gh-aw compiler happy if this ever gets inlined
template = "\n".join([
"<!-- CRANE:UNCONFIGURED -->",
"<!-- Remove the line above once you have filled in your migration. -->",
"<!-- Crane will NOT run until you do. -->",
"",
"---",
"schedule: every 6h",
"strategy: auto",
"source-language: REPLACE",
"target-languages: [REPLACE]",
"target-metric: 1.0",
"metric_direction: higher",
"---",
"",
"# Crane Migration",
"",
"<!-- Rename this file to something meaningful (e.g. stats_py_to_ts.md, cjs_to_esm.md).",
" The filename (minus .md) becomes the migration name used in issues, PRs,",
" and slash commands. Want multiple migrations? Add more .md files here. -->",
"",
"## Source",
"",
"- **Language**: REPLACE",
"- **Runtime**: REPLACE",
"- **Paths**:",
" - {bt}REPLACE/path{bt} -- (what lives here)".format(bt=bt),
"",
"## Target",
"",
"- **Languages**: REPLACE",
"- **Runtime**: REPLACE",
"- **Paths**:",
" - {bt}REPLACE/path{bt} -- (what should live here)".format(bt=bt),
"",
"## Strategy",
"",
"REPLACE -- explain choice (or leave as `auto` in frontmatter and let Crane decide).",
"",
"## Verification",
"",
"<!-- A command that prints JSON containing `migration_score` (0.0-1.0). -->",
"",
"{bt}{bt}{bt}bash".format(bt=bt),
"REPLACE_WITH_YOUR_VERIFICATION_COMMAND",
"{bt}{bt}{bt}".format(bt=bt),
"",
"The metric is {bt}migration_score{bt}. **Higher is better.**".format(bt=bt),
"",
])
with open(TEMPLATE_FILE, "w") as f:
f.write(template)
# Leave the template unstaged -- the agent will create a draft PR with it
print("BOOTSTRAPPED: created {} locally (agent will create a draft PR)".format(TEMPLATE_FILE))
def _scan_directory_migrations():
"""Return paths of directory-based migrations under ``MIGRATIONS_DIR``."""
out = []
if not os.path.isdir(MIGRATIONS_DIR):
return out
for entry in sorted(os.listdir(MIGRATIONS_DIR)):
mig_dir = os.path.join(MIGRATIONS_DIR, entry)
if os.path.isdir(mig_dir):
mig_file = os.path.join(mig_dir, "migration.md")
if os.path.isfile(mig_file):
out.append(mig_file)
return out
def _scan_bare_migrations():
"""Return paths of bare-markdown migrations under ``MIGRATIONS_DIR``."""
return sorted(glob.glob(os.path.join(MIGRATIONS_DIR, "*.md")))
def _issue_has_label(issue, label):
"""Return True if a GitHub issue payload contains ``label``."""
for raw_label in issue.get("labels") or []:
if isinstance(raw_label, dict):
name = raw_label.get("name")
else:
name = raw_label
if name == label:
return True
return False
def _fetch_open_issues_with_label(repo, github_token, label):
"""Fetch open issues with one label. Returns issue payloads."""
next_url = (
"https://api.github.com/repos/{}/issues"
"?labels={}&state=open&per_page=100".format(repo, urllib.parse.quote(label, safe=""))
)
headers = {
"Authorization": "token {}".format(github_token),
"Accept": "application/vnd.github.v3+json",
}
issues = []
while next_url:
req = urllib.request.Request(next_url, headers=headers)
with urllib.request.urlopen(req, timeout=30) as resp:
page = json.loads(resp.read().decode())
link_header = resp.headers.get("link") or resp.headers.get("Link")
issues.extend(page)
next_url = parse_link_header(link_header)
return issues
def _fetch_issue_migrations(repo, github_token):
"""Fetch open Crane-labelled issues and write their bodies to
``ISSUE_MIGRATIONS_DIR``. Returns ``(migration_files, issue_migrations)``.
Crane primarily runs issues with ``crane-migration``. It also reads open
``crane-completed`` issues so a stale completion can be recovered when the
deterministic PR-head gate did not pass.
Errors are swallowed (with a warning) so a transient API failure doesn't
block the run for non-issue-based migrations.
"""
migration_files = []
issue_migrations = {}
os.makedirs(ISSUE_MIGRATIONS_DIR, exist_ok=True)
try:
issues_by_number = {}
for label in ("crane-migration", "crane-completed"):
for issue in _fetch_open_issues_with_label(repo, github_token, label):
issues_by_number[issue.get("number")] = issue
for issue in issues_by_number.values():
if issue.get("pull_request"):
continue # skip PRs
body = issue.get("body") or ""
title = issue.get("title") or ""
number = issue["number"]
slug = slugify_issue_title(title, number)
if slug in issue_migrations:
print(
" Warning: slug '{}' (issue #{}) collides with issue #{}, "
"appending issue number".format(
slug, number, issue_migrations[slug]["issue_number"]
)
)
slug = "{}-{}".format(slug, number)
issue_file = os.path.join(ISSUE_MIGRATIONS_DIR, "{}.md".format(slug))
with open(issue_file, "w") as f:
f.write(body)
migration_files.append(issue_file)
active = _issue_has_label(issue, "crane-migration")
completed_label = _issue_has_label(issue, "crane-completed")
issue_migrations[slug] = {
"issue_number": number,
"file": issue_file,
"title": title,
"active": active,
"completed_label": completed_label,
}
label_status = "active" if active else "completed-label"
print(
" Found issue-based migration: '{}' (issue #{}, {})".format(
slug, number, label_status
)
)
except Exception as e: # noqa: BLE001 -- best-effort; logged below
print(" Warning: could not fetch issue-based migrations: {}".format(e))
return migration_files, issue_migrations
def _parse_target_metric_from_file(path):
"""Re-parse a migration file to extract its ``target-metric``, if any."""
try:
with open(path) as f:
return parse_migration_frontmatter(f.read()).get("target_metric")
except (OSError, ValueError, TypeError):
return None
def _parse_metric_direction_from_file(path):
"""Re-parse a migration file to extract its ``metric_direction``."""
try:
with open(path) as f:
return parse_migration_frontmatter(f.read()).get("metric_direction") or "higher"
except (OSError, ValueError, TypeError):
return "higher"
def _parse_strategy_from_file(path):
"""Re-parse a migration file to extract its ``strategy``."""
try:
with open(path) as f:
return parse_migration_frontmatter(f.read()).get("strategy") or "auto"
except (OSError, ValueError, TypeError):
return "auto"
# ---------------------------------------------------------------------------
# Existing PR lookup (single-PR-per-migration invariant)
# ---------------------------------------------------------------------------
def _http_get_json(url, headers, timeout=30):
"""Open ``url`` and return ``(parsed_body, link_header)``.
Returns ``(None, None)`` on any HTTP/network error so callers can fall
through to the next strategy.
"""
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=timeout) as resp:
body = json.loads(resp.read().decode())
link_header = resp.headers.get("link") or resp.headers.get("Link")
return body, link_header
except (urllib.error.URLError, urllib.error.HTTPError, ValueError, OSError):
return None, None
def find_existing_pr_for_branch(repo, migration_name, github_token, http_get_json=_http_get_json):
"""Look up the open draft PR (if any) for ``crane/{migration_name}``."""
if not repo or not migration_name or not github_token:
return None
owner = repo.split("/", 1)[0]
canonical_branch = "crane/{}".format(migration_name)
headers = {
"Authorization": "token {}".format(github_token),
"Accept": "application/vnd.github.v3+json",
}
# Strategy 1: exact canonical branch name via the head= filter.
head_q = urllib.parse.quote("{}:{}".format(owner, canonical_branch), safe="")
url = "https://api.github.com/repos/{}/pulls?head={}&state=open".format(repo, head_q)
body, _ = http_get_json(url, headers)
if isinstance(body, list) and body:
first = body[0]
if isinstance(first, dict) and first.get("number"):
return first["number"]
# Strategy 2: paginate open PRs and match either a legacy framework-suffixed
# branch (``crane/{name}-<6-40 hex>``) or a ``[Crane: {name}]`` title prefix.
suffix_regex = re.compile(
r"^crane/" + re.escape(migration_name) + r"(-[0-9a-f]{6,40})?$"
)
title_prefix = "[Crane: {}]".format(migration_name)
next_url = "https://api.github.com/repos/{}/pulls?state=open&per_page=100".format(repo)
while next_url:
body, link_header = http_get_json(next_url, headers)
if not isinstance(body, list):
break
for pr in body:
if not isinstance(pr, dict):
continue
head_ref = ""
head = pr.get("head") or {}
if isinstance(head, dict):
head_ref = head.get("ref") or ""
if suffix_regex.match(head_ref):
return pr.get("number")
title = pr.get("title")
if isinstance(title, str) and title.startswith(title_prefix):
return pr.get("number")
next_url = parse_link_header(link_header)
return None
def get_pr_head_check_gate(repo, pr_number, github_token, http_get_json=_http_get_json):
"""Return ``(passed, reason)`` for the deterministic PR-head check gate.
``passed`` is:
True - the current PR head has at least one check run and all are success
False - the PR exists, but checks are missing, pending, or failing
None - the API could not provide enough data to decide
"""
if not repo or not pr_number or not github_token:
return None, "missing-pr-or-token"
headers = {
"Authorization": "token {}".format(github_token),
"Accept": "application/vnd.github.v3+json",
}
pr_url = "https://api.github.com/repos/{}/pulls/{}".format(repo, pr_number)
pr_body, _ = http_get_json(pr_url, headers)
if not isinstance(pr_body, dict):
return None, "pr-unavailable"
head = pr_body.get("head") or {}
head_sha = head.get("sha") if isinstance(head, dict) else None
if not head_sha:
return None, "pr-head-sha-unavailable"
check_runs = []
next_url = "https://api.github.com/repos/{}/commits/{}/check-runs?per_page=100".format(
repo, head_sha
)
while next_url:
body, link_header = http_get_json(next_url, headers)
if not isinstance(body, dict):
return None, "checks-unavailable:{}".format(head_sha[:12])
page_runs = body.get("check_runs")
if not isinstance(page_runs, list):
return None, "checks-malformed:{}".format(head_sha[:12])
check_runs.extend(page_runs)
next_url = parse_link_header(link_header)
if not check_runs:
return False, "missing-checks:{}".format(head_sha[:12])
not_success = []
for run in check_runs:
if not isinstance(run, dict):
not_success.append("unknown:malformed")
continue
name = run.get("name") or "unknown"
status = run.get("status")
conclusion = run.get("conclusion")
if status != "completed" or conclusion != "success":
not_success.append("{}:{}:{}".format(name, status or "unknown", conclusion or "none"))
if not_success:
return False, "failing:{}:{}".format(head_sha[:12], ";".join(not_success[:5]))
return True, "passed:{}".format(head_sha[:12])
# ---------------------------------------------------------------------------
# Selection
# ---------------------------------------------------------------------------
def select_migration(due, forced_migration=None, all_migrations=None, unconfigured=None, issue_migrations=None):
"""Pick the migration to run.
Returns ``(selected, selected_file, selected_issue, selected_target_metric,
selected_metric_direction, selected_strategy, deferred, error)``.
"""
all_migrations = all_migrations or {}
unconfigured = unconfigured or []
issue_migrations = issue_migrations or {}
if forced_migration:
if forced_migration not in all_migrations:
return (
None, None, None, None, "higher", "auto", [],
"requested migration '{}' not found. Available migrations: {}".format(
forced_migration, list(all_migrations.keys())
),
)
if forced_migration in unconfigured:
return (
None, None, None, None, "higher", "auto", [],
"requested migration '{}' is unconfigured (has placeholders).".format(
forced_migration
),
)
selected = forced_migration
selected_file = all_migrations[forced_migration]
deferred = [p["name"] for p in due if p["name"] != forced_migration]
selected_issue = (
issue_migrations[selected]["issue_number"] if selected in issue_migrations else None
)
selected_target_metric = None
selected_metric_direction = None
selected_strategy = None
for p in due:
if p["name"] == forced_migration:
selected_target_metric = p.get("target_metric")
selected_metric_direction = p.get("metric_direction")
selected_strategy = p.get("strategy")
break
if selected_target_metric is None:
selected_target_metric = _parse_target_metric_from_file(selected_file)
if selected_metric_direction is None:
selected_metric_direction = _parse_metric_direction_from_file(selected_file)
if selected_strategy is None:
selected_strategy = _parse_strategy_from_file(selected_file)
return (
selected,
selected_file,
selected_issue,
selected_target_metric,
selected_metric_direction,
selected_strategy,
deferred,
None,
)
if due:
# Normal scheduling: pick the single most-overdue migration.
# ``last_run`` of None/empty sorts first (never run).
due_sorted = sorted(due, key=lambda p: p["last_run"] or "")
selected = due_sorted[0]["name"]
selected_file = due_sorted[0]["file"]
selected_target_metric = due_sorted[0].get("target_metric")
selected_metric_direction = due_sorted[0].get("metric_direction") or "higher"
selected_strategy = due_sorted[0].get("strategy") or "auto"
deferred = [p["name"] for p in due_sorted[1:]]
selected_issue = (
issue_migrations[selected]["issue_number"] if selected in issue_migrations else None
)
return (
selected,
selected_file,
selected_issue,
selected_target_metric,
selected_metric_direction,
selected_strategy,
deferred,
None,
)
return None, None, None, None, "higher", "auto", [], None
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def main():
github_token = os.environ.get("GITHUB_TOKEN", "")
repo = os.environ.get("GITHUB_REPOSITORY", "")
forced_migration = os.environ.get("CRANE_MIGRATION", "").strip()
_bootstrap_template_if_missing()
# Find all migration files from all locations:
# 1. Directory-based: .crane/migrations/<name>/migration.md (preferred)
# 2. Bare markdown: .crane/migrations/<name>.md (simple)
# 3. Issue-based: GitHub issues with the 'crane-migration' label
migration_files = []
migration_files.extend(_scan_directory_migrations())
migration_files.extend(_scan_bare_migrations())
issue_files, issue_migrations = _fetch_issue_migrations(repo, github_token)
migration_files.extend(issue_files)
if not migration_files:
# Fallback to single-file locations
for path in [".crane/migration.md", "migration.md"]:
if os.path.isfile(path):
migration_files = [path]
break
os.makedirs(OUTPUT_DIR, exist_ok=True)
if not migration_files:
print("NO_MIGRATIONS_FOUND")
with open(OUTPUT_FILE, "w") as f:
json.dump(
{
"due": [],
"skipped": [],
"unconfigured": [],
"stale_completed_state": [],
"no_migrations": True,
"head_branch": None,
"existing_pr": None,
},
f,
)
sys.exit(0)
now = datetime.now(timezone.utc)
due = []
skipped = []
unconfigured = []
stale_completed_state = []
all_migrations = {} # name -> file path
for pf in migration_files:
name = get_migration_name(pf)
issue_info = issue_migrations.get(name) or {}
issue_active = bool(issue_info.get("active"))
issue_completed_label = bool(issue_info.get("completed_label"))
all_migrations[name] = pf
with open(pf) as f:
content = f.read()
if is_unconfigured(content):
unconfigured.append(name)
continue
fm = parse_migration_frontmatter(content)
schedule_delta = fm["schedule_delta"]
target_metric = fm["target_metric"]
metric_direction = fm["metric_direction"]
strategy = fm["strategy"]
if fm["target_metric_invalid"] is not None:
print(" Warning: {} has invalid target-metric value: {}".format(name, fm["target_metric_invalid"]))
if fm["metric_direction_invalid"] is not None:
print(
" Warning: {} has invalid metric_direction value: {!r} (must be 'higher' or 'lower'); defaulting to 'higher'".format(
name, fm["metric_direction_invalid"]
)
)
if fm["strategy_invalid"] is not None:
print(
" Warning: {} has invalid strategy value: {!r} (must be 'in-place', 'greenfield', or 'auto'); defaulting to 'auto'".format(
name, fm["strategy_invalid"]
)
)
# Read state from repo-memory
state = read_migration_state(name)
if state:
print(
" {}: last_run={}, iteration_count={}".format(
name, state.get("last_run"), state.get("iteration_count")
)
)
else:
print(" {}: no state found (first run)".format(name))
has_stale_completed_state, recovered_completed_issue, recovery_event = (
evaluate_completed_label_recovery(
name,
state,
issue_active,
issue_completed_label,
repo,
github_token,
)
)
if recovery_event:
event_kind, recovery_pr, gate_reason = recovery_event
if event_kind == "confirmed":
print(
" {}: crane-completed label confirmed by PR #{} gate {}".format(
name, recovery_pr, gate_reason
)
)
elif event_kind == "stale_gate":
print(
" {}: crane-completed label is stale; PR #{} gate is {}".format(
name, recovery_pr, gate_reason
)
)
elif event_kind == "stale_no_pr":
print(
" {}: crane-completed label is stale; no open migration PR was found".format(
name
)
)
if has_stale_completed_state:
stale_completed_state.append(name)
if issue_active:
print(
f" {name}: issue still has crane-migration label; treating "
"Completed=true as stale until fresh verification passes"
)
if recovered_completed_issue:
print(
f" {name}: completed label will be treated as stale until "
"the deterministic completion gate passes"
)
last_run = None
lr = state.get("last_run")
if lr:
try:
last_run = datetime.fromisoformat(lr.replace("Z", "+00:00"))
except ValueError:
pass
should_skip, reason = check_skip_conditions(
state,
issue_active=issue_active or recovered_completed_issue,
)
if should_skip:
skipped.append({"name": name, "reason": reason})
continue
if has_stale_completed_state:
due.append({
"name": name,
"last_run": lr,
"file": pf,
"target_metric": target_metric,
"metric_direction": metric_direction,
"strategy": strategy,
"stale_completed_state": has_stale_completed_state,
})
continue
# Check if due based on per-migration schedule
if schedule_delta and last_run and now - last_run < schedule_delta:
skipped.append(
{
"name": name,
"reason": "not due yet",
"next_due": (last_run + schedule_delta).isoformat(),
}
)
continue
due.append({
"name": name,
"last_run": lr,
"file": pf,
"target_metric": target_metric,
"metric_direction": metric_direction,
"strategy": strategy,
"stale_completed_state": has_stale_completed_state,
})
selected, selected_file, selected_issue, selected_target_metric, selected_metric_direction, selected_strategy, deferred, error = (
select_migration(due, forced_migration, all_migrations, unconfigured, issue_migrations)
)
if error:
print("ERROR: {}".format(error))
sys.exit(1)
if forced_migration and selected:
print("FORCED: running migration '{}' (manual dispatch)".format(forced_migration))
# Look up the existing draft PR (if any) for the selected migration.
head_branch = None
existing_pr = None
if selected:
head_branch = "crane/{}".format(selected)
try:
existing_pr = find_existing_pr_for_branch(repo, selected, github_token)
except Exception as e: # noqa: BLE001 -- best-effort lookup
print(" Warning: existing PR lookup failed for {}: {}".format(selected, e))
existing_pr = None
result = {
"selected": selected,
"selected_file": selected_file,
"selected_issue": selected_issue,
"selected_target_metric": selected_target_metric,
"selected_metric_direction": selected_metric_direction,
"selected_strategy": selected_strategy,
"state_file_size_bytes": get_state_file_size(selected) if selected else 0,
"state_file_max_bytes": STATE_FILE_MAX_BYTES,
"issue_migrations": {
name: info["issue_number"] for name, info in issue_migrations.items()
},
"stale_completed_state": stale_completed_state,
"deferred": deferred,
"skipped": skipped,
"unconfigured": unconfigured,
"no_migrations": False,
"head_branch": head_branch,
"existing_pr": existing_pr,
}
with open(OUTPUT_FILE, "w") as f:
json.dump(result, f, indent=2)
print("=== Crane Migration Check ===")
print("Selected migration: {} ({})".format(selected or "(none)", selected_file or "n/a"))
print("Deferred (next run): {}".format(deferred or "(none)"))
print("Migrations skipped: {}".format([s["name"] for s in skipped] or "(none)"))
print("Migrations unconfigured: {}".format(unconfigured or "(none)"))
if not selected and not unconfigured:
print("\nNo migrations due this run. Exiting early.")
sys.exit(1) # Non-zero exit skips the agent step
if __name__ == "__main__":
main()