Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ jobs:
scripts/main_model_switch_test.py \
scripts/spans_rollup_test.py \
scripts/spans_view_test.py \
scripts/spans_weekly_test.py \
scripts/work_board_test.py \
scripts/tasker_stall_watchdog_test.py

Expand Down
1 change: 1 addition & 0 deletions changelog.d/2899-spans-weekly-wiki.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **Weekly fleet span summary on a Family Wiki page (#2899).** `scripts/spans-weekly.py` folds the hub's daily span-view records (`<state>/spans-view/data/<day>/<node>.json`, `_status.json`) for the previous Monday–Sunday (KST) into one Markdown section — per-node table (days collected n/7, turns, tool calls, tool error rate, cost USD, largest daily cost-ledger difference, a2a ok/failed when any node reported it), a fleet total, the five tools with the most errors, "big changes" against the week before (tool error rate +2 %p, or turns per collected day ≤0.5× / ≥2× — provisional, `--error-rate-pp` / `--turns-low` / `--turns-high` or `CCC_SPANS_WEEKLY_*`) and the days not collected with their reason codes. A week with no collected day is one 「수집 없음」 line. It opens no connection to any node and writes numbers and identifier-shaped tool names only (anything else in a name becomes `?`). The section goes to `pages/services/span-rollup.md` through `wiki-agent write-path` → edit → `wiki-agent pr`: each section carries `<!-- span-weekly:YYYY-Www -->` and a week already on the page or in its yearly archive is never written again; the page keeps the newest 12 weeks with a digest line for the newest one at the top, older weeks move to `span-rollup-archive-<year>.md`; `--catch-up 1` (default) re-adds a week whose PR failed on the next run. `--dry-run` prints the Markdown only. `scripts/install-spans-weekly-timer.sh` prints (dry-run) or installs (`--apply`) a Monday 05:00 Asia/Seoul timer on the hub. The nightly rollup's `metrics/span-rollup` wiki-candidate now suggests `pages/services/span-rollup.md` instead of `pages/fleet/span-rollup.md`.
42 changes: 42 additions & 0 deletions docs/bridge-ops.md
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,48 @@ Nothing is installed on the other nodes and no raw span leaves a node.
- **Who can read the pages** is decided by where `--out-dir` is served, not
by these scripts: check that folder's access policy before installing.

### Weekly fleet span summary on the Wiki (#2899)

The hub folds the daily view records into one section per week on a Family
Wiki page so agents on any node can read fleet trends (`wiki-agent find`).

- **Input:** only the records the daily view keeps
(`$CCC_STATE_DIR/spans-view/data/<day>/<node>.json`, `_status.json`); no
node is contacted. A day the hub did not collect shows as `no-run`, a node
missing from that day's status as `no-result`, otherwise the collector's
detail code (`no-folder`, `ssh-255`, …); a record that fails the shape check
counts as `record-invalid`.
- **Section** (`scripts/spans-weekly.py`, previous Monday–Sunday KST by
default, `--week YYYY-Www` for another one within the kept 12 weeks):
per-node table (days n/7, turns, tool calls, tool error rate, cost USD,
largest daily cost-ledger difference, a2a ok/failed when present), a fleet
total, the top 5 tools by errors (largest daily p95), big changes against
the week before (tool error rate +2 %p, turns per collected day ≤0.5× or
≥2× — provisional; `--error-rate-pp`, `--turns-low`, `--turns-high` or
`CCC_SPANS_WEEKLY_ERROR_PP` / `_TURNS_LOW` / `_TURNS_HIGH`) and the gaps
per node. No collected day at all → one 「수집 없음」 line. Output is the
same for the same records (no timestamps). Tool names keep only
`A-Z a-z 0-9 . _ : / @ + -` (others become `?`, 60 chars max) and sit in
code spans; a section is capped at 24 KiB.
- **Page:** `pages/services/span-rollup.md` (`--page`). Each section starts
with `<!-- span-weekly:YYYY-Www -->`; a week already on the page or in its
yearly archive is skipped, and nothing is submitted when every week is
present. Newest 12 weeks, newest first, with one `에이전트 다이제스트`
line for the newest week at the top; older sections move to
`span-rollup-archive-<ISO year>.md`. New pages get the next `[DOC-N]` from
the worktree (the work-board rule). A page that exists without that
header, a symlinked target, or a dirty worktree stops the run unchanged.
- **Submit:** `wiki-agent write-path` → write → `wiki-agent pr` (existing
gate). `--catch-up N` (default 1) also adds up to N earlier weeks still
missing, so a failed PR is retried on the next week's run. `--dry-run`
prints the target week's Markdown and opens no worktree.
- **Schedule:** `scripts/install-spans-weekly-timer.sh --nodes "…"` prints
the service + timer (Monday 05:00 Asia/Seoul, after the 04:30 view and
before the 05:30 work board that shares the wiki-agent worktree;
`Persistent=true`, 1500 s cap, failure notice through `detached_jobs.py`
when present); `--apply` installs, `--uninstall --apply` removes the units
and keeps the page. Hub only, after owner approval.

## Group rows still holding a DM session (#2075)

Before #2092, a group/room row in `sessions.json` could end up holding the
Expand Down
168 changes: 168 additions & 0 deletions scripts/install-spans-weekly-timer.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
#!/usr/bin/env bash
# Install the weekly fleet span summary as a systemd timer (#2899).
# Safe by default: dry-run unless --apply is given. Run it on the ONE hub node
# that already runs the daily span view (install-spans-view-timer.sh) and has
# a wiki-agent install; no other node needs anything.
#
# install-spans-weekly-timer.sh --nodes "a b c" [--dry-run|--apply] [--uninstall]
# [--page pages/services/span-rollup.md] [--on-calendar SPEC]
# [--service-name NAME] [--state-dir DIR]
#
# The unit runs scripts/spans-weekly.py once a week (default Monday 05:00
# Asia/Seoul — after the 04:30 daily view collection, which is capped at
# 900 s, and before the 05:30 work board that uses the same wiki-agent
# worktree). It reads only the records the daily view already keeps in the
# state folder, adds the previous week's section to one Wiki page in the
# wiki-agent PR worktree and runs `wiki-agent pr`; a week already on the page
# is never written again. The unit needs the account's HOME (wiki-agent
# worktree), so it is not sandboxed with ProtectSystem=strict.
set -euo pipefail
# --nodes is split on blanks below; a `*` in it must stay a (refused) name.
set -f

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
APPLY=0
UNINSTALL=0
NODES="${CCC_FLEET_NODES:-}"
PAGE="${CCC_SPANS_WEEKLY_PAGE:-pages/services/span-rollup.md}"
SERVICE_NAME="${CCC_SPANS_WEEKLY_SERVICE_NAME:-ccc-spans-weekly}"
ON_CALENDAR="${CCC_SPANS_WEEKLY_ON_CALENDAR:-Mon *-*-* 05:00:00 Asia/Seoul}"
STATE_DIR="${CCC_STATE_DIR:-$HOME/.claude/state}"
SYSTEMD_DIR="${CCC_SYSTEMD_DIR:-/etc/systemd/system}"
SYSTEMCTL="${CCC_SYSTEMCTL:-systemctl}"
# Reading 14 days of records takes well under a second; wiki-agent pr can wait
# on CI. 25 minutes keeps the run clear of the 05:30 work board.
TIMEOUT_START="${CCC_SPANS_WEEKLY_TIMEOUT_START:-1500}"

usage() {
cat <<'EOF'
Usage: install-spans-weekly-timer.sh --nodes "a b c" [--dry-run|--apply] [--uninstall]
[--page pages/services/span-rollup.md] [--on-calendar SPEC]
[--service-name NAME] [--state-dir DIR]

Installs (or with --uninstall removes) the systemd service + timer that adds
the weekly fleet span summary to a Family Wiki page on the hub node. Defaults
to dry-run: prints the unit files and the commands it would run. --apply is
required to change anything.
EOF
}
need_val() { [ -n "${2:-}" ] || { echo "$1 requires a value" >&2; exit 2; }; }
while [ $# -gt 0 ]; do
case "$1" in
--dry-run) APPLY=0 ;;
--apply) APPLY=1 ;;
--uninstall) UNINSTALL=1 ;;
--nodes) need_val "$1" "${2:-}"; NODES="$2"; shift ;;
--page) need_val "$1" "${2:-}"; PAGE="$2"; shift ;;
--on-calendar) need_val "$1" "${2:-}"; ON_CALENDAR="$2"; shift ;;
--service-name) need_val "$1" "${2:-}"; SERVICE_NAME="$2"; shift ;;
--state-dir) need_val "$1" "${2:-}"; STATE_DIR="$2"; shift ;;
-h|--help) usage; exit 0 ;;
*) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;;
esac
shift
done

