caelum0x 6801c08af9
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / node suites (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
feat(RIT-OPS,RIT-BRD): rename gitea -> rit everywhere we control, deployed + live-verified
apps/gitea -> apps/rithub-server; compose services/containers renamed
(rithub-server-app/postgres/act-runner) with explicit project name and
volume names pinned to the exact existing Docker volumes (no data loss);
our own GITEA_* compose/env var names -> RIT_*; new rit-admin CLI wrapper
on railyard-box; giteaSession.mjs/giteaOAuth.mjs/giteaInfo.mjs ->
ritSession/ritOAuth/ritInfo across 6 apps; GiteaForgeAdapter -> RitForgeAdapter
+ giteaSyncService/importGiteaRepos/syncGiteaRepos -> rit* in ritgram
(tsc clean); apps/console/lib/gitea.ts -> lib/ritProvision.ts; Go
internal/giteaclient -> internal/ritclient in rithub-async-import (go
build/test clean); new /auth/rit + /forges/rit/connect routes with
/gitea back-compat aliases; locale/swagger/footer/captcha template text
scrubbed of remaining "Gitea" strings.

Deployed to railyard-box: old containers stopped/removed, /srv/railyard-gitea
renamed to /srv/rithub-server with a symlink kept, docker compose up -d from
the new path, act_runner network-alias fix for its persisted instance URL.
Live-verified: docker compose config diff showed zero unintended value
changes, DB row counts unchanged (19 users, 635 repos), full route
regression 200/expected, 0 "gitea" in headers/bodies on every checked page,
real git clone+push over HTTPS and SSH with a disposable account (deleted
after). Deferred on purpose (documented in plans/railyard.md): the forge
discriminator / DB column names / Postgres role+volume names (data
migrations, not a naming change) and the upstream GITEA__ env-to-ini keys
and X-Gitea-* wire headers (hardcoded in the vendored engine binary).

See plans/railyard.md RIT-OPS/RIT-BRD entry for the full old->new map and
live evidence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-01 16:34:39 +03:00

227 lines
12 KiB
Bash

#!/usr/bin/env bash
# Shared core for server-side GitHub -> Rithub bulk migration. Sourced by
# oauth-auto-import.sh (path 1: automatic, triggered by a GitHub sign-in)
# and rithub-agent.sh (path 3: plain-words request). Same endpoint, same
# request shape, same defaults as the client-side `rit import github`
# (apps/rit/src/import_cmd.rs) — verified against the live server
# 2026-11-18 (plans/railyard.md): The engine's `MigrateRepoOptions.service` is
# the string "github" on this build, not a numeric service_type.
#
# Never echoes a token. Concurrency and load-awareness are the *caller's*
# job (flock + /proc/loadavg before calling into this file) since both
# callers need to coordinate with each other, not just with themselves.
set -euo pipefail
RITHUB_HOST="${RITHUB_HOST:-rithub.dev}"
# API calls below run server-side on railyard-box already (triggered by a
# sign-in hook or a plain-words request), so there is no reason to send
# them back out through Cloudflare's edge and in again -- that round trip
# is exactly what was timing out real imports under load (2026-11-26,
# plans/railyard.md "Lever check": a 125s migrate call hit Cloudflare's
# ~100s edge timeout and got a 524, leaving an empty repo behind). The engine's
# own loopback port has no such cap. RITHUB_HOST is kept only for the
# human-readable "already on $RITHUB_HOST" log line below.
RITHUB_API_BASE="${RITHUB_API_BASE:-http://127.0.0.1:3350}"
# _rit_api METHOD URL RIT_USER RIT_TOKEN [BODY_JSON] [MAX_TIME] ->
# prints http status (or "000" on a curl-level failure/timeout -- curl
# itself prints nothing to stdout on a hard timeout, so callers must
# treat any non-2xx/3-digit status, including "000", as a failure), leaves
# the response body in /tmp/.bulk-migrate-resp.$$ for the caller to read
# and remove. HTTP Basic auth with the token as the password — same
# scheme already proven working by `existing_rithub_repos` below and by
# `rit`'s own CLI (apps/rit/src/import_cmd.rs::rithub_request). An earlier
# version of this function used an `Authorization: token` header instead
# and was never actually exercised against the live server; a direct curl
# check against it during this fix's own verification came back empty, so
# this was corrected before shipping, not left as a latent second bug.
_rit_api() {
local method="$1" url="$2" user="$3" token="$4" body="${5:-}" max_time="${6:-30}"
if [ -n "$body" ]; then
curl -s --max-time "$max_time" -o /tmp/.bulk-migrate-resp.$$ -w '%{http_code}' \
-X "$method" "$url" -u "${user}:${token}" -H "User-Agent: rithub-bulk-migrate" \
-H "Content-Type: application/json" --data-binary "$body" || echo -n "000"
else
curl -s --max-time "$max_time" -o /tmp/.bulk-migrate-resp.$$ -w '%{http_code}' \
-X "$method" "$url" -u "${user}:${token}" -H "User-Agent: rithub-bulk-migrate" || echo -n "000"
fi
}
# List full_name + size(KB), tab-separated, sorted smallest-first. Own repos
# + forks only (no org/starred — same conservative default as the CLI).
#
# Auth scheme fix (RIT-ACT bulk-import dogfood, 2026-11-30): this used to
# send `Authorization: Bearer $token`. Verified live against the real
# GitHub REST API with a real classic OAuth-app user token (gho_... --
# exactly the token shape `external_login_user.access_token` stores for a
# GitHub-OAuth-linked Rithub account): `Bearer` gets a flat
# `401 Bad credentials`; the identical token with `Authorization: token
# $token` succeeds. GitHub's REST API only accepts Bearer for fine-grained
# PATs/GitHub Apps, not classic OAuth/PAT tokens. This meant the real
# "import all my GitHub repos" path (oauth-auto-import.sh /
# rithub-agent.sh) would have 100%-failed `list_github_repos` for every
# real GitHub-OAuth-linked user the moment GitHub sign-in is restored
# (currently disabled site-wide, so this was latent, not yet user-facing)
# -- same bug class as the agentSignup.mjs auto_init fix, caught before a
# real user hit it.
list_github_repos() {
local token="$1" page=1
while true; do
local resp
resp=$(curl -s -H "Authorization: token $token" -H "User-Agent: rithub-bulk-migrate" \
"https://api.github.com/user/repos?per_page=100&page=${page}&affiliation=owner&sort=full_name")
local count
count=$(echo "$resp" | python3 -c "import json,sys;print(len(json.load(sys.stdin)))" 2>/dev/null || echo 0)
[ "$count" -eq 0 ] && break
echo "$resp" | python3 -c "
import json,sys
for r in json.load(sys.stdin):
# Python-capitalized True/False on purpose: this field is interpolated
# directly into a Python dict literal below, not parsed as JSON/bash —
# lowercase 'false' here was a real bug (NameError: name 'false' is not
# defined), found 2026-11-19 by actually running this against a real
# GitHub account (451 repos) rather than just reading the code.
print(f\"{r['full_name']}\t{r.get('size',0)}\t{r['clone_url']}\t{str(r.get('private',False))}\")
"
[ "$count" -lt 100 ] && break
page=$((page + 1))
done | sort -t$'\t' -k2 -n
}
# Existing repo names for a Rithub user (for resumable skip-existing).
existing_rithub_repos() {
local user="$1" token="$2" page=1
while true; do
local resp
resp=$(curl -s --max-time 30 -u "${user}:${token}" "${RITHUB_API_BASE}/api/v1/users/${user}/repos?limit=50&page=${page}")
local names
names=$(echo "$resp" | python3 -c "
import json,sys
try:
for r in json.load(sys.stdin):
print(r['name'])
except Exception:
pass
" 2>/dev/null)
[ -z "$names" ] && break
echo "$names"
local count
count=$(echo "$names" | wc -l | tr -d ' ')
[ "$count" -lt 50 ] && break
page=$((page + 1))
done
}
# _disable_actions_for_mirror RIT_USER RIT_TOKEN NAME
# The engine's MigrateRepoOptions has no field to turn the Actions unit off at
# creation time -- it's always enabled by default on every new repo,
# mirror or not. For a *mirrored* repo this is pure waste: `act_runner`
# replays/queues a run for every historical ref the mirror brings in
# (seen live 2026-11-25: a handful of bulk-pushed own repos with hundreds
# of release tags each queued 200+ CI runs and pinned railyard-box at
# load1 15-22 on 2 vCPUs for most of a day -- plans/railyard.md,
# "Fixed the Rithub Actions CI backlog from mirror/dogfood pushes"). Since
# this function is only ever called right after a successful `mirror:
# true` migrate (see call sites below), it's safe unconditionally here.
# Best-effort: a failure to PATCH just leaves Actions on, which is the
# same state as before this fix existed -- never fails the migration.
_disable_actions_for_mirror() {
local rit_user="$1" rit_token="$2" name="$3"
_rit_api PATCH "${RITHUB_API_BASE}/api/v1/repos/${rit_user}/${name}" \
"$rit_user" "$rit_token" '{"has_actions":false}' "" 30 >/dev/null 2>&1 || true
rm -f /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true
}
# bulk_migrate_user RIT_USER RIT_TOKEN GITHUB_TOKEN
# Migrates every owner+fork repo for GITHUB_TOKEN's account onto Rithub
# under RIT_USER, smallest-first, skipping anything already present.
# Prints one progress line per repo to stdout (read-only list, no prompts).
bulk_migrate_user() {
local rit_user="$1" rit_token="$2" github_token="$3"
echo "[$rit_user] reading GitHub repos..."
local repos existing
repos=$(list_github_repos "$github_token")
existing=$(existing_rithub_repos "$rit_user" "$rit_token")
local total=0 done_count=0 first_visible_at="" start
start=$(date +%s)
total=$(echo "$repos" | grep -c . || true)
echo "[$rit_user] $total GitHub repo(s) found."
while IFS=$'\t' read -r full_name size_kb clone_url private; do
[ -z "$full_name" ] && continue
local name="${full_name##*/}"
if echo "$existing" | grep -qx "$name"; then
echo "[$rit_user] skip (already on $RITHUB_HOST): $full_name"
continue
fi
local body status
body=$(python3 -c "
import json
print(json.dumps({
'clone_addr': '$clone_url',
'auth_token': '$github_token',
'repo_name': '$name',
'repo_owner': '$rit_user',
'service': 'github',
'mirror': True,
'mirror_interval': '8h',
'private': $private,
'wiki': True, 'issues': True, 'pull_requests': True,
'releases': True, 'labels': True, 'milestones': True,
}))
")
status=$(_rit_api POST "${RITHUB_API_BASE}/api/v1/repos/migrate" "$rit_user" "$rit_token" "$body" 300)
resp_body=$(cat /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true)
rm -f /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true
if [ "$status" -ge 200 ] && [ "$status" -lt 300 ]; then
done_count=$((done_count + 1))
[ -z "$first_visible_at" ] && first_visible_at=$(($(date +%s) - start))
_disable_actions_for_mirror "$rit_user" "$rit_token" "$name"
echo "[$rit_user] migrated ($done_count/$total): $full_name (visible now, history fills in the background, Actions disabled)"
elif echo "$resp_body" | grep -q "comment references non existent IssueIndex"; then
# Real bug (c5, 2026-11-18/19): the engine's comment-import phase 500s on a
# GitHub comment whose own issue/PR was deleted upstream -- but only
# AFTER the repo + full git history already landed (verified live:
# erebos-labs/expo-journal, scribase/orion, caelum0x/immortal-bnb all
# exist non-empty right after this exact "FAIL"). Re-migrating would
# hit the identical bug again and can't resume just the issue phase,
# so check whether the repo is really there before calling it a
# failure -- same fix as apps/rit/src/import_cmd.rs::migrate_one.
check_status=$(_rit_api GET "${RITHUB_API_BASE}/api/v1/repos/${rit_user}/${name}" "$rit_user" "$rit_token" "" 30)
check_body=$(cat /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true)
rm -f /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true
is_empty=$(echo "$check_body" | python3 -c "import json,sys;print(json.load(sys.stdin).get('empty',True))" 2>/dev/null || echo True)
if [ "$check_status" = "200" ] && [ "$is_empty" = "False" ]; then
done_count=$((done_count + 1))
[ -z "$first_visible_at" ] && first_visible_at=$(($(date +%s) - start))
_disable_actions_for_mirror "$rit_user" "$rit_token" "$name"
echo "[$rit_user] migrated ($done_count/$total): $full_name -- note: code + most issues/PRs migrated; a few comments on an already-deleted GitHub issue/PR were skipped (Actions disabled)"
else
echo "[$rit_user] FAILED: $full_name (HTTP $status, orphan-comment bug, repo did not actually land) $(echo "$resp_body" | head -c 200)"
fi
else
# Covers both a real engine error response and a curl-level failure
# (status "000" -- connection reset/timeout). Either way, the engine may
# already have created the repo record before failing partway
# through the clone (confirmed live, 2026-11-26, plans/railyard.md
# "Lever check": a timed-out migrate left an "empty": true repo
# shell behind, visible to anyone). Check and delete it rather than
# leaving a broken shell -- never fails the batch if the check or
# delete itself fails, same best-effort shape as
# _disable_actions_for_mirror above.
cleanup_status=$(_rit_api GET "${RITHUB_API_BASE}/api/v1/repos/${rit_user}/${name}" "$rit_user" "$rit_token" "" 30)
cleanup_body=$(cat /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true)
rm -f /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true
cleanup_is_empty=$(echo "$cleanup_body" | python3 -c "import json,sys;print(json.load(sys.stdin).get('empty',False))" 2>/dev/null || echo False)
if [ "$cleanup_status" = "200" ] && [ "$cleanup_is_empty" = "True" ]; then
_rit_api DELETE "${RITHUB_API_BASE}/api/v1/repos/${rit_user}/${name}" "$rit_user" "$rit_token" "" 30 >/dev/null 2>&1 || true
rm -f /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true
echo "[$rit_user] FAILED: $full_name (HTTP $status) $(echo "$resp_body" | head -c 200) -- cleaned up the empty repo shell it left behind"
else
echo "[$rit_user] FAILED: $full_name (HTTP $status) $(echo "$resp_body" | head -c 200)"
fi
fi
done <<<"$repos"
local elapsed=$(($(date +%s) - start))
echo "[$rit_user] done: $done_count/$total migrated. time to first visible: ${first_visible_at:-0}s, total: ${elapsed}s."
}