forked from openclaw/openclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
5462 lines (5138 loc) · 293 KB
/
Copy pathci.yml
File metadata and controls
5462 lines (5138 loc) · 293 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:
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
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
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:
# Canonical main uses run-number parity for two non-canceling slots. Each
# slot keeps GitHub's single coalesced pending tip while its active run finishes.
group: ${{ 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.238.0"
IOS_SCREENSHOT_NODE_VERSION: "24.16.0"
IOS_SCREENSHOT_XCODE_VERSION: "Xcode 26.6 Build version 17F113"
NODE_VERSION: "24.x"
jobs:
# Preflight: establish routing truth and job matrices once, then let real
# work fan out from a single source of truth.
# Fork PRs cannot read base-repository vars, so their retries select hosted
# runners independently of the backend override, including preflight itself.
preflight:
permissions:
contents: read
if: github.event_name != 'pull_request' || !github.event.pull_request.draft
runs-on: ${{ (vars.OPENCLAW_CI_RUNNER_BACKEND == 'github' || vars.OPENCLAW_CI_RUNNER_BACKEND == 'hybrid') && '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' && (github.event_name != 'pull_request' || contains(fromJSON('["OWNER","MEMBER","COLLABORATOR","CONTRIBUTOR"]'), github.event.pull_request.author_association)) && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04') }}
timeout-minutes: 20
outputs:
checkout_revision: ${{ steps.checkout_ref.outputs.sha }}
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
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 }}
run_node: ${{ steps.manifest.outputs.run_node }}
# 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 }}
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_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 }}
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 }}
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_e2e_matrix: ${{ steps.manifest.outputs.ui_e2e_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_screenshots: ${{ steps.changed_scope.outputs.run_ios_screenshots }}
run_android_job: ${{ steps.manifest.outputs.run_android_job }}
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" ]; then
# Later fetch steps reuse workflow code outside the selected/deletable checkout.
cat > "$RUNNER_TEMP/ci-git-owner.py"
exec "$python_command" -I -S "$RUNNER_TEMP/ci-git-owner.py"
fi
exec "$python_command" -I -S -
}
run_owner <<'PYTHON'
# Generated from .github/actions/git-owner/owner.py; do not edit here.
import base64
import json
import os
import re
import runpy
import shutil
import signal
import subprocess
import sys
import tempfile
import time
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)
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 report EPERM for a zombie-only group. Only a checked
# census proving no live members can authorize continuing.
if group_alive(pgid, deadline):
raise
return False
return True
def group_alive(pgid, deadline):
try:
os.killpg(pgid, 0)
except ProcessLookupError:
return False
except PermissionError:
pass # EPERM can mean zombie-only; the census must still prove extinction.
# Zombies are terminated, not writers. A failed/ambiguous inspection
# never authorizes checkout reuse, including after a denied signal probe.
result = subprocess.run(
["ps", "-axo", "pgid=,stat="], stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE, text=True, check=True,
timeout=max(0.001, deadline - time.monotonic()),
)
return any(int(group) == pgid and not state.startswith("Z")
for group, state in (line.split() for line in result.stdout.splitlines()))
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()))
terminate_job(job, 1)
accounting = Accounting()
while True:
query_job(job, 1, c.byref(accounting), c.sizeof(accounting), None)
if accounting.ActiveProcesses == 0:
return
if time.monotonic() >= deadline:
raise RuntimeError("Job cleanup did not complete")
time.sleep(0.05)
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"
evidence_scripts = ("scripts/ios-screenshot-evidence.mjs", "scripts/lib/direct-run.mjs")
if kind == "linux-node" and not os.path.isfile(os.path.join(workspace, action)):
raise GitFailure(1)
harness = os.path.join(workspace, ".ci-harness")
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"]
if kind in ("platform", "linux-node"):
pathspecs += evidence_scripts
elif kind == "preflight":
pathspecs += ["scripts/lib/release-context.mjs", "scripts/lib/release-version.mjs"]
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/"]
if kind in ("platform", "linux-node"):
sparse_paths += [f"/{path}" for path in evidence_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"{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()
if __name__ == "__main__":
try:
main()
except FetchTimeout:
raise SystemExit(124)
except GitFailure as error:
raise SystemExit(error.code)
except Exception as error:
# Do not print command arguments or environment: Git may carry credentials.
print(f"::error::Git ownership/setup failed ({type(error).__name__}); refusing reuse or retry", file=sys.stderr)
raise SystemExit(125)
PYTHON
- name: Resolve checkout SHA
id: checkout_ref
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
# The owner exports matching revisions; retain Actions checkout's existing
# transport and retry contract for independently pinned workflow revisions.
- name: Checkout trusted CI harness
if: ${{ steps.checkout_ref.outputs.sha != github.workflow_sha }}
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.workflow_sha }}
path: .ci-harness
sparse-checkout: |
/.github/actions/
/scripts/lib/release-context.mjs
/scripts/lib/release-version.mjs
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Resolve logical runner profile
id: runner_profile
env:
AUTHOR_ASSOCIATION: ${{ github.event.pull_request.author_association || '' }}
CONFIGURED_RUNNER_PROFILE: ${{ vars.OPENCLAW_CI_RUNNER_BACKEND }}
HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name || '' }}
shell: bash
run: |
set -euo pipefail
runner_profile="${CONFIGURED_RUNNER_PROFILE:-blacksmith}"
case "$runner_profile" in
github | hybrid | blacksmith) ;;
*) echo "OPENCLAW_CI_RUNNER_BACKEND must be github, hybrid, or blacksmith" >&2; exit 1 ;;
esac
hosted_runner_profile_contract=false
grep -Fq "hosted-runner-profile-contract-v1" .github/workflows/ci.yml &&
hosted_runner_profile_contract=true
trusted_pull_request=false
case "$AUTHOR_ASSOCIATION" in
OWNER | MEMBER | COLLABORATOR | CONTRIBUTOR) trusted_pull_request=true ;;
esac
if [[
"$hosted_runner_profile_contract" == "true" &&
(
"$GITHUB_EVENT_NAME" == "workflow_dispatch" ||
"$GITHUB_REPOSITORY" != "openclaw/openclaw" ||
(
"$GITHUB_EVENT_NAME" == "pull_request" &&
("$HEAD_REPOSITORY" != "$GITHUB_REPOSITORY" || "$trusted_pull_request" != "true")
)
)
]]; then
runner_profile=github
fi
printf '%s\n' \
"hosted_runner_profile_contract=$hosted_runner_profile_contract" \
"runner_profile=$runner_profile" >> "$GITHUB_OUTPUT"
- name: Resolve exact diff base
id: diff_base
env:
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
EVENT_BASE_SHA: ${{ github.event_name == 'push' && github.event.before || github.event.pull_request.base.sha || '' }}
GH_TOKEN: ${{ github.event_name == 'workflow_dispatch' && !inputs.release_gate && github.token || '' }}
PULL_REQUEST_NUMBER: ${{ inputs.pull_request_number }}
RELEASE_GATE: ${{ inputs.release_gate }}
run: |
set -euo pipefail
base_sha="$EVENT_BASE_SHA"
head_sha="$(git rev-parse HEAD)"
if [ "$GITHUB_EVENT_NAME" = "push" ] && [[ "$base_sha" =~ ^0+$ ]]; then
echo "::error title=ambiguous main push::github.event.before is zero; refusing to infer a diff base for a created or recreated main branch." >&2
exit 1
fi
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
# A long-lived PR event can retain an old base SHA. The tested merge
# commit's first parent is the exact target tree for this run.
base_sha="$(node scripts/lib/merge-head-diff-base.mjs \
--base "$base_sha" --head HEAD --prefer-first-parent)"
fi
if [ "$GITHUB_EVENT_NAME" = "workflow_dispatch" ] && [ "$RELEASE_GATE" != "true" ]; then
encoded_ref="$(jq -rn --arg value "refs/heads/${DEFAULT_BRANCH}" '$value | @uri')"
default_sha="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${encoded_ref}" --jq .sha)"
if [[ ! "$default_sha" =~ ^[0-9a-f]{40}$ ]]; then
echo "Could not resolve the default branch head for the manual target." >&2
exit 1
fi
echo "default_sha=$default_sha" >> "$GITHUB_OUTPUT"
base_sha="$(
gh api --method GET \
"repos/${GITHUB_REPOSITORY}/compare/${default_sha}...${head_sha}" \
--jq '.merge_base_commit.sha'
)"
fi
if [ "$GITHUB_EVENT_NAME" = "workflow_dispatch" ] && [ "$RELEASE_GATE" = "true" ]; then
merge_ref="refs/remotes/origin/release-gate-merge"
python3 -I -S "$RUNNER_TEMP/ci-git-owner.py" --checkout-git 120 fetch \
--no-tags --no-recurse-submodules --depth=2 origin \
"+refs/pull/${PULL_REQUEST_NUMBER}/merge:${merge_ref}"
release_gate_head="$(git rev-parse "${merge_ref}^2")"
target_head="$(git rev-parse HEAD)"
if [ "$release_gate_head" != "$target_head" ]; then
echo "release_gate pull request head ${release_gate_head} does not match target ${target_head}" >&2
exit 1
fi
base_sha="$(git rev-parse "${merge_ref}^1")"
head_sha="$(git rev-parse "$merge_ref")"
fi
if [[ ! "$base_sha" =~ ^[0-9a-f]{40}$ ]]; then
echo "Could not resolve an exact diff base for ${GITHUB_EVENT_NAME}." >&2
exit 1
fi
echo "sha=$base_sha" >> "$GITHUB_OUTPUT"
echo "head_sha=$head_sha" >> "$GITHUB_OUTPUT"
- name: Validate historical release target
id: historical_target
if: inputs.historical_target_tag != ''
env:
EXPECTED_SHA: ${{ steps.checkout_ref.outputs.sha }}
GH_TOKEN: ${{ github.token }}
HISTORICAL_TARGET_TAG: ${{ inputs.historical_target_tag }}
run: |
set -euo pipefail
if [[ ! "$HISTORICAL_TARGET_TAG" =~ ^v[0-9]{4}\.[0-9]+\.[0-9]+((-(alpha|beta)\.[0-9]+)|(-[1-9][0-9]*))?$ ]]; then
echo "historical_target_tag must be a canonical OpenClaw release tag." >&2
exit 1
fi
encoded_ref="$(jq -rn --arg value "refs/tags/${HISTORICAL_TARGET_TAG}" '$value | @uri')"
tag_sha="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${encoded_ref}" --jq .sha)"
if [[ "$tag_sha" != "$EXPECTED_SHA" ]]; then
echo "Historical release tag ${HISTORICAL_TARGET_TAG} does not resolve to ${EXPECTED_SHA}." >&2
exit 1
fi
echo "eligible=true" >> "$GITHUB_OUTPUT"
- name: Validate release candidate target
id: release_candidate_target
if: inputs.release_candidate_ref != ''
env:
EXPECTED_SHA: ${{ steps.checkout_ref.outputs.sha }}
GH_TOKEN: ${{ github.token }}
RELEASE_CANDIDATE_REF: ${{ inputs.release_candidate_ref }}
run: |
set -euo pipefail
if [[ ! "$RELEASE_CANDIDATE_REF" =~ ^(release/[0-9]{4}\.[0-9]+\.[0-9]+(-[1-9][0-9]*)?|extended-stable/[0-9]{4}\.[0-9]+\.33)$ ]]; then
echo "release_candidate_ref must be a canonical OpenClaw release branch." >&2
exit 1
fi
encoded_ref="$(jq -rn --arg value "refs/heads/${RELEASE_CANDIDATE_REF}" '$value | @uri')"
branch_sha="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${encoded_ref}" --jq .sha)"
if [[ "$branch_sha" != "$EXPECTED_SHA" ]]; then
echo "Release candidate branch ${RELEASE_CANDIDATE_REF} does not resolve to ${EXPECTED_SHA}." >&2
exit 1
fi
echo "eligible=true" >> "$GITHUB_OUTPUT"
- name: Validate target context
id: target_context_target
if: inputs.target_context_ref != ''
env:
GH_TOKEN: ${{ github.token }}
TARGET_CONTEXT_REF: ${{ inputs.target_context_ref }}
TARGET_REF: ${{ inputs.target_ref }}
run: |
set -euo pipefail
if [[ ! "$TARGET_CONTEXT_REF" =~ ^(release/[0-9]{4}\.[0-9]+\.[0-9]+(-[1-9][0-9]*)?|extended-stable/[0-9]{4}\.[0-9]+\.33)$ ]]; then
echo "target_context_ref must be a canonical OpenClaw release branch." >&2
exit 1
fi
if [[ ! "$TARGET_REF" =~ ^[0-9a-f]{40}$ ]]; then
echo "target_context_ref requires target_ref to be a full commit SHA." >&2
exit 1
fi
encoded_ref="$(jq -rn --arg value "refs/heads/${TARGET_CONTEXT_REF}" '$value | @uri')"
branch_sha="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${encoded_ref}" --jq .sha)"
if [[ ! "$branch_sha" =~ ^[0-9a-f]{40}$ ]]; then
echo "target_context_ref branch ${TARGET_CONTEXT_REF} does not exist." >&2
exit 1
fi
comparison_status="$(
gh api "repos/${GITHUB_REPOSITORY}/compare/${TARGET_REF}...${branch_sha}" --jq .status
)"
if [[ "$comparison_status" != "ahead" && "$comparison_status" != "identical" ]]; then
echo "target_ref must be the declared release branch head or one of its ancestors." >&2
exit 1
fi
echo "eligible=true" >> "$GITHUB_OUTPUT"
- name: Setup manifest TypeScript runtime
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: ${{ env.NODE_VERSION }}
- name: Resolve release correction base
id: release_correction_base
if: github.event_name == 'workflow_dispatch' && (inputs.release_scope == 'npm-beta' || inputs.release_scope == 'npm-stable')
env:
GH_TOKEN: ${{ github.token }}
TARGET_CONTEXT_REF: ${{ steps.target_context_target.outputs.eligible == 'true' && inputs.target_context_ref || steps.historical_target.outputs.eligible == 'true' && inputs.historical_target_tag || '' }}
run: |
# Keep the token outside the manifest step, which imports candidate-owned code.
node --input-type=module <<'NODE'
import { execFileSync } from 'node:child_process';
import { appendFileSync, readFileSync } from 'node:fs';
import { resolveReleaseContextIdentity } from './.ci-harness/scripts/lib/release-context.mjs';
const version = JSON.parse(readFileSync('package.json', 'utf8')).version;
const identity = resolveReleaseContextIdentity(process.env.TARGET_CONTEXT_REF, version);
if (identity?.baseTag) {
const ref = encodeURIComponent(`refs/tags/${identity.baseTag}`);
const sha = execFileSync('gh', ['api', `repos/${process.env.GITHUB_REPOSITORY}/commits/${ref}`, '--jq', '.sha'], { encoding: 'utf8' }).trim();
if (!/^[0-9a-f]{40}$/u.test(sha)) throw new Error(`Could not resolve correction base ${identity.baseTag}.`);
appendFileSync(process.env.GITHUB_OUTPUT, `sha=${sha}\n`);
}
NODE
- name: Classify candidate cache trust
id: candidate_trust
env:
CHECKOUT_REVISION: ${{ steps.checkout_ref.outputs.sha }}
DEFAULT_SHA: ${{ steps.diff_base.outputs.default_sha }}
HISTORICAL_TARGET: ${{ steps.historical_target.outputs.eligible || 'false' }}
RELEASE_CANDIDATE_TARGET: ${{ steps.release_candidate_target.outputs.eligible || 'false' }}
RELEASE_GATE: ${{ inputs.release_gate && 'true' || 'false' }}
TARGET_CONTEXT_TARGET: ${{ steps.target_context_target.outputs.eligible || 'false' }}
TARGET_REF: ${{ inputs.target_ref }}
WORKFLOW_REVISION: ${{ github.workflow_sha }}
run: |
set -euo pipefail
trust=untrusted
cache_mode=off
cache_write_allowed=false
if [[ "$GITHUB_EVENT_NAME" == "push" && "$GITHUB_REF" == "refs/heads/main" ]]; then
trust=main
cache_mode=restore
cache_write_allowed=true
elif [[ "$GITHUB_EVENT_NAME" == "pull_request" ]]; then
trust=pull-request
cache_mode=restore
elif [[ "$GITHUB_EVENT_NAME" == "workflow_dispatch" ]]; then
if [[ "$RELEASE_GATE" == "true" ]]; then
trust=pull-request
cache_mode=restore
elif [[
"$HISTORICAL_TARGET" == "true" ||
"$RELEASE_CANDIDATE_TARGET" == "true" ||
"$TARGET_CONTEXT_TARGET" == "true"
]]; then
trust=release
cache_mode=restore
cache_write_allowed=true
elif [[ -n "$DEFAULT_SHA" && "$CHECKOUT_REVISION" == "$DEFAULT_SHA" ]]; then
trust=main
cache_mode=restore
cache_write_allowed=true
elif [[ -z "$TARGET_REF" && "$CHECKOUT_REVISION" == "$WORKFLOW_REVISION" ]]; then
trust=workflow
cache_mode=restore
fi
fi
{
echo "trust=$trust"
echo "cache_mode=$cache_mode"
echo "cache_write_allowed=$cache_write_allowed"