# Every value below is written into a unit file, so each one is held to a
# plain shape instead of being quoted for systemd.
plain_path() { [[ "$1" =~ ^/[A-Za-z0-9._/-]+$ ]] && [[ "$1" != *..* ]]; }
[[ "$SERVICE_NAME" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,60}$ ]] || { echo "bad --service-name" >&2; exit 2; }
[[ "$ON_CALENDAR" =~ ^[A-Za-z0-9*:,/\ ._~-]{1,80}$ ]] || { echo "bad --on-calendar" >&2; exit 2; }
[[ "$TIMEOUT_START" =~ ^[0-9]{1,5}$ ]] || { echo "bad CCC_SPANS_WEEKLY_TIMEOUT_START" >&2; exit 2; }
plain_path "$ROOT" || { echo "repository path has characters a unit file cannot carry safely" >&2; exit 2; }
plain_path "$HOME" || { echo "HOME has characters a unit file cannot carry safely" >&2; exit 2; }
plain_path "$STATE_DIR" || { echo "bad --state-dir (want a plain absolute path)" >&2; exit 2; }

SERVICE_FILE="$SYSTEMD_DIR/$SERVICE_NAME.service"
TIMER_FILE="$SYSTEMD_DIR/$SERVICE_NAME.timer"

if [ "$UNINSTALL" = 1 ]; then
if [ "$APPLY" != 1 ]; then
echo "# dry-run: would run $SYSTEMCTL disable --now $SERVICE_NAME.timer"
echo "# dry-run: would remove $SERVICE_FILE and $TIMER_FILE"
echo "# dry-run: would run $SYSTEMCTL daemon-reload"
echo "# the Wiki page and the span records are left in place"
exit 0
fi
"$SYSTEMCTL" disable --now "$SERVICE_NAME.timer" 2>/dev/null || true
rm -f "$SERVICE_FILE" "$TIMER_FILE"
"$SYSTEMCTL" daemon-reload
printf 'removed %s and %s (Wiki page and records left in place)\n' "$SERVICE_FILE" "$TIMER_FILE"
exit 0
fi

