Repository navigation
Expand file tree
/
Copy pathentrypoint.sh
More file actions
3247 lines (3101 loc) · 172 KB
/
Copy pathentrypoint.sh
File metadata and controls
3247 lines (3101 loc) · 172 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
#!/bin/sh
set -e
export TZ="${TZ:-America/New_York}"
export HIVE_API_PORT="${HIVE_API_PORT:-3002}"
export HIVE_PROXY_PORT="${HIVE_PROXY_PORT:-3001}"
export HIVE_STATIC_DIR="${HIVE_STATIC_DIR:-/opt/hive/proxy/public}"
# Packet mark (fwmark / SO_MARK) used to exempt the MITM proxy's OWN upstream
# :443 dials from the forced-egress redirect, so its traffic is not looped back
# into itself. This is the SINGLE SOURCE OF TRUTH: it is exported here (in both
# the root and the re-exec'd dev pass) so the iptables `-m mark --mark` exemption
# below and the Go proxy (which reads HIVE_PROXY_EGRESS_MARK, defaulting to this
# same 0x1112) stay in lockstep. Unlike `-m owner --uid-owner`, a packet mark
# needs no xt_owner kernel module, so the exemption works on BOTH OKE and
# OpenShift/OVN (where xt_owner is absent). Value is arbitrary but must match the
# Go default (proxy.defaultProxyEgressMark).
export HIVE_PROXY_EGRESS_MARK="${HIVE_PROXY_EGRESS_MARK:-0x1112}"
# Distinct preflight exit code (#3760 follow-up) for the "refusing to start
# because CAP_NET_ADMIN is missing" case, so an operator or orchestrator can
# tell it apart from every other startup failure in this script (bad config,
# missing iptables binary, netfilter lock contention — all still plain `exit
# 1`) from the exit code alone, without parsing the log. 77 is sysexits.h's
# EX_NOPERM ("permission denied"), the closest standard-adjacent match for
# "the container was not granted a capability it needs" — chosen over a
# script-local number so it means the same thing to anyone who already knows
# sysexits.h. See the FATAL branch below and src/docs/net-admin-requirement.md.
#
# The SAME code is reused (#6003) for the sibling preflight failure "the node's
# kernel does not provide a netfilter extension the forced-egress ruleset needs"
# (xt_owner / xt_REDIRECT). It is the same class of problem from the operator's
# side: the container was granted everything the manifest can grant, and the
# host still cannot supply what the egress gate requires, so the environment -
# not the image or the config - has to change. Both cases exit 77 with a FATAL
# line naming exactly what is missing.
EXIT_NET_ADMIN_REQUIRED=77
# ── Config backup/restore across container recreation ─────────────────
# When Watchtower recreates the container (pull new image, stop old, start
# new), the Go binary's config.Save() may write an empty/default config to
# the bind-mounted hive.yaml during shutdown or early startup, wiping the
# host file. /data/ is a Docker named volume that persists across container
# recreations, so we keep a rolling backup there.
#
# In Kubernetes, the ConfigMap is the source of truth — admins update it to
# change settings like acmm_level, is_public, etc. The PVC copy is only
# used for disaster recovery if the ConfigMap volume is missing or empty.
#
# In Docker/LXC there is no ConfigMap and no overlay: the PVC copy IS the
# boot-time source of truth, restored over the config path (or read directly
# when that path is read-only) on every boot. See the Docker branch below.
#
# ── Naming: hive.yaml.runtime, formerly hive.yaml.bak ─────────────────
# The old .bak name implied "the restorable backup", which is only half
# true and cost real debugging time: on K8s it is a post-merge SNAPSHOT
# written after the merge, while on Docker/LXC it is a live boot INPUT.
# ".runtime" is honest for both — it is the runtime config as this hive
# last had it.
#
# MIGRATION (one release): ~51 live hives have only the old-named file on
# their PVC. We WRITE the new name and READ the old one when the new is
# absent. We deliberately do NOT rename on the PVC: on Docker/LXC that
# file is the only copy of the live config, and mutating it at boot risks
# losing owner customisations with no warning. The old name is picked up
# read-only until the first save writes the new one, after which both
# exist and the new one wins. Once the new name is the boot source, every
# clean boot refreshes the old name from it (#17862) so the fallback is
# never months stale; see hive_refresh_legacy_fallback.
HIVE_CONFIG_PATH="${HIVE_CONFIG:-/etc/hive/hive.yaml}"
HIVE_CONFIG_RUNTIME="/data/hive.yaml.runtime"
HIVE_CONFIG_RUNTIME_LEGACY="/data/hive.yaml.bak"
# The uid/gid the hive process actually runs as after the privilege drop
# further down (setpriv/gosu to dev). 0600 is an OWNER-only mode, so every
# hardened config copy has to be owned by THIS user or the owner of the file
# is not the reader of the file — see hive_harden_runtime_config.
HIVE_RUNTIME_USER="dev"
HIVE_RUNTIME_GROUP="node"
# UID-isolation ownership migrations are deliberately versioned separately
# from the image. Keying the marker to every image SHA would turn every edge
# rollout back into an O(size of PVC) walk; bump this only when the ownership
# contract itself changes and an existing tree needs another full pass.
HIVE_UID_ISOLATION_REVISION="2"
HIVE_UID_MAP_PERSISTED="${HIVE_UID_MAP_PERSISTED:-/data/.hive/uid-map.json}"
HIVE_UID_MAP_RUNTIME="${HIVE_UID_MAP_RUNTIME:-/var/run/hive/uid-map.json}"
HIVE_UID_ISOLATION_MARKER_DIR="${HIVE_UID_ISOLATION_MARKER_DIR:-/data/.hive/uid-isolation}"
export HIVE_UID_ISOLATION_REVISION HIVE_UID_ISOLATION_MARKER_DIR HIVE_UID_MAP_PERSISTED HIVE_UID_MAP_RUNTIME
hive_uid_isolation_marker_path() {
echo "${HIVE_UID_ISOLATION_MARKER_DIR}/agent-$1.ready"
}
hive_uid_isolation_marker_matches() {
[ -f "$1" ] && [ "$(cat "$1" 2>/dev/null || true)" = "$2" ]
}
hive_publish_uid_isolation_marker() {
_marker_path="$1"
_marker_value="$2"
_marker_tmp="${_marker_path}.tmp.$$"
if printf '%s\n' "$_marker_value" > "$_marker_tmp" 2>/dev/null \
&& chmod 0644 "$_marker_tmp" 2>/dev/null \
&& mv -f "$_marker_tmp" "$_marker_path" 2>/dev/null; then
return 0
fi
rm -f "$_marker_tmp" 2>/dev/null || true
echo "[entrypoint] WARN: could not publish UID-isolation marker $_marker_path; the affected agent will remain held rather than enter a partially migrated tree"
return 1
}
# Run every operation whose cost scales with persistent-volume size outside
# PID 1's startup path. The Go server can therefore bind :3002 and satisfy the
# startup probe while a version flip repairs a months-old NFS tree. The UID map
# tells the Go manager which protected markers to await before launching each
# agent, so making the walk asynchronous does not create a partially-isolated
# execution window.
hive_run_uid_isolation_migration() {
_home_marker="${HIVE_UID_ISOLATION_MARKER_DIR}/home.ready"
if [ "${HIVE_HOME_MIGRATION_NEEDED:-false}" = "true" ]; then
echo "[entrypoint] UID isolation: repairing shared home in background"
chown -R dev:node /data/home/.claude /data/home/.codex /data/home/.gemini /data/home/.bob 2>/dev/null \
|| echo "[entrypoint] WARN: shared-home chown was incomplete; continuing with the existing fail-open permission policy"
if [ "${HIVE_HOME_MODE_REPAIR_NEEDED:-false}" = "true" ]; then
chmod -R g+rwX /data/home 2>/dev/null \
|| echo "[entrypoint] WARN: chmod -R g+rwX /data/home failed — is CAP_FOWNER in the pod's capabilities.add? Continuing; agents may hit EACCES under /data/home"
# The shared Claude settings.json stays hive-owned and not group-writable (#17059).
[ -L /data/home/.claude/settings.json ] || chmod go-w /data/home/.claude/settings.json 2>/dev/null || true
find /data/home -type d -exec chmod g+s {} + 2>/dev/null \
|| echo "[entrypoint] WARN: chmod g+s on /data/home dirs failed — is CAP_FOWNER/CAP_FSETID in the pod's capabilities.add? Continuing"
fi
# A marker records that the best-effort pass COMPLETED, matching the old
# fail-open behaviour when chown/chmod encounter an NFS race. A command
# failure is still logged above; withholding the marker forever would turn
# a recoverable permissions warning into a fleet-wide agent outage.
hive_publish_uid_isolation_marker "$_home_marker" "$HIVE_UID_ISOLATION_REVISION" || true
echo "[entrypoint] UID isolation: shared-home pass complete"
fi
printf '%s\n' "$AGENT_UID_LINES" | while IFS="$(printf '\t')" read -r _agent_name _agent_uid; do
[ -n "$_agent_name" ] || continue
_agent_dir="/data/agents/${_agent_name}"
_agent_marker="$(hive_uid_isolation_marker_path "$_agent_uid")"
_agent_expected="${HIVE_UID_ISOLATION_REVISION}:${_agent_uid}"
_agent_owner="$(stat -c '%u' "$_agent_dir" 2>/dev/null || echo 0)"
if hive_uid_isolation_marker_matches "$_agent_marker" "$_agent_expected" \
&& [ "$_agent_owner" = "$_agent_uid" ]; then
echo "[entrypoint] UID isolation: ${_agent_name} already current — skipping"
else
echo "[entrypoint] UID isolation: repairing ${_agent_name} (uid ${_agent_uid}) in background"
hive_reown_agent_paths_if_needed "$_agent_name" "$_agent_uid"
if [ -d "$_agent_dir" ] && ! [ -L "$_agent_dir" ]; then
chmod g+rwX "$_agent_dir" 2>/dev/null || true
fi
hive_publish_uid_isolation_marker "$_agent_marker" "$_agent_expected" || true
echo "[entrypoint] UID isolation: ${_agent_name} pass complete"
fi
done
}
hive_start_uid_isolation_migration() {
hive_run_uid_isolation_migration &
echo "[entrypoint] UID-isolation migration running in background (PID $!)"
}
# Build the stable per-agent UID allocation. The persisted map on /data is the
# source of truth across image upgrades; /var/run receives a runtime copy for
# the proxy and Go manager. On the first boot after this logic lands, existing
# PVC ownership is adopted before allocating any new UID, so an already-shifted
# fleet becomes self-consistent without a full-volume chown.
hive_build_uid_map() {
python3 - <<'PY'
import json
import os
import subprocess
base = int(os.environ.get('HIVE_UID_BASE', '2001'))
proxy_uid = int(os.environ.get('PROXY_UID', '1001'))
persisted_path = os.environ.get('HIVE_UID_MAP_PERSISTED', '/data/.hive/uid-map.json')
runtime_path = os.environ.get('HIVE_UID_MAP_RUNTIME', '/var/run/hive/uid-map.json')
data_root = os.environ.get('HIVE_DATA_ROOT', '/data').rstrip('/') or '/data'
names = sorted({n.strip() for n in os.environ.get('AGENT_NAMES', '').splitlines() if n.strip()})
def load_map(path):
try:
with open(path) as f:
raw = json.load(f) or {}
except FileNotFoundError:
return None
except (ValueError, OSError) as e:
# A 0-byte or truncated map (seen fleet-wide after node crashes on
# cephfs-backed /data) must not abort UID isolation for every later
# boot; treat it as absent so UIDs are recovered from dir ownership.
print('[entrypoint] WARN: persisted UID map %s unreadable (%s); rebuilding' % (path, e), file=os.sys.stderr)
return None
if not isinstance(raw, dict):
print('[entrypoint] WARN: persisted UID map %s is not an object; rebuilding' % path, file=os.sys.stderr)
return None
agents = {}
for name, uid in (raw.get('agents') or {}).items():
try:
agents[str(name)] = int(uid)
except (TypeError, ValueError):
pass
raw['agents'] = agents
return raw
def stat_uid(path):
try:
out = subprocess.check_output(['stat', '-c', '%u', path], stderr=subprocess.DEVNULL, text=True)
return int(out.strip())
except Exception:
return None
uid_map = load_map(persisted_path)
observed_uids = []
if uid_map is None:
uid_map = {'agents': {}}
candidates = {}
counts = {}
for name in names:
for root in ('home/agents', 'agents', 'beads'):
uid = stat_uid(f'{data_root}/{root}/{name}')
if uid is not None and uid >= base:
candidates[name] = uid
observed_uids.append(uid)
counts[uid] = counts.get(uid, 0) + 1
break
for name, uid in candidates.items():
if counts.get(uid) == 1:
uid_map['agents'][name] = uid
agents = uid_map.setdefault('agents', {})
max_uid = base - 1
for uid in agents.values():
try:
uid = int(uid)
except (TypeError, ValueError):
continue
if uid > max_uid:
max_uid = uid
for uid in observed_uids:
if uid > max_uid:
max_uid = uid
for name in names:
if name not in agents:
max_uid += 1
agents[name] = max_uid
uid_map['agents'] = {name: int(uid) for name, uid in agents.items()}
uid_map['proxy_uid'] = proxy_uid
uid_map['base_uid'] = base
uid_map['iptables_active'] = False
uid_map['isolation_marker_dir'] = os.environ['HIVE_UID_ISOLATION_MARKER_DIR']
uid_map['isolation_revision'] = os.environ['HIVE_UID_ISOLATION_REVISION']
for path in (persisted_path, runtime_path):
directory = os.path.dirname(path)
if directory:
os.makedirs(directory, exist_ok=True)
tmp = f'{path}.tmp.{os.getpid()}'
with open(tmp, 'w') as f:
json.dump(uid_map, f, indent=2)
f.write('\n')
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
print('[entrypoint] UID map written to %s and %s' % (persisted_path, runtime_path), file=os.sys.stderr)
for name in names:
print('%s\t%s' % (name, uid_map['agents'][name]))
PY
}
# hive_reown_marker_path <path> prints the per-tree completion marker for the
# incremental re-own below (#9692). Markers live under /data/.hive (dev:node
# 0700), NOT inside the agent's own tree: an agent owns its home, so a marker
# there could be forged by the very uid it vouches for. The path is flattened
# into a single file name; agent names never contain "/", so two trees cannot
# map to one marker.
hive_reown_marker_path() {
_reown_marker_dir="${HIVE_REOWN_MARKER_DIR:-${HIVE_DATA_ROOT:-/data}/.hive/reown}"
_reown_marker_key="$(printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_')"
echo "${_reown_marker_dir}/${_reown_marker_key}.done"
}
# hive_reown_path_if_needed <path> <uid> gives every entry under <path> to
# <uid>:node, and runs on PID 1's startup path before the server binds.
#
# #9692: this used to be a synchronous `chown -R` of the whole tree whenever
# the top-level owner differed. On the first boot of the per-agent-UID build a
# large agent home outlasted the hosted spoke's startup probe, kubelet killed
# the container mid-walk, and the next boot started the whole tree over, so a
# spoke could crash-loop on its own migration. It is now:
#
# - incremental: `find \! -uid` selects only entries NOT already owned by
# <uid>, so a restarted pod resumes where it was killed instead of
# re-chowning what it already did;
# - skipped once complete: a marker recording <uid> is written only after a
# walk finishes with no error. A later boot whose marker matches AND whose
# top-level entry is still owned by <uid> costs one stat;
# - post-order (-depth): the top-level entry is changed last, so it still
# reads as the old owner until every entry below it has been handed over.
#
# Symlinks: `chown -R` without -H/-L changes a symlink itself and never follows
# it (coreutils forces --no-dereference under -R -P). find's default -P plus
# `chown -h` is the same contract, so this cannot be steered through a link an
# agent planted in its own home.
#
# Killed at any point: entries already chowned stay chowned, the marker is not
# yet written (or is written atomically via rename), so the next boot walks
# again and only touches what is left.
hive_reown_path_if_needed() {
_reown_path="$1"
_reown_uid="$2"
[ -e "$_reown_path" ] || return 0
_reown_owner="$(stat -c '%u' "$_reown_path" 2>/dev/null || echo 0)"
_reown_marker="$(hive_reown_marker_path "$_reown_path")"
if [ "$_reown_owner" = "$_reown_uid" ] && [ -f "$_reown_marker" ] \
&& [ "$(cat "$_reown_marker" 2>/dev/null || true)" = "$_reown_uid" ]; then
return 0
fi
_reown_marker_parent="$(dirname "$_reown_marker")"
mkdir -p "$_reown_marker_parent" 2>/dev/null || true
chmod 0700 "$_reown_marker_parent" 2>/dev/null || true
# The changed-entry list only feeds the progress count. If it cannot be
# created the walk must still run, so fall back to /dev/null rather than
# letting a failed redirect skip the chown.
_reown_list="$(mktemp "${_reown_marker}.changed.XXXXXX" 2>/dev/null || echo /dev/null)"
_reown_start="$(date +%s)"
_reown_ok=0
if find "$_reown_path" -depth \! -uid "$_reown_uid" \
-exec chown -h "${_reown_uid}:node" {} + -print > "$_reown_list" 2>/dev/null; then
_reown_ok=1
fi
_reown_elapsed=$(( $(date +%s) - _reown_start ))
if [ "$_reown_list" = /dev/null ]; then
_reown_changed="?"
else
_reown_changed="$(wc -l < "$_reown_list" 2>/dev/null | tr -d ' ' || true)"
rm -f "$_reown_list" 2>/dev/null || true
fi
[ -n "$_reown_changed" ] || _reown_changed="?"
if [ "$_reown_ok" != 1 ]; then
echo "[entrypoint] WARN: re-own of ${_reown_path} to ${_reown_uid} incomplete (${_reown_changed} entries attempted, ${_reown_elapsed}s); the next boot resumes with only the entries still mis-owned"
return 0
fi
_reown_marker_tmp="$(mktemp "${_reown_marker}.tmp.XXXXXX" 2>/dev/null || true)"
if [ -n "$_reown_marker_tmp" ] \
&& printf '%s\n' "$_reown_uid" > "$_reown_marker_tmp" 2>/dev/null \
&& mv -f "$_reown_marker_tmp" "$_reown_marker" 2>/dev/null; then
:
else
[ -z "$_reown_marker_tmp" ] || rm -f "$_reown_marker_tmp" 2>/dev/null || true
echo "[entrypoint] WARN: could not record re-own marker ${_reown_marker}; the next boot re-walks ${_reown_path} (cheap: nothing left to change)"
fi
if [ "$_reown_owner" != "$_reown_uid" ] || [ "$_reown_changed" != 0 ]; then
echo "[entrypoint] re-owned ${_reown_path} ${_reown_owner}→${_reown_uid} (${_reown_changed} entries changed, ${_reown_elapsed}s)"
else
echo "[entrypoint] re-own: ${_reown_path} already owned by ${_reown_uid} (0 entries changed, ${_reown_elapsed}s)"
fi
}
hive_reown_agent_paths_if_needed() {
_reown_agent="$1"
_reown_uid="$2"
_reown_data_root="${HIVE_DATA_ROOT:-/data}"
hive_reown_path_if_needed "${_reown_data_root}/home/agents/${_reown_agent}" "$_reown_uid"
hive_reown_path_if_needed "${_reown_data_root}/beads/${_reown_agent}" "$_reown_uid"
hive_reown_path_if_needed "${_reown_data_root}/agents/${_reown_agent}" "$_reown_uid"
}
hive_reown_agent_token_caches_if_needed() {
_token_agent="$1"
_token_group="$2"
_token_root="${HIVE_AGENT_TOKEN_ROOT:-/var/run/hive-metrics/agent-tokens}"
_token_expected="$(id -u dev 2>/dev/null || echo 1001):${_token_group}"
for _token_path in "$_token_root/gh-token-${_token_agent}.cache" \
"$_token_root/gh-token-${_token_agent}.cache".* \
"$_token_root/gh-token-${_token_agent}"-[0-9]*.cache; do
[ -e "$_token_path" ] || continue
_token_owner="$(stat -c '%u:%G' "$_token_path" 2>/dev/null || echo 0:unknown)"
if [ "$_token_owner" != "$_token_expected" ]; then
chown "dev:${_token_group}" "$_token_path" 2>/dev/null || true
chmod 640 "$_token_path" 2>/dev/null || true
echo "[entrypoint] re-owned ${_token_path} ${_token_owner}→${_token_expected}"
fi
done
}
hive_ensure_agent_user() {
_agent_name="$1"
_agent_uid="$2"
_agent_user="hive-${_agent_name}"
_uid_owner="$(getent passwd "$_agent_uid" 2>/dev/null | awk -F: '{print $1}')"
if [ -n "$_uid_owner" ] && [ "$_uid_owner" != "$_agent_user" ]; then
case "$_uid_owner" in
hive-*) userdel "$_uid_owner" 2>/dev/null || true ;;
esac
fi
if id "$_agent_user" >/dev/null 2>&1; then
_current_uid="$(id -u "$_agent_user" 2>/dev/null || echo 0)"
if [ "$_current_uid" != "$_agent_uid" ]; then
usermod -u "$_agent_uid" -g node -d /data/home -s /bin/bash "$_agent_user" 2>/dev/null \
|| { userdel "$_agent_user" 2>/dev/null || true; useradd --system -u "$_agent_uid" -g node -d /data/home -M -s /bin/bash "$_agent_user" 2>/dev/null || true; }
fi
else
useradd --system -u "$_agent_uid" -g node -d /data/home -M -s /bin/bash "$_agent_user" 2>/dev/null || true
fi
}
# hive_collect_agent_names <config> prints, one per line and sorted, every agent
# name that needs a per-agent user, private token group and token cache file:
# the config's agents (map keys or list items), the copies its `replicas:`
# settings create, and, when an ACMM level is in force, the ACMM pack agents.
#
# ACMM packs (#16803): the runtime applies a pack at boot from the config's
# acmm_level, the level persisted in /data/hive-state.json, or HIVE_LEVEL
# (planACMMBoot), and the pack apply creates agents such as strategist that
# need not be in the config yet. Keying the pack lookup on HIVE_LEVEL alone
# left those agents without a pre-created token cache whenever the level came
# from the config or persisted state, so their scoped token was unreadable.
#
# Replicas (#13166): config.ExpandAgentReplicas derives <agent>-2 ..
# <agent>-N in memory and MarshalYAML strips them on save, so they never
# appear as keys here. Without listing them, a replica gets no user, group or
# pre-created token file: the manager runs it as a bare <uid>:<gid> and the
# token write creates the cache dev:node 0600, which the replica cannot read,
# so every gh call is blocked with token_cache_unavailable. The naming and the
# 2..MaxAgentReplicas (5) bound mirror config.replicaAgentName and
# ExpandAgentReplicas; an out-of-range count is left for config validation to
# reject and expands to nothing here.
#
# Review heads (#13542): agents.<base>.review_heads derives
# <base>-<alias>-<n> per head and replica the same way, with alias the head's
# `alias` or a slug of <backend>-<model>. head_names mirrors
# config.ReviewHeadAgentName / reviewHeadSlug / ReviewHead.EffectiveAlias.
#
# Reviewer autoscale (#14685): review.reviewers.autoscale grows the lane's
# base agent up to `max` replicas at runtime, so those names are pre-created
# here too. autoscale_lane mirrors config.ReviewerAutoscaleAgent (the
# configured agent, else the first name-sorted enabled role:reviewer agent,
# else review.reviewer_agents[0]) and the default/ceiling mirror
# DefaultReviewerAutoscaleMax / MaxAgentReplicas.
hive_collect_agent_names() {
HIVE_COLLECT_CONFIG="$1" python3 - <<'PY'
import glob, json, os, yaml
MAX_REPLICAS = 5 # config.MaxAgentReplicas
AUTOSCALE_DEFAULT_MAX = 4 # config.DefaultReviewerAutoscaleMax
def replica_names(name, spec, floor=0):
if not isinstance(spec, dict):
return []
try:
n = int(spec.get('replicas') or 0)
except (TypeError, ValueError):
return []
n = max(n, floor)
if n < 2 or n > MAX_REPLICAS:
return []
return ['%s-%d' % (name, i) for i in range(2, n + 1)]
def autoscale_lane(cfg, agent_specs):
review = cfg.get('review') if isinstance(cfg.get('review'), dict) else {}
reviewers = review.get('reviewers') if isinstance(review.get('reviewers'), dict) else {}
auto = reviewers.get('autoscale') if isinstance(reviewers.get('autoscale'), dict) else {}
if not auto.get('enabled'):
return None, 0
try:
mx = int(auto.get('max') or 0) or AUTOSCALE_DEFAULT_MAX
except (TypeError, ValueError):
mx = AUTOSCALE_DEFAULT_MAX
mx = min(mx, MAX_REPLICAS)
lane = str(auto.get('agent') or '').strip()
if lane:
return (lane if lane in agent_specs else None), mx
for name in sorted(agent_specs):
spec = agent_specs[name]
if isinstance(spec, dict) and spec.get('enabled', True) is not False and str(spec.get('role') or '').strip().lower() == 'reviewer':
return name, mx
for name in review.get('reviewer_agents') or []:
if name in agent_specs:
return name, mx
return None, 0
def head_slug(s):
out, dash = [], False
for ch in str(s or '').strip().lower():
if ('a' <= ch <= 'z') or ('0' <= ch <= '9'):
out.append(ch)
dash = False
elif not dash and out:
out.append('-')
dash = True
return ''.join(out).rstrip('-')
def head_alias(h):
alias = head_slug(h.get('alias'))
if alias:
return alias
backend, model = head_slug(h.get('backend')), head_slug(h.get('model'))
if not backend:
return model
if model == backend or model.startswith(backend + '-'):
return model
if not model:
return backend
return backend + '-' + model
def head_names(name, spec):
if not isinstance(spec, dict) or not isinstance(spec.get('review_heads'), list):
return []
out = []
for h in spec['review_heads']:
if not isinstance(h, dict) or not str(h.get('backend') or '').strip() or not str(h.get('model') or '').strip():
continue
alias = head_alias(h)
try:
n = int(h.get('replicas') or 0) or 1
except (TypeError, ValueError):
continue
if not alias or n < 1 or n > MAX_REPLICAS:
continue
out += ['%s-%s-%d' % (name, alias, i) for i in range(1, n + 1)]
return out
# Mirrors planACMMBoot: any of HIVE_LEVEL, the config's acmm_level or the
# persisted level makes the runtime apply a pack at boot.
def acmm_level_set(cfg):
if os.environ.get('HIVE_LEVEL', '') or cfg.get('acmm_level'):
return True
try:
with open(os.environ.get('HIVE_STATE_FILE', '/data/hive-state.json')) as sf:
state = json.load(sf)
return isinstance(state, dict) and bool(state.get('acmm_level'))
except Exception:
return False
names = set()
with open(os.environ['HIVE_COLLECT_CONFIG']) as f:
cfg = yaml.safe_load(f) or {}
agents = cfg.get('agents', {})
agent_specs = {}
if isinstance(agents, dict):
agent_specs = dict(agents)
elif isinstance(agents, list):
agent_specs = {a['name']: a for a in agents if isinstance(a, dict) and 'name' in a}
lane, lane_max = autoscale_lane(cfg, agent_specs)
for name, spec in agent_specs.items():
names.add(name)
names.update(replica_names(name, spec, lane_max if name == lane else 0))
names.update(head_names(name, spec))
# Also check pack YAML when an ACMM level is in force
if acmm_level_set(cfg):
pack_dirs = os.environ.get('HIVE_PACK_DIRS', '/opt/hive/packs /data/packs').split()
for p in [f for d in pack_dirs for f in glob.glob(os.path.join(d, 'level-*.yaml'))]:
try:
with open(p) as pf:
pack = yaml.safe_load(pf) or {}
pack_agents = pack.get('agents', [])
if isinstance(pack_agents, list):
for a in pack_agents:
if isinstance(a, dict) and 'name' in a:
names.add(a['name'])
elif isinstance(pack_agents, dict):
names.update(pack_agents.keys())
except Exception:
pass
print('\n'.join(sorted(names)))
PY
}
# hive_harden_runtime_config makes $1 readable by the user that reads it, and
# by nobody else: chown to dev:node, then chmod 0600.
#
# BOTH halves are load-bearing, and #5360 is what happens with only one.
#
# The mode half (#5342/#5331): every `cp` below that writes a PVC config copy
# creates the destination anew, and cp gives a newly created destination the
# SOURCE's mode — the ConfigMap seed and the bind-mounted hive.yaml are both
# 0644 — so the copy is re-widened to 0644 on every boot. Without the chmod
# the 0600 fix only holds from the first Config.Save() onward, and a hive that
# boots and never saves stays world-readable indefinitely. These files carry
# dashboard.auth_token (and github.token in PAT mode) and /data is
# world-traversable, so that is the dashboard owner credential readable by
# every unprivileged agent uid.
#
# The ownership half (#5360): those same `cp` calls run in the ROOT phase, so
# the destination is created root:root. chmod 600 on a root:root file grants
# access to root ALONE — and the hive process drops to dev (uid 1001) before
# it ever opens the config, so it reads back `permission denied` and startup
# aborts. The `chown -R dev:node /data` in the root-only block does NOT cover
# this: it is guarded by `[ "$DATA_OWNER" != "1001" ]` and src/Dockerfile
# already ships /data owned by dev:node, so on a fresh anonymous volume the
# guard is false and the recursive chown never runs at all. It is also far
# BELOW these call sites, so even when it does run it cannot help a file the
# config branch has not created yet.
#
# Do the chown FIRST and the chmod second. The reverse order leaves a window
# in which the file is 0644 and root-owned; chown does not clear the mode, so
# chown-then-chmod is never wider than 0600 for longer than the chown itself.
#
# Best-effort throughout: a read-only or foreign-owned PVC, or a container
# without CAP_CHOWN, must not abort boot. When the chown cannot be performed
# the chmod is deliberately skipped rather than applied to a file we do not
# own — locking a root-owned file to 0600 is precisely the #5360 failure, and
# a readable-but-wider file that boots beats a hardened one that cannot.
hive_harden_runtime_config() {
[ -f "$1" ] || return 0
# Already owned by the runtime user (the steady state after Config.Save(),
# and every non-root boot) — just tighten the mode.
if [ "$(stat -c '%u' "$1" 2>/dev/null || echo)" = "1001" ]; then
chmod 600 "$1" 2>/dev/null || true
return 0
fi
if chown "$HIVE_RUNTIME_USER:$HIVE_RUNTIME_GROUP" "$1" 2>/dev/null; then
chmod 600 "$1" 2>/dev/null || true
else
echo "[entrypoint] WARN: cannot chown $1 to $HIVE_RUNTIME_USER:$HIVE_RUNTIME_GROUP — leaving its mode alone so the runtime user can still read it (0600 on a foreign-owned file is #5360). Is CAP_CHOWN in the pod's capabilities.add?"
fi
}
# ── /data ownership as an INVARIANT, not a boot-time snapshot (#5369) ──
#
# HIVE_DATA_ROOT_PHASE_PATHS is the closed list of paths the root phase of this
# script creates under /data. It exists because the recursive
# `chown -R dev:node /data` further down is guarded on `[ "$DATA_OWNER" != 1001 ]`
# and src/Dockerfile already ships /data owned by dev:node — so on a normal boot
# the guard is FALSE and that chown never runs. Everything the root phase then
# creates keeps root:root, and the hive process (uid 1001, after the setpriv/gosu
# drop) cannot read it. #5360 was one instance of that; this list closes the class.
#
# The guard is NOT the bug and must stay. A recursive chown over an NFS-backed
# PVC with thousands of files costs minutes of startup. This list is the targeted
# alternative: a fixed set of shallow paths, chowned by NAME, so the cost is
# O(number of entries here) rather than O(size of the PVC) — and the invariant is
# restored without reintroducing the walk.
#
# MAINTENANCE RULE: if you add a root-phase write under /data, add its path here.
# hive_assert_runtime_readable below fails the boot LOUDLY, naming the path, when
# something in this list is unreadable to the runtime uid — so a forgotten entry
# surfaces as a named error at startup instead of as a silent EACCES later.
#
# Deliberately NOT in this list:
# /data/agents/*, /data/beads/* — chowned to per-agent hive-<name> UIDs by the
# per-agent loop, not to dev. Sweeping them to dev would undo that isolation.
# /data/secrets/bob_api_key — mode 440, chowned at its own site, and read
# by agent UIDs rather than by dev.
# /data/.hive/proxy-ca-key.pem — owner-only by design, chowned at its site.
HIVE_DATA_ROOT_PHASE_PATHS="
/data/.hive
/data/.hive/uid-isolation
/data/secrets
/data/config
/data/config/github-copilot
/data/home
/data/home/.config
/data/home/.bashrc
/data/home/.profile
"
# hive_sweep_root_phase_paths hands every existing entry of that list to the
# runtime user. Ownership ONLY — it never touches modes, because the modes are
# already deliberate at each site (2775 on /data/home, 710 on /data/secrets,
# 700 on /data/.hive) and re-deriving them here would be a second source of
# truth that silently drifts from the first.
#
# Non-recursive on purpose: `chown` without -R on a directory is a single
# syscall regardless of how many files are under it, which is what keeps the
# NFS cost bounded. Directory ENTRIES created by the root phase are named
# individually above; entries created later by dev or by an agent are already
# owned by their creator and are not ours to reassign.
#
# Fails OPEN, per #5368: a chown that cannot happen (no CAP_CHOWN, read-only or
# foreign-owned PVC) WARNs and continues. Nothing here is a security control —
# the modes set at each site are — so a failed chown must never abort a boot.
hive_sweep_root_phase_paths() {
_sweep_failed=""
for _p in $HIVE_DATA_ROOT_PHASE_PATHS; do
[ -e "$_p" ] || continue
# Never through a link: chown without -h acts on what the link names, and
# /data/home is writable by every agent uid.
[ -L "$_p" ] && continue
# Already owned by the runtime user — the steady state on almost every
# boot. Skip the syscall entirely so the common path costs one stat.
[ "$(stat -c '%u' "$_p" 2>/dev/null || echo)" = "1001" ] && continue
chown "$HIVE_RUNTIME_USER:$HIVE_RUNTIME_GROUP" "$_p" 2>/dev/null \
|| _sweep_failed="$_sweep_failed $_p"
done
if [ -n "$_sweep_failed" ]; then
echo "[entrypoint] WARN: could not chown to $HIVE_RUNTIME_USER:$HIVE_RUNTIME_GROUP:$_sweep_failed — is CAP_CHOWN in the pod's capabilities.add? Continuing; the runtime user may hit EACCES on these paths."
fi
unset _p _sweep_failed
}
# hive_assert_runtime_readable is the #5369 assertion: immediately BEFORE the
# privilege drop, prove that the paths the hive process must read are actually
# readable by the uid it is about to become — and if not, say WHICH path.
#
# This is option 3 from the issue, and it is worth having no matter how good the
# sweep above is. #5360 took four merges to diagnose because the symptom was a
# bare `permission denied` from the Go binary with no indication of which file or
# why. The same fault caught here prints the path, its owner and its mode, before
# the process that would fail on it has even started.
#
# Cheap by construction: it stats a short fixed list and, where a real read is
# possible, does ONE open() per path as the runtime user. No directory walk.
#
# Non-fatal by design. A hive that boots degraded and tells you which file is
# wrong beats one that refuses to boot on a check that may itself be wrong — and
# on hosts without a `dev` account or without root there is no way to perform the
# authoritative test at all. The Go binary still enforces what it genuinely needs;
# this exists to NAME the fault first. The one true hard failure (an unreadable
# config) already exits from the config block above.
hive_assert_runtime_readable() {
_assert_bad=""
for _p in "$@"; do
[ -e "$_p" ] || continue
_owner="$(stat -c '%u' "$_p" 2>/dev/null || echo '')"
# Owned by the runtime uid — readable by definition, no probe needed.
[ "$_owner" = "1001" ] && continue
# No usable stat (BSD stat has no -c; a stat-less image is conceivable).
# We cannot evaluate this path, and a check that cannot evaluate must stay
# SILENT rather than report a fault it did not observe. A warning that
# fires on every path on every boot trains the operator to ignore the one
# that is real — which is how #5360's actual signal got lost.
[ -n "$_owner" ] || continue
# Not owned by it. Try the real syscall as that user when we can, since
# a foreign-owned file may still be perfectly readable via group or other
# bits and flagging it on ownership alone would be a false alarm.
if [ "$(id -u)" = "0" ] && command -v gosu >/dev/null 2>&1 \
&& id -u "$HIVE_RUNTIME_USER" >/dev/null 2>&1; then
if [ -d "$_p" ]; then
gosu "$HIVE_RUNTIME_USER" test -r "$_p" -a -x "$_p" 2>/dev/null && continue
else
gosu "$HIVE_RUNTIME_USER" test -r "$_p" 2>/dev/null && continue
fi
else
# Cannot perform the authoritative test. Fall back to the mode bits: if
# the "other" class can read it, the runtime user can too. This is weaker
# than the open() above and is only used where the open() is impossible.
case "$(stat -c '%a' "$_p" 2>/dev/null || echo 000)" in
*[4567]) continue ;;
esac
fi
_assert_bad="$_assert_bad
$_p (owner uid=$_owner, mode=$(stat -c '%a' "$_p" 2>/dev/null || echo '?'))"
done
if [ -n "$_assert_bad" ]; then
echo "[entrypoint] WARN (#5369): these paths are NOT readable by the runtime user '$HIVE_RUNTIME_USER' (uid 1001) that this process is about to become:$_assert_bad"
echo "[entrypoint] WARN (#5369): they were created by the root phase and never handed over. Anything that reads them after the privilege drop will fail with EACCES. If a path above is a root-phase write, add it to HIVE_DATA_ROOT_PHASE_PATHS in this script."
fi
unset _p _owner _assert_bad
}
# Tighten pre-existing PVC config copies at boot. Files written before the
# 0600 fix (#5331) are world-readable. Routed through the helper above so
# these get the same chown-then-chmod treatment as the ones the `cp` calls
# recreate — a pre-existing root-owned copy is just as unreadable to dev.
for _cfg in "$HIVE_CONFIG_RUNTIME" "$HIVE_CONFIG_RUNTIME_LEGACY" /data/hive.yaml.dashboard; do
hive_harden_runtime_config "$_cfg"
done
unset _cfg
# hive_file_mtime echoes a file's mtime as epoch seconds (0 when unreadable).
# Both stat dialects are tried because the image is Debian but the helper
# must also behave on the BusyBox/macOS shells the tests run under.
hive_file_mtime() {
stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo 0
}
# hive_runtime_config_read echoes the path to read the persisted runtime
# config from: the new name when it is present and non-empty, else the
# legacy name when that is, else empty. Read-only — it never creates,
# renames or removes anything on the PVC.
#
# #17862: falling back to the legacy name is never routine any more. Every
# clean boot refreshes it from the runtime config (hive_refresh_legacy_fallback),
# so reaching it means the runtime config was lost or truncated since the
# last boot. Say so LOUDLY on stderr with both files' ages: a hive that
# silently booted a 3-month-old hive.yaml.bak (level 3 instead of 6) is the
# incident this guards against. When the legacy copy is OLDER than the
# runtime file it is replacing — i.e. the runtime file was written after
# the last refresh and then damaged — the WARN says the fallback is stale
# and names the overlay/audit paths an operator can reconstruct from.
hive_runtime_config_read() {
if [ -f "$HIVE_CONFIG_RUNTIME" ] && [ -s "$HIVE_CONFIG_RUNTIME" ]; then
echo "$HIVE_CONFIG_RUNTIME"
elif [ -f "$HIVE_CONFIG_RUNTIME_LEGACY" ] && [ -s "$HIVE_CONFIG_RUNTIME_LEGACY" ]; then
_rt_state="missing"
_rt_mtime=0
if [ -f "$HIVE_CONFIG_RUNTIME" ]; then
_rt_state="present but EMPTY (0 bytes — likely truncated by a kill mid-save)"
_rt_mtime="$(hive_file_mtime "$HIVE_CONFIG_RUNTIME")"
fi
_lg_mtime="$(hive_file_mtime "$HIVE_CONFIG_RUNTIME_LEGACY")"
_now="$(date +%s)"
_lg_age_h=$(( (_now - _lg_mtime) / 3600 ))
echo "[entrypoint] WARN: runtime config $HIVE_CONFIG_RUNTIME is $_rt_state; FALLING BACK to legacy $HIVE_CONFIG_RUNTIME_LEGACY (last refreshed ${_lg_age_h}h ago)." >&2
if [ "$_rt_mtime" -gt "$_lg_mtime" ] 2>/dev/null; then
echo "[entrypoint] WARN: the legacy fallback is OLDER than the damaged runtime config ($(( (_rt_mtime - _lg_mtime) / 3600 ))h behind). Settings saved since then (acmm_level, agent roster, pauses, models) are NOT in this file — check /data/hive.yaml.dashboard and /data/audit.jsonl before trusting the booted config. See hivecommons/hive#17862." >&2
fi
unset _rt_state _rt_mtime _lg_mtime _now _lg_age_h
echo "$HIVE_CONFIG_RUNTIME_LEGACY"
fi
}
# hive_refresh_legacy_fallback copies a GOOD runtime config over the legacy
# fallback name so the fallback is at most one boot stale (#17862). Before
# this, hive.yaml.bak was frozen at the rename (Aug 2026) on every hive, and
# a truncated runtime file booted a months-old config.
#
# Only runs when THIS boot is reading from the new name (so the legacy file
# is strictly older, never the only copy — the Docker/LXC worry behind the
# original never-write rule) and the runtime file parses as YAML with a
# project section (so a half-written file is never promoted to fallback).
# Copies to a temp name and renames so the fallback is never itself
# truncated by a kill. Best-effort: a failure here only means the fallback
# stays at its previous age.
hive_refresh_legacy_fallback() {
[ "$1" = "$HIVE_CONFIG_RUNTIME" ] || return 0
[ -s "$HIVE_CONFIG_RUNTIME" ] || return 0
if command -v python3 >/dev/null 2>&1; then
python3 -c '
import sys, yaml
with open(sys.argv[1]) as f:
d = yaml.safe_load(f)
sys.exit(0 if isinstance(d, dict) and isinstance(d.get("project"), dict) else 1)
' "$HIVE_CONFIG_RUNTIME" 2>/dev/null || {
echo "[entrypoint] WARN: $HIVE_CONFIG_RUNTIME does not parse as a hive config; legacy fallback $HIVE_CONFIG_RUNTIME_LEGACY left untouched" >&2
return 0
}
fi
if cmp -s "$HIVE_CONFIG_RUNTIME" "$HIVE_CONFIG_RUNTIME_LEGACY" 2>/dev/null; then
return 0
fi
_lg_tmp="${HIVE_CONFIG_RUNTIME_LEGACY}.tmp.$$"
if cp "$HIVE_CONFIG_RUNTIME" "$_lg_tmp" 2>/dev/null && mv -f "$_lg_tmp" "$HIVE_CONFIG_RUNTIME_LEGACY" 2>/dev/null; then
hive_harden_runtime_config "$HIVE_CONFIG_RUNTIME_LEGACY"
echo "[entrypoint] Legacy fallback $HIVE_CONFIG_RUNTIME_LEGACY refreshed from $HIVE_CONFIG_RUNTIME"
else
rm -f "$_lg_tmp" 2>/dev/null
echo "[entrypoint] WARN: could not refresh legacy fallback $HIVE_CONFIG_RUNTIME_LEGACY from $HIVE_CONFIG_RUNTIME" >&2
fi
unset _lg_tmp
}
# hive_ghe_git_host echoes this hive's configured GitHub host when it is NOT
# public github.com (i.e. a GitHub Enterprise instance such as github.ibm.com),
# and nothing at all otherwise. Derived the same way the Go binary's
# GitHubConfig.HostLabel() derives it (pkg/config/config.go): prefer
# github.base_url, fall back to the host portion of github.api_url, strip the
# scheme and a trailing /api/v3.
#
# Defined here, at the top, because BOTH boot phases need it: the root phase
# writes /etc/gitconfig (which every agent UID reads) and the dev phase writes
# ~dev/.gitconfig. Deriving it once keeps the two from drifting apart, which is
# exactly the failure mode #5343 was.
hive_ghe_git_host() {
_hgh_cfg="${HIVE_CONFIG:-/etc/hive/hive.yaml}"
[ -f "$_hgh_cfg" ] || return 0
python3 -c "
import sys, yaml
try:
with open(sys.argv[1]) as f:
cfg = yaml.safe_load(f) or {}
except Exception:
sys.exit(0)
gh = cfg.get('github') or {}
pick = (gh.get('base_url') or gh.get('api_url') or '').strip()
if pick.startswith('https://'):
pick = pick[len('https://'):]
elif pick.startswith('http://'):
pick = pick[len('http://'):]
pick = pick.rstrip('/')
if pick.endswith('/api/v3'):
pick = pick[: -len('/api/v3')]
host = pick.split('/', 1)[0]
if host and host.lower() != 'api.github.com' and host.lower() != 'github.com':
print(host)
" "$_hgh_cfg" 2>/dev/null || true
}
# hive_git_bot_identity echoes the git identity every agent commits as, as a
# single "name<TAB>email" line, derived from the SAME config the Go binary uses
# for Config.EffectiveAIAuthor() (pkg/config/config.go):
#
# 1. project.ai_author, when set — the operator's explicit choice, always wins.
# 2. else, unless github.app_authored_prs is false, the App bot
# "<github.app_slug or hivecommons-hive>[bot]" — but ONLY when the App is
# usable (real app_id, not the placeholder sentinel, and an
# installation_id), mirroring GitHubConfig.HasUsableApp(): a hive with no
# installed App has no bot that can author anything.
# 3. else the legacy "kubestellar-hive <hive-bot@kubestellar.io>" pair, so a
# hive that never opted in behaves exactly as before.
#
# The email depends on the SHAPE of the login (#6251, #6254):
#
# - A plain login (project.ai_author naming a user) gets
# "<login>@users.noreply.github.com", the address GitHub attributes to
# that account. It is a syntactically valid address, so DCO accepts it.
# - An App bot login ("<slug>[bot]") gets "<slug>@HIVE_GIT_BOT_EMAIL_DOMAIN"
# (default hive.kubestellar.io) — the bracket-free form. GitHub's own
# address for a bot is "<slug>[bot]@users.noreply.github.com", and that is
# exactly what MUST NOT be written here: probot-dco validates the sign-off
# email's syntax before it compares it to the author, and "[" "]" in the
# local-part fail that check, so every commit authored with the bracketed
# address is DCO-red forever — a matching Signed-off-by cannot fix it, a
# second human sign-off cannot fix it, and there is no .github/dco.yml to
# exempt it (measured on hivecommons/hive#6164: "hive-quality[bot]@users.
# noreply.github.com is not a valid email address"). The App still owns the
# PR (hive-open-pr) and the push (the credential helper); only the commit
# author/sign-off address has to be a real one. This is the same shape the
# agents' PRs that pass DCO already carry (quality@hive.kubestellar.io,
# sec-check@hive.kubestellar.io), and it is the SAME address git commit -s
# writes into the Signed-off-by trailer, so author and sign-off match.
#
# HIVE_GIT_BOT_EMAIL_DOMAIN is accepted only as [A-Za-z0-9.-] (it is written
# to a gitconfig line unquoted); anything else falls back to the default.
#
# WHY THIS EXISTS. /etc/gitconfig used to hardcode the public kubestellar-hive
# identity for every agent on every hive. A self-hosted hive with its own App
# then authored commits as a bot that does not exist for it, unattributed, and
# each agent improvised its own fix: one kick set the App login by hand, the
# next committed as "hive-quality <quality@hive.local>", the next as the
# hardcoded default — three identities on three consecutive PRs from the same
# agent. PR authorship (hive-open-pr) was already the App; commit authorship
# never was.
#
# Only [A-Za-z0-9._-] plus the literal "[bot]" suffix are accepted in a login;
# anything else falls back to the legacy pair rather than reaching a gitconfig
# line unquoted. Defined here because both boot phases need it — see
# hive_ghe_git_host.
hive_git_bot_identity() {
_hgbi_cfg="${HIVE_CONFIG:-/etc/hive/hive.yaml}"
_hgbi_login=""
if [ -f "$_hgbi_cfg" ]; then
_hgbi_login="$(python3 -c "
import re, sys, yaml
try:
with open(sys.argv[1]) as f:
cfg = yaml.safe_load(f) or {}
except Exception:
sys.exit(0)
proj = cfg.get('project') or {}
gh = cfg.get('github') or {}
login = (proj.get('ai_author') or '').strip()
if not login and gh.get('app_authored_prs') is not False:
try:
app_id = int(gh.get('app_id') or 0)
inst_id = int(gh.get('installation_id') or 0)
except (TypeError, ValueError):
app_id, inst_id = 0, 0
# 999999999 is config.PlaceholderAppID — a claimed-but-unprovisioned hive.
if app_id and app_id != 999999999 and inst_id:
slug = (gh.get('app_slug') or '').strip() or 'hivecommons-hive'
if slug.lower() == 'kubestellar-hive':
slug = 'hivecommons-hive'
if slug.lower() == 'kubestellar-hive-ghe':
slug = 'hivecommons-hive-ghe'
login = slug + '[bot]'
if re.fullmatch(r'[A-Za-z0-9._-]+(\\[bot\\])?', login):
print(login)
" "$_hgbi_cfg" 2>/dev/null || true)"
fi
if [ -n "$_hgbi_login" ]; then
case "$_hgbi_login" in
*'[bot]')
_hgbi_domain="${HIVE_GIT_BOT_EMAIL_DOMAIN:-hive.kubestellar.io}"
if [ -z "$_hgbi_domain" ] \
|| [ "$(printf '%s' "$_hgbi_domain" | tr -cd 'A-Za-z0-9.-')" != "$_hgbi_domain" ]; then
_hgbi_domain="hive.kubestellar.io"
fi
printf '%s\t%s@%s\n' "$_hgbi_login" "${_hgbi_login%\[bot\]}" "$_hgbi_domain"
;;
*)
printf '%s\t%s@users.noreply.github.com\n' "$_hgbi_login" "$_hgbi_login"
;;
esac
else
printf 'kubestellar-hive\thive-bot@kubestellar.io\n'
fi
}
# hive_write_system_gitconfig writes /etc/gitconfig — the SYSTEM-level git
# config, read by EVERY UID regardless of $HOME.
#
# WHY THIS EXISTS (#5343). The credential helper used to be installed with
# `git config --global`, which is per-$HOME. The entrypoint runs as dev