forked from openclaw/openclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
6408 lines (6011 loc) 路 394 KB
/
Copy pathci.yml
File metadata and controls
6408 lines (6011 loc) 路 394 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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
name: CI
on:
schedule:
- cron: "23 * * * *"
workflow_dispatch:
inputs:
target_ref:
description: Optional branch, tag, or full commit SHA to validate instead of the workflow ref
required: false
default: ""
type: string
runner_backend:
description: Runner qualification override; requires an exact-head canonical PR release_gate dispatch.
required: false
default: default
type: choice
options: [default, hybrid, runson]
ci_shape:
description: Main-push coverage for an admitted exact-head qualification; default preserves ordinary dispatch behavior.
required: false
default: default
type: choice
options: [default, main]
capture_ui_proof:
description: Capture and upload sanitized Control UI screenshots from real-Gateway tests.
required: false
default: false
type: boolean
include_android:
description: Run Android lanes for this manual CI dispatch.
required: false
default: false
type: boolean
validation_tier:
description: Full release coverage, or complete main coverage without release-only proofs.
required: false
default: full
type: choice
options: [full, main]
release_scope:
description: Release qualification scope; npm-beta and npm-stable defer native apps for a validated exact release target.
required: false
default: full
type: choice
options: [full, npm-beta, npm-stable]
release_gate:
description: Run an exact-SHA maintainer release-gate fallback when PR CI is capacity-stalled.
required: false
default: false
type: boolean
pull_request_number:
description: Pull request number required by the exact-SHA release gate.
required: false
default: ""
type: string
dispatch_id:
description: Optional parent workflow dispatch identifier
required: false
default: ""
type: string
historical_target_tag:
description: Semver release tag authorizing compatibility fallbacks for its exact commit
required: false
default: ""
type: string
release_candidate_ref:
description: Canonical release branch authorizing compatibility fallbacks for its exact head
required: false
default: ""
type: string
target_context_ref:
description: Canonical release branch context authorizing compatibility fallbacks for an exact-SHA target
required: false
default: ""
type: string
push:
branches: [main]
paths-ignore:
- "**/*.md"
- "docs/**"
pull_request:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
permissions:
contents: read
run-name: ${{ github.event_name == 'workflow_dispatch' && inputs.dispatch_id != '' && format('CI {0}', inputs.dispatch_id) || (github.event_name == 'workflow_dispatch' && inputs.release_gate && format('CI release gate {0}', inputs.target_ref) || 'CI') }}
concurrency:
# Keep main parity slots; isolate passive drafts except converted_to_draft.
group: >-
${{ github.event_name == 'pull_request' && github.event.pull_request.draft &&
github.event.action != 'converted_to_draft' && format('{0}-draft-v1-{1}', github.workflow, github.run_id) ||
github.event_name == 'schedule' && format('{0}-hourly-main-v2-{1}', github.workflow, github.run_id) ||
github.event_name == 'workflow_dispatch' && format('{0}-manual-v1-{1}', github.workflow, github.run_id) || (github.event_name == 'pull_request' && format('{0}-v7-{1}', github.workflow, github.event.pull_request.number) || (github.repository == 'openclaw/openclaw' && github.event_name == 'push' && github.ref == 'refs/heads/main' && format('{0}-v8-{1}-{2}', github.workflow, github.ref, (endsWith(format('{0}', github.run_number), '0') || endsWith(format('{0}', github.run_number), '2') || endsWith(format('{0}', github.run_number), '4') || endsWith(format('{0}', github.run_number), '6') || endsWith(format('{0}', github.run_number), '8')) && 'a' || 'b') || (github.repository == 'openclaw/openclaw' && format('{0}-v7-{1}', github.workflow, github.ref) || format('{0}-v7-{1}-{2}', github.workflow, github.ref, github.sha)))) }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
IOS_SCREENSHOT_FASTLANE_VERSION: "2.240.1"
IOS_SCREENSHOT_NODE_VERSION: "24.16.0"
IOS_SCREENSHOT_XCODE_VERSION: "Xcode 27.0 Build version 27A266a"
NODE_VERSION: "24.21.0"
jobs:
preflight:
permissions:
contents: read
actions: read
pull-requests: read
if: ${{ (github.event_name != 'schedule' || (github.repository == 'openclaw/openclaw' && github.ref == 'refs/heads/main')) && ((github.event_name != 'push' || github.ref != 'refs/heads/main' || vars.OPENCLAW_CI_ON_PUSH == 'true') && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) }}
runs-on: ${{ (github.event_name == 'workflow_dispatch' && startsWith(inputs.dispatch_id, 'full-release-validation-') && vars.OPENCLAW_RELEASE_RUNNER_GROUP || '') != '' && fromJSON(format('{{"group":{0},"labels":{1}}}', toJSON((github.event_name == 'workflow_dispatch' && startsWith(inputs.dispatch_id, 'full-release-validation-') && vars.OPENCLAW_RELEASE_RUNNER_GROUP || '')), toJSON((vars.OPENCLAW_CI_RUNNER_BACKEND == 'github' || (contains(fromJSON('["hybrid","runson"]'), vars.OPENCLAW_CI_RUNNER_BACKEND) && github.run_attempt != 1)) && 'ubuntu-24.04' || (github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && github.run_attempt > 1)) && 'ubuntu-24.04' || (github.repository == 'openclaw/openclaw' && (contains(fromJSON('["hybrid","runson"]'), vars.OPENCLAW_CI_RUNNER_BACKEND) && 'blacksmith-16vcpu-ubuntu-2404' || 'blacksmith-4vcpu-ubuntu-2404') || 'ubuntu-24.04')))) || ((vars.OPENCLAW_CI_RUNNER_BACKEND == 'github' || (contains(fromJSON('["hybrid","runson"]'), vars.OPENCLAW_CI_RUNNER_BACKEND) && github.run_attempt != 1)) && 'ubuntu-24.04' || (github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && github.run_attempt > 1)) && 'ubuntu-24.04' || (github.repository == 'openclaw/openclaw' && (contains(fromJSON('["hybrid","runson"]'), vars.OPENCLAW_CI_RUNNER_BACKEND) && 'blacksmith-16vcpu-ubuntu-2404' || 'blacksmith-4vcpu-ubuntu-2404') || 'ubuntu-24.04')) }}
timeout-minutes: 20
outputs:
checkout_revision: ${{ steps.checkout_ref.outputs.sha }}
pr_job_count: ${{ steps.manifest.outputs.pr_job_count }}
pr_check_job_count: ${{ steps.manifest.outputs.pr_check_job_count }}
candidate_trust: ${{ steps.candidate_trust.outputs.trust }}
cache_mode: ${{ steps.candidate_trust.outputs.cache_mode }}
cache_write_allowed: ${{ steps.candidate_trust.outputs.cache_write_allowed }}
hosted_runner_profile_contract: ${{ steps.runner_profile.outputs.hosted_runner_profile_contract }}
runner_profile: ${{ steps.runner_profile.outputs.runner_profile }} # hosted-runner-profile-contract-v1
node_runner_backend: ${{ steps.runner_profile.outputs.node_runner_backend }} # runson-runner-profile-contract-v1
ci_qualification: ${{ steps.runner_profile.outputs.ci_qualification }}
ci_shape: ${{ steps.runner_profile.outputs.ci_shape }}
qualification_runner_backend: ${{ steps.runner_profile.outputs.qualification_runner_backend }}
hybrid_hosted_offload: ${{ steps.manifest.outputs.hybrid_hosted_offload }}
hybrid_hosted_checks: ${{ steps.manifest.outputs.hybrid_hosted_checks }}
hybrid_hosted_main_checks: ${{ steps.manifest.outputs.hybrid_hosted_main_checks }}
hybrid_hosted_base_rows: ${{ steps.manifest.outputs.hybrid_hosted_base_rows }}
hybrid_hosted_total_rows: ${{ steps.manifest.outputs.hybrid_hosted_total_rows }}
diff_base_revision: ${{ steps.diff_base.outputs.sha }}
diff_head_revision: ${{ steps.diff_base.outputs.head_sha }}
docs_only: ${{ steps.manifest.outputs.docs_only }}
docs_changed: ${{ steps.manifest.outputs.docs_changed }}
release_scope: ${{ steps.manifest.outputs.release_scope }}
release_fast_lane: ${{ steps.manifest.outputs.release_fast_lane }}
validation_tier: ${{ steps.manifest.outputs.validation_tier }}
run_node: ${{ steps.manifest.outputs.run_node }}
# Freeze PR label policy once so every cancellation owner makes the same decision.
disable_fail_fast: ${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci:no-fail-fast') && 'true' || 'false' }}
# docker-seed-e2e-contract-v1: frozen targets without this marker skip the lane.
run_docker_seed_e2e: ${{ steps.manifest.outputs.run_docker_seed_e2e }}
docker_seed_lanes: ${{ steps.manifest.outputs.docker_seed_lanes }}
# published-driver-update-contract-v1: older frozen targets omit this cell.
run_published_driver_update: ${{ steps.manifest.outputs.run_published_driver_update }}
run_macos: ${{ steps.manifest.outputs.run_macos }}
run_android: ${{ steps.manifest.outputs.run_android }}
run_skills_python: ${{ steps.manifest.outputs.run_skills_python }}
run_skills_python_job: ${{ steps.manifest.outputs.run_skills_python_job }}
run_windows: ${{ steps.manifest.outputs.run_windows }}
run_build_artifacts: ${{ steps.manifest.outputs.run_build_artifacts }}
run_proof_tier: ${{ steps.manifest.outputs.run_proof_tier }}
run_browser_native_host: ${{ steps.manifest.outputs.run_browser_native_host }}
run_doctor_plugin_index: ${{ steps.manifest.outputs.run_doctor_plugin_index }}
run_discord_component_proof: ${{ steps.manifest.outputs.run_discord_component_proof }}
run_gateway_watch: ${{ steps.manifest.outputs.run_gateway_watch }}
run_tui_pty: ${{ steps.manifest.outputs.run_tui_pty }}
run_baseline_ratchets: ${{ steps.manifest.outputs.run_baseline_ratchets }}
run_checks_fast_core: ${{ steps.manifest.outputs.run_checks_fast_core }}
run_checks_fast: ${{ steps.manifest.outputs.run_checks_fast }}
historical_target: ${{ steps.manifest.outputs.historical_target }}
frozen_target: ${{ steps.manifest.outputs.frozen_target }}
run_qa_smoke_ci: ${{ steps.manifest.outputs.run_qa_smoke_ci }}
qa_smoke_ci_matrix: ${{ steps.manifest.outputs.qa_smoke_ci_matrix }}
run_prompt_snapshots: ${{ steps.manifest.outputs.run_prompt_snapshots }}
run_sqlite_session_lifecycle: ${{ steps.manifest.outputs.run_sqlite_session_lifecycle }}
checks_fast_core_matrix: ${{ steps.manifest.outputs.checks_fast_core_matrix }}
run_plugin_contracts_shards: ${{ steps.manifest.outputs.run_plugin_contracts_shards }}
plugin_contracts_matrix: ${{ steps.manifest.outputs.plugin_contracts_matrix }}
run_channel_contracts_shards: ${{ steps.manifest.outputs.run_channel_contracts_shards }}
channel_contracts_matrix: ${{ steps.manifest.outputs.channel_contracts_matrix }}
run_checks: ${{ steps.manifest.outputs.run_checks }}
source_channel_test_env_json: ${{ steps.manifest.outputs.source_channel_test_env_json }}
run_checks_node_core_nondist: ${{ steps.manifest.outputs.run_checks_node_core_nondist }}
checks_node_core_nondist_matrix: ${{ steps.manifest.outputs.checks_node_core_nondist_matrix }}
run_checks_node_core_dist: ${{ steps.manifest.outputs.run_checks_node_core_dist }}
run_check: ${{ steps.manifest.outputs.run_check }}
startup_corpus_node_revision: ${{ steps.manifest.outputs.startup_corpus_node_revision }}
startup_corpus_test_files_json: ${{ steps.manifest.outputs.startup_corpus_test_files_json }}
changed_core_test_paths_json: ${{ steps.manifest.outputs.changed_core_test_paths_json }}
narrow_check_paths_json: ${{ steps.manifest.outputs.narrow_check_paths_json }}
run_check_plan: ${{ steps.manifest.outputs.run_check_plan }}
shared_sdk_declarations: ${{ steps.manifest.outputs.shared_sdk_declarations }}
check_plan_input_json: ${{ steps.manifest.outputs.check_plan_input_json }}
check_matrix: ${{ steps.manifest.outputs.check_matrix }}
core_type_matrix: ${{ steps.manifest.outputs.core_type_matrix }}
lint_core_matrix: ${{ steps.manifest.outputs.lint_core_matrix }}
lint_extension_matrix: ${{ steps.manifest.outputs.lint_extension_matrix }}
central_lint_selection_json: ${{ steps.manifest.outputs.central_lint_selection_json }}
run_lint_core: ${{ steps.manifest.outputs.run_lint_core }}
run_lint_extensions: ${{ steps.manifest.outputs.run_lint_extensions }}
run_changed_core_type_stripes: ${{ steps.manifest.outputs.run_changed_core_type_stripes }}
type_graph_boundary_owner: ${{ steps.manifest.outputs.type_graph_boundary_owner }}
run_check_additional: ${{ steps.manifest.outputs.run_check_additional }}
check_additional_matrix: ${{ steps.manifest.outputs.check_additional_matrix }}
run_check_docs: ${{ steps.manifest.outputs.run_check_docs }}
run_format_check: ${{ steps.manifest.outputs.run_format_check }}
compatibility_target: ${{ steps.manifest.outputs.compatibility_target }}
run_control_ui_i18n: ${{ steps.manifest.outputs.run_control_ui_i18n }}
strict_control_ui_i18n: ${{ github.event_name == 'workflow_dispatch' && !inputs.release_gate && 'true' || steps.changed_scope.outputs.strict_control_ui_i18n }}
run_ui_tests: ${{ steps.manifest.outputs.run_ui_tests }}
ui_test_runtime_policy: ${{ steps.manifest.outputs.ui_test_runtime_policy }}
ui_test_matrix: ${{ steps.manifest.outputs.ui_test_matrix }}
ui_test_shard_count: ${{ steps.manifest.outputs.ui_test_shard_count }}
ui_test_groups_gzip_base64: ${{ steps.manifest.outputs.ui_test_groups_gzip_base64 }}
ui_e2e_test_groups_gzip_base64: ${{ steps.manifest.outputs.ui_e2e_test_groups_gzip_base64 }}
run_control_ui_performance: ${{ steps.manifest.outputs.run_control_ui_performance }}
run_ui_e2e: ${{ steps.manifest.outputs.run_ui_e2e }}
run_ui_real_gateway: ${{ steps.manifest.outputs.run_ui_real_gateway }}
ui_e2e_matrix: ${{ steps.manifest.outputs.ui_e2e_matrix }}
ui_real_gateway_matrix: ${{ steps.manifest.outputs.ui_real_gateway_matrix }}
run_native_i18n: ${{ steps.manifest.outputs.run_native_i18n }}
strict_native_i18n: ${{ github.event_name == 'workflow_dispatch' && !inputs.release_gate && 'true' || steps.changed_scope.outputs.strict_native_i18n }}
run_checks_windows: ${{ steps.manifest.outputs.run_checks_windows }}
checks_windows_matrix: ${{ steps.manifest.outputs.checks_windows_matrix }}
run_macos_node: ${{ steps.manifest.outputs.run_macos_node }}
macos_node_matrix: ${{ steps.manifest.outputs.macos_node_matrix }}
run_macos_swift: ${{ steps.manifest.outputs.run_macos_swift }}
run_openclawkit_tests: ${{ steps.manifest.outputs.run_openclawkit_tests }}
run_ios_build: ${{ steps.manifest.outputs.run_ios_build }}
run_ios_voice_cleanup_tests: ${{ steps.manifest.outputs.run_ios_voice_cleanup_tests }}
run_ios_lifecycle_tests: ${{ steps.manifest.outputs.run_ios_lifecycle_tests }}
ios_simulator_selection: ${{ steps.manifest.outputs.ios_simulator_selection }}
run_ios_screenshots: ${{ steps.changed_scope.outputs.run_ios_screenshots }}
run_android_job: ${{ steps.manifest.outputs.run_android_job }}
run_android_access_native: ${{ steps.manifest.outputs.run_android_access_native }}
use_compatible_android_ci: ${{ steps.manifest.outputs.use_compatible_android_ci }}
run_protocol_event_coverage: ${{ steps.manifest.outputs.run_protocol_event_coverage }}
android_matrix: ${{ steps.manifest.outputs.android_matrix }}
steps:
- name: Validate release-gate dispatch
if: github.event_name == 'workflow_dispatch' && inputs.release_gate
env:
HISTORICAL_TARGET_TAG: ${{ inputs.historical_target_tag }}
PULL_REQUEST_NUMBER: ${{ inputs.pull_request_number }}
TARGET_REF: ${{ inputs.target_ref }}
run: |
set -euo pipefail
if [[ ! "$TARGET_REF" =~ ^[0-9a-f]{40}$ ]]; then
echo "release_gate requires target_ref to be a full commit SHA" >&2
exit 1
fi
if [[ ! "$PULL_REQUEST_NUMBER" =~ ^[1-9][0-9]*$ ]]; then
echo "release_gate requires pull_request_number" >&2
exit 1
fi
if [[ "$GITHUB_SHA" != "$TARGET_REF" ]]; then
echo "release_gate must run from the branch at target_ref" >&2
exit 1
fi
if [[ -n "$HISTORICAL_TARGET_TAG" ]]; then
echo "release_gate cannot be combined with historical_target_tag" >&2
exit 1
fi
- name: Checkout
shell: bash
env:
CHECKOUT_KIND: preflight
WORKFLOW_SHA: ${{ github.workflow_sha }}
CHECKOUT_REPO: ${{ github.repository }}
CHECKOUT_TOKEN: ${{ github.token }}
CHECKOUT_REF: ${{ inputs.target_ref || github.sha }}
CHECKOUT_EVENT_REF: ${{ github.ref }}
CHECKOUT_FALLBACK_REF: ${{ github.sha }}
GITHUB_EVENT_NAME: ${{ github.event_name }}
run: &owned_checkout_run |
set -euo pipefail
python_command=python3
if [ "$RUNNER_OS" = "Windows" ]; then
python_command=python
fi
run_owner() {
if [ "$RUNNER_OS" = "Linux" ] || [ "$RUNNER_OS" = "Windows" ]; then
# Keep trusted code outside the checkout and below Windows argv limits.
printf '%s' "$1" > "$RUNNER_TEMP/ci-git-owner.py"
exec "$python_command" -I -S "$RUNNER_TEMP/ci-git-owner.py"
fi
exec "$python_command" -I -S -c "$1"
}
# Generated from .github/actions/git-owner/owner.py; do not edit here.
run_owner 'import base64
import builtins
import json
import os
import re
import runpy
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from types import TracebackType
linux = os.environ.get("RUNNER_OS", sys.platform) in ("Linux", "linux")
fetch_timeout_seconds = 120 if linux else 90
cleanup_seconds = 10
cancelled = 0
closed = False
git = shutil.which("git")
checkout_environment = {}
def cancel(signum, _frame):
global cancelled
cancelled = signum
for signame in ("SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"):
if hasattr(signal, signame):
signal.signal(getattr(signal, signame), cancel)
def check_cancelled():
if cancelled:
raise SystemExit(128 + cancelled)
# The bootstrap inherits only this Job handle and stdio, joins before spawning Git,
# then closes its copy. Even owner death before assignment kills it on that close.
windows_api = '\'''\'''\''
import ctypes as c
from ctypes import wintypes as w
import os, subprocess, sys
kernel = c.WinDLL("kernel32", use_last_error=True)
def checked(value, function, arguments):
if not value:
raise c.WinError(c.get_last_error())
return value
def bind(name, result, *arguments):
function = getattr(kernel, name)
function.restype, function.argtypes = result, arguments
function.errcheck = checked
return function
close_handle = bind("CloseHandle", w.BOOL, w.HANDLE)
'\'''\'''\''
if os.name == "nt":
exec(windows_api)
class BasicLimits(c.Structure):
_fields_ = [
("PerProcessUserTimeLimit", c.c_int64), ("PerJobUserTimeLimit", c.c_int64),
("LimitFlags", w.DWORD), ("MinimumWorkingSetSize", c.c_size_t),
("MaximumWorkingSetSize", c.c_size_t), ("ActiveProcessLimit", w.DWORD),
("Affinity", c.c_size_t), ("PriorityClass", w.DWORD), ("SchedulingClass", w.DWORD),
]
class IoCounters(c.Structure):
_fields_ = [(name, c.c_uint64) for name in (
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount",
)]
class ExtendedLimits(c.Structure):
_fields_ = [("BasicLimitInformation", BasicLimits), ("IoInfo", IoCounters)] + [
(name, c.c_size_t) for name in (
"ProcessMemoryLimit", "JobMemoryLimit", "PeakProcessMemoryUsed", "PeakJobMemoryUsed",
)
]
class Accounting(c.Structure):
_fields_ = [(name, c.c_int64) for name in (
"TotalUserTime", "TotalKernelTime", "ThisPeriodTotalUserTime", "ThisPeriodTotalKernelTime",
)] + [(name, w.DWORD) for name in (
"TotalPageFaultCount", "TotalProcesses", "ActiveProcesses", "TotalTerminatedProcesses",
)]
if (c.sizeof(BasicLimits), c.sizeof(ExtendedLimits), c.sizeof(Accounting), Accounting.ActiveProcesses.offset) != (64, 144, 48, 40):
raise RuntimeError("Unsupported Windows Job structure layout")
create_job = bind("CreateJobObjectW", w.HANDLE, c.c_void_p, w.LPCWSTR)
set_job = bind("SetInformationJobObject", w.BOOL, w.HANDLE, c.c_int, c.c_void_p, w.DWORD)
query_job = bind("QueryInformationJobObject", w.BOOL, w.HANDLE, c.c_int, c.c_void_p, w.DWORD, c.c_void_p)
terminate_job = bind("TerminateJobObject", w.BOOL, w.HANDLE, w.UINT)
open_process = bind("OpenProcess", w.HANDLE, w.DWORD, w.BOOL, w.DWORD)
in_job = bind("IsProcessInJob", w.BOOL, w.HANDLE, w.HANDLE, c.POINTER(w.BOOL))
wait_process = kernel.WaitForSingleObject
wait_process.argtypes, wait_process.restype = [w.HANDLE, w.DWORD], w.DWORD
def job_members(job, deadline):
# PIDs are discovery hints only. Hold query/synchronize handles and verify
# job membership before using them; never signal a process found by PID.
before = Accounting()
query_job(job, 1, c.byref(before), c.sizeof(before), None)
capacity = max(16, before.ActiveProcesses + 1)
while True:
if time.monotonic() >= deadline or capacity > 65536:
raise RuntimeError("Job member census did not complete")
class Members(c.Structure):
_fields_ = [("assigned", w.DWORD), ("count", w.DWORD),
("pids", c.c_size_t * capacity)]
members = Members()
try:
query_job(job, 3, c.byref(members), c.sizeof(members), None)
break
except OSError as error:
if error.winerror != 234: # ERROR_MORE_DATA: retry the census, not cleanup.
raise
capacity *= 2
handles = []
try:
for pid in members.pids[:members.count]:
handle = open_process(0x00100000 | 0x1000, False, pid)
handles.append(handle)
member = w.BOOL()
in_job(handle, job, c.byref(member))
if not member.value:
raise RuntimeError("Job member identity changed during census")
after = Accounting()
query_job(job, 1, c.byref(after), c.sizeof(after), None)
if after.TotalProcesses != before.TotalProcesses:
raise RuntimeError("Job membership grew during census")
return handles, after.TotalProcesses
except BaseException:
for handle in handles:
close_handle(handle)
raise
bootstrap = windows_api + '\'''\'''\''
job = int(sys.argv[1])
assign = bind("AssignProcessToJobObject", w.BOOL, w.HANDLE, w.HANDLE)
current = bind("GetCurrentProcess", w.HANDLE)
assign(job, current())
close_handle(job)
sys.exit(subprocess.call(sys.argv[2:], stdin=subprocess.DEVNULL))
'\'''\'''\''
def group_signal(pgid, signum, deadline):
try:
os.killpg(pgid, signum)
except ProcessLookupError:
return False
except PermissionError:
# Darwin can refuse signals while members are exiting but not yet zombies.
# Keep those members pending until drain proves termination; never accept a live denial.
states = group_states(pgid, deadline)
if any(not state.startswith("Z") and not (sys.platform == "darwin" and "E" in state)
for state in states):
raise
return any(not state.startswith("Z") for state in states)
return True
def group_alive(pgid, deadline):
return any(not state.startswith("Z") for state in group_states(pgid, deadline))
def group_states(pgid, deadline):
try:
os.killpg(pgid, 0)
except ProcessLookupError:
return []
except PermissionError:
pass # EPERM can mean zombie-only; the census must still prove extinction.
# Darwin -g selects a group; procps selects its session (a superset because
# run_git starts a new session). Pin Darwin'\''s standard, not legacy, -g syntax.
try:
result = subprocess.run(
["ps", "-o", "pgid=,stat=", "-g", str(pgid)], stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
env={**os.environ, "COMMAND_MODE": "unix2003"},
timeout=max(0.001, deadline - time.monotonic()),
)
except subprocess.TimeoutExpired as error:
print((error.stderr or b"").decode(errors="replace"), end="", file=sys.stderr)
raise
if result.stderr:
print(result.stderr, end="", file=sys.stderr)
states = []
if result.returncode != 1 or result.stdout or result.stderr:
result.check_returncode()
# Validate the complete census before ignoring zombies; Darwin ps can
# report sysctl errors on stderr with exit 0. Neither permits reuse.
if result.stderr or not re.fullmatch(
r"(?:[ \t]*[1-9][0-9]*[ \t]+[RSDTtXZxKWPIU?][<+NLlsEVWX]*[ \t]*\n)+", result.stdout
):
raise RuntimeError("Invalid process group census")
states = [state for group, state in (line.split() for line in result.stdout.splitlines())
if int(group) == pgid]
if states:
return states
# Empty selection (exit 1), or a session with only other groups, can race
# extinction. Require native ESRCH; a bare status 1 or EPERM proves nothing.
try:
os.killpg(pgid, 0)
except ProcessLookupError:
return []
raise RuntimeError("Process group census missed a present group")
def drain(child, job):
deadline = time.monotonic() + cleanup_seconds
if os.name == "nt":
# Stop/join even a pre-assignment bootstrap before terminating the Job:
# an empty Job alone cannot prove that no Git will start afterwards.
child.kill()
child.wait(timeout=max(0.001, deadline - time.monotonic()))
handles = []
terminated = False
try:
handles, total = job_members(job, deadline)
terminate_job(job, 1)
terminated = True
accounting = Accounting()
while True:
settled = True
for handle in handles:
status = wait_process(handle, 0)
if status == 258: # WAIT_TIMEOUT: accounting can reach zero first.
settled = False
elif status != 0:
raise c.WinError(c.get_last_error())
query_job(job, 1, c.byref(accounting), c.sizeof(accounting), None)
if accounting.TotalProcesses != total:
raise RuntimeError("Job membership grew during cleanup")
if accounting.ActiveProcesses == 0 and settled:
return
if time.monotonic() >= deadline:
raise RuntimeError("Job cleanup did not complete")
time.sleep(0.05)
finally:
try:
if not terminated:
terminate_job(job, 1)
finally:
for handle in handles:
close_handle(handle)
else:
# The group remains ours after leader exit. Reserve half the existing
# cleanup allowance for KILL and extinction verification after TERM.
try:
group_signal(child.pid, signal.SIGTERM, deadline)
kill_at = deadline - cleanup_seconds / 2
while True:
child.poll()
if not group_alive(child.pid, deadline):
child.wait(timeout=max(0.001, deadline - time.monotonic()))
return
if time.monotonic() >= kill_at:
group_signal(child.pid, signal.SIGKILL, deadline)
if time.monotonic() >= deadline:
raise RuntimeError("Process group cleanup did not complete")
time.sleep(0.05)
except Exception:
group_signal(child.pid, signal.SIGKILL, deadline)
# KILL queues termination; a leader wait cannot join descendants.
# Count zombies conservatively here, but never reset the allowance or retry.
while time.monotonic() < deadline:
child.poll()
if not group_signal(child.pid, 0, deadline):
break
time.sleep(0.05)
child.wait(timeout=max(0.001, deadline - time.monotonic()))
raise
class FetchTimeout(Exception):
pass
class GitFailure(Exception):
def __init__(self, code):
self.code = code
def git_lock_files(directory):
git_dir = os.path.join(os.path.realpath(directory), ".git")
if not os.path.lexists(git_dir):
return set()
if not os.path.isdir(git_dir) or os.path.realpath(git_dir) != git_dir:
raise RuntimeError("Checkout Git directory is not physical")
def scan_error(error):
raise error
locks = set()
for root, directories, files in os.walk(git_dir, onerror=scan_error):
directories[:] = [name for name in directories
if os.path.realpath(os.path.join(root, name)) == os.path.join(root, name)]
locks.update(os.path.join(root, name) for name in files if name.endswith(".lock"))
return locks
def git_auth_environment(remote, token):
# Git'\''s promisor fetch inherits this process-only config from checkout.
# Reject redirects: http.<url> matching does not re-scope redirected requests.
count = int(os.environ.get("GIT_CONFIG_COUNT", "0"))
if count < 0:
raise ValueError("Invalid Git environment configuration count")
header = f"http.{remote}.extraheader"
authorization = base64.b64encode(f"x-access-token:{token}".encode()).decode()
settings = [(header, ""), (header, f"AUTHORIZATION: basic {authorization}"),
(f"http.{remote}.followRedirects", "false")]
environment = {"GIT_CONFIG_COUNT": str(count + len(settings)), "GIT_TERMINAL_PROMPT": "0"}
for index, (key, value) in enumerate(settings, count):
environment[f"GIT_CONFIG_KEY_{index}"] = key
environment[f"GIT_CONFIG_VALUE_{index}"] = value
return environment
def run_git(directory, *arguments, timeout=None, stdout=None, stderr=None, env=None,
reclaim_locks=False):
global closed
if closed:
raise RuntimeError("Git owner is closed")
check_cancelled()
if git is None:
raise RuntimeError("Git unavailable")
# Process ownership alone does not grant metadata ownership: generic callers
# may use linked worktrees. Only exclusive checkout fetches reclaim locks.
previous_locks = git_lock_files(directory) if reclaim_locks else None
command = [git, "-C", directory, *arguments]
job = None
child = None
timed_out = False
deadline = time.monotonic() + timeout if timeout is not None else None
try:
environment = ({**os.environ, **checkout_environment, **(env or {})}
if checkout_environment or env is not None else None)
options = {"stdin": subprocess.DEVNULL, "stdout": stdout, "stderr": stderr,
"env": environment}
if os.name == "nt":
job = create_job(None, None)
limits = ExtendedLimits()
limits.BasicLimitInformation.LimitFlags = 0x2000 # KILL_ON_JOB_CLOSE; no breakaway.
set_job(job, 9, c.byref(limits), c.sizeof(limits))
os.set_handle_inheritable(job, True)
startup = subprocess.STARTUPINFO()
startup.lpAttributeList = {"handle_list": [job]}
options.update(startupinfo=startup, close_fds=True)
# The selected checkout must not inject Python startup code into its owner.
command = [sys.executable, "-I", "-S", "-c", bootstrap, str(job), *command]
else:
options["start_new_session"] = True
# Signal handlers only latch cancellation, so Popen cannot lose ownership
# between process creation and saving its handle/group for cleanup.
child = subprocess.Popen(command, **options)
if job is not None:
os.set_handle_inheritable(job, False)
while child.poll() is None and not cancelled:
if deadline is not None and time.monotonic() >= deadline:
timed_out = True
raise FetchTimeout()
time.sleep(0.05)
finally:
# Failed inspection/cleanup permanently fences this policy process. Only
# verified extinction permits another command, even after a caught error.
closed = True
try:
if child is not None:
drain(child, job)
if previous_locks is not None and (timed_out or cancelled or child.returncode):
# Forced termination skips Git'\''s lockfile cleanup. This checkout is exclusive;
# reclaim only newly created locks after tree extinction, never existing locks.
for lock in sorted(git_lock_files(directory) - previous_locks):
os.unlink(lock)
finally:
if job is not None:
close_handle(job)
closed = False
# Run even while a timeout is unwinding: cancellation received during
# draining outranks it, but failed cleanup above still outranks both.
check_cancelled()
if child.returncode:
raise GitFailure(child.returncode if child.returncode > 0 else 128 - child.returncode)
def backoff(seconds):
retry_at = time.monotonic() + seconds
while time.monotonic() < retry_at:
check_cancelled()
time.sleep(0.05)
def fetch(directory, *refs, prune=False, max_attempts=3, depth=1,
blobless=False, retry_failures=False, retry_codes=()):
for attempt in range(1, max_attempts + 1):
try:
run_git(directory, "-c", "protocol.version=2", "fetch", "--no-tags",
*(["--prune"] if prune else []), "--no-recurse-submodules", f"--depth={depth}",
*(["--filter=blob:none"] if blobless else []), "origin", *refs,
timeout=fetch_timeout_seconds, reclaim_locks=True)
return
except (FetchTimeout, GitFailure) as error:
check_cancelled()
retryable = isinstance(error, FetchTimeout) or retry_failures or error.code in retry_codes
if not retryable or attempt == max_attempts:
raise
print(f"::warning::checkout fetch failed on attempt {attempt}; retrying", flush=True)
backoff(5)
def git_output(directory, *arguments, timeout=None, env=None):
with tempfile.TemporaryFile() as output:
run_git(directory, *arguments, timeout=timeout, env=env, stdout=output)
output.seek(0)
return output.read().decode("utf-8", errors="surrogateescape")
def resolve_ref(ref):
return git_output(workspace, "rev-parse", ref).strip()
def checkout_selected_ref():
ref = os.environ["CHECKOUT_REF"]
fallback = os.environ["CHECKOUT_FALLBACK_REF"]
manual = os.environ["GITHUB_EVENT_NAME"] == "workflow_dispatch"
requested = ref if kind == "preflight" and re.fullmatch("[0-9a-f]{40}", ref) else None
# Prefer the event ref for an exact manual SHA, but detect a ref that moved in the queue.
if requested and manual and ref == fallback and os.environ.get("CHECKOUT_EVENT_REF"):
ref = os.environ["CHECKOUT_EVENT_REF"]
def fetch_ref(value):
fetch(workspace, f"+{value}:refs/remotes/origin/checkout", prune=True,
depth=1 if kind == "preflight" else 2, retry_codes=(124, 137))
try:
fetch_ref(ref)
except GitFailure as error:
if error.code in (124, 137) or not manual or os.environ["CHECKOUT_REF"] == fallback:
raise
print("::warning::workflow_dispatch target_ref is unavailable; falling back to head SHA", flush=True)
fetch_ref(fallback)
if requested:
resolved = resolve_ref("refs/remotes/origin/checkout")
if resolved != requested and ref != requested:
print("::notice::checkout ref moved; fetching requested SHA", flush=True)
fetch_ref(requested)
resolved = resolve_ref("refs/remotes/origin/checkout")
if resolved != requested:
print("::error::checkout ref did not resolve to the requested SHA", file=sys.stderr)
raise GitFailure(1)
if kind == "preflight":
# Diff-base callers need parent commits/trees, not their blobs.
try:
fetch(workspace, resolve_ref("refs/remotes/origin/checkout"), prune=True,
depth=2, blobless=True, retry_failures=True)
except (FetchTimeout, GitFailure):
raise GitFailure(1)
run_git(workspace, "checkout", "--detach", "refs/remotes/origin/checkout")
def checkout_harness(sha):
action = ".github/actions/setup-node-env/action.yml"
node_setup_scripts = ("scripts/lib/pnpm-lockfile-documents.mjs",)
evidence_scripts = ("scripts/ios-screenshot-evidence.mjs", "scripts/lib/direct-run.mjs", "scripts/ci-static-step.sh")
platform_scripts = ("scripts/lib/swift-toolchain.sh", "scripts/lib/ci-ios-smoke-plan.mjs")
upgrade_scripts = ("scripts/lib/release-upgrade-baseline.mjs", "scripts/lib/release-version.mjs")
# Preflight imports these siblings by file-relative paths.
preflight_scripts = (
"scripts/ci-build-manifest.mjs",
"scripts/lib/ci-ios-smoke-plan.mjs",
"scripts/lib/release-context.mjs",
"scripts/lib/release-version.mjs",
)
npm_lock_scripts = (
"scripts/ci-npm-lock-admission.mjs",
"scripts/generate-npm-package-lock.mjs",
"scripts/generate-npm-package-lock.mts",
"scripts/changed-lanes.mts",
"scripts/lib/merge-head-diff-base.mjs",
)
linux_node_scripts = (*upgrade_scripts, *npm_lock_scripts, "scripts/ci-additional-checks.sh")
if kind == "linux-node" and not os.path.isfile(os.path.join(workspace, action)):
raise GitFailure(1)
harness = os.path.join(workspace, ".ci-harness")
# This owner creates the harness, not candidate source. Keep strict source-status
# checks useful without hiding tracked edits or similarly named nested paths.
exclude = os.path.join(workspace, git_output(workspace, "rev-parse", "--git-path", "info/exclude").strip())
os.makedirs(os.path.dirname(exclude), exist_ok=True)
with open(exclude, "a+b") as output:
output.seek(0)
if output.read().splitlines()[-1:] != [b"/.ci-harness/"]:
output.write(b"\n/.ci-harness/\n")
os.makedirs(harness, exist_ok=True)
if sha == os.environ["WORKFLOW_SHA"]:
# Export the workflow revision from the freshly populated index, replacing
# retained harness files without updating the index or trusting later edits.
pathspecs = [".github/actions", *node_setup_scripts]
if kind in ("platform", "linux-node"):
pathspecs += evidence_scripts
elif kind == "preflight":
pathspecs += preflight_scripts
if kind == "platform":
pathspecs += platform_scripts
if kind == "linux-node":
pathspecs += linux_node_scripts
paths = git_output(workspace, "ls-files", "-z", "--", *pathspecs).split("\0")[:-1]
run_git(workspace, "checkout-index", "--force", f"--prefix={harness}/", "--", *paths)
else:
run_git(harness, "init", harness)
run_git(harness, "remote", "add", "origin", remote)
sparse_paths = ["/.github/actions/", *(f"/{path}" for path in node_setup_scripts)]
if kind in ("platform", "linux-node"):
sparse_paths += [f"/{path}" for path in evidence_scripts]
if kind == "platform":
sparse_paths += [f"/{path}" for path in platform_scripts]
if kind == "linux-node":
sparse_paths += [f"/{path}" for path in linux_node_scripts]
# Rooted non-cone patterns keep the kind-owned workflow files exact.
# Sparse first, then blob-less avoids downloading a second repository snapshot.
run_git(harness, "sparse-checkout", "set", "--no-cone", *sparse_paths)
fetch(harness, f"+{os.environ['\''WORKFLOW_SHA'\'']}:refs/remotes/origin/ci-harness",
max_attempts=1, blobless=True)
# Checkout now materializes the sparse blobs over the network, so it carries the
# fetch deadline instead of running unbounded like a local checkout.
run_git(harness, "checkout", "--force", "--detach", os.environ["WORKFLOW_SHA"],
timeout=fetch_timeout_seconds)
if not os.path.isfile(os.path.join(harness, action)):
raise GitFailure(1)
check_cancelled()
def checkout():
check_cancelled()
prerequisites = json.loads(os.environ.get("CHECKOUT_GIT_COMMITS_JSON", "null")) if kind == "linux-node" else None
if prerequisites is None:
prerequisites = []
if not isinstance(prerequisites, list) or any(
not isinstance(commit, str) or not re.fullmatch("[0-9a-f]{40}", commit)
for commit in prerequisites
):
raise ValueError("Invalid immutable test prerequisite commits")
if reset:
os.makedirs(workspace, exist_ok=True)
# Every earlier Git group has been drained before deleting its workspace.
subprocess.run(["find", workspace, "-mindepth", "1", "-maxdepth", "1",
"-exec", "rm", "-rf", "{}", "+"], check=True)
run_git(workspace, "init", workspace)
if kind in ("linux-node", "android"):
run_git(workspace, "config", "--global", "--add", "safe.directory", workspace)
run_git(workspace, "config", "gc.auto", "0")
run_git(workspace, "remote", "add", "origin", remote)
if kind in ("preflight", "manual"):
checkout_selected_ref()
if kind == "preflight" and resolve_ref("HEAD") == os.environ["WORKFLOW_SHA"]:
checkout_harness(os.environ["WORKFLOW_SHA"])
return
target = "refs/remotes/origin/ci-target" if kind in ("linux-node", "android") else "refs/remotes/origin/checkout"
sha = "refs/heads/main" if kind == "clawhub" else os.environ["CHECKOUT_SHA"]
refs = [f"+{sha}:{target}"]
base = os.environ.get("CHECKOUT_BASE_SHA") if kind == "linux-node" else None
if base:
refs.append(f"+{base}:refs/remotes/origin/ci-ratchet-base")
# Fetch full reader objects with the authenticated checkout, before its
# credential scope ends and test workers create historical worktrees.
refs.extend(prerequisites)
fetch(workspace, *refs, prune=True, max_attempts=1 if reset else 3,
retry_codes=(124, 137) if kind == "skills" else ())
run_git(workspace, "checkout", *(["--force"] if reset else []), "--detach",
sha if kind in ("linux-node", "android") else target)
if kind == "android":
if not os.access(os.path.join(workspace, "apps/android/gradlew"), os.X_OK):
raise GitFailure(1)
return
if kind in ("clawhub", "skills"):
return
checkout_harness(sha)
def main():
global kind, workspace, remote, reset
if len(sys.argv) > 1:
if sys.argv[1] == "--policy":
# The caller supplies trusted policy bytes; imports share this exact
# owner and its terminal lifecycle state, never a second supervisor.
sys.modules["ci_git_owner"] = sys.modules[__name__]
try:
if sys.argv[2] == "-":
exec(compile(sys.stdin.read(), "<git-policy>", "exec"), {"__name__": "__main__"})
else:
runpy.run_path(sys.argv[2], run_name="__main__")
finally:
if closed:
raise RuntimeError("Git owner is closed")
check_cancelled()
return
if sys.argv[1] not in ("--git", "--checkout-git"):
raise ValueError("Unknown Git owner command")
run_git(os.getcwd(), *sys.argv[3:], timeout=float(sys.argv[2]) or None,
reclaim_locks=sys.argv[1] == "--checkout-git")
return
if git is None:
raise RuntimeError("Git unavailable")
kind = os.environ.get("CHECKOUT_KIND", "linux-node" if linux else "platform")
if kind == "prepare":
raise SystemExit(0)
workspace = os.environ["GITHUB_WORKSPACE"]
remote = f"https://github.com/{os.environ['\''CHECKOUT_REPO'\'']}.git"
# The workflow'\''s token is repository-bound; never lend it to a sibling checkout.
token = os.environ.pop("CHECKOUT_TOKEN", "")
if token and os.environ["CHECKOUT_REPO"] == os.environ.get("GITHUB_REPOSITORY"):
checkout_environment.update(git_auth_environment(remote, token))
del token
if kind == "clawhub":
workspace = os.path.join(workspace, "clawhub-source")
reset = kind in ("linux-node", "android", "clawhub")
label = "ClawHub checkout" if kind == "clawhub" else "checkout"
started_at = time.monotonic()
try:
for attempt in range(1, 6 if reset else 2):
try:
checkout()
if reset:
print(f"{label} attempt {attempt}/5 succeeded", flush=True)
if kind == "clawhub":
print(f"{label} completed in {int(time.monotonic() - started_at)}s", flush=True)
raise SystemExit(0)
except (FetchTimeout, GitFailure) as error:
# Only command failures are retryable. Ownership/inspection errors
# escape to the fail-closed boundary below, never workspace deletion.
check_cancelled()
if not reset:
raise SystemExit(124 if isinstance(error, FetchTimeout) else error.code)
print(f"::warning::{label} attempt {attempt}/5 failed", flush=True)
backoff(attempt * 5)
print(f"{label} failed after 5 attempts", file=sys.stderr)
raise SystemExit(1)
finally:
checkout_environment.clear()
def terminal_diagnostic(error, owner_code):
# Code identity, not a filename supplied by policy, proves source provenance.
codes = {id(owner_code): owner_code}
pending = [owner_code]
while pending:
for value in pending.pop().co_consts:
if type(value) is type(owner_code):
codes[id(value)] = value
pending.append(value)
names = {value: value.__name__ for value in vars(builtins).values()
if isinstance(value, type) and issubclass(value, BaseException)}
names.update({FetchTimeout: "FetchTimeout", GitFailure: "GitFailure"})
records, seen, via = [], set(), "terminal"
while error is not None and id(error) not in seen and len(records) < 4:
seen.add(id(error))
record = {"type": names.get(type(error), "unknown"), "via": via}
for field in ("errno", "winerror"):
value = getattr(error, field, None)
if type(value) is int and -(2 ** 31) <= value < 2 ** 32:
record[field] = value
frames, trace = [], error.__traceback__
# Bound traversal as well as output; malformed metadata cannot stall exit.
for _ in range(256):
if trace is None:
break
if type(trace) is not TracebackType:
raise TypeError
frame, code = trace.tb_frame, trace.tb_frame.f_code
if frame.f_globals is globals() and id(code) in codes and 0 < trace.tb_lineno < 2 ** 31:
frames.append({"function": code.co_name[:64], "line": trace.tb_lineno})
frames = frames[-6:]
trace = trace.tb_next
record["owner_frames"] = frames
if trace is not None:
record["traceback_truncated"] = 1
records.append(record)
cause = error.__cause__
error, via = (cause, "cause") if cause is not None else (error.__context__, "context")
return records
if __name__ == "__main__":
exit_code, terminal_error = 0, None
try:
main()
except FetchTimeout:
exit_code = 124
except GitFailure as error:
exit_code = error.code
except Exception as error:
exit_code, terminal_error = 125, error
# Leave the handler before diagnostics or exit can raise: older Python'\''s
# implicit exception chaining can loop on an already-cyclic context.
if terminal_error is not None:
name, diagnostic = "unknown", "unavailable"
try:
records = terminal_diagnostic(terminal_error, sys._getframe().f_code)
diagnostic = json.dumps(records, separators=(",", ":"))
name = records[0]["type"]
except BaseException:
pass # Diagnostics must never replace the authoritative terminal exit.
try:
print(f"::error::Git ownership/setup failed ({name}); refusing reuse or retry", file=sys.stderr)
print(f"[ci-git-owner] diagnostic={diagnostic}", file=sys.stderr)
except BaseException:
pass
raise SystemExit(exit_code)
'
# End generated CI Git owner.
- name: Resolve checkout SHA
id: checkout_ref
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"