# No built-in node list (#1451): a node that never answered must still show up
# as 「미수집」, so the unit carries the hub's list.
[ -n "$NODES" ] || { echo "--nodes is required (space-separated node list, or CCC_FLEET_NODES)" >&2; exit 2; }
NODE_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$'
for node in $NODES; do
[[ "$node" =~ $NODE_RE ]] || { echo "bad node name in --nodes" >&2; exit 2; }
done
[[ "$NODES" =~ ^[A-Za-z0-9._\ -]*$ ]] || { echo "bad --nodes (names separated by single spaces)" >&2; exit 2; }
[[ "$PAGE" =~ ^pages/[A-Za-z0-9._/-]+\.md$ ]] && [[ "$PAGE" != *..* ]] || { echo "bad --page (want pages/<path>.md)" >&2; exit 2; }

RESULT="$STATE_DIR/$SERVICE_NAME.result"
NOTIFY="$HOME/.claude/hooks/lib/detached_jobs.py"
NOTIFY_LINE=""
# One line per run: success waits for the morning digest, a failed PR is sent
# at once (the next week's run retries the missing week).
[ ! -f "$NOTIFY" ] || NOTIFY_LINE="ExecStopPost=-/usr/bin/env python3 $NOTIFY notify --unit $SERVICE_NAME --exit \${EXIT_STATUS} --tier info --fail-tier notice --result-file $RESULT"

SERVICE_CONTENT="$(cat <<EOF
[Unit]
Description=ccc-node weekly fleet span summary (hub records -> one Wiki page)
Documentation=https://github.com/jinwon-int/ccc-node/issues/2899
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
WorkingDirectory=$ROOT
Environment=HOME=$HOME
Environment=CCC_STATE_DIR=$STATE_DIR
Environment="CCC_FLEET_NODES=$NODES"
Environment=PATH=$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin
Environment=PYTHONDONTWRITEBYTECODE=1
ExecStart=/usr/bin/env python3 $ROOT/scripts/spans-weekly.py --page $PAGE --state-dir $STATE_DIR --result-file $RESULT
${NOTIFY_LINE:+$NOTIFY_LINE
}TimeoutStartSec=$TIMEOUT_START
Nice=10
NoNewPrivileges=true
PrivateTmp=true
EOF
)"

TIMER_CONTENT="$(cat <<EOF
[Unit]
Description=Add the ccc-node weekly fleet span summary once a week
Documentation=https://github.com/jinwon-int/ccc-node/issues/2899

[Timer]
OnCalendar=$ON_CALENDAR
Persistent=true
AccuracySec=1min
Unit=$SERVICE_NAME.service

[Install]
WantedBy=timers.target
EOF
)"

