Rebuild dotfiles as one branch with per-host layers

Replaces the previous repo, which had split into two histories that never
met (mainframe on a dead GitLab remote, the laptops on Gitea) with 146
dirty files across three machines and the NAS never enrolled at all.

Branch-per-machine is gone. One main, with host differences expressed as
small files under hosts/<hostname>/ rather than as branches, so there is
nothing to merge. The reconciled zsh layer reduces 15-33 line forks to
1-7 effective lines per host; distro differences (oh-my-zsh prefix,
syntax-highlighting path, fd vs fdfind) are probed in common/ instead.

Fresh history: the old one carried six plaintext credentials, 45 MB of
mail caches, browser caches and vendored binaries. 5,096 tracked files
and 144 MB become 462 files and 2.6 MB. The .gitignore is now an
allowlist, which is what keeps that true.

Root cause of the rot: ~/.local/bin was a symlink to scripts/ with GOPATH
inside it, so every go install wrote into version control (2.2 GB on the
work laptop). PATH now points at the repo instead of the reverse.

Also: Hyprland replaces sway and is sourced in two halves so $browser is
defined before use; singleton automations carry ConditionHost= alongside
host-layer-only placement; ddns moves from cron to a guarded timer;
package manifests and pkg-snapshot/pkg-restore replace the X11-era
install_scripts/; networkmanager-dmenu added to system76 (the binding
always existed, the package never did).
This commit is contained in:
2026-09-14 14:24:37 -04:00
commit e6644d0616
462 changed files with 23524 additions and 0 deletions
+46
View File
@@ -0,0 +1,46 @@
#!/bin/sh
# Sample backlight state so an unattended dim/restore cycle can be reconstructed.
# A long gap between samples means the machine was suspended, which is the window
# where DDC writes are suspected to be lost, so that case is sampled densely.
LOG=$HOME/.local/state/backlight-probe.log
read_all() {
out=
for p in /sys/class/backlight/*; do
[ -e "$p" ] || continue
out="$out ${p##*/}=$(cat "$p/brightness" 2>/dev/null)/$(timeout 2 cat "$p/actual_brightness" 2>/dev/null || echo ERR)"
done
printf '%s' "$out"
}
cached() {
out=
for p in /sys/class/backlight/*; do
[ -e "$p" ] || continue
out="$out ${p##*/}=$(cat "$p/brightness" 2>/dev/null)"
done
printf '%s' "$out"
}
prev=
last=$(date +%s)
printf '%s START%s\n' "$(date '+%F %T')" "$(read_all)" >>"$LOG"
while :; do
now=$(date +%s); gap=$((now - last)); last=$now
cur=$(cached)
if [ "$gap" -gt 10 ]; then
printf '%s GAP %ss (suspend/resume)\n' "$(date '+%F %T')" "$gap" >>"$LOG"
i=0
while [ "$i" -lt 40 ]; do
printf '%s +%02ds%s\n' "$(date '+%F %T')" "$i" "$(read_all)" >>"$LOG"
i=$((i + 1)); sleep 1
done
prev=
elif [ "$cur" != "$prev" ]; then
printf '%s CHANGE%s\n' "$(date '+%F %T')" "$(read_all)" >>"$LOG"
prev=$cur
fi
sleep 2
done
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
# Absolute path is required: the shared $HOME puts the host's pip shim at
# ~/.local/bin/qutebrowser, which shadows the container's and runs an incompatible python.
# Both builds hash to the same IPC socket name, so a running host instance would
# silently swallow this launch and open a tab there instead.
if pgrep -f '\.local/apps/qutebrowser/\.venv/bin/python3 -m qutebrowser' >/dev/null 2>&1; then
echo "qutebrowser-arch: the host (pip) qutebrowser is running and shares the IPC socket." >&2
echo "Quit it first, or this launch will just open a tab in that instance." >&2
exit 1
fi
# QB_MODE works around eglCreateImage returning EGL_NOT_INITIALIZED under native
# Wayland, which loses the GL context and leaves pages rendering as background only.
PRE=""
EXTRA=""
case "${QB_MODE:-xwayland}" in
xwayland)
# XWayland cannot do fractional scaling, so Hyprland upscales a 1x buffer and
# blurs it. Needs `xwayland { force_zero_scaling = true }` in hyprland.conf to help.
SCALE=$(hyprctl monitors -j 2>/dev/null | grep -m1 '"scale"' | tr -dc '0-9.' )
PRE="QT_QPA_PLATFORM=xcb QT_SCALE_FACTOR=${SCALE:-1}"
;;
software) EXTRA="--qt-flag disable-gpu" ;;
wayland) ;;
*) echo "qutebrowser-arch: unknown QB_MODE '$QB_MODE' (wayland|xwayland|software)" >&2; exit 1 ;;
esac
exec "$HOME/.local/bin/distrobox" enter --no-tty --name arch -- sh -c \
"$PRE exec /usr/bin/qutebrowser $EXTRA \"\$@\"" -- "$@"
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Total time tagged language:spanish in Traggo, as decimal hours."""
import json
import subprocess
import sys
import urllib.request
from collections import defaultdict
from datetime import datetime, timezone
URL = "https://time.rcjohnstone.com/graphql"
USER = "connor"
def gql(query, cookie=None):
req = urllib.request.Request(
URL,
data=json.dumps({"query": query}).encode(),
headers={"Content-Type": "application/json"},
)
if cookie:
req.add_header("Cookie", f"traggo={cookie}")
body = json.load(urllib.request.urlopen(req))
if body.get("errors"):
sys.exit(f"traggo: {body['errors'][0]['message']}")
return body["data"]
def login():
pw = subprocess.run(
["rbw", "get", "Traggo"], capture_output=True, text=True, check=True
).stdout.strip()
data = gql(
'mutation{login(username:"%s",pass:%s,deviceName:"spanish-time",'
"type:LongExpiry,cookie:false){token}}" % (USER, json.dumps(pw))
)
return data["login"]["token"]
def spans(token):
offset, start_id = 0, None
while True:
cur = f"offset:{offset},pageSize:200"
if start_id is not None:
cur += f",startId:{start_id}"
data = gql(
'{timeSpans(fromInclusive:"2000-01-01T00:00:00Z",'
'toInclusive:"2100-01-01T00:00:00Z",cursor:{%s})'
"{cursor{hasMore offset startId} timeSpans{start end tags{key value}}}}"
% cur,
token,
)["timeSpans"]
yield from data["timeSpans"]
if not data["cursor"]["hasMore"]:
return
offset, start_id = data["cursor"]["offset"], data["cursor"]["startId"]
def main():
by_mode = defaultdict(float)
for span in spans(login()):
tags = {t["key"]: t["value"] for t in span["tags"]}
if tags.get("language") != "spanish":
continue
start = datetime.fromisoformat(span["start"])
end = (
datetime.fromisoformat(span["end"])
if span["end"]
else datetime.now(timezone.utc)
)
by_mode[tags.get("mode", "untagged")] += (end - start).total_seconds() / 3600
if "--by-mode" in sys.argv:
for mode, hours in sorted(by_mode.items(), key=lambda kv: -kv[1]):
print(f"{mode:12s} {hours:8.2f}")
print(f"{sum(by_mode.values()):.2f}")
if __name__ == "__main__":
main()
+257
View File
@@ -0,0 +1,257 @@
#!/usr/bin/env python3
"""usb3check - watch USB/Thunderbolt enumeration and report cable tier.
Plug a device in while this runs and it reports the negotiated link speed and
which cable tier that qualifies for.
Tier 1 Thunderbolt 4/5, 240W EPR dock uplink, displays, external SSDs
Tier 2 >=10Gbps, 240W EPR general data
Tier 3 charge-only, 240W EPR bench power, laptop charging
Tier 4 everything else phone charging, or the bin
Data rate is measured. Wattage is NOT - nothing in sysfs exposes the cable's
e-marker, so the tier printed is the ceiling the data rate allows. Confirm the
power rating from the purchase or an inline analyzer before promoting a cable.
Reads /sys/bus/usb/devices and /sys/bus/thunderbolt/devices. No root, no deps.
./usb3check.py watch continuously
./usb3check.py --once print current devices grouped by speed
"""
import argparse
import os
import sys
import time
USB_SYSFS = "/sys/bus/usb/devices"
TB_SYSFS = "/sys/bus/thunderbolt/devices"
TIER_NOTES = {
1: "Thunderbolt link established. Tier 1 if the cable is also 240W EPR.",
2: "SuperSpeed link established. Tier 2 if the cable is also 240W EPR.",
3: "No SuperSpeed link - data-incapable. Tier 3 if 240W EPR, else tier 4.",
4: "No link worth keeping. Tier 4.",
}
def read_attr(path, name):
try:
with open(os.path.join(path, name)) as fh:
return fh.read().strip()
except OSError:
return None
def usb_snapshot():
"""Map of sysfs name -> device info, excluding root hubs and interfaces."""
devices = {}
try:
entries = os.listdir(USB_SYSFS)
except OSError as exc:
sys.exit(f"cannot read {USB_SYSFS}: {exc}")
for name in entries:
if name.startswith("usb") or ":" in name:
continue # root hub, or an interface rather than a device
path = os.path.join(USB_SYSFS, name)
raw_speed = read_attr(path, "speed")
if raw_speed is None:
continue
try:
speed = float(raw_speed)
except ValueError:
continue
devices[name] = {
"kind": "usb",
"speed": speed,
"vid": read_attr(path, "idVendor") or "????",
"pid": read_attr(path, "idProduct") or "????",
"product": read_attr(path, "product") or "",
"vendor": read_attr(path, "manufacturer") or "",
"class": read_attr(path, "bDeviceClass") or "",
}
return devices
def tb_snapshot():
"""Map of sysfs name -> Thunderbolt device info. Empty if no TB subsystem."""
devices = {}
if not os.path.isdir(TB_SYSFS):
return devices
for name in os.listdir(TB_SYSFS):
if name.startswith("domain") or ":" in name:
continue # domain controller, or a retimer/port entry
path = os.path.join(TB_SYSFS, name)
if read_attr(path, "device_name") is None and read_attr(path, "device") is None:
continue
devices[name] = {
"kind": "thunderbolt",
"product": read_attr(path, "device_name") or "",
"vendor": read_attr(path, "vendor_name") or "",
"authorized": read_attr(path, "authorized") or "0",
"rx": read_attr(path, "rx_speed") or "",
"tx": read_attr(path, "tx_speed") or "",
"generation": read_attr(path, "generation") or "",
}
return devices
def snapshot():
combined = usb_snapshot()
for name, info in tb_snapshot().items():
combined[f"tb:{name}"] = info
return combined
def fmt_speed(mbps):
if mbps >= 1000:
return f"{mbps / 1000:g} Gbps"
return f"{mbps:g} Mbps"
def generation(mbps):
if mbps >= 20000:
return "USB 3.2 Gen 2x2"
if mbps >= 10000:
return "USB 3.1 Gen 2 (SuperSpeed+)"
if mbps >= 5000:
return "USB 3.0 (SuperSpeed)"
if mbps >= 480:
return "USB 2.0 (High Speed)"
return "USB 1.x (Full/Low Speed)"
def describe(info):
label = " ".join(x for x in (info.get("vendor", ""), info.get("product", ""))).strip()
if not label:
label = f"{info.get('vid', '????')}:{info.get('pid', '????')}"
if info["kind"] == "thunderbolt":
gen = info.get("generation")
label += f" [thunderbolt{' gen ' + gen if gen else ''}]"
elif info.get("class") == "09":
label += " [hub]"
return label
def speed_column(info):
if info["kind"] == "thunderbolt":
return info.get("rx") or "TB link"
return fmt_speed(info["speed"])
def classify(added):
"""Best tier the observed links qualify for."""
if any(i["kind"] == "thunderbolt" and i.get("authorized") == "1" for i in added.values()):
return 1
usb = [i["speed"] for i in added.values() if i["kind"] == "usb"]
if not usb:
return 4
best = max(usb)
if best >= 10000:
return 2
if best >= 5000:
return 2
if best >= 480:
return 3
return 4
def report(added, removed):
print(f"\n-- {time.strftime('%H:%M:%S')} " + "-" * 44)
for name, info in sorted(removed.items()):
print(f" - {name:<14} {'':>10} {describe(info)}")
for name, info in sorted(added.items()):
print(f" + {name:<14} {speed_column(info):>10} {describe(info)}")
if not added:
return
tier = classify(added)
usb = [i["speed"] for i in added.values() if i["kind"] == "usb"]
print()
if usb:
print(f" fastest USB link: {fmt_speed(max(usb))} ({generation(max(usb))})")
print(f" TIER {tier}: {TIER_NOTES[tier]}")
if tier >= 3:
print(" a USB 3 hub always enumerates twice - once at 480 Mbps and")
print(" again on the SuperSpeed bus. Only one showed up here.")
if tier == 2:
print(" not a Thunderbolt link. Tier 1 needs `boltctl list` with the dock.")
def print_tree(devices):
if not devices:
print("no devices found")
return
tb = {k: v for k, v in devices.items() if v["kind"] == "thunderbolt"}
usb = {k: v for k, v in devices.items() if v["kind"] == "usb"}
if tb:
print("\nThunderbolt")
for name, info in sorted(tb.items()):
state = "authorized" if info.get("authorized") == "1" else "not authorized"
print(f" {name:<14} {info.get('rx', ''):>10} {describe(info)} [{state}]")
by_speed = {}
for name, info in usb.items():
by_speed.setdefault(info["speed"], []).append((name, info))
for speed in sorted(by_speed, reverse=True):
print(f"\n{fmt_speed(speed)} ({generation(speed)})")
for name, info in sorted(by_speed[speed]):
print(f" {name:<14} {describe(info)}")
def watch(interval, settle):
base = snapshot()
fast = sum(1 for i in base.values() if i["kind"] == "usb" and i["speed"] >= 5000)
tb = sum(1 for i in base.values() if i["kind"] == "thunderbolt")
print(f"watching {USB_SYSFS}" + (f" and {TB_SYSFS}" if os.path.isdir(TB_SYSFS) else ""))
print(f"baseline: {len(base)} devices, {fast} at SuperSpeed, {tb} Thunderbolt")
print("plug something in - Ctrl-C to stop")
while True:
time.sleep(interval)
current = snapshot()
if current == base:
continue
# Let enumeration settle before reporting; a hub plus its downstream
# devices arrive over several hundred milliseconds.
while True:
time.sleep(settle)
following = snapshot()
if following == current:
break
current = following
added = {k: v for k, v in current.items() if k not in base}
removed = {k: v for k, v in base.items() if k not in current}
report(added, removed)
base = current
def main():
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--once", action="store_true",
help="print current devices grouped by speed, then exit")
parser.add_argument("--interval", type=float, default=0.4,
help="poll interval in seconds (default: 0.4)")
parser.add_argument("--settle", type=float, default=1.0,
help="settle time after a change before reporting (default: 1.0)")
args = parser.parse_args()
if args.once:
print_tree(snapshot())
return
try:
watch(args.interval, args.settle)
except KeyboardInterrupt:
print()
if __name__ == "__main__":
main()
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Hyprland propagates PRIMARY ownership across the Xwayland boundary but not the
# contents, so Xwayland clients get an empty middle-click paste. Its proxy will
# still serve a direct STRING request, but it advertises no text target, and Qt
# asks for TARGETS first and gives up. See hyprwm/Hyprland#6603.
wl-paste --primary --watch xclip -selection primary -i &
# Mapping a new Xwayland window makes Hyprland seize PRIMARY back, so re-push
# whenever the X side stops offering a text target.
while sleep 1; do
wl-paste --primary --no-newline >/dev/null 2>&1 || continue
xclip -o -selection primary -t TARGETS 2>/dev/null | grep -qE 'STRING|text/plain' && continue
wl-paste --primary --no-newline 2>/dev/null | xclip -selection primary -i
done