if [ "$APPLY" != 1 ]; then
echo "# dry-run: would write $SERVICE_FILE"
printf '%s\n' "$SERVICE_CONTENT"
echo "# dry-run: would write $TIMER_FILE"
printf '%s\n' "$TIMER_CONTENT"
echo "# dry-run: would run $SYSTEMCTL daemon-reload"
echo "# dry-run: would run $SYSTEMCTL enable --now $SERVICE_NAME.timer"
exit 0
fi

[ -d "$STATE_DIR" ] || { echo "--state-dir does not exist; nothing installed" >&2; exit 3; }
mkdir -p "$SYSTEMD_DIR"
printf '%s\n' "$SERVICE_CONTENT" > "$SERVICE_FILE"
printf '%s\n' "$TIMER_CONTENT" > "$TIMER_FILE"
chmod 0644 "$SERVICE_FILE" "$TIMER_FILE"
"$SYSTEMCTL" daemon-reload
"$SYSTEMCTL" enable --now "$SERVICE_NAME.timer"
printf 'installed %s and %s\n' "$SERVICE_FILE" "$TIMER_FILE"
84 changes: 84 additions & 0 deletions scripts/install-spans-weekly-timer.test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
# Hermetic tests for scripts/install-spans-weekly-timer.sh (#2899): dry-run by
# default, the unit contents, input gates, apply and uninstall against a temp
# unit folder with a stub systemctl. Nothing here runs the weekly summary.
# shellcheck disable=SC2034 # test variables are read inside the eval'd ok() conditions
set -uo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
I="$DIR/install-spans-weekly-timer.sh"
ROOT="$(cd "$DIR/.." && pwd)"
# shellcheck source=claude/hooks/lib/test-stub.sh
. "$ROOT/claude/hooks/lib/test-stub.sh"
ccc_test_reset_hook_env
pass=0; fail=0
TMP="$(ccc_test_tmpdir)" || exit 1
trap 'rm -rf "$TMP"' EXIT
ok() { if eval "$2"; then pass=$((pass+1)); else fail=$((fail+1)); echo "FAIL: $1"; fi; }

UNITS="$TMP/units"; LOG="$TMP/systemctl.log"; ST="$TMP/home/.claude/state"
mkdir -p "$TMP/bin" "$ST" "$TMP/home/.claude/hooks/lib"
write_exec_stub "$TMP/bin/systemctl" <<'EOF'
printf '%s\n' "$*" >> "$LOG"
EOF
export LOG
inst() { HOME="$TMP/home" CCC_STATE_DIR="$ST" CCC_SYSTEMD_DIR="$UNITS" CCC_SYSTEMCTL="$TMP/bin/systemctl" \
CCC_FLEET_NODES='' CCC_SPANS_WEEKLY_PAGE='' bash "$I" "$@"; }

# 1. dry-run is the default and changes nothing
out="$(inst --nodes "alpha beta")"; rc=$?
ok "dry-run exits 0, prints both units and writes nothing" \
'[ "$rc" = 0 ] && grep -q "^# dry-run: would write $UNITS/ccc-spans-weekly.service" <<<"$out" && grep -q "^# dry-run: would write $UNITS/ccc-spans-weekly.timer" <<<"$out" && [ ! -e "$UNITS" ] && [ ! -e "$LOG" ]'
ok "timer fires Monday 05:00 Asia/Seoul (after the 04:30 view) and catches up after downtime" \
'grep -qx "OnCalendar=Mon \*-\*-\* 05:00:00 Asia/Seoul" <<<"$out" && grep -qx "Persistent=true" <<<"$out"'
ok "service runs the weekly summary from this checkout on the services page" \
'grep -qx "ExecStart=/usr/bin/env python3 $ROOT/scripts/spans-weekly.py --page pages/services/span-rollup.md --state-dir $ST --result-file $ST/ccc-spans-weekly.result" <<<"$out"'
ok "service never passes --dry-run and is a capped oneshot" \
'! grep -q -- "--dry-run" <<<"$(grep ^ExecStart <<<"$out")" && grep -qx "Type=oneshot" <<<"$out" && grep -qx "TimeoutStartSec=1500" <<<"$out"'
ok "node list, state folder and HOME are passed as environment" \
'grep -qx "Environment=\"CCC_FLEET_NODES=alpha beta\"" <<<"$out" && grep -qx "Environment=CCC_STATE_DIR=$ST" <<<"$out" && grep -qx "Environment=HOME=$TMP/home" <<<"$out"'
ok "no notify line when the notifier is absent, and no blank line left behind" \
'! grep -q "ExecStopPost" <<<"$out" && ! grep -qx "" <<<"$(sed -n "/^\[Service\]/,/^PrivateTmp/p" <<<"$out")"'
: > "$TMP/home/.claude/hooks/lib/detached_jobs.py"
out="$(inst --nodes alpha --page pages/services/other.md)"
ok "with the notifier present a failed run is sent at once" \
'grep -qx "ExecStopPost=-/usr/bin/env python3 $TMP/home/.claude/hooks/lib/detached_jobs.py notify --unit ccc-spans-weekly --exit \${EXIT_STATUS} --tier info --fail-tier notice --result-file $ST/ccc-spans-weekly.result" <<<"$out"'
ok "--page reaches the command line" 'grep -q -- "--page pages/services/other.md " <<<"$out"'
inst >/dev/null 2>&1; rc=$?
ok "--nodes is required: a node that never answered must still be listed" '[ "$rc" = 2 ]'

# 2. input gates: every value lands in a unit file
inst --nodes $'alpha\tbeta' >/dev/null 2>&1; rc0=$?
inst --nodes "alpha be/ta" >/dev/null 2>&1; rc1=$?
inst --nodes alpha --page "../etc/x.md" >/dev/null 2>&1; rc2=$?
inst --nodes alpha --page "pages/a b.md" >/dev/null 2>&1; rc3=$?
inst --nodes alpha --on-calendar $'Mon 05:00\nExecStartPre=/bin/x' >/dev/null 2>&1; rc4=$?
inst --nodes alpha --service-name "../x" >/dev/null 2>&1; rc5=$?
inst --nodes alpha --state-dir "/tmp/a b" >/dev/null 2>&1; rc6=$?
(cd "$DIR" && inst --nodes "alpha *") >/dev/null 2>&1; rc7=$?
inst --bogus >/dev/null 2>&1; rc8=$?
ok "bad node, page, calendar, service name, state dir and unknown flag are refused (exit 2)" \
'[ "$rc0$rc1$rc2$rc3$rc4$rc5$rc6$rc7$rc8" = 222222222 ]'
ok "no refused run touched systemd" '[ ! -e "$UNITS" ] && [ ! -e "$LOG" ]'

# 3. --apply
inst --apply --nodes alpha --state-dir "$TMP/no-state" >/dev/null 2>&1; rc=$?
ok "apply refuses a state folder that does not exist and installs nothing" '[ "$rc" = 3 ] && [ ! -e "$UNITS" ] && [ ! -e "$LOG" ]'
out="$(inst --apply --nodes "alpha beta")"; rc=$?
ok "apply writes both units 0644 and enables the timer" \
'[ "$rc" = 0 ] && [ "$(stat -c %a "$UNITS/ccc-spans-weekly.service")" = 644 ] && [ "$(stat -c %a "$UNITS/ccc-spans-weekly.timer")" = 644 ] && [ "$(cat "$LOG")" = "daemon-reload
enable --now ccc-spans-weekly.timer" ]'
ok "installed service content matches the dry-run" \
'diff <(inst --nodes "alpha beta" | awk "/^# dry-run: would write .*service/{on=1;next} /^# dry-run/{on=0} on") "$UNITS/ccc-spans-weekly.service" >/dev/null'
ok "apply does not run the weekly summary" '[ ! -e "$ST/ccc-spans-weekly.result" ]'

# 4. --uninstall
: > "$LOG"
out="$(inst --uninstall)"; rc=$?
ok "uninstall dry-run changes nothing" '[ "$rc" = 0 ] && [ -e "$UNITS/ccc-spans-weekly.timer" ] && [ ! -s "$LOG" ] && grep -q "would remove" <<<"$out"'
out="$(inst --uninstall --apply)"; rc=$?
ok "uninstall --apply disables the timer and removes both units" \
'[ "$rc" = 0 ] && [ ! -e "$UNITS/ccc-spans-weekly.service" ] && [ ! -e "$UNITS/ccc-spans-weekly.timer" ] && [ "$(cat "$LOG")" = "disable --now ccc-spans-weekly.timer
daemon-reload" ]'

echo "PASS=$pass FAIL=$fail"
[ "$fail" = 0 ]
2 changes: 1 addition & 1 deletion scripts/spans-rollup.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
KST = timezone(timedelta(hours=9))
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent
SUGGESTED_PATH = "pages/fleet/span-rollup.md"
SUGGESTED_PATH = "pages/services/span-rollup.md"
ENTRY_CLASS = "metrics/span-rollup"
NOTIFY_EVENT = "SpansRollup"
#: Issue #2684 completion target for span totals vs the cost ledger.
Expand Down
Loading
Loading